Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d58809bdbc | ||
|
|
84cb5904df | ||
|
|
fc52d72a01 | ||
|
|
a7186173b4 | ||
|
|
827bef8478 | ||
|
|
b2be41d540 | ||
|
|
cc0ec0ccc8 | ||
|
|
755e6aeb88 | ||
|
|
fe6dccda83 | ||
|
|
8b8041cba1 | ||
|
|
4544bc0d8b | ||
|
|
8ecc307fc9 | ||
|
|
bf5fa54f44 | ||
|
|
c6528c2887 | ||
|
|
b196047b57 | ||
|
|
ea49cb0586 | ||
|
|
da559de912 | ||
|
|
193ca89d93 | ||
|
|
dc9a7f0dbf | ||
|
|
3c4dbf3ad0 | ||
|
|
df006ee706 | ||
|
|
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 | ||
|
|
0705101c97 | ||
|
|
5992322371 | ||
|
|
d0683f0b6d |
@@ -0,0 +1,34 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to the published WIP Rust crates are documented here.
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Breaking Protocol/HTTP migration from opaque Interface reference strings to
|
||||
exact `(scope, name)` records in Objects, fetches and calls, with optional
|
||||
opaque `scope_ref` metadata. Adds shape and placement-aware scope validation
|
||||
without changing routes, validators or the wire error-code set.
|
||||
- Breaking Host registration migration to explicit Scope publication lifetimes and
|
||||
local names, with coherent provider-attested scope Object binding for fetch and
|
||||
dispatch. Supplied scope_ref is checked at membership precedence; scope deletion
|
||||
retires retained tokens, while ordinary Object state updates preserve lifetime.
|
||||
- Integrates scoped references across filesystem and public consumers and the TUI.
|
||||
External FS scopes bind to visible current connected lineage, not retained
|
||||
registry artifacts. TUI labels use absolute safely quoted `::`/`#` notation;
|
||||
structured selection and Client scope invalidation prevent stale UI dispatch.
|
||||
The public example carries fetched scope refs and includes real HTTP lifetime,
|
||||
visibility and validator-precedence conformance tests with optional refs. See
|
||||
[MIGRATION.md](MIGRATION.md) for API/wire examples and provider responsibilities.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
Initial public release of:
|
||||
|
||||
- `wip-protocol`: transport-independent WIP logical model and validation.
|
||||
- `wip-interface-macros`: procedural-macro implementation for interface and DTO declarations.
|
||||
- `wip-interface`: public Rust interface-authoring facade and typed value codecs.
|
||||
- `wip-host`: request-scoped publication, precondition validation, and qualified operation dispatch.
|
||||
- `wip-http`: framework-independent WIP over HTTP v1 routes, strict JSON codecs, and failure classification.
|
||||
- `wip-client`: stateful Known Space, interest-driven acquisition, request ownership, and operation lifecycle.
|
||||
|
||||
The repository also contains non-published filesystem server, terminal client, and public-API conformance packages.
|
||||
Generated
+1146
-3
File diff suppressed because it is too large
Load Diff
+13
-11
@@ -1,17 +1,19 @@
|
||||
[workspace]
|
||||
members = [
|
||||
".",
|
||||
"crates/wip-host",
|
||||
"crates/wip-interface",
|
||||
"crates/wip-interface-macros",
|
||||
"crates/wip-protocol",
|
||||
]
|
||||
members = ["crates/*"]
|
||||
resolver = "3"
|
||||
|
||||
[package]
|
||||
name = "wip-rs"
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://gitea.hareworks.net/Hare/wip-rs"
|
||||
|
||||
[dependencies]
|
||||
wip-protocol = { path = "crates/wip-protocol" }
|
||||
[workspace.dependencies]
|
||||
wip-client = { version = "0.1.0", path = "crates/wip-client" }
|
||||
wip-fs-server = { version = "0.1.0", path = "crates/wip-fs-server" }
|
||||
wip-host = { version = "0.1.0", path = "crates/wip-host" }
|
||||
wip-http = { version = "0.1.0", path = "crates/wip-http" }
|
||||
wip-interface = { version = "0.1.0", path = "crates/wip-interface" }
|
||||
wip-interface-macros = { version = "0.1.0", path = "crates/wip-interface-macros" }
|
||||
wip-protocol = { version = "0.1.0", path = "crates/wip-protocol" }
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
# Structured Interface reference and scope publication migration
|
||||
|
||||
This unreleased API/wire change follows `wip-reference` canonical Core Model,
|
||||
Protocol and WIP over HTTP at `6086f3c5ef10aa1464ce9c824750d7f667217bfd`.
|
||||
It replaces the earlier opaque Interface reference contract; HTTP routes and
|
||||
error codes have **not** changed. Peers must upgrade together: the codec does
|
||||
not accept legacy strings or display shorthand as Protocol references.
|
||||
|
||||
## Rust API
|
||||
|
||||
`Object.interfaces` is now `Vec<InterfaceReference>`.
|
||||
`FetchInterfaceRequest.interface`, `FetchInterfaceResponse.interface`, and
|
||||
`InterfaceTarget.reference` all use the same record:
|
||||
|
||||
```rust
|
||||
use wip_protocol::{FetchInterfaceRequest, InterfaceReference, InterfaceTarget};
|
||||
|
||||
let reference = InterfaceReference {
|
||||
scope: "/github".into(),
|
||||
name: "issue.read".into(),
|
||||
};
|
||||
reference.validate()?; // reference shape, no target Object path needed
|
||||
let fetch = FetchInterfaceRequest { interface: reference.clone() };
|
||||
let target = InterfaceTarget {
|
||||
reference,
|
||||
scope_ref: Some("opaque-scope-object-ref".into()),
|
||||
validator: None,
|
||||
};
|
||||
# Ok::<(), wip_protocol::ValidationError>(())
|
||||
```
|
||||
|
||||
Construct scope and name explicitly from your Worldspace publication context.
|
||||
There is no implicit conversion from a string, delimiter parser, normalization,
|
||||
case folding, or URL decoding. A name may contain `/`, `.`, `::`, `#`, or Unicode;
|
||||
only an empty name is invalid. Scope must be a canonical absolute Worldspace
|
||||
path: `/`, or nonempty slash-separated segments other than `.` and `..`, with
|
||||
no empty segments or trailing slash. `%2F` is ordinary field text, not an escape
|
||||
for a Worldspace path separator.
|
||||
|
||||
Equality, hashing and ordering operate on both fields, independent of member
|
||||
order/JSON escape spelling. Use the record itself as a membership/cache key;
|
||||
identical names in different scopes are different references. The descriptor
|
||||
still contains only format, documentation, types and operations, not identity.
|
||||
|
||||
`FetchInterfaceResponse` and `InterfaceTarget` additionally require the Rust
|
||||
field `scope_ref: Option<String>` in struct literals. Use `None` when omitted,
|
||||
not an invented identity. This is an opaque scope Object ref observation/call
|
||||
precondition, **not** a third Interface identity component or a validator.
|
||||
Host enforces scope publication lifetimes and optional scope-ref identity
|
||||
inside the provider boundary. Client caches keep the complete structured reference
|
||||
and optional fetched scope binding; confirmed scope deletion or ref replacement
|
||||
invalidates bound observations, while local eviction is not deletion evidence.
|
||||
Do not mistake registry artifact retention for publication.
|
||||
|
||||
## Validation boundaries
|
||||
|
||||
- `InterfaceReference::validate()` and `FetchInterfaceRequest::validate()`
|
||||
check reference shape independently of a target Object path.
|
||||
- `Object::validate()` checks shape and duplicate `(scope, name)` pairs;
|
||||
`Object::validate_at_path()` additionally checks placement, including scope.
|
||||
`ObserveRequest::validate_response()` checks every derived node path,
|
||||
including the depth boundary. Invalid success responses are Client-local
|
||||
`InvalidResponse`, not Host-returned Protocol errors.
|
||||
- `InterfaceReference::validate_for_path(path)` checks ancestor-or-self scope
|
||||
compatibility by path segments. Root and self scope are valid; `/a` is not
|
||||
an ancestor of `/ab`. This has no indexability dependency.
|
||||
- `CallOperationRequest::validate()` checks descriptor-independent shape.
|
||||
`validate_with()` adds operation/argument checks but does not replace Host
|
||||
publication lookup. Host interface selection checks scope compatibility and
|
||||
exact membership **after** target lookup: invalid reference shape is
|
||||
`InvalidRequest`, but a valid reference outside the target's scope is
|
||||
`InterfaceMismatch`, with `NotFound` retaining precedence.
|
||||
|
||||
## HTTP wire
|
||||
|
||||
All four reference positions use an exact object with required string fields:
|
||||
|
||||
```json
|
||||
{"scope":"/github","name":"issue.read"}
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```json
|
||||
{
|
||||
"interface": {"scope":"/github","name":"issue.read"},
|
||||
"scope_ref": "opaque-scope-object-ref",
|
||||
"descriptor": {"format":"wip-interface/1","types":[],"operations":[]}
|
||||
}
|
||||
```
|
||||
|
||||
A call uses:
|
||||
|
||||
```json
|
||||
{
|
||||
"target": {"path":"/github/issues/123"},
|
||||
"interface": {
|
||||
"reference": {"scope":"/github","name":"issue.read"},
|
||||
"scope_ref": "opaque-scope-object-ref"
|
||||
},
|
||||
"operation":"refresh",
|
||||
"arguments":{}
|
||||
}
|
||||
```
|
||||
|
||||
Unknown/duplicate members, missing fields, null fields, relative scopes, empty
|
||||
names, legacy `"interface-v1"` and shorthand `"/github::issue.read"` strings
|
||||
are rejected. Field order and JSON escaping do not affect decoded identity.
|
||||
`scope_ref` is a normal opaque string, **not Base64**; omission is allowed but
|
||||
explicit null and nonstrings are invalid. An empty string is a valid opaque
|
||||
ref. Validators remain canonical padded standard Base64.
|
||||
|
||||
Descriptor-independent HTTP call metadata decoding enforces reference shape
|
||||
and the same strict JSON rules without turning scope compatibility into early
|
||||
`InvalidRequest`. Normal descriptor-bound encode/decode uses the same reference
|
||||
codec. Request violations retain the existing `400 invalid_request` boundary;
|
||||
malformed success responses retain Client-local `InvalidResponse`. Standard
|
||||
`POST v1/observe`, `v1/fetch_interface`, `v1/call_operation`, error-code/status
|
||||
mapping and Transport failure classification are unchanged.
|
||||
|
||||
## Host registration and provider migration
|
||||
|
||||
Registration now requires an explicit canonical Scope and local name:
|
||||
|
||||
```rust,ignore
|
||||
let mut registry = wip_host::InterfaceRegistry::new();
|
||||
let scope = wip_host::Scope::new("/service")?;
|
||||
let api = registry.register(&scope, "catalog", CatalogDefinition, None)?;
|
||||
|
||||
// INSIDE the backend transaction/lock/stable-handle boundary:
|
||||
let current = wip_host::ScopeObservation::new(&scope, ¤t_scope_object);
|
||||
let publication = wip_host::PublishedObject::new(current_target_object)
|
||||
.expose(&api)?
|
||||
.bind_scope(current);
|
||||
```
|
||||
|
||||
Collision keys are exact `(scope, name)` coordinates, not Rust Definition TypeId.
|
||||
The same Definition can be registered in different scopes or under different
|
||||
names. Root, self and ancestor scopes are valid, but ancestor compatibility and
|
||||
explicit target membership remain independent checks. Descriptors still have
|
||||
no publication identity fields.
|
||||
|
||||
A Scope carries a private publication lifetime, not a generated Protocol ref.
|
||||
Clone it only while the same scope Object remains published: ordinary Object
|
||||
state/validator updates do not retire it. Deletion, replacement or movement
|
||||
requires retiring the old lifetime with `registry.remove_scope(&scope)` and
|
||||
creating a fresh Scope before republication, even at the same path or ref.
|
||||
Retained registration tokens cannot fetch or start calls after retirement.
|
||||
Ref-less replacement cannot be tracked by a Client identity precondition; refs
|
||||
and scope_ref remain optional, not forcibly generated.
|
||||
|
||||
`ScopeObservation::new(&scope, &object)` is a provider attestation that this
|
||||
lifetime currently belongs to the Object at the scope path. Construct and attach
|
||||
it with `PublishedObject::bind_scope` inside the same coherent boundary as target
|
||||
resolution, membership, Descriptor/validator selection, implementation and
|
||||
backend handles, through dispatch and commit/rollback. A matching ref or an
|
||||
independent scope prelookup is not sufficient. The scope Object need not expose
|
||||
any interfaces. Providers own atomicity and external-writer limitations; the
|
||||
runtime checks the attached lifetime and optional scope_ref, and validates both
|
||||
arguments and results against the same frozen Descriptor. A supplied scope_ref
|
||||
mismatch, including a missing current ref, is `InterfaceMismatch` at membership
|
||||
precedence, after target existence and a supplied Object validator mismatch.
|
||||
Omission applies no scope identity precondition.
|
||||
|
||||
Artifact-only `registry.fetch_interface(reference)` is removed. Prefer
|
||||
`ObjectProvider::fetch_interface(&provider, ®istry, &reference)`, which resolves
|
||||
the visible scope Object with `with_object` and uses its attached current binding.
|
||||
Low-level `registry.fetch_interface(&reference, ¤t_observation)` requires
|
||||
the same coherent current attestation, not a cached snapshot. Fetch returns
|
||||
Descriptor, Interface validator and optional scope Object ref together; Clients
|
||||
need not additionally fetch an ancestor Object. `registry.scopes()` may repeat
|
||||
a handle for several names; do not treat it as a unique-scope iterator.
|
||||
|
||||
`PublishedObject::protocol_object()` is a path-free composition projection, not
|
||||
publication authority. For current observations use `ObjectProvider::observe_object`
|
||||
or `publication.protocol_object_at(path)` inside the coherent provider boundary;
|
||||
the latter also validates compatible live scope associations and response shape.
|
||||
|
||||
## Downstream status
|
||||
|
||||
The filesystem default registers local names `file.read`, `symlink.inspect` and
|
||||
`file.write` at its deployment-pinned root Scope, displayed as `/::file.read` etc.
|
||||
External compositions choose explicit Scope/local names and implement
|
||||
`Composition::scope` to attest a non-root lifetime from the exact refreshed backend
|
||||
entry in its connected lineage. The engine never independently resolves a scope
|
||||
path during dispatch. Default composition remains root-scoped; exposing non-root
|
||||
registrations requires the application's current lifetime attestation, not merely
|
||||
an artifact or matching ref/validator. All bindings are formed inside backend
|
||||
execution, with current principal lineage visibility and publication metadata.
|
||||
Retire/recreate Scope handles on deletion, replacement or movement; a pinned leaf
|
||||
alone is not evidence that a self-scope Object remains published at that path.
|
||||
The Linux deployment root remains pinned across textual root rename/replacement,
|
||||
and its ref-less default publication continues to omit scope_ref.
|
||||
|
||||
The public API example self-scopes `catalog`, `audit` and `diagnostics` at
|
||||
`/article-service`, fetches through its provider, and constructs call metadata
|
||||
from the fetched structured reference and scope_ref. External-style conformance
|
||||
tests also cross real TCP HTTP for root/self-scopes, same names in different
|
||||
scopes, optional refs, stale refs, deletion/republication and validator precedence.
|
||||
|
||||
The TUI stores structured references in cache keys, selections, actions, editors
|
||||
and in-flight subjects. Normal screens reuse the canonical absolute scoped
|
||||
formatter (`/scope::name#operation`, with JSON component quoting when needed).
|
||||
Labels are never parsed to reconstruct identity, and scope_ref/validators are not
|
||||
normal-screen reference labels. Client invalidation is synchronized back into UI
|
||||
observations before dispatch; re-observation is not automatic execution. Typed
|
||||
result entries are still fetched on selection, not all at once, and do not create
|
||||
inferred indexable edges. Interface authoring/macros remain descriptor-only.
|
||||
@@ -2,6 +2,139 @@
|
||||
|
||||
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
|
||||
Published libraries
|
||||
|
||||
wip-client
|
||||
├── wip-http
|
||||
│ └── wip-protocol
|
||||
└── wip-protocol
|
||||
|
||||
wip-host
|
||||
├── wip-interface
|
||||
│ ├── wip-interface-macros
|
||||
│ └── wip-protocol
|
||||
└── wip-protocol
|
||||
|
||||
Workspace-only applications and conformance consumers
|
||||
|
||||
wip-tui
|
||||
├── wip-client
|
||||
├── wip-http
|
||||
└── wip-protocol
|
||||
|
||||
wip-fs-server
|
||||
├── wip-host
|
||||
├── wip-http
|
||||
├── wip-interface
|
||||
└── wip-protocol
|
||||
|
||||
wip-public-api-example
|
||||
├── wip-host
|
||||
├── 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, and error/status classification. | 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, 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. |
|
||||
|
||||
## Published crates
|
||||
|
||||
The `0.1.0` release consists of these six crates:
|
||||
|
||||
- `wip-protocol`
|
||||
- `wip-interface-macros` — implementation dependency re-exported by `wip-interface`
|
||||
- `wip-interface`
|
||||
- `wip-host`
|
||||
- `wip-http`
|
||||
- `wip-client`
|
||||
|
||||
The filesystem server, terminal client, and public-API example are workspace-only packages and set `publish = false`. All workspace packages require Rust 1.88 or newer and are licensed under either Apache-2.0 or MIT at your option.
|
||||
|
||||
See [RELEASING.md](RELEASING.md) for the dependency-ordered crates.io procedure and [CHANGELOG.md](CHANGELOG.md) for release contents.
|
||||
|
||||
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.
|
||||
|
||||
## Structured Interface references
|
||||
|
||||
The unreleased Protocol/HTTP API uses explicit `InterfaceReference { scope,
|
||||
name }` records and optional `scope_ref` observation/precondition metadata.
|
||||
Legacy opaque-string wire references are rejected. See [MIGRATION.md](MIGRATION.md)
|
||||
for construction examples, validation boundaries and downstream migration status.
|
||||
The filesystem default publishes `/::file.read`, `/::symlink.inspect` and
|
||||
`/::file.write`; external compositions explicitly choose Scope/local names.
|
||||
The TUI retains structured references for selection and dispatch, while normal
|
||||
screens use absolute `scope::name#operation` labels with safely quoted components.
|
||||
These labels are display-only: they are never parsed as cache keys or call targets,
|
||||
and scope refs/validators remain runtime metadata rather than normal-screen labels.
|
||||
Client scope invalidation is reflected in the UI before another explicit call.
|
||||
|
||||
## 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 structured interface references, descriptors, and
|
||||
descriptor validators;
|
||||
6. calls qualified by `target.path`, object validator, interface reference and
|
||||
validator, operation, and schema-neutral `Value` arguments;
|
||||
7. validated result values decoded back to the typed application result;
|
||||
8. independent dispatch of the same `status` operation name on both interfaces;
|
||||
9. distinct domain rejection, rollback-confirmed and outcome-unknown
|
||||
host/backend failures, `PermissionDenied`, stale validator recovery, interface
|
||||
membership, and lookup failure codes; and
|
||||
10. canonical failure precedence when several request fields are invalid.
|
||||
|
||||
Run it inside the development shell:
|
||||
|
||||
```console
|
||||
nix develop
|
||||
cargo run --package wip-public-api-example
|
||||
```
|
||||
|
||||
The public-only conformance suite is in
|
||||
[`crates/wip-public-api-example/tests/end_to_end.rs`](crates/wip-public-api-example/tests/end_to_end.rs).
|
||||
It covers canonical object/descriptor shape, ordered interfaces,
|
||||
schema-neutral record/enum/union/entry/JSON values, fully qualified calls, and
|
||||
the distinct domain, host, authorization, validator-recovery, and interface
|
||||
failure classes. Exhaustive public type construction and matching make legacy
|
||||
ObjectId, descriptor `name`, and semantic `Value` variants compile-time
|
||||
regressions. Unit tests in the public crates additionally cover every host
|
||||
dispatch failure, `InvalidRequest` versus descriptor-bound `InvalidArguments`,
|
||||
invalid local responses, validators, same-named operations, and exhaustive
|
||||
per-interaction protocol error-code sets.
|
||||
|
||||
## Interface authoring
|
||||
|
||||
Applications depend on `wip-interface`, normally imported as `wip`:
|
||||
@@ -30,42 +163,69 @@ pub trait Messenger {
|
||||
```
|
||||
|
||||
The `interface` attribute and `WipType` derive are re-exported by the facade;
|
||||
users do not import `wip-interface-macros` directly. The generated
|
||||
`MessengerDefinition` constructs an `InterfaceDescriptor`, decodes named
|
||||
arguments, encodes results, validates both boundaries, and provides typed
|
||||
dispatch for any `T: Messenger`.
|
||||
users do not import `wip-interface-macros` or generated private support symbols.
|
||||
The generated `MessengerDefinition` constructs an `InterfaceDescriptor`,
|
||||
decodes named arguments, encodes results, validates both boundaries, and
|
||||
provides typed dispatch for any `T: Messenger`.
|
||||
|
||||
### Type mapping
|
||||
### Supported Rust syntax
|
||||
|
||||
A supported interface is a public, non-generic trait containing methods with:
|
||||
|
||||
- exactly an immutable `&self` receiver;
|
||||
- simple named, owned parameters;
|
||||
- an explicit `wip::OperationResult<T>` return;
|
||||
- `()` only as the application return when no value is produced; and
|
||||
- direct `Option<T>` only for an omittable parameter.
|
||||
|
||||
`WipType` derives support named-field structs, all-unit enums, and unions whose
|
||||
cases may be unit variants or variants containing exactly one unnamed payload.
|
||||
The macros reject private,
|
||||
generic, inherited, unsafe, auto, or associated-item traits; const, async,
|
||||
unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
|
||||
borrowed/custom-lifetime values; tuple/unit/generic structs; Rust unions;
|
||||
named-field/multi-field enum variants; explicit discriminants; nested `Option`; and
|
||||
`Option` in returns, collections, entries, or union payloads. These diagnostics
|
||||
are compile-fail tested under `crates/wip-interface/tests/ui`.
|
||||
|
||||
### Rust type mapping
|
||||
|
||||
| Rust | Protocol |
|
||||
| --- | --- |
|
||||
| `()` as an operation result | no returned value |
|
||||
| `()` | unit / `Value::Unit` |
|
||||
| `bool` | boolean |
|
||||
| integer primitives | JavaScript-lossless integer |
|
||||
| `f32`, `f64` | finite number |
|
||||
| `String` | string |
|
||||
| `wip::Bytes` | bytes |
|
||||
| `wip::wip_protocol::JsonValue` | JSON |
|
||||
| `wip::Entry<K, V>` | entry |
|
||||
| `wip::JsonValue` | JSON interpreted over the schema-neutral `Value` tree |
|
||||
| `wip::Entry` | canonical absolute Worldspace path encoded as a string |
|
||||
| `Vec<T>` | list |
|
||||
| named-field `#[derive(wip::WipType)]` struct | named record |
|
||||
| all-unit `#[derive(wip::WipType)]` enum | named enum |
|
||||
| all-newtype `#[derive(wip::WipType)]` enum | named tagged union |
|
||||
| all-unit `#[derive(wip::WipType)]` enum | named enum encoded as a string |
|
||||
| mixed unit/newtype or all-newtype enum | named union encoded as a discriminator record |
|
||||
|
||||
`Option<T>` is accepted only for a direct DTO field or operation parameter and
|
||||
means that the named value may be omitted. It is not protocol null. Domain
|
||||
failures are modeled in the application result (usually a derived union) and
|
||||
returned through `Ok`; `wip::HostError` is only for host/runtime failures.
|
||||
`Option<T>` means that a direct DTO field or operation parameter may be
|
||||
omitted; it is not protocol null. JSON null remains available inside
|
||||
`wip::JsonValue`.
|
||||
|
||||
#### Migration from the pre-canonical value API
|
||||
|
||||
The old generic `wip::Entry<K, V>` represented an application key/value pair
|
||||
and is no longer available. Use `wip::Entry::new("/canonical/path")` for a
|
||||
Worldspace entry path and place any associated application data in a record.
|
||||
`Entry` encodes as `Value::String` and validates the canonical absolute path.
|
||||
|
||||
The semantic `Value::Json`, `Value::Entry`, `Value::Enum`, and `Value::Union`
|
||||
variants have also been removed. JSON recursively uses `Unit`, primitive,
|
||||
`List`, and `Record` values and rejects `Bytes`; enums use `String`; unions use
|
||||
a `Record` containing `$case` and, for payload-bearing cases, `value`. Unit
|
||||
operation results are represented explicitly as `Value::Unit`.
|
||||
|
||||
Rust doc comments become descriptor metadata. For an operation, a `# Returns`
|
||||
section documents the return declaration; text before that section documents
|
||||
the operation itself.
|
||||
|
||||
The supported interface slice is deliberately non-generic: public traits,
|
||||
`&self`, named parameters, and `OperationResult<T>`. Generic traits or methods,
|
||||
associated items, custom lifetimes, inheritance, default method bodies, and
|
||||
other receiver forms are rejected at their source spans.
|
||||
|
||||
## Host publication and dispatch
|
||||
|
||||
Applications use `wip-host` to register generated definitions and explicitly
|
||||
@@ -73,27 +233,128 @@ 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 scope = wip_host::Scope::new("/service")?;
|
||||
let messenger = interfaces.register(&scope, "messenger", MessengerDefinition, None)?;
|
||||
|
||||
// Inside the provider coherent backend boundary, not a stale scope prelookup:
|
||||
let current = wip_host::ScopeObservation::new(&scope, ¤t_scope_object);
|
||||
|
||||
let published = wip_host::PublishedObject::new(request_scoped_object)
|
||||
.expose(&messenger)?;
|
||||
let protocol_object = published.protocol_object();
|
||||
.expose(&messenger)?
|
||||
.bind_scope(current);
|
||||
let protocol_object = published.protocol_object_at("/service/item")?;
|
||||
```
|
||||
|
||||
`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; descriptor names and
|
||||
Rust type names are not used as wire identity.
|
||||
references are rejected. Registry collisions use exact `(scope, name)` pairs,
|
||||
not Rust Definition identity; the same Definition may be registered at multiple
|
||||
coordinates. Structured references remain outside the Descriptor.
|
||||
|
||||
Dispatch is qualified by interface reference and operation name. The host checks
|
||||
current object identity and validator policy, current interface membership,
|
||||
interface validator, descriptor operation, arguments, and result while retaining
|
||||
the selected object and registered artifact. Host-private fields and backend
|
||||
handles are never projected by `WipObject`.
|
||||
`Scope` carries a private Object publication lifetime. Keep it for ordinary state
|
||||
updates; retire it with `remove_scope` and create a fresh Scope on deletion,
|
||||
replacement or movement, even at the same path. Providers attach a current
|
||||
`ScopeObservation` from the scope Object inside the coherent target/backend
|
||||
boundary, never from a separate prelookup. The scope Object need not expose any
|
||||
interfaces. Fetch uses `ObjectProvider::fetch_interface(&provider, ®istry,
|
||||
&reference)` to observe the visible scope Object and return its optional ref,
|
||||
Descriptor and Interface validator together; retained artifacts alone are not
|
||||
publication. Calls require the current attached lifetime and check supplied
|
||||
`scope_ref` at membership precedence; omission adds no identity precondition.
|
||||
Refs, Object validators and Interface validators retain distinct responsibilities.
|
||||
See [MIGRATION.md](MIGRATION.md) for the provider atomicity and lifecycle contract.
|
||||
|
||||
Providers remain responsible for backend atomicity. Enter a transaction, lock,
|
||||
stable-handle scope, or conditional-update primitive before constructing and
|
||||
dispatching the request-scoped `PublishedObject`, and retain it until dispatch
|
||||
returns. The runtime never validates one object and then resolves a second
|
||||
snapshot, but it cannot make an arbitrary external backend atomic by itself.
|
||||
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 scope lifetime/optional scope_ref and 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,75 @@
|
||||
# Releasing
|
||||
|
||||
The six crates published from this workspace use one version and must be released in dependency order. The filesystem server, terminal client, and public-API example set `publish = false` and are never uploaded.
|
||||
|
||||
## Preconditions
|
||||
|
||||
1. Work from a clean `master` whose `HEAD` matches `origin/master`.
|
||||
2. Confirm the intended version in `[workspace.package]` and every internal requirement in `[workspace.dependencies]`.
|
||||
3. Confirm ownership of all six names on crates.io.
|
||||
4. Run the complete repository validation suite:
|
||||
|
||||
```console
|
||||
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
|
||||
```
|
||||
|
||||
## Publish order
|
||||
|
||||
Before uploading anything, dry-run the exact public package set together. Cargo uses a temporary local registry for unpublished workspace dependencies during this check:
|
||||
|
||||
```console
|
||||
cargo publish --dry-run --workspace \
|
||||
--exclude wip-fs-server \
|
||||
--exclude wip-public-api-example \
|
||||
--exclude wip-tui
|
||||
```
|
||||
|
||||
Then dry-run and publish each layer before moving to a crate that depends on it:
|
||||
|
||||
```console
|
||||
cargo publish --dry-run --package wip-protocol
|
||||
cargo publish --package wip-protocol
|
||||
|
||||
cargo publish --dry-run --package wip-interface-macros
|
||||
cargo publish --package wip-interface-macros
|
||||
```
|
||||
|
||||
Wait until both versions are available from the crates.io index, then continue:
|
||||
|
||||
```console
|
||||
cargo publish --dry-run --package wip-interface
|
||||
cargo publish --package wip-interface
|
||||
|
||||
cargo publish --dry-run --package wip-http
|
||||
cargo publish --package wip-http
|
||||
```
|
||||
|
||||
After those versions are available from the index:
|
||||
|
||||
```console
|
||||
cargo publish --dry-run --package wip-host
|
||||
cargo publish --package wip-host
|
||||
|
||||
cargo publish --dry-run --package wip-client
|
||||
cargo publish --package wip-client
|
||||
```
|
||||
|
||||
Registry propagation can take time. A dependent dry-run reporting that a WIP crate is unavailable means the previous publish is not visible in the selected registry yet; do not bypass verification.
|
||||
|
||||
## Tag
|
||||
|
||||
After all six uploads resolve successfully, tag the exact published commit and push the tag:
|
||||
|
||||
```console
|
||||
git tag -a v0.1.0 -m "release: 0.1.0"
|
||||
git push origin v0.1.0
|
||||
```
|
||||
|
||||
Do not move or recreate a published version or its tag. Prepare a new version for any subsequent correction.
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "wip-client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Presentation-independent stateful WIP client runtime"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-client"
|
||||
|
||||
[dependencies]
|
||||
wip-http.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,36 @@
|
||||
# wip-client
|
||||
|
||||
Presentation-independent stateful runtime for Web Interface Protocol (WIP) clients.
|
||||
|
||||
`wip-client` manages endpoint- and security-context-isolated Known Space, object and Interface Descriptor observations, bounded request ownership, supersession, out-of-order response suppression, validator recovery, and operation call contexts. It produces and consumes framework-neutral `wip-http` messages but performs no network I/O and contains no UI types.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-client = "0.1.0"
|
||||
```
|
||||
|
||||
Applications provide the HTTP adapter and presentation layer, send each prepared request exactly as owned by the runtime, then return the corresponding response for completion.
|
||||
|
||||
## Interface identity and scope lifetime
|
||||
|
||||
Interface acquisition and call APIs use `wip_protocol::InterfaceReference { scope, name }` directly. Within an endpoint/security-context session, the complete scoped pair is the cache key and the Object membership key: equal names in different scopes remain distinct. A scope is a canonical absolute Worldspace path and must be an ancestor of, or equal to, the call target path. Root scope (`/`) and self scope are valid; clients must not rewrite either into a different reference.
|
||||
|
||||
`InterfaceObservation::scope_ref` is optional opaque metadata identifying the scope Object, not a third reference component, a path, or an Interface Descriptor validator. Its absence does not prevent acquisition or calls. Calls copy the exact observed reference, optional `scope_ref`, and optional Interface Descriptor validator into `InterfaceTarget`; the target Object validator is copied separately. The `CallContext` fixes those observations, the descriptor, and the operation declaration before dispatch.
|
||||
|
||||
A descriptor without an Interface Descriptor validator is immutable only within the lifetime of its scope Object, not forever at that path. Descriptors with validators are also bound to that scope lifetime. When accepted observations establish that a known scope binding has changed or been lost, dependent cached interface state is invalidated and cannot authorize a new call until explicitly reacquired. A superseded interface response must not restore an observation from the old lifetime. A previously prepared call retains its original context rather than silently adopting a new scope identity or descriptor.
|
||||
|
||||
Scope binding evidence is shared across Interface names at the same scope path: a new binding learned by fetching one name retires older descriptors for the other names too. Separately observed Object refs also provide lifetime evidence even when a descriptor's `scope_ref` was omitted. This corroboration is private bounded cache state, not an invented identity, and never fills in missing call metadata. Same-lifetime descriptor validation still applies; a detected ref change or loss retires the old lifetime instead.
|
||||
|
||||
Object deletion, entry-edge removal, and local cache eviction are different events. A direct observe `NotFound` confirms unavailability at the requested scope path and removes cached interfaces scoped to that path; it does not guarantee identity-wide Object deletion or unavailability through every alias. Removing one entry edge likewise does not prove that the Object was deleted or invalidate every remaining alias. Cache eviction is local loss of retained knowledge, not evidence of Host deletion. Losing a known binding at an interface's scope path nevertheless ends safe reuse of descriptors dependent on that binding, even if the same Object remains reachable elsewhere. Optional `scope_ref` can provide identity evidence, but clients do not fabricate it when it is absent.
|
||||
|
||||
Without Object `ref` or `scope_ref` identity evidence, a replacement at the same scope path can be indistinguishable from the previous Object. The runtime cannot detect every ref-less replacement from path and descriptor contents alone; absence of detectable change is not proof that the scope lifetime continued.
|
||||
|
||||
## Explicit recovery and operation outcomes
|
||||
|
||||
`ensure_observed` and `ensure_interface` avoid duplicate fresh or loading work; they do not automatically refresh retained stale or failed observations. Use the explicit object/children refresh APIs and `prepare_interface` to recover the observations required for a new call. An operation `InterfaceMismatch` invalidates both sides of the call's assumptions: it marks the target Object observation stale and invalidates the selected cached interface observation, so recovery requires reobserving membership and reacquiring the descriptor. Reobserving an Object and reacquiring its interface are retrievals, not a retry of an operation.
|
||||
|
||||
The runtime never automatically retries an operation. Mark a call dispatched when handing it to the transport and report completion or transport failure with its original `RequestId`. A timeout, disconnect, or invalid response after dispatch can leave the outcome unknown: execution or commit cannot be ruled out. Refreshing stale state does not resolve that uncertainty and must not automatically resubmit the call; any new operation is an explicit application decision.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-client) for session, acquisition, cache, and call APIs.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,713 @@
|
||||
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: "/".into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
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, decode_call_operation_request, decode_fetch_interface_request,
|
||||
encode_fetch_interface_response, encode_observe_response, encode_protocol_error_response,
|
||||
};
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1,
|
||||
InterfaceDescriptor, InterfaceReference, InterfaceTarget, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ParameterDeclaration, ProtocolError, ProtocolErrorCode,
|
||||
ProtocolInteraction, ReturnDeclaration, Target, TypeExpr, Value,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 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![root_reference("math")],
|
||||
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,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn observe(client: &mut Client, session: &wip_client::SessionId, path: &str, value: Object) {
|
||||
let request = client.refresh_object(session, path).unwrap();
|
||||
client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: path.into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: value,
|
||||
children: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn fetch(
|
||||
client: &mut Client,
|
||||
session: &wip_client::SessionId,
|
||||
value: FetchInterfaceResponse,
|
||||
) -> Completion {
|
||||
let request = client
|
||||
.prepare_interface(session, value.interface.clone())
|
||||
.unwrap();
|
||||
let logical = FetchInterfaceRequest {
|
||||
interface: value.interface.clone(),
|
||||
};
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(request.request.body(), limits()).unwrap(),
|
||||
logical
|
||||
);
|
||||
client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_fetch_interface_response(&logical, &value, limits()).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_accepts_same_name_interfaces_in_different_scopes() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_object(&session, "/item").unwrap();
|
||||
let completion = client
|
||||
.complete(
|
||||
request.id,
|
||||
response(
|
||||
StatusCode::OK,
|
||||
br#"{"object":{"name":"item","interfaces":[{"scope":"/","name":"math"},{"scope":"/item","name":"math"}]}}"#,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let expected = vec![root_reference("math"), reference("/item", "math")];
|
||||
assert!(matches!(
|
||||
completion,
|
||||
Completion::Object(observation)
|
||||
if observation.state == ObservationState::Fresh
|
||||
&& observation.object.as_ref().unwrap().interfaces == expected
|
||||
));
|
||||
let cached = client.object(&session, "/item").unwrap();
|
||||
assert_eq!(cached.state, ObservationState::Fresh);
|
||||
assert_eq!(cached.object.unwrap().interfaces, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_different_scopes_have_independent_requests_and_cached_descriptors() {
|
||||
let (mut client, session) = setup();
|
||||
let root = root_reference("math");
|
||||
let scoped = reference("/area", "math");
|
||||
let root_request = client
|
||||
.ensure_interface(&session, root.clone())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let scoped_request = client
|
||||
.ensure_interface(&session, scoped.clone())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_ne!(root_request.id, scoped_request.id);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(root_request.request.body(), limits()).unwrap(),
|
||||
FetchInterfaceRequest {
|
||||
interface: root.clone(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(scoped_request.request.body(), limits()).unwrap(),
|
||||
FetchInterfaceRequest {
|
||||
interface: scoped.clone(),
|
||||
}
|
||||
);
|
||||
for selected in [&root, &scoped] {
|
||||
assert!(
|
||||
client
|
||||
.ensure_interface(&session, selected.clone())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(client.in_flight_len(), 2);
|
||||
|
||||
// Reverse completion order must not supersede the other scope's request.
|
||||
for (request, selected, documentation, scope_ref, validator) in [
|
||||
(
|
||||
scoped_request,
|
||||
&scoped,
|
||||
"area math",
|
||||
Some("area-object"),
|
||||
Some(b"area-v1".to_vec()),
|
||||
),
|
||||
(root_request, &root, "root math", None, None),
|
||||
] {
|
||||
let mut expected_descriptor = descriptor(INTERFACE_FORMAT_V1);
|
||||
expected_descriptor.documentation = Some(wip_protocol::Documentation {
|
||||
summary: documentation.into(),
|
||||
details: None,
|
||||
});
|
||||
let value = FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
descriptor: expected_descriptor.clone(),
|
||||
validator: validator.clone(),
|
||||
};
|
||||
let completion = client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: selected.clone(),
|
||||
},
|
||||
&value,
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(completion, Completion::Interface(_)));
|
||||
let cached = client.interface(&session, selected).unwrap();
|
||||
assert_eq!(cached.reference, *selected);
|
||||
assert_eq!(cached.descriptor, Some(expected_descriptor));
|
||||
assert_eq!(cached.scope_ref, value.scope_ref);
|
||||
assert_eq!(cached.validator, validator);
|
||||
assert_eq!(cached.state, ObservationState::Fresh);
|
||||
}
|
||||
for selected in [&root, &scoped] {
|
||||
assert!(
|
||||
client
|
||||
.ensure_interface(&session, selected.clone())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
assert_eq!(
|
||||
client
|
||||
.interface(&session, &root)
|
||||
.unwrap()
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.map(|documentation| documentation.summary.as_str()),
|
||||
Some("root math")
|
||||
);
|
||||
assert_eq!(
|
||||
client
|
||||
.interface(&session, &scoped)
|
||||
.unwrap()
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.map(|documentation| documentation.summary.as_str()),
|
||||
Some("area math")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_completion_retains_optional_scope_ref_independently_of_validator() {
|
||||
for scope_ref in [None, Some("opaque scope identity / not a path")] {
|
||||
for validator in [None, Some(b"interface-v1".to_vec())] {
|
||||
let (mut client, session) = setup();
|
||||
let selected = reference("/area", "math");
|
||||
let expected = wip_client::InterfaceObservation {
|
||||
reference: selected.clone(),
|
||||
descriptor: Some(descriptor(INTERFACE_FORMAT_V1)),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: validator.clone(),
|
||||
state: ObservationState::Fresh,
|
||||
};
|
||||
let completion = fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: expected.descriptor.clone().unwrap(),
|
||||
scope_ref: expected.scope_ref.clone(),
|
||||
validator,
|
||||
},
|
||||
);
|
||||
assert_eq!(completion, Completion::Interface(expected.clone()));
|
||||
assert_eq!(client.interface(&session, &selected), Some(&expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_membership_requires_the_complete_scope_and_name_pair() {
|
||||
let (mut client, session) = setup();
|
||||
let member = reference("/item", "math");
|
||||
let same_name = root_reference("math");
|
||||
let mut value = object();
|
||||
value.interfaces = vec![member.clone()];
|
||||
observe(&mut client, &session, "/item", value);
|
||||
for selected in [&member, &same_name] {
|
||||
fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
scope_ref: None,
|
||||
validator: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let arguments = BTreeMap::from([("value".into(), Value::Integer(2))]);
|
||||
assert_eq!(
|
||||
client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&same_name,
|
||||
"calculate",
|
||||
arguments.clone(),
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ClientErrorKind::InvalidRequest
|
||||
);
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
let call = client
|
||||
.prepare_call(&session, "/item", &member, "calculate", arguments)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_request(
|
||||
call.request.body(),
|
||||
&descriptor(INTERFACE_FORMAT_V1),
|
||||
limits(),
|
||||
)
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
member
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_copy_exact_observed_references_metadata_and_validators_for_root_ancestor_and_self_scopes()
|
||||
{
|
||||
for (path, scope) in [
|
||||
("/", "/"),
|
||||
("/item", "/"),
|
||||
("/item", "/item"),
|
||||
("/area/item", "/area"),
|
||||
("/area/item", "/area/item"),
|
||||
] {
|
||||
for scope_ref in [None, Some("opaque scope identity / not a path")] {
|
||||
for interface_validator in [None, Some(b"interface-v1".to_vec())] {
|
||||
for object_validator in [None, Some(b"object-v1".to_vec())] {
|
||||
let (mut client, session) = setup();
|
||||
let selected = reference(scope, "math");
|
||||
let expected_descriptor = descriptor(INTERFACE_FORMAT_V1);
|
||||
let mut value = object();
|
||||
value.name = path.rsplit('/').next().unwrap().into();
|
||||
value.interfaces = vec![selected.clone()];
|
||||
value.validator = object_validator.clone();
|
||||
if path == scope {
|
||||
value.r#ref = scope_ref.map(str::to_owned);
|
||||
}
|
||||
observe(&mut client, &session, path, value.clone());
|
||||
fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: expected_descriptor.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: interface_validator.clone(),
|
||||
},
|
||||
);
|
||||
let expected_interface = client.interface(&session, &selected).unwrap().clone();
|
||||
let expected_object = client.object(&session, path).unwrap();
|
||||
let arguments = BTreeMap::from([("value".into(), Value::Integer(2))]);
|
||||
let expected = CallOperationRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: object_validator,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: selected.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: interface_validator.clone(),
|
||||
},
|
||||
operation: "calculate".into(),
|
||||
arguments: arguments.clone(),
|
||||
};
|
||||
let call = client
|
||||
.prepare_call(&session, path, &selected, "calculate", arguments)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_request(
|
||||
call.request.body(),
|
||||
&expected_descriptor,
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
let context = client.pending_call_context(call.id).unwrap();
|
||||
assert_eq!(context.request(), &expected);
|
||||
assert_eq!(context.interface(), &expected_interface);
|
||||
assert_eq!(context.object(), &expected_object);
|
||||
assert_eq!(context.object().object.as_ref(), Some(&value));
|
||||
assert_eq!(context.descriptor(), &expected_descriptor);
|
||||
assert_eq!(context.operation(), &expected_descriptor.operations[0]);
|
||||
assert_eq!(context.session(), &session);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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":[{"scope":"/","name":"math"},{"scope":"/","name":"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 resource_envelope_on_413_uses_code_and_records_canonical_422_mismatch() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||
message: "logical observation limit exceeded".into(),
|
||||
};
|
||||
let mut encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||
*encoded.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||
|
||||
assert_eq!(
|
||||
client.complete(request.id, encoded).unwrap(),
|
||||
Completion::ProtocolFailure(error)
|
||||
);
|
||||
assert_eq!(
|
||||
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||
DiagnosticKind::HttpStatusMismatch
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_success_without_valid_envelope_remains_transport_failure() {
|
||||
for status in [StatusCode::BAD_GATEWAY, StatusCode::PAYLOAD_TOO_LARGE] {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = client
|
||||
.complete(request.id, response(status, b"infrastructure failure"))
|
||||
.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, root_reference("math"))
|
||||
.unwrap();
|
||||
let logical = FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
};
|
||||
let value = FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
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, root_reference("math"))
|
||||
.unwrap();
|
||||
client
|
||||
.complete(
|
||||
interface.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
validator: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let call = client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&root_reference("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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
||||
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, root_reference("math"))
|
||||
.unwrap();
|
||||
client
|
||||
.complete(
|
||||
interface.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
validator: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let call = client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&root_reference("math"),
|
||||
"calculate",
|
||||
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||
)
|
||||
.unwrap();
|
||||
client.mark_dispatched(call.id).unwrap();
|
||||
|
||||
let completion = client
|
||||
.complete(
|
||||
call.id,
|
||||
Response::builder()
|
||||
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
completion,
|
||||
Completion::Call(record)
|
||||
if matches!(
|
||||
&record.outcome,
|
||||
CallOutcome::Unknown {
|
||||
reason: OutcomeUnknownReason::ResponseDecode,
|
||||
failure: Some(failure),
|
||||
} if failure.kind == ClientErrorKind::Transport
|
||||
)
|
||||
));
|
||||
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,21 @@
|
||||
[package]
|
||||
name = "wip-fs-server"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Extensible request-time filesystem projection library and WIP over HTTP server"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
http = "1"
|
||||
rustix = { version = "1.1", features = ["fs"] }
|
||||
wip-host.workspace = true
|
||||
wip-http.workspace = true
|
||||
wip-interface.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,309 @@
|
||||
# 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, and HTTP status mapping.
|
||||
|
||||
## Library assembly and migration
|
||||
|
||||
`ServerConfig`, `WipFsServer::new`, `handle_http` and CLI flags retain their
|
||||
assembly shape. The scoped Host/Protocol API is a breaking Rust/wire migration:
|
||||
Interface references are `{scope, name}` values, registration takes a `Scope`
|
||||
and local name, and calls use `interface.reference` plus optional `scope_ref`.
|
||||
Fetch returns the same structured reference and current scope Object's optional
|
||||
ref. This is the standard WIP wire format, not an FS-specific profile.
|
||||
|
||||
Use `default_projection(root, access, limits)` to obtain the default Linux engine
|
||||
without starting a listener. `projection.view(&principal)` is the effective view;
|
||||
it owns canonical `observe` and `fetch_interface` and implements the standard
|
||||
`wip_host::ObjectProvider` typed `call_operation` API. `DefaultPolicy` has the unit
|
||||
principal `()`; default engines also offer unit-principal convenience methods.
|
||||
|
||||
For an external backend/composition:
|
||||
|
||||
1. Implement `BackendEntry` on a local, cloneable, root-confined stable capability.
|
||||
Its `WipObject` metadata is public-only; its validator binds identity and the
|
||||
protected state. Implement `FilesystemBackend` to resolve one connected
|
||||
`ResolvedEntry<Entry>` (root-to-parent ancestry plus pinned target), enumerate
|
||||
bounded children, and execute against that already-resolved lineage.
|
||||
2. Create `wip_host::Scope::new("/")` for the deployment-pinned root, then
|
||||
register generated definitions with `registry.register(&scope, name,
|
||||
Definition, validator)`. `DefaultInterfaces::register(&mut registry, &scope)`
|
||||
optionally supplies reusable built-in tokens named `file.read`,
|
||||
`symlink.inspect`, and `file.write`; tokens do not force publication. For a
|
||||
non-root scope, create a handle at its canonical WIP path and implement
|
||||
`Composition::scope(path, &entry, context)` to attest that handle only for
|
||||
its current Object lifetime. Local names are exact names, not parsed `::`/`#`
|
||||
display strings; the same local name can be registered at different scopes.
|
||||
3. Implement `Composition<Entry>` on a local type. Its local Object wraps the entry
|
||||
and implements both `WipObject` and the chosen generated traits, avoiding orphan
|
||||
rules. `PublishedObject::expose` proves each implementation at compile time.
|
||||
Publication can add, replace, reorder or omit built-ins based on entry metadata
|
||||
and actual backend capabilities, not just entry kind. `LinuxEntry` implements
|
||||
bounded `FileRead`, `FileWrite` and `SymlinkInspect` for safe delegation; never
|
||||
advertise write in read-only mode or link operations on a non-link capability.
|
||||
4. Assemble `Projection::new(backend, registry, composition, policy, limits)`.
|
||||
`ProjectionPolicy` supplies an opaque associated `Principal`, hides Objects and
|
||||
entire hidden subtrees, selects an ordered subset of implemented interfaces,
|
||||
controls descriptor/operation visibility, and permits or denies execution.
|
||||
5. An authenticated deployment chooses the principal and `ExecutionContext`. To
|
||||
use HTTP, construct `HttpAdapter::new(&view, &endpoint, limits)` and invoke
|
||||
`handle_http_with_context`. This uses the standard `wip-http` binding, not a
|
||||
filesystem wire profile. Enforce body collection, header, concurrency and
|
||||
deadline bounds in the deployment's listener; the adapter owns none of these
|
||||
intake resources. The bundled loopback listener remains a thin default user.
|
||||
|
||||
A complete external-style memory backend, local Object with multiple custom
|
||||
Operations, typed registration, principal policy and HTTP flow is exercised in
|
||||
[`tests/extensions.rs`](tests/extensions.rs). It uses no Linux filesystem for its
|
||||
backend. The public library APIs do not require private types, a fork, an HTTP
|
||||
listener, a global object registry, or dynamic plugin loading.
|
||||
|
||||
### Extension security contract
|
||||
|
||||
Backend implementations and Operation authors are trusted code, not sandboxed
|
||||
plugins. `FilesystemBackend::resolve` returns `ResolvedEntry::new(ancestors, target)`
|
||||
from one connected backend traversal/snapshot, not independent path-prefix
|
||||
resolutions. A root target has no ancestors; other targets retain the root first,
|
||||
then intermediate parent containers. This is backend-private context, never wire
|
||||
metadata. Backend `resolve` and `execute` signatures both carry this type;
|
||||
compositions receive exact retained entries, including publication of the root
|
||||
scope Object while another target is executing, never independent raw-path
|
||||
lookups. Root publication must be deterministic and side-effect-free.
|
||||
|
||||
Every lineage must retain the same deployment-pinned root Object. Replacing that
|
||||
Object requires a new projection and fresh `Scope`, not reuse of registrations
|
||||
at the same path. The engine constructs `ScopeObservation` from the published
|
||||
root Object's metadata using the refreshed retained root capability **inside**
|
||||
`FilesystemBackend::execute`, then attaches it with `PublishedObject::bind_scope`.
|
||||
It never independently looks up the raw configured root path. Root Objects need
|
||||
not expose any interfaces. Calls check both the private lifetime and optional
|
||||
`scope_ref`; normal root state updates do not retire the lifetime.
|
||||
|
||||
`Composition::scope` is the trusted non-root lifetime attestation hook. It runs
|
||||
only for registered scope paths in the refreshed, principal-visible execution
|
||||
lineage, never through independent scope-path resolution. Return `Some(scope)`
|
||||
only when the retained entry is still the current Object published at that path;
|
||||
use retained backend identity and application publication-lifecycle state under
|
||||
the backend boundary, not ref or validator equality. Deletion, replacement or
|
||||
movement needs a fresh handle and registration, even if a ref is absent or reused.
|
||||
Ordinary state changes retain the handle. A different returned path is an internal
|
||||
publication failure; `None` or a fresh unregistered lifetime hides old artifacts.
|
||||
The default hook returns `None`, so existing compositions fail closed outside `/`.
|
||||
|
||||
Self-scope needs special care: a backend may allow ordinary execution against an
|
||||
unlinked/replaced pinned leaf, but that does not establish that leaf as the current
|
||||
scope Object. The hook must attest current membership as well as retained identity
|
||||
within the same boundary. The default Linux composition does not attest non-root
|
||||
lifetimes or invent inode-based Object refs. External compositions must provide
|
||||
that guarantee themselves, including their documented external-writer limits.
|
||||
Scope metadata is obtained by publishing that retained entry (reusing the target
|
||||
publication for self-scope); scope Objects need not expose interfaces. Optional
|
||||
refs are taken from the published Object, not from a raw backend entry. Calls
|
||||
without `scope_ref` remain valid when the lifetime is current; supplied stale refs
|
||||
reject with `InterfaceMismatch` after Object validator checks.
|
||||
|
||||
`with_object` (including fetch) and individual tree Object publications also
|
||||
enter this backend boundary. Generic read callbacks use a `NotStarted` attempt
|
||||
as an adapter to the existing execution API; no typed operation runs and no
|
||||
commit is implied. Tree observations are bounded traversals, not one global tree
|
||||
transaction. Fetch resolves the visible scope Object through the provider and
|
||||
returns its ref, Descriptor and Interface validator together; retained registry
|
||||
artifacts alone never establish publication.
|
||||
|
||||
`FilesystemBackend::execute` must validate ancestor membership/identity and
|
||||
refresh **all** lineage state/validators inside its transaction or lock before
|
||||
calling the engine callback, retaining the same target and connected ancestry
|
||||
through validation and dispatch. Replaced/detached ancestors must return
|
||||
`NotFound` without callback invocation, even when the replacement is visible.
|
||||
The engine evaluates Object visibility for every refreshed ancestor and target
|
||||
inside that same boundary; a hidden ancestor rejects the entire subtree before
|
||||
publication/typed dispatch. Never fix a changed lineage by resolving the raw path
|
||||
again and substituting capabilities. Participating policy-relevant backend state
|
||||
changes must be serialized by this boundary, not just target-content writes.
|
||||
Return the committed post-operation validator. Retained ancestry is subject to
|
||||
handle/work ceilings; resource exhaustion is an error, not missing ancestry.
|
||||
Confirm rollback only after rollback succeeds. Pre-dispatch failures
|
||||
must never commit; failed started operations without a non-commit guarantee remain
|
||||
`OperationOutcomeUnknown`. Object implementations must delegate validators to
|
||||
that entry and declare requirements per `(InterfaceRef, operation)`, rather than
|
||||
classify all operations by a read/write name. Operations use the scoped entry and
|
||||
propagated context, not a fresh raw-path resolution; they must check deadlines,
|
||||
cancellation and resource budgets throughout backend work and report effects
|
||||
truthfully. POSIX symlinks, identity, atomic mutations and locking cannot be assumed
|
||||
for other backends.
|
||||
|
||||
The default Linux backend acquires advisory exclusive locks in root-to-parent
|
||||
order and then on the lockable target (directory or regular file). It compares
|
||||
retained ancestor identity to no-follow descriptor-relative lookup results,
|
||||
refreshes lineage snapshots after acquiring the locks, and holds the guards
|
||||
through post-dispatch state observation. The configured root remains its pinned
|
||||
capability even if its textual path is renamed; replaced intermediate ancestors
|
||||
are rejected. Leaf path replacement never redirects execution to a new inode.
|
||||
This serializes cooperating library calls; it does **not** promise transactional
|
||||
isolation from unrelated processes ignoring `flock`. Linux capabilities only
|
||||
expose bounded methods, not raw descriptors or backend paths.
|
||||
|
||||
A policy must be stable/deterministic within one effective Worldspace view.
|
||||
Interface/operation visibility is uniform per registered reference within that
|
||||
view, so observation, fetch and dispatch use the identical filtered descriptor.
|
||||
For entry-specific operation sets, register distinct interface definitions and
|
||||
select them by entry. Different principals may have different effective views.
|
||||
Changing a policy must establish a new view/reference lifetime (e.g. rebuild the
|
||||
registry/engine); do not keep validator-free references while changing their
|
||||
meaning. Execution permission may deny a visible Operation without hiding it.
|
||||
A published interface is always fetchable by that principal; hidden operations
|
||||
are omitted (along with their unreachable named types and interface-wide docs)
|
||||
and guessed calls return `OperationNotFound`, whereas visible denied
|
||||
operations return `PermissionDenied`. Hidden Objects and descendants return
|
||||
`NotFound` and are absent from parent observations. Work spent scanning hidden
|
||||
entries still counts against traversal bounds; resource limits are not a
|
||||
constant-time/side-channel guarantee.
|
||||
|
||||
Never put absolute paths, hidden metadata, credentials or policy internals in
|
||||
public `WipObject` metadata, descriptions, validators or normal logs. Validators
|
||||
must be opaque public tokens, not confidential content. Engine/HTTP failures use
|
||||
bounded generic diagnostics; arbitrary trusted implementation metadata/logging
|
||||
cannot be sanitized automatically. Do not log credentials or sensitive panic
|
||||
payloads from extensions.
|
||||
|
||||
## 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 a structured read interface reference and an
|
||||
object validator. Built-ins explicitly use scope `/` and the local names
|
||||
`file.read`, `symlink.inspect`, and `file.write`. The Linux root does not issue an
|
||||
Object ref, so fetch omits `scope_ref`; its private publication lifetime still
|
||||
binds fetch and call to the pinned deployment root. Copy the complete reference
|
||||
from the observation to retrieve that descriptor:
|
||||
|
||||
```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":{"scope":"/","name":"file.read"}}'
|
||||
```
|
||||
|
||||
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":{"scope":"/","name":"file.read"}},
|
||||
"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":{"scope":"/","name":"file.write"}},
|
||||
"operation":"replace",
|
||||
"arguments":{"contents":"dXBkYXRlZA=="}
|
||||
}'
|
||||
```
|
||||
|
||||
## Resource and failure behavior
|
||||
|
||||
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
||||
nesting, 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,155 @@
|
||||
//! Reusable default Linux composition; no listener or authentication dependency.
|
||||
use crate::engine::{BackendEntry, Composition, DefaultPolicy, EntryKind, Projection};
|
||||
use crate::interfaces::{
|
||||
FileRead, FileReadDefinition, FileWrite, FileWriteDefinition, SymlinkInspect,
|
||||
SymlinkInspectDefinition,
|
||||
};
|
||||
use crate::projection::{LinuxBackend, LinuxEntry};
|
||||
use crate::{AccessMode, ResourceLimits};
|
||||
use wip_host::{
|
||||
ExecutionContext, HostError, InterfaceRef, InterfaceRegistry, PublishedObject,
|
||||
RegisteredInterface, RegistrationError, Scope, Validator, WipObject,
|
||||
};
|
||||
use wip_interface as wip;
|
||||
|
||||
/// Registered built-in interfaces, usable by external compositions and Objects.
|
||||
pub struct DefaultInterfaces {
|
||||
/// Bounded regular-file reads.
|
||||
pub read: RegisteredInterface<FileReadDefinition>,
|
||||
/// No-follow link inspection.
|
||||
pub symlink: RegisteredInterface<SymlinkInspectDefinition>,
|
||||
/// Validator-protected replacement.
|
||||
pub write: RegisteredInterface<FileWriteDefinition>,
|
||||
}
|
||||
impl DefaultInterfaces {
|
||||
/// Register reusable descriptors at an explicit publication scope.
|
||||
///
|
||||
/// Built-in local names are `file.read`, `symlink.inspect`, and `file.write`.
|
||||
/// The default deployment registers them at `/`; external compositions may
|
||||
/// register them at non-root scopes attested by `Composition::scope`.
|
||||
pub fn register(
|
||||
registry: &mut InterfaceRegistry,
|
||||
scope: &Scope,
|
||||
) -> Result<Self, RegistrationError> {
|
||||
Ok(Self {
|
||||
read: registry.register(scope, "file.read", FileReadDefinition, None)?,
|
||||
symlink: registry.register(scope, "symlink.inspect", SymlinkInspectDefinition, None)?,
|
||||
write: registry.register(scope, "file.write", FileWriteDefinition, None)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Default capability-aware Linux publication, independent of HTTP.
|
||||
pub struct DefaultComposition {
|
||||
interfaces: DefaultInterfaces,
|
||||
}
|
||||
impl DefaultComposition {
|
||||
/// Use previously registered built-in interface tokens.
|
||||
pub fn new(interfaces: DefaultInterfaces) -> Self {
|
||||
Self { interfaces }
|
||||
}
|
||||
}
|
||||
|
||||
/// Request-scoped default Object; external Objects may instead wrap `LinuxEntry`.
|
||||
pub struct DefaultObject {
|
||||
entry: LinuxEntry,
|
||||
write: InterfaceRef,
|
||||
}
|
||||
impl DefaultObject {
|
||||
/// The pinned, bounded capability used by every operation on this Object.
|
||||
pub fn entry(&self) -> &LinuxEntry {
|
||||
&self.entry
|
||||
}
|
||||
}
|
||||
impl WipObject for DefaultObject {
|
||||
fn name(&self) -> &str {
|
||||
self.entry.name()
|
||||
}
|
||||
fn description(&self) -> Option<&str> {
|
||||
self.entry.description()
|
||||
}
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.entry.reference()
|
||||
}
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
self.entry.validator()
|
||||
}
|
||||
fn requires_validator(&self, interface: &InterfaceRef, operation: &str) -> bool {
|
||||
interface == &self.write && operation == "replace"
|
||||
}
|
||||
}
|
||||
impl FileRead for DefaultObject {
|
||||
fn read(&self, offset: Option<u64>, length: Option<u64>) -> wip::OperationResult<wip::Bytes> {
|
||||
self.entry.read(offset, length)
|
||||
}
|
||||
}
|
||||
impl SymlinkInspect for DefaultObject {
|
||||
fn read_link(&self) -> wip::OperationResult<wip::Bytes> {
|
||||
self.entry.read_link()
|
||||
}
|
||||
}
|
||||
impl FileWrite for DefaultObject {
|
||||
fn replace(&self, contents: wip::Bytes) -> wip::OperationResult<()> {
|
||||
self.entry.replace(contents)
|
||||
}
|
||||
}
|
||||
impl Composition<LinuxEntry> for DefaultComposition {
|
||||
type Object = DefaultObject;
|
||||
fn publish(
|
||||
&self,
|
||||
entry: LinuxEntry,
|
||||
_: &ExecutionContext,
|
||||
) -> Result<PublishedObject<Self::Object>, HostError> {
|
||||
let kind = entry.kind();
|
||||
let writable = entry.access_mode() == AccessMode::ReadWrite;
|
||||
let mut publication = PublishedObject::new(DefaultObject {
|
||||
entry,
|
||||
write: self.interfaces.write.reference().clone(),
|
||||
});
|
||||
match kind {
|
||||
EntryKind::Regular => {
|
||||
publication = publication
|
||||
.expose(&self.interfaces.read)
|
||||
.map_err(publication_error)?;
|
||||
if writable {
|
||||
publication = publication
|
||||
.expose(&self.interfaces.write)
|
||||
.map_err(publication_error)?;
|
||||
}
|
||||
}
|
||||
EntryKind::Symlink => {
|
||||
publication = publication
|
||||
.expose(&self.interfaces.symlink)
|
||||
.map_err(publication_error)?;
|
||||
}
|
||||
EntryKind::Directory | EntryKind::Unsupported => {}
|
||||
}
|
||||
Ok(publication)
|
||||
}
|
||||
}
|
||||
fn publication_error(_: wip_host::PublicationError) -> HostError {
|
||||
HostError::internal(
|
||||
"default publication failed",
|
||||
wip_host::EffectGuarantee::NotCommitted,
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct the secure-by-default Linux engine without binding a listener.
|
||||
pub fn default_projection(
|
||||
root: &std::path::Path,
|
||||
access: AccessMode,
|
||||
limits: ResourceLimits,
|
||||
) -> Result<Projection<LinuxBackend, DefaultComposition, DefaultPolicy>, std::io::Error> {
|
||||
let backend = LinuxBackend::open(root, access, limits)?;
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let scope = Scope::new("/").map_err(std::io::Error::other)?;
|
||||
let interfaces =
|
||||
DefaultInterfaces::register(&mut registry, &scope).map_err(std::io::Error::other)?;
|
||||
Ok(Projection::new(
|
||||
backend,
|
||||
registry,
|
||||
DefaultComposition::new(interfaces),
|
||||
DefaultPolicy,
|
||||
limits,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,831 @@
|
||||
//! Transport-independent projection, publication, and principal view boundaries.
|
||||
|
||||
use crate::ResourceLimits;
|
||||
use wip_host::{
|
||||
EffectGuarantee, ExecutionContext, HostError, InterfaceRef, InterfaceRegistry, ObjectProvider,
|
||||
OperationAttempt, ProviderResult, PublishedObject, Scope, ScopeObservation, WipObject,
|
||||
};
|
||||
use wip_protocol::{
|
||||
FetchInterfaceRequest, FetchInterfaceResponse, ObjectObservation, ObserveRequest,
|
||||
ObserveResponse, ProtocolError, ProtocolErrorCode,
|
||||
};
|
||||
|
||||
/// Portable entry classification; capabilities must not be inferred from kind alone.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EntryKind {
|
||||
/// Container whose children can be enumerated.
|
||||
Directory,
|
||||
/// Regular data entry.
|
||||
Regular,
|
||||
/// Link itself, never implicitly followed.
|
||||
Symlink,
|
||||
/// Metadata-only entry unless the composition supplies a capability.
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
/// A root-confined, request-time capability, not a path to resolve again.
|
||||
///
|
||||
/// Metadata must be safe for public exposure. Validators bind both identity and
|
||||
/// protected state. Cloning must retain the same target rather than re-resolve it.
|
||||
pub trait BackendEntry: WipObject + Clone {
|
||||
/// Classification for observation and publication selection.
|
||||
fn kind(&self) -> EntryKind;
|
||||
}
|
||||
|
||||
/// A single resolved target together with its retained root-to-parent lineage.
|
||||
///
|
||||
/// The backend must resolve a connected lineage, never independent raw-path
|
||||
/// prefixes. At execution it validates ancestor membership/identity, refreshes
|
||||
/// their policy metadata, and pins that snapshot through dispatch. Target
|
||||
/// replacement must not redirect the original capability. This value is private
|
||||
/// backend context, not protocol metadata.
|
||||
#[derive(Clone)]
|
||||
pub struct ResolvedEntry<E> {
|
||||
ancestors: Vec<E>,
|
||||
target: E,
|
||||
}
|
||||
|
||||
impl<E> ResolvedEntry<E> {
|
||||
/// Create backend resolution context. `/` has no ancestors; a non-root target
|
||||
/// has the pinned root first, followed by its intermediate parent containers.
|
||||
pub fn new(ancestors: Vec<E>, target: E) -> Self {
|
||||
Self { ancestors, target }
|
||||
}
|
||||
/// Pinned ancestor capabilities, ordered from the root to the direct parent.
|
||||
pub fn ancestors(&self) -> &[E] {
|
||||
&self.ancestors
|
||||
}
|
||||
/// The original resolved target capability, never a redirected replacement.
|
||||
pub fn target(&self) -> &E {
|
||||
&self.target
|
||||
}
|
||||
/// Consume this snapshot for refresh or request-time publication.
|
||||
pub fn into_parts(self) -> (Vec<E>, E) {
|
||||
(self.ancestors, self.target)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trusted backend boundary. Implementations need not use POSIX semantics.
|
||||
///
|
||||
/// Resolve and enumerate pinned capabilities within the configured root. Enforce
|
||||
/// context cancellation, deadlines and work budgets during backend work. Do not
|
||||
/// advertise capabilities the backend cannot guarantee. Errors must not include
|
||||
/// backend paths, credentials or hidden metadata.
|
||||
///
|
||||
/// The root is a deployment-pinned Object: every resolution/execution lineage
|
||||
/// must retain that same root, even if its textual backend path is renamed or
|
||||
/// replaced. Replacing the deployment root requires a new projection and Scope
|
||||
/// lifetime. The engine binds `/` to this pinned deployment root. Non-root
|
||||
/// lifetimes are attested by [`Composition::scope`] from the refreshed lineage.
|
||||
///
|
||||
/// `execute` must retain the same target and complete lineage and serialize
|
||||
/// ancestor identity/membership checks, policy metadata, validator observation,
|
||||
/// publication, validation, typed dispatch and commit/rollback. Changed/detached
|
||||
/// ancestors must return `NotFound` before the callback; never substitute a new
|
||||
/// ancestor or redirect the target by re-resolving its raw path. Refresh *all*
|
||||
/// lineage metadata/validators inside the boundary and retain that snapshot
|
||||
/// through dispatch, then return the committed post-operation validator. Never
|
||||
/// upgrade an unknown outcome except after confirmed rollback. Locks only protect
|
||||
/// actors participating in the protocol; document any external-writer limits.
|
||||
pub trait FilesystemBackend {
|
||||
/// Stable capability supplied to the composition.
|
||||
type Entry: BackendEntry;
|
||||
/// Resolve a canonical WIP path and retain its connected ancestry.
|
||||
///
|
||||
/// Obtain the target and lineage in one backend traversal/snapshot. Enforce
|
||||
/// configured handle/work budgets while retaining ancestors; do not silently
|
||||
/// omit ancestry on resource exhaustion.
|
||||
fn resolve(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
) -> ProviderResult<ResolvedEntry<Self::Entry>>;
|
||||
/// Enumerate direct children, at most `maximum`; excess must fail, not truncate.
|
||||
fn children(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
entry: &Self::Entry,
|
||||
maximum: usize,
|
||||
) -> Result<Vec<Self::Entry>, HostError>;
|
||||
/// Execute against this already-resolved target within an atomic boundary.
|
||||
fn execute(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
entry: ResolvedEntry<Self::Entry>,
|
||||
operation: impl FnOnce(ResolvedEntry<Self::Entry>) -> OperationAttempt,
|
||||
) -> ProviderResult<OperationAttempt>;
|
||||
}
|
||||
|
||||
/// Typed publication extension point, implementable on an external crate's type.
|
||||
///
|
||||
/// Use `InterfaceRegistry::register` and `PublishedObject::expose` with generated
|
||||
/// definitions. An external local Object can wrap the entry and implement any
|
||||
/// number of interfaces, avoiding orphan rules. Its `WipObject` implementation
|
||||
/// declares validator requirements per qualified operation. Operation failures
|
||||
/// declare their own `EffectGuarantee`, not a fixed read/write classification.
|
||||
pub trait Composition<E: BackendEntry> {
|
||||
/// Local typed operation implementation and safe public metadata.
|
||||
type Object: WipObject;
|
||||
/// Attest the current non-root scope lifetime of this exact backend entry.
|
||||
///
|
||||
/// Called only within `FilesystemBackend::execute`, for refreshed entries in
|
||||
/// its connected lineage. Return the same handle used for registration only
|
||||
/// while this same Object remains published at `path`. After deletion,
|
||||
/// replacement or movement return `None` or a fresh Scope, even without an
|
||||
/// Object ref (or when the replacement reuses that ref). Ordinary state
|
||||
/// changes retain the handle. In particular a self-scope target must still
|
||||
/// be the current member at `path`: a backend's ordinary pinned-leaf guarantee
|
||||
/// alone may allow execution after leaf replacement and is not sufficient
|
||||
/// evidence for a scope lifetime. Do not re-resolve `path` or infer lifetime from
|
||||
/// a validator/ref alone: use the entry's retained backend identity and the
|
||||
/// application's publication lifecycle, serialized by the backend boundary.
|
||||
///
|
||||
/// The default attests no non-root scopes. The deployment-pinned root is
|
||||
/// bound automatically; this hook is not called for `/`. Returning a Scope
|
||||
/// for a different path is an internal publication error. A scope Object
|
||||
/// need not expose any interfaces and its public ref remains optional.
|
||||
fn scope(
|
||||
&self,
|
||||
_path: &str,
|
||||
_entry: &E,
|
||||
_context: &ExecutionContext,
|
||||
) -> Result<Option<Scope>, HostError> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Build a request-scoped publication using this exact capability/context.
|
||||
///
|
||||
/// Publication and policy hooks must be side-effect-free with respect to the
|
||||
/// backend. This hook may also publish retained scope ancestors to observe
|
||||
/// their metadata while another target is executing. Scope publication must
|
||||
/// be deterministic within the view and use this same retained capability.
|
||||
/// A publication failure is a pre-dispatch rejection, never a
|
||||
/// started Operation. Delegate metadata/validators to the boundary snapshot.
|
||||
fn publish(
|
||||
&self,
|
||||
entry: E,
|
||||
context: &ExecutionContext,
|
||||
) -> Result<PublishedObject<Self::Object>, HostError>;
|
||||
}
|
||||
|
||||
/// Principal-specific view policy, independent of authentication transport.
|
||||
///
|
||||
/// Keep decisions deterministic and stable within an effective Worldspace view.
|
||||
/// A changed policy requires a new view/reference lifetime (or interface
|
||||
/// validators). Operation visibility is interface-wide within a view so every
|
||||
/// published reference has exactly the descriptor returned by fetch. Entry-
|
||||
/// specific differences should select different registered interfaces. Hooks
|
||||
/// cannot add implementations, metadata, or raw paths to a publication.
|
||||
pub trait ProjectionPolicy<E: BackendEntry, O: WipObject> {
|
||||
/// Opaque deployment-established principal/request identity.
|
||||
type Principal;
|
||||
/// Whether the entry is visible. Invisible ancestors hide their whole subtree.
|
||||
fn object_visible(&self, principal: &Self::Principal, entry: &E) -> bool;
|
||||
/// Whether an interface descriptor may be fetched in this view.
|
||||
fn interface_visible(&self, _principal: &Self::Principal, _interface: &InterfaceRef) -> bool {
|
||||
true
|
||||
}
|
||||
/// Select/order a subset of implemented interfaces; defaults to all.
|
||||
fn interfaces(
|
||||
&self,
|
||||
_principal: &Self::Principal,
|
||||
_entry: &E,
|
||||
available: &[InterfaceRef],
|
||||
) -> Vec<InterfaceRef> {
|
||||
available.to_vec()
|
||||
}
|
||||
/// Whether an operation is present in this view's descriptor and dispatch.
|
||||
fn operation_visible(
|
||||
&self,
|
||||
_principal: &Self::Principal,
|
||||
_interface: &InterfaceRef,
|
||||
_operation: &str,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
/// Execution permission for a visible operation, after canonical preconditions.
|
||||
fn authorize(
|
||||
&self,
|
||||
_principal: &Self::Principal,
|
||||
_object: &O,
|
||||
_interface: &InterfaceRef,
|
||||
_operation: &str,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// No authentication assumption: all configured objects/operations are visible.
|
||||
pub struct DefaultPolicy;
|
||||
impl<E: BackendEntry, O: WipObject> ProjectionPolicy<E, O> for DefaultPolicy {
|
||||
type Principal = ();
|
||||
fn object_visible(&self, _: &(), _: &E) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical request-time engine, independent of HTTP and Linux.
|
||||
pub struct Projection<B, C, P> {
|
||||
backend: B,
|
||||
registry: InterfaceRegistry,
|
||||
composition: C,
|
||||
policy: P,
|
||||
limits: ResourceLimits,
|
||||
}
|
||||
|
||||
impl<B, C, P> Projection<B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
/// Assemble trusted components. The registry must contain all exposed tokens.
|
||||
pub fn new(
|
||||
backend: B,
|
||||
registry: InterfaceRegistry,
|
||||
composition: C,
|
||||
policy: P,
|
||||
limits: ResourceLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
backend,
|
||||
registry,
|
||||
composition,
|
||||
policy,
|
||||
limits,
|
||||
}
|
||||
}
|
||||
/// Backend access for trusted composition/configuration, never serialized.
|
||||
pub fn backend(&self) -> &B {
|
||||
&self.backend
|
||||
}
|
||||
/// Borrow one effective principal view for observation, fetch and dispatch.
|
||||
pub fn view<'a>(&'a self, principal: &'a P::Principal) -> ProjectionView<'a, B, C, P> {
|
||||
ProjectionView {
|
||||
projection: self,
|
||||
principal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A coherent principal view implementing canonical typed host dispatch.
|
||||
pub struct ProjectionView<'a, B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
projection: &'a Projection<B, C, P>,
|
||||
principal: &'a P::Principal,
|
||||
}
|
||||
|
||||
impl<B, C, P> ProjectionView<'_, B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
fn resolve(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
) -> ProviderResult<ResolvedEntry<B::Entry>> {
|
||||
if let Err(error) = preflight(context) {
|
||||
return ProviderResult::Failure(error);
|
||||
}
|
||||
if wip_protocol::validate_path(path).is_err() {
|
||||
return ProviderResult::NotFound;
|
||||
}
|
||||
match self.projection.backend.resolve(context, path) {
|
||||
ProviderResult::Found(resolved) => {
|
||||
if !lineage_matches_path(&resolved, path) {
|
||||
return ProviderResult::Failure(internal());
|
||||
}
|
||||
if !self.lineage_visible(&resolved) {
|
||||
return ProviderResult::NotFound;
|
||||
}
|
||||
ProviderResult::Found(resolved)
|
||||
}
|
||||
ProviderResult::NotFound => ProviderResult::NotFound,
|
||||
ProviderResult::Failure(error) => ProviderResult::Failure(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn lineage_visible(&self, resolved: &ResolvedEntry<B::Entry>) -> bool {
|
||||
resolved
|
||||
.ancestors()
|
||||
.iter()
|
||||
.chain(std::iter::once(resolved.target()))
|
||||
.all(|entry| self.projection.policy.object_visible(self.principal, entry))
|
||||
}
|
||||
|
||||
fn publication(
|
||||
&self,
|
||||
resolved: &ResolvedEntry<B::Entry>,
|
||||
context: &ExecutionContext,
|
||||
) -> Result<PublishedObject<C::Object>, HostError> {
|
||||
let entry = resolved.target();
|
||||
let publication = self
|
||||
.projection
|
||||
.composition
|
||||
.publish(entry.clone(), context)?;
|
||||
let mut current_scopes = Vec::new();
|
||||
let mut path = String::from("/");
|
||||
// Only this refreshed, visible, connected lineage can attest scopes.
|
||||
// Never independently resolve a scope path while a target is executing.
|
||||
for (index, scope_entry) in resolved
|
||||
.ancestors()
|
||||
.iter()
|
||||
.chain(std::iter::once(entry))
|
||||
.enumerate()
|
||||
{
|
||||
if index > 0 {
|
||||
if path != "/" {
|
||||
path.push('/');
|
||||
}
|
||||
path.push_str(scope_entry.name());
|
||||
}
|
||||
if !self
|
||||
.projection
|
||||
.registry
|
||||
.scopes()
|
||||
.any(|scope| scope.path() == path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let scopes = if path == "/" {
|
||||
self.projection
|
||||
.registry
|
||||
.scopes()
|
||||
.filter(|scope| scope.path() == "/")
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
self.projection
|
||||
.composition
|
||||
.scope(&path, scope_entry, context)?
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
if scopes.iter().any(|scope| scope.path() != path) {
|
||||
return Err(internal());
|
||||
}
|
||||
if scopes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Refs belong to the Composition's published Object, not necessarily
|
||||
// the raw entry. Self-scope reuses exactly the target publication.
|
||||
let scope_publication = if index == resolved.ancestors().len() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
self.projection
|
||||
.composition
|
||||
.publish(scope_entry.clone(), context)?,
|
||||
)
|
||||
};
|
||||
let object = scope_publication
|
||||
.as_ref()
|
||||
.map_or(publication.implementation(), |scope| scope.implementation());
|
||||
current_scopes.extend(
|
||||
scopes
|
||||
.iter()
|
||||
.map(|scope| ScopeObservation::new(scope, object)),
|
||||
);
|
||||
}
|
||||
let available = publication
|
||||
.protocol_object()
|
||||
.interfaces
|
||||
.iter()
|
||||
.map(|reference| {
|
||||
self.projection
|
||||
.registry
|
||||
.resolve(reference)
|
||||
.ok_or_else(internal)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut selected = self
|
||||
.projection
|
||||
.policy
|
||||
.interfaces(self.principal, entry, &available);
|
||||
selected.retain(|reference| {
|
||||
let reference_value = reference.protocol_reference();
|
||||
current_scopes.iter().any(|current| {
|
||||
self.projection
|
||||
.registry
|
||||
.fetch_interface(&reference_value, current)
|
||||
.is_ok()
|
||||
}) && self
|
||||
.projection
|
||||
.policy
|
||||
.interface_visible(self.principal, reference)
|
||||
});
|
||||
let mut publication = publication
|
||||
.project(&selected, |reference, operation| {
|
||||
self.projection
|
||||
.policy
|
||||
.operation_visible(self.principal, reference, operation)
|
||||
})
|
||||
.map_err(|_| internal())?;
|
||||
for current in current_scopes {
|
||||
publication = publication.bind_scope(current);
|
||||
}
|
||||
Ok(publication)
|
||||
}
|
||||
|
||||
// Adapt read-only callbacks to the existing backend execution boundary. The
|
||||
// sentinel is NotStarted: no typed operation ran and no commit/rollback may
|
||||
// be inferred. The actual callback result never escapes until execute exits.
|
||||
fn with_publication<R>(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
resolved: ResolvedEntry<B::Entry>,
|
||||
operation: impl FnOnce(&PublishedObject<C::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
let mut observed = None;
|
||||
let boundary = self
|
||||
.projection
|
||||
.backend
|
||||
.execute(context, resolved, |resolved| {
|
||||
if !lineage_matches_path(&resolved, path) {
|
||||
observed = Some(ProviderResult::Failure(internal()));
|
||||
return OperationAttempt::reject(wip_host::CallErrorKind::Internal);
|
||||
}
|
||||
if !self.lineage_visible(&resolved) {
|
||||
observed = Some(ProviderResult::NotFound);
|
||||
return OperationAttempt::reject(wip_host::CallErrorKind::NotFound);
|
||||
}
|
||||
observed = Some(
|
||||
match preflight(context).and_then(|()| {
|
||||
self.publication(&resolved, context)
|
||||
.map(|publication| operation(&publication))
|
||||
}) {
|
||||
Ok(result) => ProviderResult::Found(result),
|
||||
Err(error) => ProviderResult::Failure(error),
|
||||
},
|
||||
);
|
||||
OperationAttempt::reject(wip_host::CallErrorKind::Internal)
|
||||
});
|
||||
match boundary {
|
||||
ProviderResult::Found(_) => {
|
||||
observed.unwrap_or_else(|| ProviderResult::Failure(internal()))
|
||||
}
|
||||
ProviderResult::NotFound => ProviderResult::NotFound,
|
||||
ProviderResult::Failure(error) => ProviderResult::Failure(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve the descriptor with precisely this principal's visible operations.
|
||||
pub fn fetch_interface(
|
||||
&self,
|
||||
request: &FetchInterfaceRequest,
|
||||
) -> Result<FetchInterfaceResponse, ProtocolError> {
|
||||
read_boundary(|| self.fetch_interface_inner(request))
|
||||
}
|
||||
|
||||
fn fetch_interface_inner(
|
||||
&self,
|
||||
request: &FetchInterfaceRequest,
|
||||
) -> Result<FetchInterfaceResponse, ProtocolError> {
|
||||
let observation =
|
||||
ObjectProvider::fetch_interface(self, &self.projection.registry, &request.interface)?;
|
||||
if !self
|
||||
.projection
|
||||
.policy
|
||||
.interface_visible(self.principal, &observation.reference)
|
||||
{
|
||||
return Err(protocol(
|
||||
ProtocolErrorCode::InterfaceNotFound,
|
||||
"interface is not published",
|
||||
));
|
||||
}
|
||||
let reference = observation.reference.clone();
|
||||
observation
|
||||
.project_operations(|operation| {
|
||||
self.projection
|
||||
.policy
|
||||
.operation_visible(self.principal, &reference, operation)
|
||||
})
|
||||
.protocol_response()
|
||||
}
|
||||
|
||||
/// Observe a complete bounded tree, omitting invisible children and subtrees.
|
||||
pub fn observe(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
request: &ObserveRequest,
|
||||
) -> Result<ObserveResponse, ProtocolError> {
|
||||
read_boundary(|| self.observe_inner(context, request))
|
||||
}
|
||||
|
||||
fn observe_inner(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
request: &ObserveRequest,
|
||||
) -> Result<ObserveResponse, ProtocolError> {
|
||||
request
|
||||
.validate()
|
||||
.map_err(|_| protocol(ProtocolErrorCode::InvalidRequest, "invalid observe request"))?;
|
||||
if request.depth > self.projection.limits.max_observation_depth {
|
||||
return Err(resource_protocol());
|
||||
}
|
||||
let entry = match self.resolve(context, &request.path) {
|
||||
ProviderResult::Found(entry) => entry,
|
||||
ProviderResult::NotFound => {
|
||||
return Err(protocol(
|
||||
ProtocolErrorCode::NotFound,
|
||||
"target path is not published",
|
||||
));
|
||||
}
|
||||
ProviderResult::Failure(error) => return Err(read_error(error)),
|
||||
};
|
||||
let mut remaining = u64::from(self.projection.limits.max_observation_nodes)
|
||||
.min(context.resource_budget().unwrap_or(u64::MAX));
|
||||
let response =
|
||||
self.observe_entry(context, &request.path, entry, request.depth, &mut remaining)?;
|
||||
request.validate_response(&response).map_err(|_| {
|
||||
protocol(
|
||||
ProtocolErrorCode::Internal,
|
||||
"invalid projection observation",
|
||||
)
|
||||
})?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn observe_entry(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
resolved: ResolvedEntry<B::Entry>,
|
||||
depth: u32,
|
||||
remaining: &mut u64,
|
||||
) -> Result<ObjectObservation, ProtocolError> {
|
||||
preflight(context).map_err(read_error)?;
|
||||
if *remaining == 0 {
|
||||
return Err(resource_protocol());
|
||||
}
|
||||
*remaining -= 1;
|
||||
let object = match self.with_publication(context, path, resolved.clone(), |publication| {
|
||||
publication.protocol_object_at(path)
|
||||
}) {
|
||||
ProviderResult::Found(object) => object.map_err(|error| error.protocol_error())?,
|
||||
ProviderResult::NotFound => {
|
||||
return Err(protocol(
|
||||
ProtocolErrorCode::NotFound,
|
||||
"target path is not published",
|
||||
));
|
||||
}
|
||||
ProviderResult::Failure(error) => return Err(read_error(error)),
|
||||
};
|
||||
let (mut ancestors, entry) = resolved.into_parts();
|
||||
if depth == 0 {
|
||||
return Ok(ObjectObservation {
|
||||
object,
|
||||
children: None,
|
||||
});
|
||||
}
|
||||
let mut children = Vec::new();
|
||||
if entry.kind() == EntryKind::Directory {
|
||||
let entries = self
|
||||
.projection
|
||||
.backend
|
||||
.children(
|
||||
context,
|
||||
&entry,
|
||||
usize::try_from(*remaining).unwrap_or(usize::MAX),
|
||||
)
|
||||
.map_err(read_error)?;
|
||||
if entries.len() as u64 > *remaining {
|
||||
return Err(resource_protocol());
|
||||
}
|
||||
ancestors.push(entry.clone());
|
||||
for child in entries {
|
||||
if self
|
||||
.projection
|
||||
.policy
|
||||
.object_visible(self.principal, &child)
|
||||
{
|
||||
let child_path = if path == "/" {
|
||||
format!("/{}", child.name())
|
||||
} else {
|
||||
format!("{path}/{}", child.name())
|
||||
};
|
||||
children.push(self.observe_entry(
|
||||
context,
|
||||
&child_path,
|
||||
ResolvedEntry::new(ancestors.clone(), child),
|
||||
depth - 1,
|
||||
remaining,
|
||||
)?);
|
||||
} else {
|
||||
if *remaining == 0 {
|
||||
return Err(resource_protocol());
|
||||
}
|
||||
*remaining -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ObjectObservation {
|
||||
object,
|
||||
children: Some(children),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, C, P> ObjectProvider for ProjectionView<'_, B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
type Object = C::Object;
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
match self.resolve(context, path) {
|
||||
ProviderResult::Found(resolved) => {
|
||||
self.with_publication(context, path, resolved, operation)
|
||||
}
|
||||
ProviderResult::NotFound => ProviderResult::NotFound,
|
||||
ProviderResult::Failure(error) => ProviderResult::Failure(error),
|
||||
}
|
||||
}
|
||||
fn execute_operation(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
|
||||
) -> ProviderResult<OperationAttempt> {
|
||||
let entry = match self.resolve(context, path) {
|
||||
ProviderResult::Found(entry) => entry,
|
||||
ProviderResult::NotFound => return ProviderResult::NotFound,
|
||||
ProviderResult::Failure(error) => return ProviderResult::Failure(error),
|
||||
};
|
||||
self.projection.backend.execute(context, entry, |resolved| {
|
||||
// Backend validates retained lineage membership/identity and refreshes
|
||||
// all metadata before this callback under the same boundary as dispatch.
|
||||
if !lineage_matches_path(&resolved, path) {
|
||||
return OperationAttempt::reject(wip_host::CallErrorKind::Internal);
|
||||
}
|
||||
if !self.lineage_visible(&resolved) {
|
||||
return OperationAttempt::reject(wip_host::CallErrorKind::NotFound);
|
||||
}
|
||||
if let Err(error) = preflight(context) {
|
||||
return OperationAttempt::reject(match error.kind() {
|
||||
wip_host::HostErrorKind::Internal => wip_host::CallErrorKind::Internal,
|
||||
wip_host::HostErrorKind::ResourceLimitExceeded => {
|
||||
wip_host::CallErrorKind::ResourceLimitExceeded
|
||||
}
|
||||
});
|
||||
}
|
||||
match self.publication(&resolved, context) {
|
||||
Ok(publication) => operation(&publication),
|
||||
Err(error) => OperationAttempt::reject(match error.kind() {
|
||||
wip_host::HostErrorKind::Internal => wip_host::CallErrorKind::Internal,
|
||||
wip_host::HostErrorKind::ResourceLimitExceeded => {
|
||||
wip_host::CallErrorKind::ResourceLimitExceeded
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
||||
}
|
||||
fn authorize(
|
||||
&self,
|
||||
_: &str,
|
||||
object: &Self::Object,
|
||||
interface: &InterfaceRef,
|
||||
operation: &str,
|
||||
) -> bool {
|
||||
self.projection
|
||||
.policy
|
||||
.authorize(self.principal, object, interface, operation)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, C, P> ObjectProvider for Projection<B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object, Principal = ()>,
|
||||
{
|
||||
type Object = C::Object;
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
self.view(&()).with_object(context, path, operation)
|
||||
}
|
||||
fn execute_operation(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
|
||||
) -> ProviderResult<OperationAttempt> {
|
||||
self.view(&()).execute_operation(context, path, operation)
|
||||
}
|
||||
fn authorize(
|
||||
&self,
|
||||
path: &str,
|
||||
object: &Self::Object,
|
||||
interface: &InterfaceRef,
|
||||
operation: &str,
|
||||
) -> bool {
|
||||
self.view(&()).authorize(path, object, interface, operation)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, C, P> Projection<B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object, Principal = ()>,
|
||||
{
|
||||
/// Observe the default unit-principal view.
|
||||
pub fn observe(
|
||||
&self,
|
||||
context: &ExecutionContext,
|
||||
request: &ObserveRequest,
|
||||
) -> Result<ObserveResponse, ProtocolError> {
|
||||
self.view(&()).observe(context, request)
|
||||
}
|
||||
/// Fetch in the default unit-principal view.
|
||||
pub fn fetch_interface(
|
||||
&self,
|
||||
request: &FetchInterfaceRequest,
|
||||
) -> Result<FetchInterfaceResponse, ProtocolError> {
|
||||
self.view(&()).fetch_interface(request)
|
||||
}
|
||||
}
|
||||
|
||||
fn lineage_matches_path<E: BackendEntry>(resolved: &ResolvedEntry<E>, path: &str) -> bool {
|
||||
let names: Vec<_> = if path == "/" {
|
||||
vec![""]
|
||||
} else {
|
||||
std::iter::once("").chain(path[1..].split('/')).collect()
|
||||
};
|
||||
if resolved.ancestors().len() + 1 != names.len()
|
||||
|| resolved.target().name() != names[names.len() - 1]
|
||||
{
|
||||
return false;
|
||||
}
|
||||
resolved
|
||||
.ancestors()
|
||||
.iter()
|
||||
.zip(names)
|
||||
.all(|(entry, name)| entry.kind() == EntryKind::Directory && entry.name() == name)
|
||||
}
|
||||
|
||||
fn read_boundary<T>(
|
||||
operation: impl FnOnce() -> Result<T, ProtocolError>,
|
||||
) -> Result<T, ProtocolError> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation))
|
||||
.unwrap_or_else(|_| Err(protocol(ProtocolErrorCode::Internal, "projection failed")))
|
||||
}
|
||||
|
||||
fn internal() -> HostError {
|
||||
HostError::internal(
|
||||
"projection publication failed",
|
||||
EffectGuarantee::NotCommitted,
|
||||
)
|
||||
}
|
||||
fn protocol(code: ProtocolErrorCode, message: &str) -> ProtocolError {
|
||||
ProtocolError {
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
fn resource_protocol() -> ProtocolError {
|
||||
protocol(
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
"projection resource limit exceeded",
|
||||
)
|
||||
}
|
||||
fn read_error(error: HostError) -> ProtocolError {
|
||||
match error.kind() {
|
||||
wip_host::HostErrorKind::ResourceLimitExceeded => resource_protocol(),
|
||||
wip_host::HostErrorKind::Internal => {
|
||||
protocol(ProtocolErrorCode::Internal, "projection failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
fn preflight(context: &ExecutionContext) -> Result<(), HostError> {
|
||||
if context.cancellation().is_cancelled()
|
||||
|| context
|
||||
.deadline()
|
||||
.is_some_and(|deadline| std::time::Instant::now() >= deadline)
|
||||
|| context.resource_budget() == Some(0)
|
||||
{
|
||||
Err(HostError::resource_limit(
|
||||
"projection work limit exceeded",
|
||||
EffectGuarantee::NotCommitted,
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Framework-neutral standard WIP over HTTP mapping for a projection view.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use http::header::ALLOW;
|
||||
use http::{Request, Response, StatusCode};
|
||||
use wip_host::{ExecutionContext, ObjectProvider};
|
||||
use wip_http::{
|
||||
CodecError, EncodeHttpError, Endpoint, RequestMetadataError, Route,
|
||||
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
|
||||
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
|
||||
encode_protocol_error_response, validate_http_request,
|
||||
};
|
||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||
|
||||
use crate::engine::ProjectionView;
|
||||
use crate::{Composition, FilesystemBackend, ProjectionPolicy, ResourceLimits};
|
||||
|
||||
/// Standard HTTP routes and codecs over a caller-scoped projection view.
|
||||
///
|
||||
/// The adapter borrows the view and endpoint without owning a listener, selecting
|
||||
/// a principal, or imposing a new execution context. Integrations must enforce
|
||||
/// the request body limit while collecting bytes, before calling this adapter.
|
||||
pub struct HttpAdapter<'a, 'view, B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
view: &'a ProjectionView<'view, B, C, P>,
|
||||
endpoint: &'a Endpoint,
|
||||
limits: ResourceLimits,
|
||||
}
|
||||
|
||||
impl<'a, 'view, B, C, P> HttpAdapter<'a, 'view, B, C, P>
|
||||
where
|
||||
B: FilesystemBackend,
|
||||
C: Composition<B::Entry>,
|
||||
P: ProjectionPolicy<B::Entry, C::Object>,
|
||||
{
|
||||
/// Creates an adapter for an already-selected principal's projection view.
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
view: &'a ProjectionView<'view, B, C, P>,
|
||||
endpoint: &'a Endpoint,
|
||||
limits: ResourceLimits,
|
||||
) -> Self {
|
||||
Self {
|
||||
view,
|
||||
endpoint,
|
||||
limits,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles one buffered request using the supplied execution controls.
|
||||
///
|
||||
/// Observation and operation dispatch receive the original context, including
|
||||
/// cancellation and resource budget. An elapsed deadline after dispatch keeps
|
||||
/// the listener's existing empty HTTP 504 transport-failure behavior.
|
||||
#[must_use]
|
||||
pub fn handle_http_with_context(
|
||||
&self,
|
||||
request: Request<Vec<u8>>,
|
||||
context: &ExecutionContext,
|
||||
) -> Response<Vec<u8>> {
|
||||
let Some(route) = self.route(request.uri()) else {
|
||||
return empty_response(StatusCode::NOT_FOUND);
|
||||
};
|
||||
if let Err(error) = validate_http_request(self.endpoint, route, &request) {
|
||||
return self.metadata_error(error);
|
||||
}
|
||||
let response = match route {
|
||||
Route::Observe => self.observe(request.body(), context),
|
||||
Route::FetchInterface => self.fetch_interface(request.body()),
|
||||
Route::CallOperation => self.call_operation(request.body(), context),
|
||||
};
|
||||
if context
|
||||
.deadline()
|
||||
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
{
|
||||
empty_response(StatusCode::GATEWAY_TIMEOUT)
|
||||
} else {
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
fn route(&self, uri: &http::Uri) -> Option<Route> {
|
||||
if uri.query().is_some() {
|
||||
return None;
|
||||
}
|
||||
[Route::Observe, Route::FetchInterface, Route::CallOperation]
|
||||
.into_iter()
|
||||
.find(|route| self.endpoint.route(*route).path() == uri.path())
|
||||
}
|
||||
|
||||
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||
let request = match decode_observe_request(body, self.limits.wire) {
|
||||
Ok(request) => request,
|
||||
Err(error) => return self.codec_error(ProtocolInteraction::Observe, error),
|
||||
};
|
||||
match self.view.observe(context, &request) {
|
||||
Ok(tree) => {
|
||||
encode_observe_response(&request, &tree, self.limits.wire).unwrap_or_else(|error| {
|
||||
self.read_encode_error(ProtocolInteraction::Observe, error)
|
||||
})
|
||||
}
|
||||
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_interface(&self, body: &[u8]) -> Response<Vec<u8>> {
|
||||
let request = match decode_fetch_interface_request(body, self.limits.wire) {
|
||||
Ok(request) => request,
|
||||
Err(error) => return self.codec_error(ProtocolInteraction::FetchInterface, error),
|
||||
};
|
||||
match self.view.fetch_interface(&request) {
|
||||
Ok(interface) => {
|
||||
encode_fetch_interface_response(&request, &interface, self.limits.wire)
|
||||
.unwrap_or_else(|error| {
|
||||
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
||||
})
|
||||
}
|
||||
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_operation(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||
let metadata = match decode_call_operation_metadata(body, self.limits.wire) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) => return self.codec_error(ProtocolInteraction::CallOperation, error),
|
||||
};
|
||||
let decoded = std::sync::Mutex::new(None);
|
||||
let execution = self.view.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.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 {
|
||||
return self.protocol_error(
|
||||
ProtocolInteraction::CallOperation,
|
||||
&operation_outcome_unknown(),
|
||||
);
|
||||
};
|
||||
encode_call_operation_response(&request, &descriptor, &result, self.limits.wire)
|
||||
.unwrap_or_else(|error| self.operation_encode_error(error))
|
||||
}
|
||||
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn operation_encode_error(&self, error: EncodeHttpError) -> Response<Vec<u8>> {
|
||||
if matches!(&error, EncodeHttpError::Codec(codec) if is_transport_limit(codec)) {
|
||||
return empty_response(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
// Any successfully executed operation may have committed effects. Its
|
||||
// name cannot establish a non-commit guarantee after response failure.
|
||||
self.protocol_error(
|
||||
ProtocolInteraction::CallOperation,
|
||||
&operation_outcome_unknown(),
|
||||
)
|
||||
}
|
||||
|
||||
fn metadata_error(&self, error: RequestMetadataError) -> Response<Vec<u8>> {
|
||||
match error {
|
||||
RequestMetadataError::NotFound => empty_response(StatusCode::NOT_FOUND),
|
||||
error @ RequestMetadataError::MethodNotAllowed => Response::builder()
|
||||
.status(error.status())
|
||||
.header(
|
||||
ALLOW,
|
||||
error
|
||||
.allow()
|
||||
.expect("method-not-allowed metadata has an Allow value"),
|
||||
)
|
||||
.body(Vec::new())
|
||||
.expect("static method response is valid"),
|
||||
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 is_transport_limit(&error) {
|
||||
empty_response(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
} else {
|
||||
self.protocol_error(
|
||||
interaction,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::InvalidRequest,
|
||||
message: "malformed WIP request".into(),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_encode_error(
|
||||
&self,
|
||||
interaction: ProtocolInteraction,
|
||||
error: EncodeHttpError,
|
||||
) -> Response<Vec<u8>> {
|
||||
match error {
|
||||
EncodeHttpError::Codec(codec) if is_transport_limit(&codec) => {
|
||||
empty_response(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
_ => self.protocol_error(
|
||||
interaction,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::Internal,
|
||||
message: "HTTP adapter failed".into(),
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_error(
|
||||
&self,
|
||||
interaction: ProtocolInteraction,
|
||||
error: &ProtocolError,
|
||||
) -> Response<Vec<u8>> {
|
||||
// Engine and policy diagnostics may contain paths, argument values, or
|
||||
// backend details. Emit only fixed, bounded diagnostics on the wire.
|
||||
let sanitized = ProtocolError {
|
||||
code: error.code,
|
||||
message: sanitized_message(error.code).into(),
|
||||
};
|
||||
encode_protocol_error_response(interaction, &sanitized, self.limits.wire)
|
||||
.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||
}
|
||||
}
|
||||
|
||||
fn operation_outcome_unknown() -> ProtocolError {
|
||||
ProtocolError {
|
||||
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
message: "operation completed but its response could not be encoded".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitized_message(code: ProtocolErrorCode) -> &'static str {
|
||||
match code {
|
||||
ProtocolErrorCode::InvalidRequest => "malformed WIP request",
|
||||
ProtocolErrorCode::NotFound => "target path is not published",
|
||||
ProtocolErrorCode::InterfaceNotFound => "interface is not published",
|
||||
ProtocolErrorCode::InterfaceMismatch => "interface is not published on the target",
|
||||
ProtocolErrorCode::OperationNotFound => "operation is not published",
|
||||
ProtocolErrorCode::InvalidArguments => "arguments do not match the operation",
|
||||
ProtocolErrorCode::ValidatorRequired => "object validator is required",
|
||||
ProtocolErrorCode::ValidatorMismatch => "object validator does not match",
|
||||
ProtocolErrorCode::InterfaceValidatorRequired => "interface validator is required",
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch => "interface validator does not match",
|
||||
ProtocolErrorCode::PermissionDenied => "operation is not permitted",
|
||||
ProtocolErrorCode::ResourceLimitExceeded => "projection resource limit exceeded",
|
||||
ProtocolErrorCode::Internal => "HTTP adapter failed",
|
||||
ProtocolErrorCode::OperationOutcomeUnknown => "operation outcome is unknown",
|
||||
}
|
||||
}
|
||||
|
||||
fn is_transport_limit(error: &CodecError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodecError::BodyTooLarge { .. } | CodecError::NestingTooDeep { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.body(Vec::new())
|
||||
.expect("static status builds an HTTP response")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
use wip_http::{
|
||||
DecodedResponse, Limits, decode_fetch_interface_response, decode_observe_response,
|
||||
encode_fetch_interface_request, encode_observe_request,
|
||||
};
|
||||
use wip_protocol::{FetchInterfaceRequest, ObserveRequest};
|
||||
|
||||
#[test]
|
||||
fn adapter_serves_observation_and_interface_fetch_without_server() {
|
||||
let root = tempdir().unwrap();
|
||||
std::fs::write(root.path().join("file"), b"contents").unwrap();
|
||||
let limits = ResourceLimits::default();
|
||||
let projection =
|
||||
crate::default_projection(root.path(), crate::AccessMode::ReadOnly, limits).unwrap();
|
||||
let view = projection.view(&());
|
||||
let endpoint = Endpoint::parse("http://localhost/custom").unwrap();
|
||||
let adapter = HttpAdapter::new(&view, &endpoint, limits);
|
||||
let context = ExecutionContext::new();
|
||||
let request = ObserveRequest {
|
||||
path: "/file".into(),
|
||||
depth: 0,
|
||||
};
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_observe_request(&endpoint, &request, limits.wire).unwrap(),
|
||||
&context,
|
||||
);
|
||||
let DecodedResponse::Success(observation) =
|
||||
decode_observe_response(&request, &response, limits.wire).unwrap()
|
||||
else {
|
||||
panic!("expected observation success")
|
||||
};
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: observation.object.interfaces[0].clone(),
|
||||
};
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_fetch_interface_request(&endpoint, &request, limits.wire).unwrap(),
|
||||
&context,
|
||||
);
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_response(&request, &response, limits.wire).unwrap(),
|
||||
DecodedResponse::Success(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_preserves_transport_boundaries_and_execution_context() {
|
||||
let root = tempdir().unwrap();
|
||||
let limits = ResourceLimits::default();
|
||||
let projection =
|
||||
crate::default_projection(root.path(), crate::AccessMode::ReadOnly, limits).unwrap();
|
||||
let view = projection.view(&());
|
||||
let endpoint = Endpoint::parse("http://localhost/wip").unwrap();
|
||||
let adapter = HttpAdapter::new(&view, &endpoint, limits);
|
||||
let context = ExecutionContext::new();
|
||||
for uri in [
|
||||
"/wip/v1/observe?query=1",
|
||||
"/wip/v1/unknown",
|
||||
"/wip/v1/observe/extra",
|
||||
] {
|
||||
let response = adapter.handle_http_with_context(
|
||||
Request::builder().uri(uri).body(Vec::new()).unwrap(),
|
||||
&context,
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert!(response.body().is_empty());
|
||||
}
|
||||
let response = adapter.handle_http_with_context(
|
||||
Request::builder()
|
||||
.uri("/wip/v1/observe")
|
||||
.body(Vec::new())
|
||||
.unwrap(),
|
||||
&context,
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
assert_eq!(response.headers()[ALLOW], "POST");
|
||||
assert!(response.body().is_empty());
|
||||
let request = ObserveRequest {
|
||||
path: "/".into(),
|
||||
depth: 0,
|
||||
};
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_observe_request(&endpoint, &request, limits.wire).unwrap(),
|
||||
&ExecutionContext::new().with_resource_budget(0),
|
||||
);
|
||||
let text = std::str::from_utf8(response.body()).unwrap();
|
||||
assert!(text.contains("resource_limit_exceeded"));
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_observe_request(&endpoint, &request, limits.wire).unwrap(),
|
||||
&ExecutionContext::new().with_deadline(Instant::now()),
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT);
|
||||
assert!(response.body().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_success_encoding_is_unknown_except_empty_transport_limit_failure() {
|
||||
let root = tempdir().unwrap();
|
||||
let limits = ResourceLimits::default();
|
||||
let projection =
|
||||
crate::default_projection(root.path(), crate::AccessMode::ReadOnly, limits).unwrap();
|
||||
let view = projection.view(&());
|
||||
let endpoint = Endpoint::parse("http://localhost/wip").unwrap();
|
||||
let adapter = HttpAdapter::new(&view, &endpoint, limits);
|
||||
let error = decode_observe_request(b"{", limits.wire).unwrap_err();
|
||||
let response = adapter.operation_encode_error(EncodeHttpError::Codec(error));
|
||||
assert!(
|
||||
std::str::from_utf8(response.body())
|
||||
.unwrap()
|
||||
.contains("operation_outcome_unknown")
|
||||
);
|
||||
let tiny_limits = Limits::new(1, 1, 1).unwrap();
|
||||
let error = decode_observe_request(b"{}", tiny_limits).unwrap_err();
|
||||
assert!(is_transport_limit(&error));
|
||||
let response = adapter.operation_encode_error(EncodeHttpError::Codec(error));
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert!(response.body().is_empty());
|
||||
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_error_diagnostics_are_sanitized_and_bounded() {
|
||||
let root = tempdir().unwrap();
|
||||
let limits = ResourceLimits::default();
|
||||
let projection =
|
||||
crate::default_projection(root.path(), crate::AccessMode::ReadOnly, limits).unwrap();
|
||||
let view = projection.view(&());
|
||||
let endpoint = Endpoint::parse("http://localhost/wip").unwrap();
|
||||
let adapter = HttpAdapter::new(&view, &endpoint, limits);
|
||||
let response = adapter.protocol_error(
|
||||
ProtocolInteraction::Observe,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::Internal,
|
||||
message: "/private/backend/secret".repeat(1000),
|
||||
},
|
||||
);
|
||||
assert!(response.body().len() < 512);
|
||||
assert!(
|
||||
!std::str::from_utf8(response.body())
|
||||
.unwrap()
|
||||
.contains("secret")
|
||||
);
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -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,235 @@
|
||||
//! 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, and status mapping;
|
||||
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
||||
//!
|
||||
//! # Extension boundary
|
||||
//!
|
||||
//! [`Projection`] composes a [`FilesystemBackend`], typed [`Composition`] and
|
||||
//! [`ProjectionPolicy`]. External local Objects can wrap a [`BackendEntry`] and
|
||||
//! implement generated interfaces without orphan-rule workarounds. The backend
|
||||
//! retains a root-confined target and atomic validator/dispatch boundary; the
|
||||
//! engine owns recursive observation and standard host typed validation. No
|
||||
//! listener is needed to use [`ProjectionView`]. [`HttpAdapter`] applies the
|
||||
//! existing standard HTTP binding to a deployment-established principal view.
|
||||
//!
|
||||
//! # Scope publication migration
|
||||
//!
|
||||
//! Registration uses `registry.register(&scope, name, Definition, validator)`.
|
||||
//! [`DefaultInterfaces::register`] takes an explicit [`wip_host::Scope`]; built-ins
|
||||
//! use root-local names `file.read`, `symlink.inspect` and `file.write`. The engine
|
||||
//! binds its deployment-pinned root lifetime automatically inside the backend
|
||||
//! execution boundary. External [`Composition::scope`] implementations attest
|
||||
//! non-root lifetimes using the refreshed connected lineage in that same boundary.
|
||||
//! Without an attestation non-root registrations fail closed. Scope refs come
|
||||
//! from the current published scope Object and remain optional.
|
||||
//! The Linux root survives textual root renames and does not issue an Object ref;
|
||||
//! fetch therefore omits `scope_ref` without weakening the private lifetime check.
|
||||
//!
|
||||
//! Backends and Operations are trusted code, responsible for truthful effects,
|
||||
//! public-only metadata and ongoing execution-context bounds. Policies must be
|
||||
//! stable within a view; changing descriptor visibility requires new reference
|
||||
//! lifetimes. See the crate README for implementer security and migration details.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use wip_fs_server::{default_projection, AccessMode, ResourceLimits};
|
||||
//! use wip_host::{ExecutionContext, ObjectProvider};
|
||||
//! use wip_protocol::ObserveRequest;
|
||||
//!
|
||||
//! let engine = default_projection(std::path::Path::new("./public"),
|
||||
//! AccessMode::ReadOnly, ResourceLimits::default())?;
|
||||
//! let view = engine.view(&());
|
||||
//! let context = ExecutionContext::new().with_resource_budget(128);
|
||||
//! let tree = view.observe(&context, &ObserveRequest { path: "/".into(), depth: 1 })?;
|
||||
//! assert_eq!(tree.object.name, "");
|
||||
//! let object = view.observe_object_with_context(&context, "/")?;
|
||||
//! assert!(object.interfaces.is_empty());
|
||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
//! ```
|
||||
//!
|
||||
//! 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 defaults;
|
||||
mod engine;
|
||||
mod http_adapter;
|
||||
mod interfaces;
|
||||
mod projection;
|
||||
mod server;
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
pub use defaults::{DefaultComposition, DefaultInterfaces, DefaultObject, default_projection};
|
||||
pub use engine::{
|
||||
BackendEntry, Composition, DefaultPolicy, EntryKind, FilesystemBackend, Projection,
|
||||
ProjectionPolicy, ProjectionView, ResolvedEntry,
|
||||
};
|
||||
pub use http_adapter::HttpAdapter;
|
||||
pub use interfaces::{
|
||||
FileRead, FileReadDefinition, FileWrite, FileWriteDefinition, SymlinkInspect,
|
||||
SymlinkInspectDefinition,
|
||||
};
|
||||
pub use projection::{LinuxBackend, LinuxEntry};
|
||||
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, and nesting 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)
|
||||
.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,427 @@
|
||||
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;
|
||||
use wip_http::Endpoint;
|
||||
|
||||
use crate::engine::Projection;
|
||||
use crate::http_adapter::HttpAdapter;
|
||||
use crate::{ConfigError, DefaultComposition, DefaultPolicy, LinuxBackend, ServerConfig};
|
||||
|
||||
/// Default Linux filesystem projection and bounded loopback HTTP listener.
|
||||
pub struct WipFsServer {
|
||||
config: ServerConfig,
|
||||
endpoint: Endpoint,
|
||||
effective_root: std::path::PathBuf,
|
||||
projection: Arc<Projection<LinuxBackend, DefaultComposition, DefaultPolicy>>,
|
||||
}
|
||||
|
||||
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 = crate::default_projection(&config.root, config.access, config.limits)?;
|
||||
let effective_root = projection.backend().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 context = ExecutionContext::new()
|
||||
.with_deadline(deadline)
|
||||
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
||||
let view = self.projection.view(&());
|
||||
HttpAdapter::new(&view, &self.endpoint, self.config.limits)
|
||||
.handle_http_with_context(request, &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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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) => Some(empty_response(StatusCode::PAYLOAD_TOO_LARGE)),
|
||||
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);
|
||||
}
|
||||
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 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 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,586 @@
|
||||
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::{
|
||||
ClientResponseError, DecodedResponse, Endpoint, JSON_CONTENT_TYPE, Limits, Route,
|
||||
TransportFailureKind, decode_call_operation_response, decode_fetch_interface_response,
|
||||
decode_observe_response, 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_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 {
|
||||
scope_ref: None,
|
||||
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 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 {
|
||||
scope_ref: None,
|
||||
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 real_listener_keeps_route_method_and_malformed_body_boundaries_distinct() {
|
||||
let temporary = tempdir().expect("temporary root");
|
||||
let mut config = ServerConfig::for_root(temporary.path());
|
||||
config.limits.wire = Limits::new(64, 4_096, 64).expect("wire limits");
|
||||
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))
|
||||
};
|
||||
|
||||
for uri in [
|
||||
"/wip/v1/unknown",
|
||||
"/wip/v1/batch",
|
||||
"/wip/v1/observe?unexpected=true",
|
||||
"/wip/v1/observe/extra",
|
||||
] {
|
||||
let response = exchange(address, json_request(http::Method::POST, uri, b"{}"));
|
||||
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||
assert!(response.body().is_empty());
|
||||
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||
assert!(!response.headers().contains_key(http::header::ALLOW));
|
||||
}
|
||||
|
||||
let wrong_method = exchange(
|
||||
address,
|
||||
json_request(http::Method::GET, "/wip/v1/observe", b""),
|
||||
);
|
||||
assert_eq!(wrong_method.status(), http::StatusCode::METHOD_NOT_ALLOWED);
|
||||
assert_eq!(wrong_method.headers()[http::header::ALLOW], "POST");
|
||||
assert!(wrong_method.body().is_empty());
|
||||
assert!(
|
||||
!wrong_method
|
||||
.headers()
|
||||
.contains_key(http::header::CONTENT_TYPE)
|
||||
);
|
||||
|
||||
let mut unsupported_coding = json_request(
|
||||
http::Method::POST,
|
||||
"/wip/v1/observe",
|
||||
br#"{"path":"/","depth":0}"#,
|
||||
);
|
||||
unsupported_coding
|
||||
.headers_mut()
|
||||
.insert(http::header::CONTENT_ENCODING, "gzip".parse().unwrap());
|
||||
let unsupported_coding = exchange(address, unsupported_coding);
|
||||
assert_eq!(
|
||||
unsupported_coding.status(),
|
||||
http::StatusCode::UNSUPPORTED_MEDIA_TYPE
|
||||
);
|
||||
assert!(unsupported_coding.body().is_empty());
|
||||
assert!(
|
||||
!unsupported_coding
|
||||
.headers()
|
||||
.contains_key(http::header::CONTENT_TYPE)
|
||||
);
|
||||
|
||||
let malformed = exchange(
|
||||
address,
|
||||
json_request(http::Method::POST, "/wip/v1/observe", b"{"),
|
||||
);
|
||||
assert_eq!(malformed.status(), http::StatusCode::BAD_REQUEST);
|
||||
assert_eq!(
|
||||
malformed.headers()[http::header::CONTENT_TYPE],
|
||||
JSON_CONTENT_TYPE
|
||||
);
|
||||
assert!(
|
||||
std::str::from_utf8(malformed.body())
|
||||
.expect("UTF-8 error envelope")
|
||||
.contains("\"invalid_request\"")
|
||||
);
|
||||
|
||||
let oversized = exchange(
|
||||
address,
|
||||
json_request(http::Method::POST, "/wip/v1/observe", &[b'x'; 65]),
|
||||
);
|
||||
assert_eq!(oversized.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||
assert!(oversized.body().is_empty());
|
||||
assert!(!oversized.headers().contains_key(http::header::CONTENT_TYPE));
|
||||
|
||||
let mut header_only = TcpStream::connect(address).expect("connect header-only client");
|
||||
header_only
|
||||
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||
.expect("set header-only timeout");
|
||||
write!(
|
||||
header_only,
|
||||
"POST /wip/v1/observe HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: 65\r\n\r\n"
|
||||
)
|
||||
.expect("write oversized request head");
|
||||
header_only.flush().expect("flush oversized request head");
|
||||
let mut raw = Vec::new();
|
||||
header_only
|
||||
.read_to_end(&mut raw)
|
||||
.expect("read immediate limit response");
|
||||
assert!(raw.starts_with(b"HTTP/1.1 413 "));
|
||||
assert!(raw.ends_with(b"\r\n\r\n"));
|
||||
assert!(
|
||||
!raw.windows(b"resource_limit_exceeded".len())
|
||||
.any(|window| { window == b"resource_limit_exceeded" })
|
||||
);
|
||||
|
||||
shutdown.store(true, Ordering::Release);
|
||||
worker
|
||||
.join()
|
||||
.expect("join listener")
|
||||
.expect("listener exits cleanly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_decoder_limits_are_transport_failures() {
|
||||
let temporary = tempdir().expect("temporary root");
|
||||
let mut config = ServerConfig::for_root(temporary.path());
|
||||
config.limits.wire = Limits::new(4_096, 4_096, 8).expect("wire limits");
|
||||
let server = WipFsServer::new(config).expect("build server");
|
||||
|
||||
let nested = br#"{"path":[[[[[[[[["/"]]]]]]]]],"depth":0}"#;
|
||||
let response = server.handle_http(json_request(http::Method::POST, "/wip/v1/observe", nested));
|
||||
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||
assert!(response.body().is_empty());
|
||||
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_observation_limit_remains_protocol_resource_failure() {
|
||||
let temporary = tempdir().expect("temporary root");
|
||||
let mut config = ServerConfig::for_root(temporary.path());
|
||||
config.limits.max_observation_depth = 0;
|
||||
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: "/".into(),
|
||||
depth: 1,
|
||||
};
|
||||
|
||||
let response = server.handle_http(
|
||||
encode_observe_request(&endpoint, &request, limits).expect("encode observation"),
|
||||
);
|
||||
assert_eq!(response.status(), http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request, &response, limits).expect("decode logical limit"),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: None,
|
||||
} if error.code == ProtocolErrorCode::ResourceLimitExceeded
|
||||
));
|
||||
}
|
||||
|
||||
#[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 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":{"scope":"/","name":"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_is_transport_local() {
|
||||
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).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 {
|
||||
scope_ref: None,
|
||||
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::INTERNAL_SERVER_ERROR);
|
||||
assert!(response.body().is_empty());
|
||||
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||
assert!(matches!(
|
||||
decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
||||
.expect_err("oversized representation is not a protocol failure"),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == http::StatusCode::INTERNAL_SERVER_ERROR
|
||||
&& failure.kind == TransportFailureKind::HttpStatus
|
||||
));
|
||||
}
|
||||
|
||||
fn success<T>(response: DecodedResponse<T>) -> T {
|
||||
match response {
|
||||
DecodedResponse::Success(value) => value,
|
||||
DecodedResponse::ProtocolFailure { error, .. } => panic!("protocol failure: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_request(method: http::Method, uri: &str, body: &[u8]) -> http::Request<Vec<u8>> {
|
||||
http::Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||
.header(http::header::ACCEPT, "application/json")
|
||||
.body(body.to_vec())
|
||||
.expect("build JSON request")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,456 @@
|
||||
//! External non-root scope regression coverage, sharing the memory backend.
|
||||
use super::*;
|
||||
|
||||
struct ScopedObject {
|
||||
inner: Object,
|
||||
reference: Option<String>,
|
||||
}
|
||||
impl WipObject for ScopedObject {
|
||||
fn name(&self) -> &str {
|
||||
self.inner.name()
|
||||
}
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.reference.as_deref()
|
||||
}
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
self.inner.validator()
|
||||
}
|
||||
fn requires_validator(&self, _: &InterfaceRef, operation: &str) -> bool {
|
||||
operation == "read"
|
||||
}
|
||||
}
|
||||
impl FileRead for ScopedObject {
|
||||
fn read(&self, offset: Option<u64>, length: Option<u64>) -> wip::OperationResult<wip::Bytes> {
|
||||
FileRead::read(&self.inner, offset, length)
|
||||
}
|
||||
}
|
||||
struct ScopedComposition {
|
||||
shared: Arc<Shared>,
|
||||
associations: BTreeMap<String, (Arc<Node>, Scope)>,
|
||||
interfaces: Vec<RegisteredInterface<wip_fs_server::FileReadDefinition>>,
|
||||
with_refs: bool,
|
||||
}
|
||||
impl Composition<Entry> for ScopedComposition {
|
||||
type Object = ScopedObject;
|
||||
fn scope(
|
||||
&self,
|
||||
path: &str,
|
||||
entry: &Entry,
|
||||
context: &ExecutionContext,
|
||||
) -> Result<Option<Scope>, HostError> {
|
||||
assert!(matches!(
|
||||
self.shared.transaction.try_lock(),
|
||||
Err(TryLockError::WouldBlock)
|
||||
));
|
||||
assert_eq!(path, entry.path);
|
||||
self.shared.record("scope", path, context);
|
||||
assert_eq!(
|
||||
entry.validator,
|
||||
Entry::snapshot(entry.path.clone(), entry.node.clone()).validator
|
||||
);
|
||||
let nodes = self.shared.nodes.lock().unwrap();
|
||||
// Self-scope also requires current membership; ordinary pinned-leaf
|
||||
// execution intentionally need not check its path mapping.
|
||||
Ok(self.associations.get(path).and_then(|(identity, scope)| {
|
||||
(Arc::ptr_eq(identity, &entry.node)
|
||||
&& nodes
|
||||
.get(path)
|
||||
.is_some_and(|node| Arc::ptr_eq(node, identity)))
|
||||
.then(|| scope.clone())
|
||||
}))
|
||||
}
|
||||
fn publish(
|
||||
&self,
|
||||
entry: Entry,
|
||||
context: &ExecutionContext,
|
||||
) -> Result<PublishedObject<ScopedObject>, HostError> {
|
||||
assert!(matches!(
|
||||
self.shared.transaction.try_lock(),
|
||||
Err(TryLockError::WouldBlock)
|
||||
));
|
||||
self.shared.record("scoped_publish", &entry.path, context);
|
||||
let path = entry.path.clone();
|
||||
let regular = entry.kind() == EntryKind::Regular;
|
||||
let reference = self
|
||||
.with_refs
|
||||
.then(|| format!("published-object-{}", entry.node.id));
|
||||
let mut publication = PublishedObject::new(ScopedObject {
|
||||
inner: Object {
|
||||
entry,
|
||||
custom: self.interfaces[0].reference().clone(),
|
||||
shared: self.shared.clone(),
|
||||
context: context.clone(),
|
||||
},
|
||||
reference,
|
||||
});
|
||||
// Containers expose no interfaces but remain valid fetch subjects.
|
||||
if regular {
|
||||
for interface in &self.interfaces {
|
||||
if interface
|
||||
.reference()
|
||||
.protocol_reference()
|
||||
.validate_for_path(&path)
|
||||
.is_ok()
|
||||
{
|
||||
publication = publication.expose(interface).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(publication)
|
||||
}
|
||||
}
|
||||
struct ScopedPolicy;
|
||||
impl ProjectionPolicy<Entry, ScopedObject> for ScopedPolicy {
|
||||
type Principal = Principal;
|
||||
fn object_visible(&self, principal: &Principal, entry: &Entry) -> bool {
|
||||
!entry.hidden && (!matches!(principal, Principal::Limited) || entry.path != "/secret")
|
||||
}
|
||||
fn interface_visible(&self, principal: &Principal, interface: &InterfaceRef) -> bool {
|
||||
!(matches!(principal, Principal::Limited)
|
||||
&& interface.protocol_reference().scope == "/added")
|
||||
}
|
||||
}
|
||||
type ScopedEngine = Projection<MemoryBackend, ScopedComposition, ScopedPolicy>;
|
||||
fn scoped_engine(shared: Arc<Shared>, with_refs: bool) -> ScopedEngine {
|
||||
configured_engine(shared, with_refs, None)
|
||||
}
|
||||
fn configured_engine(
|
||||
shared: Arc<Shared>,
|
||||
with_refs: bool,
|
||||
interface_validator: Option<Validator>,
|
||||
) -> ScopedEngine {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let mut associations = BTreeMap::new();
|
||||
let mut interfaces = Vec::new();
|
||||
for path in ["/", "/secret", "/secret/nested", "/added"] {
|
||||
let scope = Scope::new(path).unwrap();
|
||||
let validator = if path == "/secret" {
|
||||
interface_validator.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
interfaces.push(
|
||||
registry
|
||||
.register(
|
||||
&scope,
|
||||
"file.read",
|
||||
wip_fs_server::FileReadDefinition,
|
||||
validator,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
associations.insert(path.into(), (shared.node(path), scope));
|
||||
}
|
||||
Projection::new(
|
||||
MemoryBackend::new(shared.clone()),
|
||||
registry,
|
||||
ScopedComposition {
|
||||
shared,
|
||||
associations,
|
||||
interfaces,
|
||||
with_refs,
|
||||
},
|
||||
ScopedPolicy,
|
||||
ResourceLimits::default(),
|
||||
)
|
||||
}
|
||||
fn reference(scope: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: "file.read".into(),
|
||||
}
|
||||
}
|
||||
fn request(path: &str, scope: &str, scope_ref: Option<String>) -> CallOperationRequest {
|
||||
CallOperationRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: None,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: reference(scope),
|
||||
scope_ref,
|
||||
validator: None,
|
||||
},
|
||||
operation: "read".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonroot_observe_fetch_call_with_optional_refs_over_http() {
|
||||
for with_refs in [false, true] {
|
||||
let fixture = Fixture::new();
|
||||
let engine = scoped_engine(fixture.shared.clone(), with_refs);
|
||||
let view = engine.view(&Principal::Admin);
|
||||
let limits = ResourceLimits::default();
|
||||
let endpoint = Endpoint::parse("https://example.test/scopes").unwrap();
|
||||
let adapter = HttpAdapter::new(&view, &endpoint, limits);
|
||||
for (path, scope) in [("/secret/nested/data", "/secret"), ("/added", "/added")] {
|
||||
let observe = observe_request(path, 0);
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_observe_request(&endpoint, &observe, limits.wire).unwrap(),
|
||||
&ExecutionContext::new(),
|
||||
);
|
||||
let DecodedResponse::Success(observed) =
|
||||
decode_observe_response(&observe, &response, limits.wire).unwrap()
|
||||
else {
|
||||
panic!("observation must succeed");
|
||||
};
|
||||
assert!(observed.object.interfaces.contains(&reference(scope)));
|
||||
let fetch = fetch_request(&reference(scope));
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_fetch_interface_request(&endpoint, &fetch, limits.wire).unwrap(),
|
||||
&ExecutionContext::new(),
|
||||
);
|
||||
let DecodedResponse::Success(fetched) =
|
||||
decode_fetch_interface_response(&fetch, &response, limits.wire).unwrap()
|
||||
else {
|
||||
panic!("fetch must succeed");
|
||||
};
|
||||
assert_eq!(
|
||||
fetched.scope_ref,
|
||||
with_refs.then(|| format!("published-object-{}", fixture.shared.node(scope).id))
|
||||
);
|
||||
let mut call = request(path, scope, fetched.scope_ref);
|
||||
call.target.validator = observed.object.validator;
|
||||
let response = adapter.handle_http_with_context(
|
||||
encode_call_operation_request(&endpoint, &call, &fetched.descriptor, limits.wire)
|
||||
.unwrap(),
|
||||
&ExecutionContext::new(),
|
||||
);
|
||||
let DecodedResponse::Success(result) =
|
||||
decode_call_operation_response(&call, &fetched.descriptor, &response, limits.wire)
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("call must succeed");
|
||||
};
|
||||
assert_eq!(result.result, Value::Bytes(b"hello memory".to_vec()));
|
||||
if !with_refs {
|
||||
call.interface.scope_ref = Some("ref-not-provided-by-publication".into());
|
||||
assert_eq!(
|
||||
view.call_operation(call).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
view.observe_object("/secret")
|
||||
.unwrap()
|
||||
.interfaces
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
view.observe_object("/secret/nested/data")
|
||||
.unwrap()
|
||||
.interfaces,
|
||||
[
|
||||
reference("/"),
|
||||
reference("/secret"),
|
||||
reference("/secret/nested")
|
||||
]
|
||||
);
|
||||
let limited = engine.view(&Principal::Limited);
|
||||
for scope in ["/secret", "/secret/nested", "/added"] {
|
||||
assert_eq!(
|
||||
limited
|
||||
.fetch_interface(&fetch_request(&reference(scope)))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
limited
|
||||
.observe_object("/secret/nested/data")
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
wip_host::CallErrorKind::NotFound
|
||||
);
|
||||
assert!(
|
||||
!limited
|
||||
.observe_object("/added")
|
||||
.unwrap()
|
||||
.interfaces
|
||||
.contains(&reference("/added"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_refs_and_object_validator_precedence_use_current_atomic_lineage() {
|
||||
let fixture = Fixture::new();
|
||||
let engine = scoped_engine(fixture.shared.clone(), true);
|
||||
let view = engine.view(&Principal::Admin);
|
||||
let mut call = request("/secret/nested/data", "/secret", Some("stale".into()));
|
||||
call.target.validator = Some(vec![0]);
|
||||
assert_eq!(
|
||||
view.call_operation(call.clone()).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::ValidatorMismatch
|
||||
);
|
||||
call.target.validator = view.observe_object(&call.target.path).unwrap().validator;
|
||||
assert_eq!(
|
||||
view.call_operation(call.clone()).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
call.interface.scope_ref = view
|
||||
.fetch_interface(&fetch_request(&call.interface.reference))
|
||||
.unwrap()
|
||||
.scope_ref;
|
||||
// Scope state changes do not retire its lifetime; the published ref is not
|
||||
// its validator, and the hook runs on refreshed metadata under the lock.
|
||||
fixture.shared.controls.lock().unwrap().bump_ancestor = Some("/secret".into());
|
||||
fixture.shared.seen.lock().unwrap().clear();
|
||||
view.call_operation(call).unwrap();
|
||||
let seen = fixture.shared.seen.lock().unwrap();
|
||||
let resolves: Vec<_> = seen
|
||||
.iter()
|
||||
.filter(|event| event.stage == "resolve")
|
||||
.map(|event| event.path.as_str())
|
||||
.collect();
|
||||
assert_eq!(resolves, ["/secret/nested/data"]);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|event| event.stage == "scope" && event.path == "/secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonroot_interface_validator_checks_follow_scope_ref_checks() {
|
||||
let fixture = Fixture::new();
|
||||
let engine = configured_engine(fixture.shared.clone(), true, Some(Validator::new(vec![7])));
|
||||
let view = engine.view(&Principal::Admin);
|
||||
let fetched = view
|
||||
.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap();
|
||||
assert_eq!(fetched.validator, Some(vec![7]));
|
||||
let mut call = request("/secret/nested/data", "/secret", Some("stale".into()));
|
||||
call.target.validator = view.observe_object(&call.target.path).unwrap().validator;
|
||||
assert_eq!(
|
||||
view.call_operation(call.clone()).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
call.interface.scope_ref = fetched.scope_ref;
|
||||
assert_eq!(
|
||||
view.call_operation(call.clone()).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceValidatorRequired
|
||||
);
|
||||
call.interface.validator = Some(vec![8]);
|
||||
assert_eq!(
|
||||
view.call_operation(call.clone()).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceValidatorMismatch
|
||||
);
|
||||
assert!(
|
||||
fixture
|
||||
.shared
|
||||
.node(&call.target.path)
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
call.interface.validator = fetched.validator;
|
||||
view.call_operation(call).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_and_replacement_races_reject_before_dispatch() {
|
||||
for replace in [false, true] {
|
||||
let fixture = Fixture::new();
|
||||
let engine = scoped_engine(fixture.shared.clone(), false);
|
||||
let view = engine.view(&Principal::Admin);
|
||||
let mut call = request("/secret/nested/data", "/secret", None);
|
||||
call.target.validator = view.observe_object(&call.target.path).unwrap().validator;
|
||||
let leaf = fixture.shared.node(&call.target.path);
|
||||
if replace {
|
||||
fixture.shared.controls.lock().unwrap().replace_ancestor = Some("/secret".into());
|
||||
} else {
|
||||
fixture.shared.controls.lock().unwrap().hide_ancestor = Some("/secret".into());
|
||||
}
|
||||
assert_eq!(
|
||||
view.call_operation(call).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::NotFound
|
||||
);
|
||||
assert!(leaf.calls.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
view.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_replacement_and_self_scope_do_not_reuse_registry_lifetimes() {
|
||||
for with_refs in [false, true] {
|
||||
let fixture = Fixture::new();
|
||||
let engine = scoped_engine(fixture.shared.clone(), with_refs);
|
||||
let view = engine.view(&Principal::Admin);
|
||||
let old_scope = fixture.shared.node("/secret");
|
||||
let old_ref = view
|
||||
.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap()
|
||||
.scope_ref;
|
||||
fixture.shared.nodes.lock().unwrap().remove("/secret");
|
||||
assert_eq!(
|
||||
view.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
// Reuse even the same id/public ref: refs cannot attest a lifetime.
|
||||
fixture.shared.nodes.lock().unwrap().insert(
|
||||
"/secret".into(),
|
||||
Arc::new(Node {
|
||||
id: old_scope.id,
|
||||
kind: EntryKind::Directory,
|
||||
data: Mutex::new(old_scope.data.lock().unwrap().clone()),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
}),
|
||||
);
|
||||
assert_eq!(
|
||||
view.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
let mut call = request("/secret/nested/data", "/secret", old_ref);
|
||||
call.target.validator = view.observe_object(&call.target.path).unwrap().validator;
|
||||
assert_eq!(
|
||||
view.call_operation(call).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert!(
|
||||
fixture
|
||||
.shared
|
||||
.node("/secret/nested/data")
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
// Fresh registration/engine attests the new publication.
|
||||
let republished = scoped_engine(fixture.shared.clone(), with_refs);
|
||||
republished
|
||||
.view(&Principal::Admin)
|
||||
.fetch_interface(&fetch_request(&reference("/secret")))
|
||||
.unwrap();
|
||||
// Scope == target: ordinary execution pins the old leaf, but cannot
|
||||
// attest it as the current scope after its mapping is replaced.
|
||||
let leaf = fixture.shared.node("/added");
|
||||
let mut call = request("/added", "/added", None);
|
||||
call.target.validator = view.observe_object("/added").unwrap().validator;
|
||||
fixture.shared.controls.lock().unwrap().replace_mapping = true;
|
||||
assert_eq!(
|
||||
view.call_operation(call).unwrap_err().kind(),
|
||||
wip_host::CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert!(leaf.calls.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
view.fetch_interface(&fetch_request(&reference("/added")))
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
[package]
|
||||
name = "wip-host"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Host-side object publication and operation dispatch for WIP"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-host"
|
||||
|
||||
[dependencies]
|
||||
wip-interface = { path = "../wip-interface" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
wip-interface.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1"
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,19 @@
|
||||
# wip-host
|
||||
|
||||
Framework-independent Host publication and operation dispatch for the Web Interface Protocol (WIP).
|
||||
|
||||
`wip-host` registers generated interfaces, explicitly publishes them on request-scoped objects, validates object and interface preconditions, and performs interface-qualified operation dispatch against one host-owned instance. Backend transactions, persistence, and network serving remain application responsibilities.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-host = "0.1.0"
|
||||
wip-interface = "0.1.0"
|
||||
```
|
||||
|
||||
Protocol publication and dispatch use `wip_protocol::InterfaceReference { scope, name }` and compare both fields exactly. The legacy `InterfaceRef` registration token remains Host-private: `protocol_reference()` maps its opaque string verbatim to the name at root scope `/`, without parsing it. Registry lookup and fetch accept structured references; non-root references do not resolve legacy registrations. Legacy responses omit `scope_ref`.
|
||||
|
||||
Malformed interface-reference shapes fail calls as `InvalidRequest` before object resolution. A well-shaped reference outside the target path's ancestor-or-self scope fails at the membership check as `InterfaceMismatch`.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-host) for publication, provider, execution-context, and effect-guarantee boundaries.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
+1256
-254
File diff suppressed because it is too large
Load Diff
+1100
-319
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,560 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::BTreeMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wip_host::{
|
||||
CallErrorKind, CallRequest, ExecutionContext, InterfaceRegistry, InterfaceTarget,
|
||||
ObjectProvider, ProviderResult, PublishedObject, RegisteredInterface, RegistrationError, Scope,
|
||||
ScopeObservation, Target, Validator, WipObject,
|
||||
};
|
||||
use wip_interface::{OperationResult, interface};
|
||||
use wip_protocol::{InterfaceReference, ProtocolErrorCode, Value};
|
||||
|
||||
#[interface]
|
||||
pub trait Read {
|
||||
fn read(&self, value: String) -> OperationResult<String>;
|
||||
}
|
||||
|
||||
#[interface]
|
||||
pub trait Count {
|
||||
fn read(&self, value: i64) -> OperationResult<i64>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Metadata {
|
||||
name: String,
|
||||
reference: Option<String>,
|
||||
validator: Option<Validator>,
|
||||
}
|
||||
impl WipObject for Metadata {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.reference.as_deref()
|
||||
}
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
self.validator.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
type OnStart = Rc<RefCell<Option<Box<dyn Fn()>>>>;
|
||||
|
||||
struct Implementation {
|
||||
metadata: Metadata,
|
||||
calls: Rc<Cell<usize>>,
|
||||
on_start: OnStart,
|
||||
}
|
||||
impl WipObject for Implementation {
|
||||
fn name(&self) -> &str {
|
||||
self.metadata.name()
|
||||
}
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.metadata.reference()
|
||||
}
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
self.metadata.validator()
|
||||
}
|
||||
}
|
||||
impl Read for Implementation {
|
||||
fn read(&self, value: String) -> OperationResult<String> {
|
||||
self.calls.set(self.calls.get() + 1);
|
||||
if let Some(action) = self.on_start.borrow_mut().take() {
|
||||
action();
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
struct Provider {
|
||||
interface: RegisteredInterface<ReadDefinition>,
|
||||
current: Rc<RefCell<Option<(Scope, Metadata)>>>,
|
||||
target_path: String,
|
||||
target_exists: Cell<bool>,
|
||||
member: Cell<bool>,
|
||||
calls: Rc<Cell<usize>>,
|
||||
resolutions: Cell<usize>,
|
||||
on_start: OnStart,
|
||||
}
|
||||
impl Provider {
|
||||
fn new(
|
||||
scope: &Scope,
|
||||
interface: RegisteredInterface<ReadDefinition>,
|
||||
target: &str,
|
||||
reference: Option<&str>,
|
||||
) -> Self {
|
||||
Self {
|
||||
interface,
|
||||
current: Rc::new(RefCell::new(Some((
|
||||
scope.clone(),
|
||||
Metadata {
|
||||
name: scope.path().rsplit('/').next().unwrap().into(),
|
||||
reference: reference.map(str::to_owned),
|
||||
validator: Some(Validator::new(b"scope-state-v1")),
|
||||
},
|
||||
)))),
|
||||
target_path: target.into(),
|
||||
target_exists: Cell::new(true),
|
||||
member: Cell::new(true),
|
||||
calls: Rc::new(Cell::new(0)),
|
||||
resolutions: Cell::new(0),
|
||||
on_start: Rc::new(RefCell::new(None)),
|
||||
}
|
||||
}
|
||||
fn request(&self, scope_ref: Option<&str>) -> CallRequest {
|
||||
CallRequest {
|
||||
target: Target {
|
||||
path: self.target_path.clone(),
|
||||
validator: None,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: self.interface.reference().protocol_reference(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: Some(b"descriptor-v1".to_vec()),
|
||||
},
|
||||
operation: "read".into(),
|
||||
arguments: BTreeMap::from([("value".into(), Value::String("original backend".into()))]),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ObjectProvider for Provider {
|
||||
type Object = Implementation;
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
_: &ExecutionContext,
|
||||
path: &str,
|
||||
callback: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
self.resolutions.set(self.resolutions.get() + 1);
|
||||
// A single boundary captures both the target and the live scope association.
|
||||
let current = self.current.borrow().clone();
|
||||
let target = path == self.target_path;
|
||||
let metadata = if target {
|
||||
if !self.target_exists.get() {
|
||||
return ProviderResult::NotFound;
|
||||
}
|
||||
if let Some((scope, object)) = ¤t
|
||||
&& scope.path() == path
|
||||
{
|
||||
object.clone()
|
||||
} else {
|
||||
Metadata {
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
reference: None,
|
||||
validator: Some(Validator::new(b"target-v1")),
|
||||
}
|
||||
}
|
||||
} else if let Some((scope, object)) = ¤t {
|
||||
if path != scope.path() {
|
||||
return ProviderResult::NotFound;
|
||||
}
|
||||
object.clone()
|
||||
} else {
|
||||
return ProviderResult::NotFound;
|
||||
};
|
||||
let mut publication = PublishedObject::new(Implementation {
|
||||
metadata,
|
||||
calls: self.calls.clone(),
|
||||
on_start: self.on_start.clone(),
|
||||
});
|
||||
if target && self.member.get() {
|
||||
publication = publication.expose(&self.interface).unwrap();
|
||||
}
|
||||
if let Some((scope, object)) = current {
|
||||
publication = publication.bind_scope(ScopeObservation::new(&scope, &object));
|
||||
}
|
||||
ProviderResult::Found(callback(&publication))
|
||||
}
|
||||
}
|
||||
fn setup(
|
||||
scope: &str,
|
||||
target: &str,
|
||||
reference: Option<&str>,
|
||||
) -> (InterfaceRegistry, Scope, Provider) {
|
||||
let scope = Scope::new(scope).unwrap();
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let interface = registry
|
||||
.register(
|
||||
&scope,
|
||||
"read::#日本語",
|
||||
ReadDefinition,
|
||||
Some(Validator::new(b"descriptor-v1")),
|
||||
)
|
||||
.unwrap();
|
||||
let provider = Provider::new(&scope, interface, target, reference);
|
||||
(registry, scope, provider)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registrations_use_scope_name_not_definition_type_or_delimiters() {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let left = Scope::new("/left").unwrap();
|
||||
let right = Scope::new("/right").unwrap();
|
||||
let a = registry
|
||||
.register(&left, "read::#日本語", ReadDefinition, None)
|
||||
.unwrap();
|
||||
let b = registry
|
||||
.register(&right, "read::#日本語", ReadDefinition, None)
|
||||
.unwrap();
|
||||
assert_ne!(a.reference(), b.reference());
|
||||
assert_eq!(
|
||||
a.reference().protocol_reference(),
|
||||
InterfaceReference {
|
||||
scope: "/left".into(),
|
||||
name: "read::#日本語".into(),
|
||||
}
|
||||
);
|
||||
assert!(matches!(
|
||||
registry.register(&left, "read::#日本語", CountDefinition, None),
|
||||
Err(RegistrationError::AlreadyRegistered)
|
||||
));
|
||||
assert!(matches!(
|
||||
registry.register(&left, "", ReadDefinition, None),
|
||||
Err(RegistrationError::InvalidReference(_))
|
||||
));
|
||||
assert!(Scope::new("/invalid/").is_err());
|
||||
registry
|
||||
.register(&left, "another", ReadDefinition, None)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_root_ancestor_and_membership_are_independent() {
|
||||
for (scope, target) in [
|
||||
("/", "/"),
|
||||
("/", "/target"),
|
||||
("/scope", "/scope"),
|
||||
("/scope", "/scope/target"),
|
||||
] {
|
||||
let (registry, _, provider) = setup(scope, target, Some("scope-id"));
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(Some("scope-id")))
|
||||
.unwrap()
|
||||
.result,
|
||||
Value::String("original backend".into())
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.fetch_interface(®istry, &provider.request(None).interface.reference)
|
||||
.unwrap()
|
||||
.scope_ref
|
||||
.as_deref(),
|
||||
Some("scope-id")
|
||||
);
|
||||
provider.member.set(false);
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
}
|
||||
// Non-self scope Objects need not implement or expose any Interface.
|
||||
let (registry, _, provider) = setup("/scope", "/scope/target", None);
|
||||
assert!(
|
||||
provider
|
||||
.observe_object("/scope")
|
||||
.unwrap()
|
||||
.interfaces
|
||||
.is_empty()
|
||||
);
|
||||
provider
|
||||
.fetch_interface(®istry, &provider.request(None).interface.reference)
|
||||
.unwrap();
|
||||
for target in ["/sibling/target", "/scopelong", "/"] {
|
||||
let (_, _, provider) = setup("/scope", target, None);
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
assert_eq!(
|
||||
provider.observe_object(target).unwrap_err().kind(),
|
||||
CallErrorKind::Internal
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_scope_ref_and_state_validator_have_distinct_responsibilities() {
|
||||
for current in [Some("scope-id"), None, Some("")] {
|
||||
let (registry, _, provider) = setup("/scope", "/scope/target", current);
|
||||
let observation = provider
|
||||
.fetch_interface(®istry, &provider.request(None).interface.reference)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
observation
|
||||
.protocol_response()
|
||||
.unwrap()
|
||||
.scope_ref
|
||||
.as_deref(),
|
||||
current
|
||||
);
|
||||
assert_eq!(
|
||||
observation.validator,
|
||||
Some(Validator::new(b"descriptor-v1"))
|
||||
);
|
||||
provider.call_operation(provider.request(None)).unwrap();
|
||||
if let Some(reference) = current {
|
||||
provider
|
||||
.call_operation(provider.request(Some(reference)))
|
||||
.unwrap();
|
||||
}
|
||||
let before = provider.calls.get();
|
||||
for supplied in ["other", "missing"] {
|
||||
let mut call = provider.request(Some(supplied));
|
||||
call.interface.validator = None;
|
||||
call.operation = "missing".into();
|
||||
assert_eq!(
|
||||
provider.call_operation(call).unwrap_err().kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
}
|
||||
assert_eq!(provider.calls.get(), before);
|
||||
provider.current.borrow_mut().as_mut().unwrap().1.validator =
|
||||
Some(Validator::new(b"scope-state-v2"));
|
||||
provider.call_operation(provider.request(current)).unwrap();
|
||||
assert_eq!(
|
||||
provider
|
||||
.fetch_interface(®istry, &provider.request(None).interface.reference)
|
||||
.unwrap(),
|
||||
observation
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_precondition_is_membership_stage_in_both_dispatch_paths() {
|
||||
let (_, _, provider) = setup("/scope", "/scope/target", Some("current"));
|
||||
let mut call = provider.request(Some("stale"));
|
||||
call.target.validator = Some(b"wrong".to_vec());
|
||||
assert_eq!(
|
||||
provider.call_operation(call.clone()).unwrap_err().kind(),
|
||||
CallErrorKind::ValidatorMismatch
|
||||
);
|
||||
provider.target_exists.set(false);
|
||||
assert_eq!(
|
||||
provider.call_operation(call).unwrap_err().kind(),
|
||||
CallErrorKind::NotFound
|
||||
);
|
||||
provider.target_exists.set(true);
|
||||
let call = provider.request(Some("stale"));
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation_with_context_and_decoder(
|
||||
&ExecutionContext::new(),
|
||||
call.target,
|
||||
call.interface,
|
||||
call.operation,
|
||||
|_| -> Result<BTreeMap<String, Value>, ()> { panic!("decoder must not run") }
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_republication_and_movement_never_inherit_retained_artifacts() {
|
||||
let (mut registry, scope, provider) = setup("/scope", "/scope/target", Some("old"));
|
||||
let reference = provider.request(None).interface.reference;
|
||||
provider.fetch_interface(®istry, &reference).unwrap();
|
||||
*provider.current.borrow_mut() = None;
|
||||
provider.target_exists.set(false);
|
||||
assert_eq!(
|
||||
provider
|
||||
.fetch_interface(®istry, &reference)
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::NotFound
|
||||
);
|
||||
provider.target_exists.set(true);
|
||||
// Even the same ref is not proof that a replacement inherits registration.
|
||||
let replacement = Scope::new("/scope").unwrap();
|
||||
*provider.current.borrow_mut() = Some((
|
||||
replacement.clone(),
|
||||
Metadata {
|
||||
name: "scope".into(),
|
||||
reference: Some("old".into()),
|
||||
validator: None,
|
||||
},
|
||||
));
|
||||
assert_eq!(
|
||||
provider
|
||||
.fetch_interface(®istry, &reference)
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(Some("old")))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
registry.remove_scope(&scope);
|
||||
assert!(matches!(
|
||||
registry.register(&scope, "new", ReadDefinition, None),
|
||||
Err(RegistrationError::RetiredScope)
|
||||
));
|
||||
let fresh = registry
|
||||
.register(&replacement, reference.name.clone(), ReadDefinition, None)
|
||||
.unwrap();
|
||||
provider.fetch_interface(®istry, &reference).unwrap();
|
||||
// Old target membership still binds the old lifetime, even after new publication.
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
let new_provider = Provider::new(&replacement, fresh, "/scope/target", Some("new"));
|
||||
let mut new_call = new_provider.request(Some("new"));
|
||||
new_call.interface.validator = None;
|
||||
new_provider.call_operation(new_call).unwrap();
|
||||
let moved = Scope::new("/moved").unwrap();
|
||||
new_provider.target_exists.set(false);
|
||||
*new_provider.current.borrow_mut() = Some((
|
||||
moved.clone(),
|
||||
Metadata {
|
||||
name: "moved".into(),
|
||||
reference: Some("new".into()),
|
||||
validator: None,
|
||||
},
|
||||
));
|
||||
assert_eq!(
|
||||
new_provider
|
||||
.fetch_interface(®istry, &reference)
|
||||
.unwrap_err()
|
||||
.code,
|
||||
ProtocolErrorCode::InterfaceNotFound
|
||||
);
|
||||
assert_eq!(
|
||||
new_provider
|
||||
.call_operation(new_provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::NotFound
|
||||
);
|
||||
let moved_interface = registry
|
||||
.register(&moved, reference.name, ReadDefinition, None)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
moved_interface.reference().protocol_reference().scope,
|
||||
"/moved"
|
||||
);
|
||||
assert_eq!(provider.calls.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_after_fetch_rejects_old_ref_but_omission_and_refless_are_allowed() {
|
||||
for previous_ref in [Some("old"), None] {
|
||||
let (mut registry, old_scope, old_provider) =
|
||||
setup("/scope", "/scope/target", previous_ref);
|
||||
let observed = old_provider
|
||||
.fetch_interface(®istry, &old_provider.request(None).interface.reference)
|
||||
.unwrap();
|
||||
registry.remove_scope(&old_scope);
|
||||
let new_scope = Scope::new("/scope").unwrap();
|
||||
let token = registry
|
||||
.register(
|
||||
&new_scope,
|
||||
"read::#日本語",
|
||||
ReadDefinition,
|
||||
Some(Validator::new(b"descriptor-v1")),
|
||||
)
|
||||
.unwrap();
|
||||
let new_provider = Provider::new(&new_scope, token, "/scope/target", None);
|
||||
if let Some(reference) = observed.scope_ref {
|
||||
assert_eq!(
|
||||
new_provider
|
||||
.call_operation(new_provider.request(Some(&reference)))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(new_provider.calls.get(), 0);
|
||||
}
|
||||
new_provider
|
||||
.call_operation(new_provider.request(None))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn started_execution_retains_target_and_same_descriptor_through_replacement() {
|
||||
let (registry, old_scope, provider) = setup("/scope", "/scope/target", Some("old"));
|
||||
let registry = Rc::new(RefCell::new(registry));
|
||||
let current = provider.current.clone();
|
||||
let replacement = Scope::new("/scope").unwrap();
|
||||
let registry_for_action = registry.clone();
|
||||
let replacement_for_action = replacement.clone();
|
||||
*provider.on_start.borrow_mut() = Some(Box::new(move || {
|
||||
let mut registry = registry_for_action.borrow_mut();
|
||||
registry.remove_scope(&old_scope);
|
||||
registry
|
||||
.register(
|
||||
&replacement_for_action,
|
||||
"read::#日本語",
|
||||
CountDefinition,
|
||||
Some(Validator::new(b"descriptor-v2")),
|
||||
)
|
||||
.unwrap();
|
||||
*current.borrow_mut() = Some((
|
||||
replacement_for_action.clone(),
|
||||
Metadata {
|
||||
name: "scope".into(),
|
||||
reference: Some("new".into()),
|
||||
validator: None,
|
||||
},
|
||||
));
|
||||
}));
|
||||
let call = provider.request(Some("old"));
|
||||
let result = provider
|
||||
.call_operation_with_context_and_decoder(
|
||||
&ExecutionContext::new(),
|
||||
call.target,
|
||||
call.interface,
|
||||
call.operation,
|
||||
|descriptor| {
|
||||
assert_eq!(descriptor, &ReadDefinition::descriptor());
|
||||
Ok::<_, ()>(call.arguments)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.result, Value::String("original backend".into()));
|
||||
assert_eq!(provider.calls.get(), 1);
|
||||
assert_eq!(provider.resolutions.get(), 1);
|
||||
let new = provider
|
||||
.fetch_interface(
|
||||
®istry.borrow(),
|
||||
&provider.request(None).interface.reference,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(new.descriptor, CountDefinition::descriptor());
|
||||
assert_eq!(new.scope_ref.as_deref(), Some("new"));
|
||||
// The old bound target can no longer start a call against the new descriptor.
|
||||
assert_eq!(
|
||||
provider
|
||||
.call_operation(provider.request(None))
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
CallErrorKind::InterfaceMismatch
|
||||
);
|
||||
assert_eq!(provider.calls.get(), 1);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use wip_host::{InterfaceRegistry, PublishedObject, WipObject};
|
||||
use wip_interface::{OperationResult, interface};
|
||||
use wip_protocol::ObjectId;
|
||||
|
||||
#[interface]
|
||||
pub trait Search {
|
||||
@@ -10,13 +9,13 @@ pub trait Search {
|
||||
struct Object;
|
||||
|
||||
impl WipObject for Object {
|
||||
fn id(&self) -> ObjectId {
|
||||
ObjectId("object".into())
|
||||
fn name(&self) -> &str {
|
||||
"object"
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let search = registry.register(SearchDefinition, None).unwrap();
|
||||
let search = registry.register(&wip_host::Scope::new("/").unwrap(), "search", SearchDefinition, None).unwrap();
|
||||
let _published = PublishedObject::new(Object).expose(&search).unwrap();
|
||||
}
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
error[E0277]: the trait bound `Object: Search` is not satisfied
|
||||
--> tests/ui/unimplemented_interface.rs:21:58
|
||||
--> tests/ui/unimplemented_interface.rs:20:58
|
||||
|
|
||||
21 | let _published = PublishedObject::new(Object).expose(&search).unwrap();
|
||||
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:10:1
|
||||
--> tests/ui/unimplemented_interface.rs:9:1
|
||||
|
|
||||
10 | struct Object;
|
||||
9 | struct Object;
|
||||
| ^^^^^^^^^^^^^
|
||||
help: this trait has no implementations, consider adding one
|
||||
--> tests/ui/unimplemented_interface.rs:6:1
|
||||
|
|
||||
6 | pub trait Search {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
note: required for `SearchDefinition` to implement `InterfaceImplementation<Object>`
|
||||
--> tests/ui/unimplemented_interface.rs:5:1
|
||||
|
|
||||
5 | #[interface]
|
||||
5 | pub trait Search {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
note: required for `SearchDefinition` to implement `InterfaceImplementation<Object>`
|
||||
--> tests/ui/unimplemented_interface.rs:4:1
|
||||
|
|
||||
4 | #[interface]
|
||||
| ^^^^^^^^^^^^
|
||||
6 | pub trait Search {
|
||||
5 | pub trait Search {
|
||||
| ^^^^^^
|
||||
note: required by a bound in `PublishedObject::<T>::expose`
|
||||
--> src/lib.rs
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "wip-http"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Framework-independent standard WIP over HTTP v1 binding"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-http"
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
http = "1"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
url = "2"
|
||||
wip-protocol.workspace = true
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,52 @@
|
||||
# wip-http
|
||||
|
||||
Framework-independent WIP over HTTP v1 endpoint, route, JSON codec, and response-classification support.
|
||||
|
||||
The crate maps the three WIP Core interactions to fixed HTTP routes and strict UTF-8 JSON representations. It constructs and validates `http` request and response values but deliberately performs no network I/O and does not define TLS, authentication, proxy, or connection policy.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-http = "0.1.0"
|
||||
```
|
||||
|
||||
```rust
|
||||
use wip_http::wip_protocol::ObserveRequest;
|
||||
use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let endpoint = Endpoint::parse("https://example.test/wip")?;
|
||||
let limits = Limits::new(64 * 1024, 1024 * 1024, 64)?;
|
||||
let request = encode_observe_request(
|
||||
&endpoint,
|
||||
&ObserveRequest { path: "/".into(), depth: 0 },
|
||||
limits,
|
||||
)?;
|
||||
assert_eq!(request.uri(), "https://example.test/wip/v1/observe");
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Interface references and scope identity
|
||||
|
||||
Every interface reference is encoded as an exact JSON object with required
|
||||
`scope` and `name` strings, for example `{"scope":"/github","name":"issue.read"}`.
|
||||
This applies to `Object.interfaces` elements, fetch request/response `interface`,
|
||||
and call `interface.reference`. Scope must be a canonical absolute Worldspace
|
||||
path and name must be nonempty. Legacy opaque strings, short-form strings,
|
||||
relative scopes, missing fields, and extra members are rejected. Unicode, `::`,
|
||||
and `#` in names remain literal data; comparison uses decoded field values,
|
||||
independent of JSON member order and escapes. HTTP endpoint prefixes do not
|
||||
change Worldspace scope.
|
||||
|
||||
Fetch responses and call interface targets additionally carry optional
|
||||
`scope_ref`, an opaque string copied from the scope Object's `ref` observation.
|
||||
It is not base64 and is not part of interface identity. Absent values are omitted;
|
||||
null and nonstring values are rejected. Descriptor-independent call metadata
|
||||
validates reference shape, but leaves scope ancestry and identity preconditions
|
||||
to the Host's `InterfaceMismatch` check, preserving protocol error precedence.
|
||||
Invalid success responses remain client-local `InvalidResponse` errors; protocol
|
||||
error envelopes and transport failures retain their existing classification.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-http) for codec and failure-boundary details.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
@@ -0,0 +1,598 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use http::header::{ACCEPT, CONTENT_ENCODING, 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, 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> {
|
||||
if !has_supported_content_coding(response.headers()) {
|
||||
return Err(response::unsupported_content_coding(response.status()));
|
||||
}
|
||||
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 request URI does not exactly identify the selected standard route.
|
||||
NotFound,
|
||||
/// A known standard route was requested with a method other than `POST`.
|
||||
MethodNotAllowed,
|
||||
/// The request body does not use UTF-8 `application/json` or identity coding.
|
||||
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::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
|
||||
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the value for an `Allow` response header, when required.
|
||||
#[must_use]
|
||||
pub const fn allow(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::MethodNotAllowed => Some("POST"),
|
||||
Self::NotFound | Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RequestMetadataError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotFound => formatter.write_str("request URI is not a standard WIP route"),
|
||||
Self::MethodNotAllowed => formatter.write_str("standard WIP routes require POST"),
|
||||
Self::UnsupportedMediaType => {
|
||||
formatter.write_str("expected identity-coded UTF-8 application/json Content-Type")
|
||||
}
|
||||
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RequestMetadataError {}
|
||||
|
||||
pub(crate) fn has_supported_content_coding(headers: &HeaderMap) -> bool {
|
||||
headers.get_all(CONTENT_ENCODING).iter().all(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
let mut codings = value.split(',').map(str::trim);
|
||||
let first = codings.next();
|
||||
first.is_some_and(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||
&& codings.all(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let expected = endpoint.route(route);
|
||||
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||
return Err(RequestMetadataError::NotFound);
|
||||
}
|
||||
if value.method() != Method::POST {
|
||||
return Err(RequestMetadataError::MethodNotAllowed);
|
||||
}
|
||||
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 || !has_supported_content_coding(value.headers()) {
|
||||
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.
|
||||
///
|
||||
/// Validates reference shape without requiring a target Object path.
|
||||
pub fn encode_fetch_interface_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &FetchInterfaceRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
value.interface.validate().map_err(CodecError::from)?;
|
||||
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.
|
||||
///
|
||||
/// Reference shape is validated, but scope ancestry and `scope_ref` identity
|
||||
/// are left to Host resolution so `NotFound`, validator failures, and
|
||||
/// `InterfaceMismatch` retain their protocol precedence.
|
||||
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. Logical `resource_limit_exceeded` failures use HTTP 422;
|
||||
/// representation and deployment limits are not protocol errors.
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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,139 @@
|
||||
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,
|
||||
}
|
||||
|
||||
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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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; 3] = [Route::Observe, Route::FetchInterface, Route::CallOperation];
|
||||
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,180 @@
|
||||
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,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// Creates a nonzero limit set.
|
||||
pub fn new(
|
||||
max_request_bytes: usize,
|
||||
max_response_bytes: usize,
|
||||
max_nesting: 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);
|
||||
}
|
||||
Ok(Self {
|
||||
max_request_bytes,
|
||||
max_response_bytes,
|
||||
max_nesting,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,67 @@
|
||||
//! 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. 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`.
|
||||
//!
|
||||
//! Interface references use exact JSON objects with required `scope` and `name`
|
||||
//! strings in every position. Legacy strings and display shorthand are rejected.
|
||||
//! Scope is a canonical absolute Worldspace path, not an HTTP endpoint prefix.
|
||||
//! Optional `scope_ref` metadata on fetch responses and call interface targets is
|
||||
//! an opaque string, never base64; absent fields are omitted and null is rejected.
|
||||
//! Call metadata validates reference shape without resolving scope ancestry or
|
||||
//! identity, which remain Host checks with `InterfaceMismatch` precedence.
|
||||
//!
|
||||
//! ```
|
||||
//! 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)?;
|
||||
//! 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 codec;
|
||||
mod endpoint;
|
||||
mod error;
|
||||
mod json;
|
||||
mod 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, is_json_content_type, validate_http_request,
|
||||
};
|
||||
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits};
|
||||
pub use response::{
|
||||
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||
};
|
||||
|
||||
/// 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,347 @@
|
||||
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, 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,
|
||||
/// The response uses a content coding the client does not support.
|
||||
UnsupportedContentCoding,
|
||||
/// 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 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.
|
||||
#[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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||
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,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_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);
|
||||
}
|
||||
protocol_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 unsupported_content_coding(status: StatusCode) -> ClientResponseError {
|
||||
ClientResponseError::TransportBinding(TransportBindingFailure {
|
||||
status,
|
||||
kind: TransportFailureKind::UnsupportedContentCoding,
|
||||
})
|
||||
}
|
||||
|
||||
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,528 @@
|
||||
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,
|
||||
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
|
||||
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||
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).unwrap()
|
||||
}
|
||||
|
||||
fn endpoint() -> Endpoint {
|
||||
Endpoint::parse("https://example.test/wip").unwrap()
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(name: &str, validator: &[u8]) -> Object {
|
||||
Object {
|
||||
name: name.into(),
|
||||
description: Some("description".into()),
|
||||
interfaces: vec![reference("/", "interface-v1")],
|
||||
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: reference("/", "interface-v1"),
|
||||
scope_ref: None,
|
||||
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: reference("/", "interface-v1"),
|
||||
},
|
||||
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: reference("/", "interface-v1"),
|
||||
};
|
||||
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(),
|
||||
scope_ref: None,
|
||||
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": {"scope": "/", "name": "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_remain_local_codec_failures() {
|
||||
let tiny = Limits::new(8, 8, 2).unwrap();
|
||||
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
||||
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||
|
||||
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
||||
let nesting_limited = Limits::new(1024, 1024, 2).unwrap();
|
||||
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
||||
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||
|
||||
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1).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: reference("/", "interface-v1"),
|
||||
};
|
||||
let mut interface = FetchInterfaceResponse {
|
||||
interface: request.interface.clone(),
|
||||
scope_ref: None,
|
||||
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":{"scope":"/","name":"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":{"scope":"/","name":"wrong"},"descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
||||
br#"{"interface":{"scope":"/","name":"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,740 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value as Json, json};
|
||||
use wip_http::http::{Response, StatusCode};
|
||||
use wip_http::wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1,
|
||||
InterfaceDescriptor, InterfaceReference, InterfaceTarget, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
ReturnDeclaration, Target, TypeExpr,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||
TransportFailureKind, decode_call_operation_metadata, decode_call_operation_request,
|
||||
decode_call_operation_response, decode_fetch_interface_request,
|
||||
decode_fetch_interface_response, decode_observe_response, encode_call_operation_request,
|
||||
encode_fetch_interface_request, encode_fetch_interface_response, encode_observe_response,
|
||||
encode_protocol_error_response,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||
}
|
||||
|
||||
fn endpoint() -> Endpoint {
|
||||
Endpoint::parse("https://example.test/deployment/prefix").unwrap()
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "run#::操作".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn call(reference: InterfaceReference, scope_ref: Option<String>) -> CallOperationRequest {
|
||||
CallOperationRequest {
|
||||
target: Target {
|
||||
path: "/世界::#/item".into(),
|
||||
validator: Some(vec![0, 255]),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference,
|
||||
scope_ref,
|
||||
validator: Some(vec![1, 255]),
|
||||
},
|
||||
operation: "run#::操作".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn observation(references: Vec<InterfaceReference>) -> ObjectObservation {
|
||||
ObjectObservation {
|
||||
object: Object {
|
||||
name: "item".into(),
|
||||
description: None,
|
||||
interfaces: references,
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
},
|
||||
children: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn observe_request() -> ObserveRequest {
|
||||
ObserveRequest {
|
||||
path: "/世界::#/item".into(),
|
||||
depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn response(status: StatusCode, value: Json) -> Response<Vec<u8>> {
|
||||
raw_response(status, &serde_json::to_vec(&value).unwrap())
|
||||
}
|
||||
|
||||
fn raw_response(status: StatusCode, body: &[u8]) -> Response<Vec<u8>> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header("content-type", "application/json")
|
||||
.body(body.to_vec())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn fetch_json(interface: Json) -> Json {
|
||||
json!({
|
||||
"interface": interface,
|
||||
"descriptor": {"format": INTERFACE_FORMAT_V1, "types": [], "operations": []}
|
||||
})
|
||||
}
|
||||
|
||||
fn call_json(reference: Json) -> Json {
|
||||
json!({
|
||||
"target": {"path": "/世界::#/item"},
|
||||
"interface": {"reference": reference},
|
||||
"operation": "run#::操作",
|
||||
"arguments": {}
|
||||
})
|
||||
}
|
||||
|
||||
fn invalid_success<T: std::fmt::Debug>(result: Result<T, ClientResponseError>) {
|
||||
assert!(matches!(
|
||||
result.unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_structured_reference_is_encoded_and_round_tripped_in_every_position() {
|
||||
let interface_ref = reference("/世界::#", "é::接口#read/with\"quote\\slash");
|
||||
let expected = json!({"scope": interface_ref.scope, "name": interface_ref.name});
|
||||
let fetch_request = FetchInterfaceRequest {
|
||||
interface: interface_ref.clone(),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &fetch_request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
encoded.uri().path(),
|
||||
"/deployment/prefix/v1/fetch_interface"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Json>(encoded.body()).unwrap(),
|
||||
json!({"interface": expected})
|
||||
);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
fetch_request
|
||||
);
|
||||
|
||||
let fetch_response = FetchInterfaceResponse {
|
||||
interface: interface_ref.clone(),
|
||||
scope_ref: Some("opaque:世界::# not base64!".into()),
|
||||
descriptor: descriptor(),
|
||||
validator: Some(vec![1, 255]),
|
||||
};
|
||||
let encoded =
|
||||
encode_fetch_interface_response(&fetch_request, &fetch_response, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(body["interface"], expected);
|
||||
assert_eq!(body["scope_ref"], "opaque:世界::# not base64!");
|
||||
assert_eq!(body["validator"], "Af8=");
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&fetch_request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(fetch_response)
|
||||
);
|
||||
|
||||
let observation = observation(vec![interface_ref.clone(), reference("/", "root")]);
|
||||
let encoded = encode_observe_response(&observe_request(), &observation, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body["object"]["interfaces"],
|
||||
json!([expected, {"scope": "/", "name": "root"}])
|
||||
);
|
||||
assert_eq!(
|
||||
decode_observe_response(&observe_request(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(observation)
|
||||
);
|
||||
|
||||
let request = call(interface_ref, Some("opaque:世界::# not base64!".into()));
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(body["interface"]["reference"], expected);
|
||||
assert_eq!(body["interface"]["scope_ref"], "opaque:世界::# not base64!");
|
||||
assert_eq!(body["interface"]["validator"], "Af8=");
|
||||
assert_eq!(body["target"]["validator"], "AP8=");
|
||||
assert_eq!(body["operation"], "run#::操作");
|
||||
assert_eq!(
|
||||
decode_call_operation_request(encoded.body(), &descriptor(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(encoded.body(), limits())
|
||||
.unwrap()
|
||||
.interface,
|
||||
request.interface
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_reference_corpus_is_rejected_in_all_positions() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "interface-v1"),
|
||||
};
|
||||
for bad in [
|
||||
json!("interface-v1"),
|
||||
json!("/::interface-v1"),
|
||||
json!("interface-v1#run"),
|
||||
Json::Null,
|
||||
json!(false),
|
||||
json!(1),
|
||||
json!([]),
|
||||
json!({}),
|
||||
json!({"name": "interface-v1"}),
|
||||
json!({"scope": "/"}),
|
||||
json!({"scope": null, "name": "interface-v1"}),
|
||||
json!({"scope": 1, "name": "interface-v1"}),
|
||||
json!({"scope": "/", "name": null}),
|
||||
json!({"scope": "/", "name": []}),
|
||||
json!({"scope": "/", "name": ""}),
|
||||
json!({"scope": "/", "name": "interface-v1", "extra": true}),
|
||||
json!({"scope": "/", "name": "interface-v1", "scope_ref": "identity"}),
|
||||
json!({"Scope": "/", "name": "interface-v1"}),
|
||||
json!({"scope": "", "name": "interface-v1"}),
|
||||
json!({"scope": "relative", "name": "interface-v1"}),
|
||||
json!({"scope": ".", "name": "interface-v1"}),
|
||||
json!({"scope": "..", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/", "name": "interface-v1"}),
|
||||
json!({"scope": "//a", "name": "interface-v1"}),
|
||||
json!({"scope": "/a//b", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/./b", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/../b", "name": "interface-v1"}),
|
||||
] {
|
||||
let body = serde_json::to_vec(&json!({"interface": bad})).unwrap();
|
||||
assert!(
|
||||
decode_fetch_interface_request(&body, limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
let body = serde_json::to_vec(&call_json(bad.clone())).unwrap();
|
||||
assert!(
|
||||
decode_call_operation_metadata(&body, limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(
|
||||
decode_call_operation_request(&body, &descriptor(), limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch_json(bad.clone())),
|
||||
limits(),
|
||||
));
|
||||
let mut future = fetch_json(bad.clone());
|
||||
future["descriptor"] = json!({"format": "future-format", "future": true});
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, future),
|
||||
limits(),
|
||||
));
|
||||
invalid_success(decode_observe_response(
|
||||
&observe_request(),
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
json!({"object": {"name": "item", "interfaces": [bad]}}),
|
||||
),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_reference_members_are_rejected_even_when_escaped_or_equal() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
for bad in [
|
||||
r#"{"scope":"/","scope":"/","name":"x"}"#,
|
||||
r#"{"scope":"/","name":"x","name":"x"}"#,
|
||||
r#"{"scope":"/","name":"x","na\u006de":"x"}"#,
|
||||
] {
|
||||
let fetch = format!(r#"{{"interface":{bad}}}"#);
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_request(fetch.as_bytes(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
let call = format!(
|
||||
r#"{{"target":{{"path":"/"}},"interface":{{"reference":{bad}}},"operation":"run","arguments":{{}}}}"#
|
||||
);
|
||||
assert!(matches!(
|
||||
decode_call_operation_metadata(call.as_bytes(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_call_operation_request(call.as_bytes(), &descriptor(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
let fetch_response = format!(
|
||||
r#"{{"interface":{bad},"descriptor":{{"format":"wip-interface/1","types":[],"operations":[]}}}}"#
|
||||
);
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&raw_response(StatusCode::OK, fetch_response.as_bytes()),
|
||||
limits(),
|
||||
));
|
||||
let observe = format!(r#"{{"object":{{"name":"item","interfaces":[{bad}]}}}}"#);
|
||||
invalid_success(decode_observe_response(
|
||||
&observe_request(),
|
||||
&raw_response(StatusCode::OK, observe.as_bytes()),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_order_and_json_escapes_do_not_change_reference_identity() {
|
||||
let expected = reference("/世界::#", "é::接口#");
|
||||
let raw_reference = r#"{"name":"\u00e9::\u63a5\u53e3#","scope":"\/\u4e16\u754c::#"}"#;
|
||||
let fetch = format!(r#"{{"interface":{raw_reference}}}"#);
|
||||
let request = decode_fetch_interface_request(fetch.as_bytes(), limits()).unwrap();
|
||||
assert_eq!(request.interface, expected);
|
||||
let fetch_response = format!(
|
||||
r#"{{"descriptor":{{"operations":[],"types":[],"format":"wip-interface/1"}},"interface":{raw_reference}}}"#
|
||||
);
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &raw_response(StatusCode::OK, fetch_response.as_bytes()), limits()).unwrap(), DecodedResponse::Success(value) if value.interface == expected)
|
||||
);
|
||||
let call = format!(
|
||||
r#"{{"arguments":{{}},"operation":"run#::操作","interface":{{"reference":{raw_reference}}},"target":{{"path":"/世界::#/item"}}}}"#
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(call.as_bytes(), limits())
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_request(call.as_bytes(), &descriptor(), limits())
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
expected
|
||||
);
|
||||
let observe = format!(r#"{{"object":{{"interfaces":[{raw_reference}],"name":"item"}}}}"#);
|
||||
assert!(
|
||||
matches!(decode_observe_response(&observe_request(), &raw_response(StatusCode::OK, observe.as_bytes()), limits()).unwrap(), DecodedResponse::Success(value) if value.object.interfaces == vec![expected])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_comparison_is_exact_without_normalization_case_or_url_decoding() {
|
||||
for different in [
|
||||
reference("/", "e\u{301}"),
|
||||
reference("/", "É"),
|
||||
reference("/", "%C3%A9"),
|
||||
reference("/other", "é"),
|
||||
] {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "é"),
|
||||
};
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
fetch_json(json!({"scope": different.scope, "name": different.name})),
|
||||
),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/%2E", "é"),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "."),
|
||||
};
|
||||
assert!(encode_fetch_interface_request(&endpoint(), &request, limits()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_encoding_rejects_invalid_reference_shape_without_needing_a_fetch_target() {
|
||||
for bad in [
|
||||
reference("relative", "x"),
|
||||
reference("", "x"),
|
||||
reference("/a/../b", "x"),
|
||||
reference("/", ""),
|
||||
] {
|
||||
assert!(
|
||||
encode_fetch_interface_request(
|
||||
&endpoint(),
|
||||
&FetchInterfaceRequest {
|
||||
interface: bad.clone()
|
||||
},
|
||||
limits()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
encode_call_operation_request(&endpoint(), &call(bad, None), &descriptor(), limits())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/unrelated/scope", "x"),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_metadata_leaves_valid_out_of_scope_references_and_identity_to_host_resolution() {
|
||||
let request = call(
|
||||
reference("/elsewhere", "x"),
|
||||
Some("not-current-identity".into()),
|
||||
);
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||
assert_eq!(metadata.interface, request.interface);
|
||||
assert_eq!(
|
||||
metadata
|
||||
.decode_request(encoded.body(), &descriptor(), limits())
|
||||
.unwrap(),
|
||||
request
|
||||
);
|
||||
|
||||
// Neither an unknown operation nor descriptor-bound argument values are
|
||||
// resolved by the metadata boundary before Host precondition checks.
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["operation"] = json!("missing");
|
||||
body["arguments"] = json!({"not_declared": [null, {"anything": true}]});
|
||||
let metadata =
|
||||
decode_call_operation_metadata(&serde_json::to_vec(&body).unwrap(), limits()).unwrap();
|
||||
assert_eq!(metadata.operation, "missing");
|
||||
assert_eq!(metadata.interface, request.interface);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observation_scope_validation_uses_each_nodes_path_and_structural_duplicates() {
|
||||
let request = ObserveRequest {
|
||||
path: "/a".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let valid = json!({
|
||||
"object": {"name": "a", "interfaces": [{"scope": "/", "name": "x"}, {"scope": "/a", "name": "x"}]},
|
||||
"children": [{"object": {"name": "b", "interfaces": [{"scope": "/a/b", "name": "x"}]}}]
|
||||
});
|
||||
assert!(
|
||||
decode_observe_response(&request, &response(StatusCode::OK, valid.clone()), limits())
|
||||
.is_ok()
|
||||
);
|
||||
for scope in ["/ab", "/elsewhere", "/a/b/c"] {
|
||||
let mut bad = valid.clone();
|
||||
bad["children"][0]["object"]["interfaces"][0]["scope"] = json!(scope);
|
||||
invalid_success(decode_observe_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, bad),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
let mut duplicate = valid;
|
||||
duplicate["object"]["interfaces"] =
|
||||
json!([{"scope": "/a", "name": "x"}, {"name": "x", "scope": "/a"}]);
|
||||
invalid_success(decode_observe_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, duplicate),
|
||||
limits(),
|
||||
));
|
||||
let root_request = ObserveRequest {
|
||||
path: "/".into(),
|
||||
depth: 0,
|
||||
};
|
||||
for (scope, valid) in [("/", true), ("/a", false)] {
|
||||
let result = decode_observe_response(
|
||||
&root_request,
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
json!({"object": {"name": "", "interfaces": [{"scope": scope, "name": "x"}]}}),
|
||||
),
|
||||
limits(),
|
||||
);
|
||||
if valid {
|
||||
assert!(result.is_ok());
|
||||
} else {
|
||||
invalid_success(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_omission_and_opaque_strings_round_trip_in_both_positions() {
|
||||
for scope_ref in [
|
||||
None,
|
||||
Some(String::new()),
|
||||
Some("opaque::# 世界 ! not base64 /+=".into()),
|
||||
Some("\"\\\n\u{0}".into()),
|
||||
] {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let expected = FetchInterfaceResponse {
|
||||
interface: request.interface.clone(),
|
||||
scope_ref: scope_ref.clone(),
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
};
|
||||
let encoded = encode_fetch_interface_response(&request, &expected, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body.get("scope_ref"),
|
||||
scope_ref
|
||||
.as_ref()
|
||||
.map(|value| Json::String(value.clone()))
|
||||
.as_ref()
|
||||
);
|
||||
assert!(body.get("validator").is_none());
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(expected)
|
||||
);
|
||||
let call = call(request.interface, scope_ref);
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &call, &descriptor(), limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body["interface"].get("scope_ref"),
|
||||
call.interface
|
||||
.scope_ref
|
||||
.as_ref()
|
||||
.map(|value| Json::String(value.clone()))
|
||||
.as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(encoded.body(), limits())
|
||||
.unwrap()
|
||||
.interface,
|
||||
call.interface
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_request(encoded.body(), &descriptor(), limits()).unwrap(),
|
||||
call
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_null_and_every_nonstring_type_are_rejected_before_descriptor_resolution() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
for bad in [Json::Null, json!(true), json!(0), json!([]), json!({})] {
|
||||
let mut fetch = fetch_json(json!({"scope": "/", "name": "x"}));
|
||||
fetch["scope_ref"] = bad.clone();
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch.clone()),
|
||||
limits(),
|
||||
));
|
||||
// Unknown format does not mask malformed common response fields.
|
||||
fetch["descriptor"] = json!({"format": "future-format", "future": true});
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch),
|
||||
limits(),
|
||||
));
|
||||
let mut call = call_json(json!({"scope": "/", "name": "x"}));
|
||||
call["interface"]["scope_ref"] = bad.clone();
|
||||
let body = serde_json::to_vec(&call).unwrap();
|
||||
let error = decode_call_operation_metadata(&body, limits()).unwrap_err();
|
||||
if bad.is_null() {
|
||||
assert!(matches!(error, CodecError::NullOptionalField { .. }));
|
||||
} else {
|
||||
assert!(matches!(error, CodecError::InvalidField { .. }));
|
||||
}
|
||||
assert!(decode_call_operation_request(&body, &descriptor(), limits()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_is_only_allowed_on_fetch_responses_and_call_interface_targets() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let reference = json!({"scope": "/", "name": "x"});
|
||||
let fetch_request = json!({"interface": reference, "scope_ref": "identity"});
|
||||
assert!(
|
||||
decode_fetch_interface_request(&serde_json::to_vec(&fetch_request).unwrap(), limits())
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mut call = call_json(reference.clone());
|
||||
call["scope_ref"] = json!("identity");
|
||||
assert!(decode_call_operation_metadata(&serde_json::to_vec(&call).unwrap(), limits()).is_err());
|
||||
let mut call = call_json(reference);
|
||||
call["target"]["scope_ref"] = json!("identity");
|
||||
assert!(decode_call_operation_metadata(&serde_json::to_vec(&call).unwrap(), limits()).is_err());
|
||||
|
||||
let duplicate = br#"{"interface":{"scope":"/","name":"x"},"scope_ref":"identity","scope_ref":"identity","descriptor":{"format":"wip-interface/1","types":[],"operations":[]}}"#;
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&raw_response(StatusCode::OK, duplicate),
|
||||
limits(),
|
||||
));
|
||||
let duplicate = br#"{"target":{"path":"/"},"interface":{"reference":{"scope":"/","name":"x"},"scope_ref":"identity","scope_ref":"identity"},"operation":"run#::\u64cd\u4f5c","arguments":{}}"#;
|
||||
assert!(matches!(
|
||||
decode_call_operation_metadata(duplicate, limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_call_operation_request(duplicate, &descriptor(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_correspondence_includes_reference_and_scope_ref_but_not_wire_order() {
|
||||
let request = call(reference("/", "x"), Some("identity".into()));
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||
for (field, changed) in [
|
||||
("scope_ref", json!("other")),
|
||||
("reference", json!({"scope": "/", "name": "other"})),
|
||||
] {
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["interface"][field] = changed;
|
||||
assert!(
|
||||
matches!(metadata.decode_request(&serde_json::to_vec(&body).unwrap(), &descriptor(), limits()).unwrap_err(), CodecError::InvalidField { field, .. } if field == "request")
|
||||
);
|
||||
}
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["interface"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("scope_ref");
|
||||
assert!(
|
||||
metadata
|
||||
.decode_request(&serde_json::to_vec(&body).unwrap(), &descriptor(), limits())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_classification_preserves_transport_status_and_error_envelope_semantics() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let valid = fetch_json(json!({"scope": "/", "name": "x"}));
|
||||
for (status, kind) in [
|
||||
(
|
||||
StatusCode::CREATED,
|
||||
InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||
),
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||
),
|
||||
] {
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &response(status, valid.clone()), limits()).unwrap_err(), ClientResponseError::InvalidResponse { kind: actual, .. } if actual == kind)
|
||||
);
|
||||
}
|
||||
for status in [
|
||||
StatusCode::UNAUTHORIZED,
|
||||
StatusCode::FORBIDDEN,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
] {
|
||||
let malformed = response(status, fetch_json(json!("legacy")));
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &malformed, limits()).unwrap_err(), ClientResponseError::TransportBinding(failure) if failure.status == status)
|
||||
);
|
||||
}
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::InterfaceNotFound,
|
||||
message: "unpublished".into(),
|
||||
};
|
||||
let mut encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::FetchInterface, &error, limits())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error: error.clone(),
|
||||
status_mismatch: None
|
||||
}
|
||||
);
|
||||
*encoded.status_mut() = StatusCode::BAD_GATEWAY;
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &encoded, limits()).unwrap(), DecodedResponse::ProtocolFailure { error: actual, status_mismatch: Some(_) } if actual == error)
|
||||
);
|
||||
*encoded.status_mut() = StatusCode::OK;
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||
..
|
||||
}
|
||||
));
|
||||
let disallowed = response(
|
||||
StatusCode::CONFLICT,
|
||||
json!({"error": {"code": "interface_mismatch", "message": "wrong interaction"}}),
|
||||
);
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_response(&request, &disallowed, limits()).unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::DisallowedProtocolCode,
|
||||
..
|
||||
}
|
||||
));
|
||||
let mut coded = response(StatusCode::OK, valid);
|
||||
coded
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "gzip".parse().unwrap());
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &coded, limits()).unwrap_err(), ClientResponseError::TransportBinding(failure) if failure.kind == TransportFailureKind::UnsupportedContentCoding)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_interface_mismatch_envelope_remains_protocol_failure_with_structured_metadata() {
|
||||
let request = call(reference("/unrelated", "x"), Some("stale identity".into()));
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::InterfaceMismatch,
|
||||
message: "interface precondition".into(),
|
||||
};
|
||||
let encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::CallOperation, &error, limits())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_response(&request, &descriptor(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: None
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
use wip_http::http::{Response, StatusCode};
|
||||
use wip_http::wip_protocol::{
|
||||
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, TransportFailureKind,
|
||||
decode_observe_response, encode_protocol_error_response, error_code_name, is_json_content_type,
|
||||
status_for_error,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 32).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 logical_resource_limit_uses_only_422_and_bare_413_is_transport_failure() {
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||
message: "logical observation limit exceeded".into(),
|
||||
};
|
||||
let encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||
assert_eq!(encoded.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(
|
||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error: error.clone(),
|
||||
status_mismatch: None,
|
||||
}
|
||||
);
|
||||
|
||||
let mut noncanonical = encoded;
|
||||
*noncanonical.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||
assert_eq!(
|
||||
decode_observe_response(&request(), &noncanonical, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: Some(wip_http::StatusMismatch {
|
||||
actual: StatusCode::PAYLOAD_TOO_LARGE,
|
||||
expected: StatusCode::UNPROCESSABLE_ENTITY,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
let bare_413 = Response::builder()
|
||||
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &bare_413, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::PAYLOAD_TOO_LARGE
|
||||
&& failure.kind == TransportFailureKind::HttpStatus
|
||||
));
|
||||
}
|
||||
|
||||
#[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 unsupported_response_content_coding_is_transport_failure() {
|
||||
let mut encoded = encode_protocol_error_response(
|
||||
ProtocolInteraction::Observe,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::NotFound,
|
||||
message: "missing".into(),
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap();
|
||||
encoded
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "gzip".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &encoded, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::NOT_FOUND
|
||||
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||
));
|
||||
|
||||
let success = response(StatusCode::OK, br#"{"object":{"name":"","interfaces":[]}}"#);
|
||||
let mut identity = success.clone();
|
||||
identity
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "identity".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &identity, limits()).unwrap(),
|
||||
DecodedResponse::Success(_)
|
||||
));
|
||||
|
||||
let mut unsupported = success;
|
||||
unsupported
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "br".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &unsupported, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::OK
|
||||
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||
));
|
||||
}
|
||||
|
||||
#[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,182 @@
|
||||
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"),
|
||||
];
|
||||
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();
|
||||
let error = validate_http_request(&endpoint, Route::Observe, &wrong_method).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::MethodNotAllowed));
|
||||
assert_eq!(error.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
assert_eq!(error.allow(), Some("POST"));
|
||||
|
||||
let wrong_route = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/fetch_interface")
|
||||
.header("content-type", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error = validate_http_request(&endpoint, Route::Observe, &wrong_route).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::NotFound));
|
||||
assert_eq!(error.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(error.allow(), None);
|
||||
|
||||
let query_and_wrong_method = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/wip/v1/observe?unexpected=true")
|
||||
.header("content-type", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
validate_http_request(&endpoint, Route::Observe, &query_and_wrong_method).unwrap_err(),
|
||||
RequestMetadataError::NotFound
|
||||
));
|
||||
|
||||
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);
|
||||
|
||||
for coding in ["gzip", "identity, gzip"] {
|
||||
let unsupported_coding = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("content-encoding", coding)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error =
|
||||
validate_http_request(&endpoint, Route::Observe, &unsupported_coding).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||
}
|
||||
|
||||
let identity_coding = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("content-encoding", "identity")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(validate_http_request(&endpoint, Route::Observe, &identity_coding).is_ok());
|
||||
}
|
||||
|
||||
#[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/batch",
|
||||
"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,9 +1,13 @@
|
||||
[package]
|
||||
name = "wip-interface-macros"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Procedural macros for WIP interface declarations and DTO codecs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-interface-macros"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,9 @@
|
||||
# wip-interface-macros
|
||||
|
||||
Procedural-macro implementation used by [`wip-interface`](https://crates.io/crates/wip-interface).
|
||||
|
||||
Applications should depend on `wip-interface`, which re-exports `#[interface]` and `#[derive(WipType)]` together with the traits and types required by generated code. Direct use of this implementation crate is not a supported application API.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-interface-macros) for the exported macro entry points.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
@@ -1,4 +1,10 @@
|
||||
//! Procedural macros backing the public `wip-interface` authoring facade.
|
||||
//!
|
||||
//! This is an implementation crate. Applications should depend on
|
||||
//! `wip-interface`, which re-exports both macros alongside the traits and types
|
||||
//! used by their generated code.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -162,9 +168,11 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
||||
#(#declaration_collectors)*
|
||||
|
||||
::wip_interface::wip_protocol::InterfaceDescriptor {
|
||||
name: ::std::string::String::from(stringify!(#trait_ident)),
|
||||
format: ::std::string::String::from(
|
||||
::wip_interface::wip_protocol::INTERFACE_FORMAT_V1,
|
||||
),
|
||||
documentation: #trait_doc,
|
||||
declarations,
|
||||
types: declarations,
|
||||
operations: ::std::vec![#(#operation_declarations),*],
|
||||
}
|
||||
}
|
||||
@@ -174,9 +182,12 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
||||
fn dispatch(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: ::std::vec::Vec<::wip_interface::wip_protocol::NamedValue>,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<
|
||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::DispatchError,
|
||||
> {
|
||||
let descriptor = Self::descriptor();
|
||||
@@ -201,9 +212,12 @@ fn expand_interface(attribute: TokenStream2, item: ItemTrait) -> syn::Result<Tok
|
||||
pub fn dispatch<T: #trait_ident>(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: ::std::vec::Vec<::wip_interface::wip_protocol::NamedValue>,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<
|
||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::DispatchError,
|
||||
> {
|
||||
<Self as ::wip_interface::InterfaceImplementation<T>>::dispatch(
|
||||
@@ -470,13 +484,18 @@ fn parse_operation_result(output: &ReturnType) -> syn::Result<Type> {
|
||||
_ => None,
|
||||
});
|
||||
let result = types.next().cloned();
|
||||
if arguments.args.len() != 1 || result.is_none() || types.next().is_some() {
|
||||
if arguments.args.len() != 1 || types.next().is_some() {
|
||||
return Err(Error::new_spanned(
|
||||
arguments,
|
||||
"`OperationResult` must have exactly one application result type",
|
||||
));
|
||||
}
|
||||
let result = result.expect("checked above");
|
||||
let result = result.ok_or_else(|| {
|
||||
Error::new_spanned(
|
||||
arguments,
|
||||
"`OperationResult` must have exactly one application result type",
|
||||
)
|
||||
})?;
|
||||
if direct_option(&result)?.is_some() || contains_option(&result) {
|
||||
return Err(Error::new_spanned(
|
||||
result,
|
||||
@@ -490,8 +509,13 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
let arguments_ident = &operation.arguments_ident;
|
||||
let fields = operation.parameters.iter().map(|parameter| {
|
||||
let ident = ¶meter.ident;
|
||||
let name = ¶meter.name;
|
||||
let ty = parameter_rust_type(parameter);
|
||||
quote!(pub #ident: #ty)
|
||||
let documentation = format!("Decoded `{name}` operation argument.");
|
||||
quote!(
|
||||
#[doc = #documentation]
|
||||
pub #ident: #ty
|
||||
)
|
||||
});
|
||||
let decoders = operation.parameters.iter().map(|parameter| {
|
||||
let ident = ¶meter.ident;
|
||||
@@ -507,12 +531,11 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
let encode_result = if operation.unit_result {
|
||||
quote! {
|
||||
let () = result;
|
||||
::std::result::Result::Ok(::std::option::Option::None)
|
||||
::std::result::Result::Ok(::wip_interface::wip_protocol::Value::Unit)
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
<#result_ty as ::wip_interface::WipType>::encode(result)
|
||||
.map(::std::option::Option::Some)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -525,9 +548,12 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
impl #arguments_ident {
|
||||
/// Decodes named logical values into typed operation arguments.
|
||||
pub fn decode(
|
||||
arguments: ::std::vec::Vec<::wip_interface::wip_protocol::NamedValue>,
|
||||
arguments: ::std::collections::BTreeMap<
|
||||
::std::string::String,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
>,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(arguments)?;
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(arguments);
|
||||
let decoded = Self {
|
||||
#(#decoders,)*
|
||||
};
|
||||
@@ -539,7 +565,7 @@ fn argument_item(operation: &Operation) -> TokenStream2 {
|
||||
pub fn encode_result(
|
||||
result: #result_ty,
|
||||
) -> ::std::result::Result<
|
||||
::std::option::Option<::wip_interface::wip_protocol::Value>,
|
||||
::wip_interface::wip_protocol::Value,
|
||||
::wip_interface::CodecError,
|
||||
> {
|
||||
#encode_result
|
||||
@@ -559,22 +585,18 @@ fn operation_declaration(operation: &Operation) -> TokenStream2 {
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::ParameterDeclaration {
|
||||
name: ::std::string::String::from(#parameter_name),
|
||||
required: !#optional,
|
||||
documentation: #parameter_doc,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
optional: #optional,
|
||||
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
}
|
||||
});
|
||||
let returns = if operation.unit_result {
|
||||
quote!(::std::option::Option::None)
|
||||
} else {
|
||||
let result_ty = &operation.result_ty;
|
||||
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
||||
quote! {
|
||||
::std::option::Option::Some(::wip_interface::wip_protocol::ReturnDeclaration {
|
||||
documentation: #return_doc,
|
||||
ty: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
||||
})
|
||||
let result_ty = &operation.result_ty;
|
||||
let return_doc = documentation_tokens(operation.return_documentation.as_ref());
|
||||
let returns = quote! {
|
||||
::wip_interface::wip_protocol::ReturnDeclaration {
|
||||
documentation: #return_doc,
|
||||
r#type: <#result_ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -625,14 +647,17 @@ fn dispatch_arm(operation: &Operation) -> TokenStream2 {
|
||||
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
||||
let decoded = #arguments_ident::decode(arguments)
|
||||
.map_err(::wip_interface::DispatchError::Decode)?;
|
||||
let result = implementation.#method_ident(#(#arguments),*)
|
||||
.map_err(::wip_interface::DispatchError::Host)?;
|
||||
let encoded = #arguments_ident::encode_result(result)
|
||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||
descriptor
|
||||
.validate_return(#operation_name, encoded.as_ref())
|
||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
||||
::std::result::Result::Ok(encoded)
|
||||
::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
|
||||
let result = implementation.#method_ident(#(#arguments),*)
|
||||
.map_err(::wip_interface::DispatchError::Host)?;
|
||||
let encoded = #arguments_ident::encode_result(result)
|
||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||
descriptor
|
||||
.validate_result(#operation_name, &encoded)
|
||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
||||
::std::result::Result::Ok(encoded)
|
||||
}))
|
||||
.map_err(|_| ::wip_interface::DispatchError::Panic)?
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -698,7 +723,12 @@ fn derive_record(
|
||||
let mut parsed_fields = Vec::new();
|
||||
let mut names = HashSet::new();
|
||||
for field in fields {
|
||||
let field_ident = field.ident.clone().expect("named fields have identifiers");
|
||||
let Some(field_ident) = field.ident.clone() else {
|
||||
return Err(Error::new_spanned(
|
||||
field,
|
||||
"`WipType` record fields must be named",
|
||||
));
|
||||
};
|
||||
let name = source_name(&field_ident);
|
||||
if !names.insert(name.clone()) {
|
||||
return Err(Error::new(
|
||||
@@ -726,9 +756,9 @@ fn derive_record(
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::FieldDeclaration {
|
||||
name: ::std::string::String::from(#name),
|
||||
required: !#optional,
|
||||
documentation: #documentation,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
optional: #optional,
|
||||
r#type: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -744,18 +774,18 @@ fn derive_record(
|
||||
if field.optional {
|
||||
quote! {
|
||||
if let ::std::option::Option::Some(value) = #field_ident {
|
||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
||||
name: ::std::string::String::from(#field_name),
|
||||
value: <#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
});
|
||||
fields.insert(
|
||||
::std::string::String::from(#field_name),
|
||||
<#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
fields.push(::wip_interface::wip_protocol::NamedValue {
|
||||
name: ::std::string::String::from(#field_name),
|
||||
value: <#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
||||
});
|
||||
fields.insert(
|
||||
::std::string::String::from(#field_name),
|
||||
<#ty as ::wip_interface::WipType>::encode(#field_ident)?,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -773,9 +803,9 @@ fn derive_record(
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -783,13 +813,13 @@ fn derive_record(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Record(
|
||||
::wip_interface::wip_protocol::RecordDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Record {
|
||||
fields: ::std::vec![#(#field_declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||
#(#dependency_collectors)*
|
||||
}
|
||||
@@ -802,7 +832,7 @@ fn derive_record(
|
||||
::wip_interface::CodecError,
|
||||
> {
|
||||
let Self { #(#destructured_fields),* } = self;
|
||||
let mut fields = ::std::vec::Vec::new();
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
#(#encoders)*
|
||||
::std::result::Result::Ok(
|
||||
::wip_interface::wip_protocol::Value::Record(fields),
|
||||
@@ -814,7 +844,7 @@ fn derive_record(
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Record(fields) => {
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(fields)?;
|
||||
let mut decoder = ::wip_interface::__private::RecordDecoder::new(fields);
|
||||
let decoded = Self {
|
||||
#(#decoders,)*
|
||||
};
|
||||
@@ -849,14 +879,14 @@ fn derive_enum(
|
||||
.variants
|
||||
.iter()
|
||||
.all(|variant| matches!(variant.fields, Fields::Unit));
|
||||
let all_payload = !data.variants.is_empty()
|
||||
&& data.variants.iter().all(|variant| {
|
||||
matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
||||
});
|
||||
let valid_union = data.variants.iter().all(|variant| {
|
||||
matches!(variant.fields, Fields::Unit)
|
||||
|| matches!(&variant.fields, Fields::Unnamed(fields) if fields.unnamed.len() == 1)
|
||||
});
|
||||
|
||||
if all_unit {
|
||||
derive_unit_enum(ident, type_name, type_documentation, data)
|
||||
} else if all_payload {
|
||||
} else if valid_union {
|
||||
derive_union_enum(ident, type_name, type_documentation, data)
|
||||
} else {
|
||||
let span = data
|
||||
@@ -869,7 +899,7 @@ fn derive_enum(
|
||||
.map_or_else(|| data.enum_token.span, Spanned::span);
|
||||
Err(Error::new(
|
||||
span,
|
||||
"a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported",
|
||||
"a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -885,7 +915,7 @@ fn derive_unit_enum(
|
||||
let name = source_name(&variant.ident);
|
||||
let documentation = documentation_tokens(documentation(&variant.attrs).as_ref());
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::EnumVariantDeclaration {
|
||||
::wip_interface::wip_protocol::EnumCase {
|
||||
name: ::std::string::String::from(#name),
|
||||
documentation: #documentation,
|
||||
}
|
||||
@@ -905,9 +935,9 @@ fn derive_unit_enum(
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -915,13 +945,13 @@ fn derive_unit_enum(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Enum(
|
||||
::wip_interface::wip_protocol::EnumDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
variants: ::std::vec![#(#declarations),*],
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Enum {
|
||||
cases: ::std::vec![#(#declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
let _ = ::wip_interface::__private::register_declaration(
|
||||
declarations,
|
||||
declaration,
|
||||
@@ -938,7 +968,7 @@ fn derive_unit_enum(
|
||||
#(#encoders,)*
|
||||
};
|
||||
::std::result::Result::Ok(
|
||||
::wip_interface::wip_protocol::Value::Enum(
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(variant),
|
||||
),
|
||||
)
|
||||
@@ -948,7 +978,7 @@ fn derive_unit_enum(
|
||||
value: ::wip_interface::wip_protocol::Value,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Enum(variant) => {
|
||||
::wip_interface::wip_protocol::Value::String(variant) => {
|
||||
match variant.as_str() {
|
||||
#(#decoders,)*
|
||||
_ => ::std::result::Result::Err(
|
||||
@@ -977,30 +1007,36 @@ fn derive_union_enum(
|
||||
struct Variant<'a> {
|
||||
ident: &'a Ident,
|
||||
name: String,
|
||||
ty: &'a Type,
|
||||
payload: Option<&'a Type>,
|
||||
documentation: Option<Documentation>,
|
||||
}
|
||||
|
||||
let mut variants = Vec::new();
|
||||
for variant in &data.variants {
|
||||
let Fields::Unnamed(fields) = &variant.fields else {
|
||||
unreachable!("enum shape was checked before union generation");
|
||||
let payload = match &variant.fields {
|
||||
Fields::Unit => None,
|
||||
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
||||
let field = fields.unnamed.first().expect("length checked");
|
||||
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
||||
return Err(Error::new_spanned(
|
||||
&field.ty,
|
||||
"`Option<T>` is only supported directly on DTO fields and operation parameters",
|
||||
));
|
||||
}
|
||||
validate_value_type(&field.ty, "union case payload")?;
|
||||
Some(&field.ty)
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
variant,
|
||||
"a `WipType` union case must be unit-like or contain exactly one unnamed payload",
|
||||
));
|
||||
}
|
||||
};
|
||||
let field = fields
|
||||
.unnamed
|
||||
.first()
|
||||
.expect("union variants have one field");
|
||||
if direct_option(&field.ty)?.is_some() || contains_option(&field.ty) {
|
||||
return Err(Error::new_spanned(
|
||||
&field.ty,
|
||||
"`Option<T>` is only supported directly on DTO fields and operation parameters",
|
||||
));
|
||||
}
|
||||
validate_value_type(&field.ty, "union variant payload")?;
|
||||
variants.push(Variant {
|
||||
ident: &variant.ident,
|
||||
name: source_name(&variant.ident),
|
||||
ty: &field.ty,
|
||||
payload,
|
||||
documentation: documentation(&variant.attrs),
|
||||
});
|
||||
}
|
||||
@@ -1009,50 +1045,95 @@ fn derive_union_enum(
|
||||
let declarations = variants.iter().map(|variant| {
|
||||
let name = &variant.name;
|
||||
let documentation = documentation_tokens(variant.documentation.as_ref());
|
||||
let ty = variant.ty;
|
||||
let payload = match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
::std::option::Option::Some(
|
||||
<#ty as ::wip_interface::WipType>::type_expr(),
|
||||
)
|
||||
},
|
||||
None => quote!(::std::option::Option::None),
|
||||
};
|
||||
quote! {
|
||||
::wip_interface::wip_protocol::UnionVariantDeclaration {
|
||||
::wip_interface::wip_protocol::UnionCase {
|
||||
name: ::std::string::String::from(#name),
|
||||
documentation: #documentation,
|
||||
ty: <#ty as ::wip_interface::WipType>::type_expr(),
|
||||
payload: #payload,
|
||||
}
|
||||
}
|
||||
});
|
||||
let dependency_collectors = variants.iter().map(|variant| {
|
||||
let ty = variant.ty;
|
||||
quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);)
|
||||
let dependency_collectors = variants.iter().filter_map(|variant| {
|
||||
variant.payload.map(
|
||||
|ty| quote!(<#ty as ::wip_interface::WipType>::collect_declarations(declarations);),
|
||||
)
|
||||
});
|
||||
let encoders = variants.iter().map(|variant| {
|
||||
let variant_ident = variant.ident;
|
||||
let name = &variant.name;
|
||||
let ty = variant.ty;
|
||||
quote! {
|
||||
Self::#variant_ident(value) => {
|
||||
::wip_interface::wip_protocol::Value::Union {
|
||||
variant: ::std::string::String::from(#name),
|
||||
value: ::std::boxed::Box::new(
|
||||
match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
Self::#variant_ident(value) => {
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
),
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(#name),
|
||||
),
|
||||
);
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_VALUE_FIELD,
|
||||
),
|
||||
<#ty as ::wip_interface::WipType>::encode(value)?,
|
||||
),
|
||||
);
|
||||
::wip_interface::wip_protocol::Value::Record(fields)
|
||||
}
|
||||
}
|
||||
},
|
||||
None => quote! {
|
||||
Self::#variant_ident => {
|
||||
let mut fields = ::std::collections::BTreeMap::new();
|
||||
fields.insert(
|
||||
::std::string::String::from(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
),
|
||||
::wip_interface::wip_protocol::Value::String(
|
||||
::std::string::String::from(#name),
|
||||
),
|
||||
);
|
||||
::wip_interface::wip_protocol::Value::Record(fields)
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
let decoders = variants.iter().map(|variant| {
|
||||
let variant_ident = variant.ident;
|
||||
let name = &variant.name;
|
||||
let ty = variant.ty;
|
||||
quote! {
|
||||
#name => <#ty as ::wip_interface::WipType>::decode(*value)
|
||||
.map(Self::#variant_ident)
|
||||
match variant.payload {
|
||||
Some(ty) => quote! {
|
||||
#name => {
|
||||
let value = decoder.required::<#ty>(
|
||||
::wip_interface::wip_protocol::UNION_VALUE_FIELD,
|
||||
)?;
|
||||
decoder.finish()?;
|
||||
::std::result::Result::Ok(Self::#variant_ident(value))
|
||||
}
|
||||
},
|
||||
None => quote! {
|
||||
#name => {
|
||||
decoder.finish()?;
|
||||
::std::result::Result::Ok(Self::#variant_ident)
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
Ok(quote! {
|
||||
impl ::wip_interface::WipType for #ident {
|
||||
fn type_expr() -> ::wip_interface::wip_protocol::TypeExpr {
|
||||
::wip_interface::wip_protocol::TypeExpr::Named(
|
||||
::std::string::String::from(#type_name),
|
||||
)
|
||||
::wip_interface::wip_protocol::TypeExpr::Named {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(
|
||||
@@ -1060,13 +1141,13 @@ fn derive_union_enum(
|
||||
::wip_interface::wip_protocol::TypeDeclaration,
|
||||
>,
|
||||
) {
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration::Union(
|
||||
::wip_interface::wip_protocol::UnionDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
variants: ::std::vec![#(#declarations),*],
|
||||
let declaration = ::wip_interface::wip_protocol::TypeDeclaration {
|
||||
name: ::std::string::String::from(#type_name),
|
||||
documentation: #declaration_doc,
|
||||
definition: ::wip_interface::wip_protocol::TypeExpr::Union {
|
||||
cases: ::std::vec![#(#declarations),*],
|
||||
},
|
||||
);
|
||||
};
|
||||
if ::wip_interface::__private::register_declaration(declarations, declaration) {
|
||||
#(#dependency_collectors)*
|
||||
}
|
||||
@@ -1088,26 +1169,30 @@ fn derive_union_enum(
|
||||
value: ::wip_interface::wip_protocol::Value,
|
||||
) -> ::std::result::Result<Self, ::wip_interface::CodecError> {
|
||||
match value {
|
||||
::wip_interface::wip_protocol::Value::Union { variant, value } => {
|
||||
match variant.as_str() {
|
||||
::wip_interface::wip_protocol::Value::Record(fields) => {
|
||||
let mut decoder =
|
||||
::wip_interface::__private::RecordDecoder::new(fields);
|
||||
let case = decoder.required::<::std::string::String>(
|
||||
::wip_interface::wip_protocol::UNION_CASE_FIELD,
|
||||
)?;
|
||||
match case.as_str() {
|
||||
#(#decoders,)*
|
||||
_ => ::std::result::Result::Err(
|
||||
::wip_interface::__private::decode_unknown_variant(
|
||||
#type_name,
|
||||
variant,
|
||||
case,
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
actual => ::std::result::Result::Err(
|
||||
::wip_interface::__private::decode_type_mismatch("union", actual),
|
||||
::wip_interface::__private::decode_type_mismatch("union record", actual),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_type(ty: &Type, context: &str) -> syn::Result<(bool, Type)> {
|
||||
if let Some(inner) = direct_option(ty)? {
|
||||
if contains_option(&inner) {
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
[package]
|
||||
name = "wip-interface"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Public Rust authoring API for WIP interfaces and operation value codecs"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-interface"
|
||||
|
||||
[dependencies]
|
||||
wip-interface-macros = { path = "../wip-interface-macros" }
|
||||
wip-protocol = { path = "../wip-protocol" }
|
||||
wip-interface-macros.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = "1"
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,32 @@
|
||||
# wip-interface
|
||||
|
||||
Public Rust authoring API for Web Interface Protocol (WIP) interfaces and application DTO codecs.
|
||||
|
||||
The crate re-exports `#[interface]` and `#[derive(WipType)]`, generates Interface Descriptors and typed dispatch companions, and converts application-owned Rust values to and from the transport-independent value model.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-interface = "0.1.0"
|
||||
```
|
||||
|
||||
```rust
|
||||
use wip_interface as wip;
|
||||
|
||||
#[derive(wip::WipType)]
|
||||
struct Greeting {
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[wip::interface]
|
||||
pub trait Greeter {
|
||||
/// Builds a greeting.
|
||||
///
|
||||
/// # Returns
|
||||
/// The generated greeting.
|
||||
fn greet(&self, name: String) -> wip::OperationResult<Greeting>;
|
||||
}
|
||||
```
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-interface) for supported interface syntax, DTO shapes, and failure semantics.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
+356
-112
@@ -30,37 +30,65 @@
|
||||
//!
|
||||
//! | Rust type | Protocol type/value |
|
||||
//! | --- | --- |
|
||||
//! | `()` as an operation result | no return declaration / no value |
|
||||
//! | `()` | `Unit` |
|
||||
//! | `bool` | `Boolean` |
|
||||
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
|
||||
//! | `f32`, `f64` | finite `Number` |
|
||||
//! | `String` | `String` |
|
||||
//! | [`Bytes`] | `Bytes` |
|
||||
//! | [`wip_protocol::JsonValue`] | `Json` |
|
||||
//! | [`Entry<K, V>`] | `Entry<K, V>` |
|
||||
//! | [`JsonValue`] | schema-neutral `Json` value tree |
|
||||
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
|
||||
//! | `Vec<T>` | `List<T>` |
|
||||
//! | a named-field struct deriving [`WipType`] | named record |
|
||||
//! | an all-unit enum deriving [`WipType`] | named enum |
|
||||
//! | an all-newtype enum deriving [`WipType`] | named tagged union |
|
||||
//! | an enum mixing unit and single-payload cases deriving [`WipType`] | named union |
|
||||
//!
|
||||
//! `Option<T>` is supported only directly as a record field or operation
|
||||
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||
//! an application return enum/union and is returned as `Ok(value)`.
|
||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
||||
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
|
||||
//! [`HostErrorKind`] plus [`EffectGuarantee`]. The required [`OperationResult`]
|
||||
//! convention therefore keeps domain failures separate from runtime failures and
|
||||
//! makes outcome uncertainty visible to Host dispatch.
|
||||
//!
|
||||
//! # Migration to canonical values
|
||||
//!
|
||||
//! Earlier releases exposed `Entry<K, V>` and semantic `Value::Json`,
|
||||
//! `Value::Entry`, `Value::Enum`, and `Value::Union` variants. Those forms are
|
||||
//! intentionally gone: [`Entry`] is now one validated absolute Worldspace path,
|
||||
//! while JSON, enum, and union meaning comes only from the descriptor. Codecs
|
||||
//! exchange only raw [`Value`] strings, records, lists, and primitives. Unit
|
||||
//! operation results now cross the boundary as [`Value::Unit`] rather than an
|
||||
//! absent value.
|
||||
//!
|
||||
//! # Supported interface syntax
|
||||
//!
|
||||
//! An interface is a public, non-generic trait whose operations use exactly
|
||||
//! `&self`, simple named owned parameters, and an explicit
|
||||
//! `OperationResult<T>`. `WipType` derives support named-field structs,
|
||||
//! all-unit enums as protocol enums, and enums made from any mix of unit and
|
||||
//! single-payload cases as protocol unions.
|
||||
//!
|
||||
//! The macros reject trait inheritance and associated items; const, async,
|
||||
//! unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
|
||||
//! borrowed values and custom lifetimes; tuple, unit, or generic structs;
|
||||
//! unsupported named-field or multi-field enum variants; explicit discriminants; Rust unions;
|
||||
//! and `Option` anywhere except a direct DTO field or operation parameter.
|
||||
//! Unsupported inputs produce source-located compile errors rather than
|
||||
//! generating a partial interface.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
pub use wip_interface_macros::{WipType, interface};
|
||||
pub use wip_protocol;
|
||||
pub use wip_protocol::{
|
||||
Documentation, EnumDeclaration, EnumVariantDeclaration, FieldDeclaration, InterfaceDescriptor,
|
||||
JsonMember, JsonValue, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NamedValue, OperationDeclaration,
|
||||
ParameterDeclaration, RecordDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
||||
UnionDeclaration, UnionVariantDeclaration, ValidationError, Value,
|
||||
Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
|
||||
MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
|
||||
TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
|
||||
};
|
||||
|
||||
/// Converts one Rust application type to and from its protocol representation.
|
||||
@@ -103,8 +131,8 @@ pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
||||
fn dispatch(
|
||||
implementation: &T,
|
||||
operation: &str,
|
||||
arguments: Vec<NamedValue>,
|
||||
) -> Result<Option<Value>, DispatchError>;
|
||||
arguments: BTreeMap<String, Value>,
|
||||
) -> Result<Value, DispatchError>;
|
||||
}
|
||||
|
||||
/// Result convention required for generated interface operations.
|
||||
@@ -113,29 +141,107 @@ pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||
pub type OperationResult<T> = Result<T, HostError>;
|
||||
|
||||
/// A host/runtime failure, kept separate from the operation's application
|
||||
/// Whether an operation failure proves that no effects were committed.
|
||||
///
|
||||
/// This guarantee is consumed by Host dispatch when choosing a protocol failure:
|
||||
/// only [`NotCommitted`](Self::NotCommitted) failures may become `Internal` or
|
||||
/// `ResourceLimitExceeded`; [`Unknown`](Self::Unknown) failures must become
|
||||
/// `OperationOutcomeUnknown`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EffectGuarantee {
|
||||
/// The operation was not invoked, or every effect was rolled back.
|
||||
NotCommitted,
|
||||
/// The operation may have committed effects.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Host/runtime failure category used when effects are known not to be committed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostErrorKind {
|
||||
/// The Host or backend encountered an internal failure.
|
||||
Internal,
|
||||
/// A cancellation, deadline, or bounded resource limit was exceeded.
|
||||
ResourceLimitExceeded,
|
||||
}
|
||||
|
||||
/// A typed host/runtime failure, kept separate from the operation's application
|
||||
/// return type.
|
||||
///
|
||||
/// The effect guarantee is mandatory. Host runtimes must ignore the diagnostic
|
||||
/// when producing a wire response; it is bounded here for local observability but
|
||||
/// can still contain backend-private information.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostError {
|
||||
kind: HostErrorKind,
|
||||
effect_guarantee: EffectGuarantee,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl HostError {
|
||||
/// Creates a host failure with a human-readable diagnostic.
|
||||
/// Creates an internal Host failure with an explicit effect guarantee.
|
||||
#[must_use]
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||
Self::new(HostErrorKind::Internal, effect_guarantee, message)
|
||||
}
|
||||
|
||||
/// Creates a resource-limit Host failure with an explicit effect guarantee.
|
||||
#[must_use]
|
||||
pub fn resource_limit(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||
Self::new(
|
||||
HostErrorKind::ResourceLimitExceeded,
|
||||
effect_guarantee,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
fn new(
|
||||
kind: HostErrorKind,
|
||||
effect_guarantee: EffectGuarantee,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
kind,
|
||||
effect_guarantee,
|
||||
message: bounded_diagnostic(message.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the diagnostic message.
|
||||
/// Returns the typed Host failure category.
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> HostErrorKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// Returns the operation-effect guarantee attached by the implementation.
|
||||
#[must_use]
|
||||
pub fn effect_guarantee(&self) -> EffectGuarantee {
|
||||
self.effect_guarantee
|
||||
}
|
||||
|
||||
/// Returns the bounded local diagnostic message.
|
||||
///
|
||||
/// Host runtimes must not place this value in protocol responses because it
|
||||
/// can contain backend paths, credentials, or other private details.
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_DIAGNOSTIC_BYTES: usize = 512;
|
||||
|
||||
fn bounded_diagnostic(mut message: String) -> String {
|
||||
if message.len() <= MAX_DIAGNOSTIC_BYTES {
|
||||
return message;
|
||||
}
|
||||
let mut end = MAX_DIAGNOSTIC_BYTES;
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
message.truncate(end);
|
||||
message
|
||||
}
|
||||
|
||||
impl Display for HostError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
@@ -215,12 +321,59 @@ pub enum DispatchError {
|
||||
Decode(CodecError),
|
||||
/// The implementation reported a host/runtime failure.
|
||||
Host(HostError),
|
||||
/// The implementation panicked after invocation began.
|
||||
///
|
||||
/// Panic payloads are deliberately discarded because they can contain
|
||||
/// backend-private diagnostics.
|
||||
Panic,
|
||||
/// The Rust result could not be encoded.
|
||||
Encode(CodecError),
|
||||
/// The encoded result did not match the generated declaration.
|
||||
InvalidResult(wip_protocol::ValidationError),
|
||||
}
|
||||
|
||||
/// Whether generated dispatch failed before or after typed implementation
|
||||
/// invocation began.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DispatchPhase {
|
||||
/// Typed implementation code was not invoked.
|
||||
BeforeInvocation,
|
||||
/// Typed implementation invocation began, so effects require an explicit
|
||||
/// non-commit or rollback guarantee.
|
||||
AfterInvocation,
|
||||
}
|
||||
|
||||
impl DispatchError {
|
||||
/// Returns the execution phase in which this dispatch failure occurred.
|
||||
#[must_use]
|
||||
pub fn phase(&self) -> DispatchPhase {
|
||||
match self {
|
||||
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => {
|
||||
DispatchPhase::BeforeInvocation
|
||||
}
|
||||
Self::Host(_) | Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||
DispatchPhase::AfterInvocation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a post-invocation effect guarantee when the implementation
|
||||
/// supplied one.
|
||||
///
|
||||
/// Panic, encode, and result-validation failures default to `Unknown` until
|
||||
/// a provider confirms rollback. Pre-invocation failures return `None`.
|
||||
#[must_use]
|
||||
pub fn effect_guarantee(&self) -> Option<EffectGuarantee> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => None,
|
||||
Self::Host(error) => Some(error.effect_guarantee()),
|
||||
Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||
Some(EffectGuarantee::Unknown)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DispatchError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
@@ -230,6 +383,7 @@ impl Display for DispatchError {
|
||||
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
||||
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
||||
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
|
||||
Self::Panic => formatter.write_str("operation implementation panicked"),
|
||||
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
||||
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
||||
}
|
||||
@@ -239,7 +393,7 @@ impl Display for DispatchError {
|
||||
impl Error for DispatchError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::UnknownOperation(_) => None,
|
||||
Self::UnknownOperation(_) | Self::Panic => None,
|
||||
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
||||
Self::Decode(error) | Self::Encode(error) => Some(error),
|
||||
Self::Host(error) => Some(error),
|
||||
@@ -266,13 +420,101 @@ impl From<Bytes> for Vec<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed protocol key/value entry.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry<K, V> {
|
||||
/// Entry key.
|
||||
pub key: K,
|
||||
/// Entry value.
|
||||
pub value: V,
|
||||
/// A canonical absolute path to an entry in the current Worldspace.
|
||||
///
|
||||
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
|
||||
/// entry from a path such as `/articles/1`; application data associated with
|
||||
/// that entry belongs in an ordinary record alongside this value.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Entry(String);
|
||||
|
||||
impl Entry {
|
||||
/// Validates and creates an entry path.
|
||||
pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
|
||||
let path = path.into();
|
||||
validate_entry_path(&path)?;
|
||||
Ok(Self(path))
|
||||
}
|
||||
|
||||
/// Returns the canonical absolute Worldspace path.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Consumes the entry and returns its path.
|
||||
#[must_use]
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Entry {
|
||||
type Error = CodecError;
|
||||
|
||||
fn try_from(path: String) -> Result<Self, Self::Error> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Entry {
|
||||
type Err = CodecError;
|
||||
|
||||
fn from_str(path: &str) -> Result<Self, Self::Err> {
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// One member in a [`JsonValue::Object`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct JsonMember {
|
||||
/// Member name.
|
||||
pub name: String,
|
||||
/// Member value.
|
||||
pub value: JsonValue,
|
||||
}
|
||||
|
||||
/// JSON data represented independently of any application schema.
|
||||
///
|
||||
/// Its codec uses the ordinary schema-neutral [`Value`] variants. JSON null is
|
||||
/// [`Value::Unit`], arrays are [`Value::List`], and objects are
|
||||
/// [`Value::Record`]. Protocol bytes have no JSON representation and decoding
|
||||
/// a tree containing [`Value::Bytes`] is rejected.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum JsonValue {
|
||||
/// JSON null.
|
||||
Null,
|
||||
/// A JSON boolean.
|
||||
Boolean(bool),
|
||||
/// An interoperable integral JSON number.
|
||||
Integer(i64),
|
||||
/// A finite non-integral JSON number.
|
||||
Number(f64),
|
||||
/// A JSON string.
|
||||
String(String),
|
||||
/// A JSON array.
|
||||
Array(Vec<JsonValue>),
|
||||
/// A JSON object. Duplicate member names are rejected while encoding.
|
||||
Object(Vec<JsonMember>),
|
||||
}
|
||||
|
||||
impl WipType for () {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Unit
|
||||
}
|
||||
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Unit)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Unit => Ok(()),
|
||||
other => Err(CodecError::expected("unit", &other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WipType for bool {
|
||||
@@ -441,52 +683,87 @@ impl WipType for JsonValue {
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
validate_json(&self)?;
|
||||
Ok(Value::Json(self))
|
||||
encode_json(self)
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
match value {
|
||||
Value::Json(value) => {
|
||||
validate_json(&value)?;
|
||||
Ok(value)
|
||||
decode_json(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_json(value: JsonValue) -> Result<Value, CodecError> {
|
||||
match value {
|
||||
JsonValue::Null => Ok(Value::Unit),
|
||||
JsonValue::Boolean(value) => Ok(Value::Boolean(value)),
|
||||
JsonValue::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(Value::Integer(value))
|
||||
}
|
||||
JsonValue::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(Value::Number(value))
|
||||
}
|
||||
JsonValue::String(value) => Ok(Value::String(value)),
|
||||
JsonValue::Array(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| encode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(Value::List),
|
||||
JsonValue::Object(members) => {
|
||||
let mut fields = BTreeMap::new();
|
||||
for member in members {
|
||||
let name = member.name;
|
||||
let value = encode_json(member.value).map_err(|error| error.at(name.clone()))?;
|
||||
if fields.insert(name.clone(), value).is_some() {
|
||||
return Err(CodecError::new(format!("duplicate JSON member `{name}`")).at(name));
|
||||
}
|
||||
}
|
||||
other => Err(CodecError::expected("json", &other)),
|
||||
Ok(Value::Record(fields))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_json(value: &JsonValue) -> Result<(), CodecError> {
|
||||
fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
|
||||
match value {
|
||||
JsonValue::Integer(value) => ensure_safe_integer(*value),
|
||||
JsonValue::Number(value) => ensure_finite(*value),
|
||||
JsonValue::Array(values) => {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
validate_json(value).map_err(|error| error.at(index.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Unit => Ok(JsonValue::Null),
|
||||
Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
|
||||
Value::Integer(value) => {
|
||||
ensure_safe_integer(value)?;
|
||||
Ok(JsonValue::Integer(value))
|
||||
}
|
||||
JsonValue::Object(members) => {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for member in members {
|
||||
if !names.insert(member.name.as_str()) {
|
||||
return Err(CodecError::new(format!(
|
||||
"duplicate JSON member `{}`",
|
||||
member.name
|
||||
))
|
||||
.at(member.name.clone()));
|
||||
}
|
||||
validate_json(&member.value).map_err(|error| error.at(member.name.clone()))?;
|
||||
}
|
||||
Ok(())
|
||||
Value::Number(value) => {
|
||||
ensure_finite(value)?;
|
||||
Ok(JsonValue::Number(value))
|
||||
}
|
||||
JsonValue::Null | JsonValue::Boolean(_) | JsonValue::String(_) => Ok(()),
|
||||
Value::String(value) => Ok(JsonValue::String(value)),
|
||||
Value::Bytes(_) => Err(CodecError::new("bytes are not valid inside JSON")),
|
||||
Value::List(values) => values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| decode_json(value).map_err(|error| error.at(index.to_string())))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Array),
|
||||
Value::Record(fields) => fields
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
decode_json(value)
|
||||
.map(|value| JsonMember {
|
||||
name: name.clone(),
|
||||
value,
|
||||
})
|
||||
.map_err(|error| error.at(name))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(JsonValue::Object),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: WipType> WipType for Vec<T> {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::List(Box::new(T::type_expr()))
|
||||
TypeExpr::List {
|
||||
items: Box::new(T::type_expr()),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
@@ -513,37 +790,31 @@ impl<T: WipType> WipType for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
impl WipType for Entry {
|
||||
fn type_expr() -> TypeExpr {
|
||||
TypeExpr::Entry {
|
||||
key: Box::new(K::type_expr()),
|
||||
value: Box::new(V::type_expr()),
|
||||
}
|
||||
TypeExpr::Entry
|
||||
}
|
||||
|
||||
fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
|
||||
K::collect_declarations(declarations);
|
||||
V::collect_declarations(declarations);
|
||||
}
|
||||
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||
|
||||
fn encode(self) -> Result<Value, CodecError> {
|
||||
Ok(Value::Entry {
|
||||
key: Box::new(self.key.encode().map_err(|error| error.at("key"))?),
|
||||
value: Box::new(self.value.encode().map_err(|error| error.at("value"))?),
|
||||
})
|
||||
validate_entry_path(&self.0)?;
|
||||
Ok(Value::String(self.0))
|
||||
}
|
||||
|
||||
fn decode(value: Value) -> Result<Self, CodecError> {
|
||||
let Value::Entry { key, value } = value else {
|
||||
return Err(CodecError::expected("entry", &value));
|
||||
let Value::String(path) = value else {
|
||||
return Err(CodecError::expected("entry path string", &value));
|
||||
};
|
||||
Ok(Self {
|
||||
key: K::decode(*key).map_err(|error| error.at("key"))?,
|
||||
value: V::decode(*value).map_err(|error| error.at("value"))?,
|
||||
})
|
||||
Self::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_entry_path(path: &str) -> Result<(), CodecError> {
|
||||
wip_protocol::validate_path(path)
|
||||
.map_err(|error| CodecError::new(format!("invalid canonical Worldspace path: {error}")))
|
||||
}
|
||||
|
||||
/// Implementation details used by code emitted from the facade's macros.
|
||||
///
|
||||
/// These APIs are public only because macro expansions execute in the
|
||||
@@ -551,12 +822,9 @@ impl<K: WipType, V: WipType> WipType for Entry<K, V> {
|
||||
/// and are not intended for direct use.
|
||||
#[doc(hidden)]
|
||||
pub mod __private {
|
||||
use std::collections::HashSet;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_protocol::{
|
||||
InterfaceDescriptor, NamedValue, ObjectId, OperationCall, OperationTarget, TypeDeclaration,
|
||||
ValidationError, Value,
|
||||
};
|
||||
use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};
|
||||
|
||||
use crate::{CodecError, Documentation, WipType};
|
||||
|
||||
@@ -591,16 +859,9 @@ pub mod __private {
|
||||
pub fn validate_arguments(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
arguments: &[NamedValue],
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(&OperationCall {
|
||||
target: OperationTarget {
|
||||
object: ObjectId("<typed-dispatch>".into()),
|
||||
interface: descriptor.name.clone(),
|
||||
operation: operation.into(),
|
||||
},
|
||||
arguments: arguments.to_vec(),
|
||||
})
|
||||
descriptor.validate_arguments(operation, arguments)
|
||||
}
|
||||
|
||||
/// Builds a codec error for a generated structural mismatch.
|
||||
@@ -618,22 +879,13 @@ pub mod __private {
|
||||
|
||||
/// Decoder for a protocol record or operation's named argument collection.
|
||||
pub struct RecordDecoder {
|
||||
fields: Vec<NamedValue>,
|
||||
seen: HashSet<String>,
|
||||
fields: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
impl RecordDecoder {
|
||||
/// Starts decoding record fields or named operation arguments and
|
||||
/// rejects duplicate names.
|
||||
pub fn new(fields: Vec<NamedValue>) -> Result<Self, CodecError> {
|
||||
let mut seen = HashSet::new();
|
||||
for field in &fields {
|
||||
if !seen.insert(field.name.clone()) {
|
||||
return Err(CodecError::new(format!("duplicate field `{}`", field.name))
|
||||
.at(field.name.clone()));
|
||||
}
|
||||
}
|
||||
Ok(Self { fields, seen })
|
||||
/// Starts decoding record fields or named operation arguments.
|
||||
pub fn new(fields: BTreeMap<String, Value>) -> Self {
|
||||
Self { fields }
|
||||
}
|
||||
|
||||
/// Decodes a required field.
|
||||
@@ -654,23 +906,15 @@ pub mod __private {
|
||||
|
||||
/// Rejects any fields that were not consumed by generated code.
|
||||
pub fn finish(self) -> Result<(), CodecError> {
|
||||
if let Some(field) = self.fields.first() {
|
||||
Err(CodecError::new(format!("unknown field `{}`", field.name))
|
||||
.at(field.name.clone()))
|
||||
if let Some(name) = self.fields.keys().next() {
|
||||
Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, name: &str) -> Option<Value> {
|
||||
let index = self.fields.iter().position(|field| field.name == name)?;
|
||||
Some(self.fields.remove(index).value)
|
||||
}
|
||||
|
||||
/// Returns the set of names supplied to this decoder.
|
||||
#[allow(dead_code)]
|
||||
pub fn supplied_names(&self) -> &HashSet<String> {
|
||||
&self.seen
|
||||
self.fields.remove(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use wip_interface::wip_protocol::{
|
||||
EnumDeclaration, JsonMember, JsonValue, NamedValue, RecordDeclaration, TypeDeclaration,
|
||||
TypeExpr, UnionDeclaration, Value,
|
||||
};
|
||||
use wip_interface::{Bytes, Entry, WipType};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, Value};
|
||||
use wip_interface::{Bytes, Entry, JsonMember, JsonValue, WipType};
|
||||
|
||||
/// A request record.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -11,8 +10,8 @@ struct Request {
|
||||
title: String,
|
||||
/// Optional priority.
|
||||
priority: Option<i32>,
|
||||
/// Related entries.
|
||||
related: Vec<Entry<String, bool>>,
|
||||
/// Related Worldspace entries.
|
||||
related: Vec<Entry>,
|
||||
/// Opaque bytes.
|
||||
body: Bytes,
|
||||
/// Arbitrary metadata.
|
||||
@@ -38,33 +37,53 @@ struct Receipt {
|
||||
/// Application-level publication outcome.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
enum PublishOutcome {
|
||||
/// Work has not completed and carries no payload.
|
||||
Pending,
|
||||
/// Application success.
|
||||
Published(Receipt),
|
||||
/// Domain rejection, not a host failure.
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
fn field<'a>(record: &'a BTreeMap<String, Value>, name: &str) -> &'a Value {
|
||||
record
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("missing `{name}`"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_values_round_trip() {
|
||||
fn primitive_unit_record_list_entry_and_json_values_round_trip() {
|
||||
assert_eq!(().encode().unwrap(), Value::Unit);
|
||||
assert_eq!(<()>::decode(Value::Unit).unwrap(), ());
|
||||
assert_eq!(<()>::type_expr(), TypeExpr::Unit);
|
||||
|
||||
let request = Request {
|
||||
title: "hello".into(),
|
||||
priority: None,
|
||||
related: vec![Entry {
|
||||
key: "/articles/1".into(),
|
||||
value: true,
|
||||
}],
|
||||
related: vec![Entry::new("/articles/1").unwrap()],
|
||||
body: Bytes(vec![1, 2, 3]),
|
||||
metadata: JsonValue::Object(vec![JsonMember {
|
||||
name: "source".into(),
|
||||
value: JsonValue::String("test".into()),
|
||||
value: JsonValue::Array(vec![JsonValue::String("test".into()), JsonValue::Null]),
|
||||
}]),
|
||||
};
|
||||
|
||||
let encoded = request.clone().encode().unwrap();
|
||||
let Value::Record(fields) = &encoded else {
|
||||
panic!("record derive must encode a protocol record")
|
||||
panic!("record derive must encode a raw protocol record")
|
||||
};
|
||||
assert!(fields.iter().all(|field| field.name != "priority"));
|
||||
assert!(!fields.contains_key("priority"));
|
||||
assert_eq!(
|
||||
field(fields, "related"),
|
||||
&Value::List(vec![Value::String("/articles/1".into())])
|
||||
);
|
||||
assert_eq!(
|
||||
field(fields, "metadata"),
|
||||
&Value::Record(BTreeMap::from([(
|
||||
"source".into(),
|
||||
Value::List(vec![Value::String("test".into()), Value::Unit]),
|
||||
)]))
|
||||
);
|
||||
assert_eq!(Request::decode(encoded).unwrap(), request);
|
||||
|
||||
let number = 42.5_f64;
|
||||
@@ -77,92 +96,136 @@ fn supported_values_round_trip() {
|
||||
f32::decode(narrow_number.encode().unwrap()).unwrap(),
|
||||
narrow_number
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enums_are_strings_and_unions_are_discriminated_records() {
|
||||
for color in [Color::Red, Color::Blue] {
|
||||
let encoded = color.clone().encode().unwrap();
|
||||
let decoded = Color::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, color);
|
||||
assert!(matches!(encoded, Value::String(_)));
|
||||
assert_eq!(Color::decode(encoded).unwrap(), color);
|
||||
}
|
||||
|
||||
let pending = PublishOutcome::Pending.encode().unwrap();
|
||||
assert_eq!(
|
||||
pending,
|
||||
Value::Record(BTreeMap::from([(
|
||||
UNION_CASE_FIELD.into(),
|
||||
Value::String("Pending".into()),
|
||||
)]))
|
||||
);
|
||||
|
||||
let published = PublishOutcome::Published(Receipt { number: 7 })
|
||||
.encode()
|
||||
.unwrap();
|
||||
let Value::Record(fields) = &published else {
|
||||
panic!("union must encode as a record")
|
||||
};
|
||||
assert_eq!(
|
||||
fields.get(UNION_CASE_FIELD),
|
||||
Some(&Value::String("Published".into()))
|
||||
);
|
||||
assert!(matches!(
|
||||
fields.get(UNION_VALUE_FIELD),
|
||||
Some(Value::Record(_))
|
||||
));
|
||||
|
||||
for outcome in [
|
||||
PublishOutcome::Pending,
|
||||
PublishOutcome::Published(Receipt { number: 7 }),
|
||||
PublishOutcome::Rejected("policy".into()),
|
||||
] {
|
||||
let encoded = outcome.clone().encode().unwrap();
|
||||
let decoded = PublishOutcome::decode(encoded).unwrap();
|
||||
assert_eq!(decoded, outcome);
|
||||
assert_eq!(PublishOutcome::decode(encoded).unwrap(), outcome);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_declarations_include_docs_optionality_and_dependencies() {
|
||||
fn derived_declarations_use_canonical_named_type_expressions() {
|
||||
let mut declarations = Vec::new();
|
||||
Request::collect_declarations(&mut declarations);
|
||||
Color::collect_declarations(&mut declarations);
|
||||
PublishOutcome::collect_declarations(&mut declarations);
|
||||
|
||||
let TypeDeclaration::Record(RecordDeclaration {
|
||||
documentation,
|
||||
fields,
|
||||
..
|
||||
}) = &declarations[0]
|
||||
else {
|
||||
let request = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name == "Request")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request.documentation.as_ref().unwrap().summary,
|
||||
"A request record."
|
||||
);
|
||||
let TypeExpr::Record { fields } = &request.definition else {
|
||||
panic!("Request must be a record declaration")
|
||||
};
|
||||
assert_eq!(documentation.as_ref().unwrap().summary, "A request record.");
|
||||
assert_eq!(
|
||||
fields[0].documentation.as_ref().unwrap().summary,
|
||||
"Required title."
|
||||
);
|
||||
assert!(!fields[0].optional);
|
||||
assert!(fields[1].optional);
|
||||
assert_eq!(fields[1].ty, TypeExpr::Integer);
|
||||
assert!(fields[0].required);
|
||||
assert!(!fields[1].required);
|
||||
assert_eq!(fields[1].r#type, TypeExpr::Integer);
|
||||
assert_eq!(
|
||||
fields[2].ty,
|
||||
TypeExpr::List(Box::new(TypeExpr::Entry {
|
||||
key: Box::new(TypeExpr::String),
|
||||
value: Box::new(TypeExpr::Boolean),
|
||||
}))
|
||||
fields[2].r#type,
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Entry),
|
||||
}
|
||||
);
|
||||
|
||||
let color = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "Color")
|
||||
.find(|declaration| declaration.name == "Color")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Enum(EnumDeclaration { variants, .. }) = color else {
|
||||
let TypeExpr::Enum { cases } = &color.definition else {
|
||||
panic!("Color must be an enum declaration")
|
||||
};
|
||||
assert_eq!(
|
||||
variants[0].documentation.as_ref().unwrap().summary,
|
||||
cases[0].documentation.as_ref().unwrap().summary,
|
||||
"Warm red."
|
||||
);
|
||||
|
||||
let outcome = declarations
|
||||
.iter()
|
||||
.find(|declaration| declaration.name() == "PublishOutcome")
|
||||
.find(|declaration| declaration.name == "PublishOutcome")
|
||||
.unwrap();
|
||||
let TypeDeclaration::Union(UnionDeclaration { variants, .. }) = outcome else {
|
||||
let TypeExpr::Union { cases } = &outcome.definition else {
|
||||
panic!("PublishOutcome must be a union declaration")
|
||||
};
|
||||
assert_eq!(variants[0].ty, TypeExpr::Named("Receipt".into()));
|
||||
assert_eq!(cases[0].payload, None);
|
||||
assert_eq!(
|
||||
cases[1].payload,
|
||||
Some(TypeExpr::Named {
|
||||
name: "Receipt".into(),
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
declarations
|
||||
.iter()
|
||||
.any(|declaration| declaration.name() == "Receipt")
|
||||
.any(|declaration| declaration.name == "Receipt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_reject_invalid_boundaries() {
|
||||
fn codecs_reject_invalid_boundaries_and_json_bytes() {
|
||||
assert!(i64::MAX.encode().is_err());
|
||||
assert!(f64::NAN.encode().is_err());
|
||||
assert!(Request::decode(Value::Record(vec![])).is_err());
|
||||
assert!(Request::decode(Value::Record(BTreeMap::new())).is_err());
|
||||
assert!(
|
||||
Request::decode(Value::Record(vec![NamedValue {
|
||||
name: "unknown".into(),
|
||||
value: Value::String("value".into()),
|
||||
}]))
|
||||
Request::decode(Value::Record(BTreeMap::from([(
|
||||
"unknown".into(),
|
||||
Value::String("value".into()),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::String("Green".into())).is_err());
|
||||
assert!(Entry::new("articles/1").is_err());
|
||||
assert!(Entry::decode(Value::String("/articles/../1".into())).is_err());
|
||||
assert!(JsonValue::decode(Value::Bytes(vec![1])).is_err());
|
||||
assert!(
|
||||
JsonValue::decode(Value::Record(BTreeMap::from([(
|
||||
"nested".into(),
|
||||
Value::List(vec![Value::Bytes(vec![1])]),
|
||||
)])))
|
||||
.is_err()
|
||||
);
|
||||
assert!(Color::decode(Value::Enum("Green".into())).is_err());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
use wip_interface::wip_protocol::{NamedValue, TypeDeclaration, TypeExpr, Value};
|
||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||
use wip_interface::{
|
||||
DispatchError, DispatchPhase, EffectGuarantee, HostError, HostErrorKind, OperationResult,
|
||||
WipType, interface,
|
||||
};
|
||||
|
||||
/// Publication request.
|
||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||
@@ -36,7 +41,7 @@ pub trait Catalog {
|
||||
note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome>;
|
||||
|
||||
/// Checks connectivity without returning an application value.
|
||||
/// Checks connectivity without returning application data.
|
||||
fn ping(&self) -> OperationResult<()>;
|
||||
|
||||
/// Demonstrates a host/runtime failure.
|
||||
@@ -64,7 +69,10 @@ impl Catalog for AcceptingCatalog {
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
Err(HostError::new("backend unavailable"))
|
||||
Err(HostError::internal(
|
||||
"backend unavailable",
|
||||
EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,36 +96,49 @@ impl Catalog for RejectingCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
fn named(name: &str, value: Value) -> NamedValue {
|
||||
NamedValue {
|
||||
name: name.into(),
|
||||
value,
|
||||
struct PanickingCatalog;
|
||||
|
||||
impl Catalog for PanickingCatalog {
|
||||
fn publish(
|
||||
&self,
|
||||
_request: PublishRequest,
|
||||
_note: Option<String>,
|
||||
) -> OperationResult<PublishOutcome> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn ping(&self) -> OperationResult<()> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
|
||||
fn host_value(&self) -> OperationResult<String> {
|
||||
panic!("private panic payload")
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_arguments(with_note: bool) -> Vec<NamedValue> {
|
||||
let mut arguments = vec![named(
|
||||
"request",
|
||||
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||
let mut arguments = BTreeMap::from([(
|
||||
"request".into(),
|
||||
PublishRequest {
|
||||
title: "example".into(),
|
||||
}
|
||||
.encode()
|
||||
.unwrap(),
|
||||
)];
|
||||
)]);
|
||||
if with_note {
|
||||
arguments.push(named("note", Value::String("audit".into())));
|
||||
arguments.insert("note".into(), Value::String("audit".into()));
|
||||
}
|
||||
arguments
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
fn descriptor_is_canonical_and_generated_only_from_the_trait_declaration() {
|
||||
let first = CatalogDefinition::descriptor();
|
||||
let second = CatalogDefinition::descriptor();
|
||||
assert_eq!(first, second);
|
||||
first.validate().unwrap();
|
||||
|
||||
assert_eq!(first.name, "Catalog");
|
||||
assert_eq!(first.format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
first.documentation.as_ref().unwrap().summary,
|
||||
"Catalog editing capability."
|
||||
@@ -139,84 +160,110 @@ fn descriptor_is_generated_only_from_the_trait_declaration() {
|
||||
.summary,
|
||||
"Item to publish."
|
||||
);
|
||||
assert!(!publish.parameters[0].optional);
|
||||
assert!(publish.parameters[1].optional);
|
||||
assert!(publish.parameters[0].required);
|
||||
assert!(!publish.parameters[1].required);
|
||||
assert_eq!(
|
||||
publish
|
||||
.returns
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.summary,
|
||||
publish.returns.documentation.as_ref().unwrap().summary,
|
||||
"The application publication outcome."
|
||||
);
|
||||
assert_eq!(
|
||||
publish.returns.as_ref().unwrap().ty,
|
||||
TypeExpr::Named("PublishOutcome".into())
|
||||
publish.returns.r#type,
|
||||
TypeExpr::Named {
|
||||
name: "PublishOutcome".into(),
|
||||
}
|
||||
);
|
||||
assert!(first.operations[1].returns.is_none());
|
||||
assert_eq!(first.operations[1].returns.r#type, TypeExpr::Unit);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Record(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Record { .. }))
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.declarations
|
||||
.types
|
||||
.iter()
|
||||
.any(|declaration| matches!(declaration, TypeDeclaration::Union(_)))
|
||||
.any(|declaration| matches!(declaration.definition, TypeExpr::Union { .. }))
|
||||
);
|
||||
|
||||
// Both implementation types satisfy the same generated dispatch boundary;
|
||||
// neither can affect the descriptor shape.
|
||||
// Both implementation types satisfy one immutable generated definition;
|
||||
// implementation selection cannot contribute fields to the descriptor.
|
||||
fn accepts_definition<T: Catalog>(_: &T) {}
|
||||
accepts_definition(&AcceptingCatalog);
|
||||
accepts_definition(&RejectingCatalog);
|
||||
assert_eq!(CatalogDefinition::descriptor(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_argument_decoder_and_result_encoder_round_trip() {
|
||||
fn generated_argument_decoder_and_result_encoder_use_raw_values() {
|
||||
let decoded = CatalogPublishArguments::decode(publish_arguments(false)).unwrap();
|
||||
assert_eq!(decoded.request.title, "example");
|
||||
assert_eq!(decoded.note, None);
|
||||
|
||||
let encoded = CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let encoded =
|
||||
CatalogPublishArguments::encode_result(PublishOutcome::Rejected("domain".into())).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(encoded).unwrap(),
|
||||
PublishOutcome::Rejected("domain".into())
|
||||
);
|
||||
assert_eq!(
|
||||
CatalogPingArguments::encode_result(()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
||||
let value = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let value =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", publish_arguments(true)).unwrap();
|
||||
assert_eq!(
|
||||
PublishOutcome::decode(value).unwrap(),
|
||||
PublishOutcome::Published(true)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", vec![]).unwrap(),
|
||||
None
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "ping", BTreeMap::new()).unwrap(),
|
||||
Value::Unit
|
||||
);
|
||||
|
||||
let invalid = CatalogDefinition::dispatch(&AcceptingCatalog, "publish", vec![]).unwrap_err();
|
||||
let invalid =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||
assert_eq!(invalid.phase(), DispatchPhase::BeforeInvocation);
|
||||
assert_eq!(invalid.effect_guarantee(), None);
|
||||
|
||||
let host = CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", vec![]).unwrap_err();
|
||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
||||
let host =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(
|
||||
matches!(&host, DispatchError::Host(error) if error.message() == "backend unavailable")
|
||||
);
|
||||
assert_eq!(host.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(host.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
|
||||
let unknown = CatalogDefinition::dispatch(&AcceptingCatalog, "missing", vec![]).unwrap_err();
|
||||
let panic =
|
||||
CatalogDefinition::dispatch(&PanickingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(panic, DispatchError::Panic));
|
||||
assert_eq!(panic.phase(), DispatchPhase::AfterInvocation);
|
||||
assert_eq!(panic.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||
assert!(!panic.to_string().contains("private panic payload"));
|
||||
|
||||
let unknown =
|
||||
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_errors_require_a_typed_kind_and_effect_guarantee() {
|
||||
let internal = HostError::internal("x".repeat(4_096), EffectGuarantee::NotCommitted);
|
||||
assert_eq!(internal.kind(), HostErrorKind::Internal);
|
||||
assert_eq!(internal.effect_guarantee(), EffectGuarantee::NotCommitted);
|
||||
assert!(internal.message().len() <= 512);
|
||||
|
||||
let resource = HostError::resource_limit("deadline", EffectGuarantee::Unknown);
|
||||
assert_eq!(resource.kind(), HostErrorKind::ResourceLimitExceeded);
|
||||
assert_eq!(resource.effect_guarantee(), EffectGuarantee::Unknown);
|
||||
}
|
||||
|
||||
/// Operations whose distinct source names normalize to the same PascalCase.
|
||||
#[interface]
|
||||
pub trait DistinctOperations {
|
||||
@@ -245,12 +292,12 @@ fn distinct_operation_names_always_generate_distinct_public_items() {
|
||||
assert_eq!(descriptor.operations[0].name, "item");
|
||||
assert_eq!(descriptor.operations[1].name, "item_");
|
||||
|
||||
let first = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let second = DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", vec![])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let first =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item", BTreeMap::new())
|
||||
.unwrap();
|
||||
let second =
|
||||
DistinctOperationsDefinition::dispatch(&DistinctImplementation, "item_", BTreeMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(first, Value::String("item".into()));
|
||||
assert_eq!(second, Value::String("item_".into()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::interface;
|
||||
|
||||
#[interface]
|
||||
pub trait AsyncOperation {
|
||||
async fn status(&self) -> wip_interface::OperationResult<String>;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: async operations are not supported
|
||||
--> tests/ui/async_operation.rs:5:5
|
||||
|
|
||||
5 | async fn status(&self) -> wip_interface::OperationResult<String>;
|
||||
| ^^^^^
|
||||
@@ -0,0 +1,10 @@
|
||||
use wip_interface::interface;
|
||||
|
||||
#[interface]
|
||||
pub trait DefaultMethod {
|
||||
fn status(&self) -> wip_interface::OperationResult<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
error: WIP operation methods must not have a body
|
||||
--> tests/ui/default_method.rs:5:64
|
||||
|
|
||||
5 | fn status(&self) -> wip_interface::OperationResult<String> {
|
||||
| ________________________________________________________________^
|
||||
6 | | Ok(String::new())
|
||||
7 | | }
|
||||
| |_____^
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
struct GenericDto<T> {
|
||||
value: T,
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: generic DTOs are not supported by `WipType`
|
||||
--> tests/ui/generic_dto.rs:4:18
|
||||
|
|
||||
4 | struct GenericDto<T> {
|
||||
| ^^^
|
||||
@@ -1,9 +1,9 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
enum MixedEnum {
|
||||
enum UnsupportedEnum {
|
||||
Empty,
|
||||
Payload(String),
|
||||
Payload { value: String },
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: a `WipType` enum must contain either only unit variants or only single-field tuple variants; mixed and named-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:4:1
|
||||
error: a `WipType` enum must contain unit variants and/or single-field tuple variants; named-field and multi-field variants are unsupported
|
||||
--> tests/ui/mixed_enum.rs:6:5
|
||||
|
|
||||
4 | enum MixedEnum {
|
||||
| ^^^^
|
||||
6 | Payload { value: String },
|
||||
| ^^^^^^^
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use wip_interface::WipType;
|
||||
|
||||
#[derive(WipType)]
|
||||
struct NestedOption {
|
||||
values: Vec<Option<String>>,
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
error: `Option<T>` must appear directly as the DTO field type
|
||||
--> tests/ui/nested_option.rs:5:13
|
||||
|
|
||||
5 | values: Vec<Option<String>>,
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
@@ -4,16 +4,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0277]: the trait bound `(std::string::String, std::string::String): WipType` is not satisfied
|
||||
--> tests/ui/unsupported_type.rs:5:26
|
||||
@@ -24,16 +19,11 @@ error[E0277]: the trait bound `(std::string::String, std::string::String): WipTy
|
||||
5 | fn load(&self, pair: (String, String)) -> OperationResult<String>;
|
||||
| ^^^^^^^^^^^^^^^^ the trait `WipType` is not implemented for `(std::string::String, std::string::String)`
|
||||
|
|
||||
= help: the following other types implement trait `WipType`:
|
||||
JsonValue
|
||||
Vec<T>
|
||||
bool
|
||||
f32
|
||||
f64
|
||||
i128
|
||||
i16
|
||||
i32
|
||||
and $N others
|
||||
help: the trait `WipType` is implemented for `()`
|
||||
--> src/lib.rs
|
||||
|
|
||||
| impl WipType for () {
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
note: required by a bound in `wip_interface::__private::RecordDecoder::required`
|
||||
--> src/lib.rs
|
||||
|
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
[package]
|
||||
name = "wip-protocol"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Transport-independent logical model and validation for WIP"
|
||||
license = "MIT OR Apache-2.0"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/wip-protocol"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,23 @@
|
||||
# wip-protocol
|
||||
|
||||
Transport-independent logical types and validation for the Web Interface Protocol (WIP).
|
||||
|
||||
This crate defines the canonical Object and Interface Descriptor models, the three Core interaction request and response types, schema-neutral operation `Value`s, validators, protocol errors, and structural validation. It does not define an HTTP mapping, application DTOs, persistence, or network I/O.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-protocol = "0.1.0"
|
||||
```
|
||||
|
||||
Interface identity is an exact `InterfaceReference { scope, name }` pair.
|
||||
`scope` is a canonical absolute Worldspace path and `name` is nonempty Unicode.
|
||||
Use `validate()` for shape, `validate_for_path()` for ancestor-or-self placement,
|
||||
and Object/interaction validation at response boundaries. Fetching needs no
|
||||
target Object path. Fetch responses and interface call targets carry optional
|
||||
opaque string `scope_ref` metadata, not a third identity field. Descriptors do
|
||||
not embed identity. See the repository's [migration guide](../../MIGRATION.md)
|
||||
for the breaking Rust and HTTP wire changes and deferred consumer semantics.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-protocol) for the complete model and validation rules.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
@@ -62,7 +62,7 @@ pub enum PathSegment {
|
||||
Return,
|
||||
/// Object at a Worldspace path.
|
||||
Object(String),
|
||||
/// Child object in a tree response.
|
||||
/// Child object in an observation response.
|
||||
Child(String),
|
||||
}
|
||||
|
||||
@@ -143,8 +143,17 @@ pub enum ValidationErrorKind {
|
||||
},
|
||||
/// An object's ordered interface set contains a duplicate.
|
||||
DuplicateInterface {
|
||||
/// Duplicate opaque interface reference.
|
||||
reference: String,
|
||||
/// Duplicate structured interface reference.
|
||||
reference: crate::InterfaceReference,
|
||||
},
|
||||
/// The local interface name is empty.
|
||||
EmptyInterfaceName,
|
||||
/// A valid scope is not an ancestor-or-self of the target path.
|
||||
InterfaceScopeMismatch {
|
||||
/// Selected scope path.
|
||||
scope: String,
|
||||
/// Target Object path.
|
||||
path: String,
|
||||
},
|
||||
/// A string is not a canonical absolute Worldspace path.
|
||||
InvalidPath {
|
||||
@@ -163,24 +172,22 @@ pub enum ValidationErrorKind {
|
||||
/// Shared opaque object reference.
|
||||
reference: String,
|
||||
},
|
||||
/// A `fetch_tree` request used a zero limit.
|
||||
ZeroTreeLimit,
|
||||
/// A tree response exceeds the requested maximum depth.
|
||||
TreeDepthExceeded {
|
||||
/// Requested maximum depth.
|
||||
maximum: u32,
|
||||
/// An observation omitted children before reaching the requested depth.
|
||||
ChildrenMissingBeforeDepth {
|
||||
/// Node depth where children were required.
|
||||
depth: u32,
|
||||
},
|
||||
/// A tree response exceeds the requested maximum node count.
|
||||
TreeLimitExceeded {
|
||||
/// Requested maximum node count.
|
||||
limit: 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,
|
||||
/// Requested structured reference (boxed to keep validation errors small).
|
||||
expected: Box<crate::InterfaceReference>,
|
||||
/// Returned structured reference (boxed to keep validation errors small).
|
||||
actual: Box<crate::InterfaceReference>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -223,10 +230,27 @@ impl Display for ValidationError {
|
||||
|
||||
impl Error for ValidationError {}
|
||||
|
||||
/// Stable protocol failure code returned by a host or produced by a client.
|
||||
/// One core interaction whose failure codes form a closed set.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProtocolInteraction {
|
||||
/// Observe one object and its indexable descendants to a requested depth.
|
||||
Observe,
|
||||
/// Fetch one interface descriptor by its structured reference.
|
||||
FetchInterface,
|
||||
/// Invoke one operation on a path-targeted object.
|
||||
CallOperation,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// The request is structurally invalid before an operation descriptor is fixed.
|
||||
InvalidRequest,
|
||||
/// The target object is not published.
|
||||
NotFound,
|
||||
@@ -236,10 +260,8 @@ pub enum ProtocolErrorCode {
|
||||
InterfaceMismatch,
|
||||
/// The selected operation is not declared by the current interface.
|
||||
OperationNotFound,
|
||||
/// Supplied operation arguments are invalid.
|
||||
/// Supplied arguments do not match the fixed operation declaration.
|
||||
InvalidArguments,
|
||||
/// A host result does not satisfy the declaration.
|
||||
InvalidResult,
|
||||
/// The operation requires an object validator and none was supplied.
|
||||
ValidatorRequired,
|
||||
/// The supplied object validator does not match current state.
|
||||
@@ -251,9 +273,88 @@ pub enum ProtocolErrorCode {
|
||||
/// 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.
|
||||
/// 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.
|
||||
@@ -264,3 +365,15 @@ pub struct ProtocolError {
|
||||
/// Bounded human-readable diagnostic. Consumers must not branch on it.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Display for ProtocolError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"protocol failure ({:?}): {}",
|
||||
self.code, self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ProtocolError {}
|
||||
|
||||
@@ -11,15 +11,27 @@
|
||||
//! | Interface Descriptor | [`InterfaceDescriptor`] |
|
||||
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
|
||||
//! | Schema-neutral primitive/composite value | [`Value`] |
|
||||
//! | `fetch` | [`FetchRequest`] / [`FetchResponse`] |
|
||||
//! | `fetch_tree` | [`FetchTreeRequest`] / [`FetchTreeResponse`] |
|
||||
//! | `observe` | [`ObserveRequest`] / [`ObserveResponse`] |
|
||||
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
||||
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
||||
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
||||
//! | Stable failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
||||
//! | 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
|
||||
//! Interface refs use [`InterfaceReference`]; other metadata use strings/bytes in their
|
||||
//! fields. In particular, object refs are optional, operation targeting uses a
|
||||
//! path, and this crate defines no interaction that fetches an object by ref.
|
||||
//!
|
||||
@@ -35,13 +47,13 @@ mod model;
|
||||
mod validation;
|
||||
|
||||
pub use error::{
|
||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ValidationError,
|
||||
ValidationErrorKind, ValueKind,
|
||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
ValidationError, ValidationErrorKind, ValueKind,
|
||||
};
|
||||
pub use model::{
|
||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest, FetchTreeResponse,
|
||||
FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object, ObjectTreeNode,
|
||||
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceReference,
|
||||
InterfaceTarget, Object, ObjectObservation, ObserveRequest, ObserveResponse,
|
||||
OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
|
||||
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||
};
|
||||
|
||||
@@ -11,9 +11,49 @@ pub struct Documentation {
|
||||
pub details: Option<String>,
|
||||
}
|
||||
|
||||
/// An interface identified by an exact `(scope, name)` pair in one Worldspace.
|
||||
///
|
||||
/// Neither field is normalized, case-folded, URL-decoded, or split on display
|
||||
/// delimiters. Descriptor identity is external to the descriptor itself.
|
||||
///
|
||||
/// ```
|
||||
/// use wip_protocol::{FetchInterfaceRequest, InterfaceReference};
|
||||
/// let reference = InterfaceReference {
|
||||
/// scope: "/世::界/#".into(),
|
||||
/// name: "read::書く#λ".into(),
|
||||
/// };
|
||||
/// reference.validate_for_path("/世::界/#/item")?;
|
||||
/// // Fetching is independent of an Object target path.
|
||||
/// FetchInterfaceRequest { interface: reference }.validate()?;
|
||||
/// # Ok::<(), wip_protocol::ValidationError>(())
|
||||
/// ```
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct InterfaceReference {
|
||||
/// Canonical absolute Worldspace path of the interface's scope Object.
|
||||
pub scope: String,
|
||||
/// Nonempty Unicode local name, with no delimiter restrictions.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl InterfaceReference {
|
||||
/// Validates reference shape without requiring a target Object path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_interface_reference(self)
|
||||
}
|
||||
|
||||
/// Validates shape and that scope is an ancestor-or-self of `path`.
|
||||
///
|
||||
/// This is independent of indexability. A Host maps a valid reference's
|
||||
/// scope mismatch to `InterfaceMismatch` at the interface-selection stage,
|
||||
/// not to the earlier shape-validation `InvalidRequest` stage.
|
||||
pub fn validate_for_path(&self, path: &str) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_interface_scope(self, path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol projection currently published at one Worldspace path.
|
||||
///
|
||||
/// `name` is a path segment, `interfaces` is an ordered set of opaque interface
|
||||
/// `name` is a path segment, `interfaces` is an ordered set of structured interface
|
||||
/// references, `r#ref` is optional object identity, and `validator` is an
|
||||
/// independent optional observation precondition. In particular, neither the
|
||||
/// path nor `r#ref` is a mandatory object identifier.
|
||||
@@ -23,8 +63,8 @@ pub struct Object {
|
||||
pub name: String,
|
||||
/// Short public description of the object.
|
||||
pub description: Option<String>,
|
||||
/// Opaque interface references in host publication order.
|
||||
pub interfaces: Vec<String>,
|
||||
/// Structured interface references in host publication order.
|
||||
pub interfaces: Vec<InterfaceReference>,
|
||||
/// Optional opaque identity within one client-facing Worldspace.
|
||||
pub r#ref: Option<String>,
|
||||
/// Optional opaque validator for the object's observed state.
|
||||
@@ -218,57 +258,41 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Request for the object currently published at one path.
|
||||
/// Request for the object currently published at one path and its indexable descendants.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchRequest {
|
||||
/// Canonical absolute Worldspace path.
|
||||
pub struct ObserveRequest {
|
||||
/// Canonical absolute path of the observation root.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// Successful `fetch` response.
|
||||
pub type FetchResponse = Object;
|
||||
|
||||
/// Request for a bounded breadth-first object-tree observation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchTreeRequest {
|
||||
/// Canonical absolute path of the tree root.
|
||||
pub path: String,
|
||||
/// Maximum depth, where the requested object has depth zero.
|
||||
/// Maximum observed depth, where the requested object has depth zero.
|
||||
pub depth: u32,
|
||||
/// Maximum total node count, including the root. Must be nonzero.
|
||||
pub limit: u32,
|
||||
}
|
||||
|
||||
/// One node in a tree observation.
|
||||
/// One node in an object observation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObjectTreeNode {
|
||||
/// Object observed at this tree position.
|
||||
pub struct ObjectObservation {
|
||||
/// Object observed at this Worldspace position.
|
||||
pub object: Object,
|
||||
/// Direct children in host-defined traversal order.
|
||||
pub children: Vec<ObjectTreeNode>,
|
||||
/// Complete direct children when observed, or `None` at the requested depth boundary.
|
||||
pub children: Option<Vec<ObjectObservation>>,
|
||||
}
|
||||
|
||||
/// Successful `fetch_tree` response.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchTreeResponse {
|
||||
/// Observed tree rooted at the requested path.
|
||||
pub root: ObjectTreeNode,
|
||||
/// Whether public indexable children were omitted by depth or limit.
|
||||
pub truncated: bool,
|
||||
}
|
||||
/// Successful `observe` response.
|
||||
pub type ObserveResponse = ObjectObservation;
|
||||
|
||||
/// Request for the current descriptor of one opaque interface reference.
|
||||
/// Request for the current descriptor of one structured interface reference.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchInterfaceRequest {
|
||||
/// Opaque interface reference obtained from an object.
|
||||
pub interface: String,
|
||||
/// Structured interface reference obtained from an object.
|
||||
pub interface: InterfaceReference,
|
||||
}
|
||||
|
||||
/// Successful `fetch_interface` response.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchInterfaceResponse {
|
||||
/// Opaque interface reference corresponding to the request.
|
||||
pub interface: String,
|
||||
/// Structured interface reference corresponding to the request.
|
||||
pub interface: InterfaceReference,
|
||||
/// Optional opaque ref of the scope Object, not part of interface identity.
|
||||
pub scope_ref: Option<String>,
|
||||
/// Current validated descriptor.
|
||||
pub descriptor: InterfaceDescriptor,
|
||||
/// Optional opaque validator for this descriptor observation.
|
||||
@@ -287,8 +311,10 @@ pub struct Target {
|
||||
/// 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,
|
||||
/// Structured reference selected from the object's interface set.
|
||||
pub reference: InterfaceReference,
|
||||
/// Optional scope Object ref copied from the same interface observation.
|
||||
pub scope_ref: Option<String>,
|
||||
/// Optional validator copied from the interface observation.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
@@ -372,41 +398,51 @@ impl InterfaceDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchRequest {
|
||||
impl ObserveRequest {
|
||||
/// Validates the request path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_path(&self.path)
|
||||
}
|
||||
|
||||
/// Validates an object returned for this request.
|
||||
pub fn validate_response(&self, response: &FetchResponse) -> Result<(), ValidationError> {
|
||||
response.validate_at_path(&self.path)
|
||||
/// 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 FetchTreeRequest {
|
||||
/// Validates the request path and nonzero node limit.
|
||||
impl FetchInterfaceRequest {
|
||||
/// Validates reference shape; fetching an interface needs no target path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_fetch_tree_request(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchTreeResponse {
|
||||
/// Validates tree shape, names, depth, and node limit for `request`.
|
||||
pub fn validate_for(&self, request: &FetchTreeRequest) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_fetch_tree_response(self, request)
|
||||
self.interface.validate()
|
||||
}
|
||||
}
|
||||
|
||||
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`.
|
||||
/// Validates descriptor-independent request shape only.
|
||||
///
|
||||
/// Scope compatibility is deliberately deferred to interface selection so
|
||||
/// that `NotFound` precedes `InterfaceMismatch` at the Host boundary.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_call_shape(self)
|
||||
}
|
||||
|
||||
/// Validates this call's shape and descriptor-bound operation/arguments.
|
||||
/// Scope compatibility and membership require Host publication context.
|
||||
pub fn validate_with(&self, descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(self)
|
||||
}
|
||||
@@ -414,6 +450,9 @@ impl CallOperationRequest {
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, FetchTreeRequest,
|
||||
FetchTreeResponse, InterfaceDescriptor, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace,
|
||||
Object, ObjectTreeNode, PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD,
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
||||
InterfaceReference, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace, Object,
|
||||
ObjectObservation, ObserveRequest, PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD,
|
||||
UNION_VALUE_FIELD, ValidationError, ValidationErrorKind, Value, ValueKind,
|
||||
};
|
||||
|
||||
@@ -11,8 +11,13 @@ pub(crate) fn validate_object(object: &Object) -> Result<(), ValidationError> {
|
||||
validate_object_name(&object.name, true)?;
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
for interface in &object.interfaces {
|
||||
if !seen.insert(interface.as_str()) {
|
||||
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||
interface.validate().map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Index(index))
|
||||
.prepend(PathSegment::Field("interfaces".into()))
|
||||
})?;
|
||||
if !seen.insert(interface) {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::DuplicateInterface {
|
||||
reference: interface.clone(),
|
||||
@@ -51,6 +56,14 @@ pub(crate) fn validate_object_at_path(object: &Object, path: &str) -> Result<(),
|
||||
.next()
|
||||
.expect("non-root path has a segment")
|
||||
};
|
||||
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||
interface.validate_for_path(path).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Index(index))
|
||||
.prepend(PathSegment::Field("interfaces".into()))
|
||||
.prepend(PathSegment::Object(path.to_owned()))
|
||||
})?;
|
||||
}
|
||||
if object.name == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -106,6 +119,54 @@ pub(crate) fn validate_path(path: &str) -> Result<(), ValidationError> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_interface_reference(
|
||||
reference: &InterfaceReference,
|
||||
) -> Result<(), ValidationError> {
|
||||
validate_path(&reference.scope)
|
||||
.map_err(|error| error.prepend(PathSegment::Field("scope".into())))?;
|
||||
if reference.name.is_empty() {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::EmptyInterfaceName)
|
||||
.prepend(PathSegment::Field("name".into())),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_interface_scope(
|
||||
reference: &InterfaceReference,
|
||||
path: &str,
|
||||
) -> Result<(), ValidationError> {
|
||||
reference.validate()?;
|
||||
validate_path(path)?;
|
||||
let scope = reference.scope.as_str();
|
||||
if scope == "/"
|
||||
|| path == scope
|
||||
|| path
|
||||
.strip_prefix(scope)
|
||||
.is_some_and(|rest| rest.starts_with('/'))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new(
|
||||
ValidationErrorKind::InterfaceScopeMismatch {
|
||||
scope: reference.scope.clone(),
|
||||
path: path.to_owned(),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_call_shape(request: &CallOperationRequest) -> Result<(), ValidationError> {
|
||||
validate_path(&request.target.path)
|
||||
.map_err(|error| error.prepend(PathSegment::Field("target".into())))?;
|
||||
request.interface.reference.validate().map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Field("reference".into()))
|
||||
.prepend(PathSegment::Field("interface".into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_descriptor(descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||
let declarations = declaration_map(descriptor)?;
|
||||
|
||||
@@ -582,8 +643,7 @@ pub(crate) fn validate_call(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
request: &CallOperationRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
validate_path(&request.target.path)
|
||||
.map_err(|error| error.prepend(PathSegment::Field("target".into())))?;
|
||||
request.validate()?;
|
||||
validate_arguments(descriptor, &request.operation, &request.arguments)
|
||||
}
|
||||
|
||||
@@ -604,60 +664,38 @@ fn find_operation<'a>(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_fetch_tree_request(
|
||||
request: &FetchTreeRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
validate_path(&request.path)?;
|
||||
if request.limit == 0 {
|
||||
Err(ValidationError::new(ValidationErrorKind::ZeroTreeLimit))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_fetch_tree_response(
|
||||
response: &FetchTreeResponse,
|
||||
request: &FetchTreeRequest,
|
||||
pub(crate) fn validate_observe_response(
|
||||
response: &ObjectObservation,
|
||||
request: &ObserveRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
request.validate()?;
|
||||
let mut node_count = 0_u32;
|
||||
validate_tree_node(
|
||||
&response.root,
|
||||
&request.path,
|
||||
0,
|
||||
request.depth,
|
||||
request.limit,
|
||||
&mut node_count,
|
||||
)
|
||||
validate_observation_node(response, &request.path, 0, request.depth)
|
||||
}
|
||||
|
||||
fn validate_tree_node(
|
||||
node: &ObjectTreeNode,
|
||||
fn validate_observation_node(
|
||||
node: &ObjectObservation,
|
||||
path: &str,
|
||||
depth: u32,
|
||||
maximum_depth: u32,
|
||||
limit: u32,
|
||||
node_count: &mut u32,
|
||||
) -> Result<(), ValidationError> {
|
||||
if depth > maximum_depth {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::TreeDepthExceeded {
|
||||
maximum: maximum_depth,
|
||||
})
|
||||
.prepend(PathSegment::Object(path.to_owned())),
|
||||
);
|
||||
}
|
||||
*node_count = node_count.saturating_add(1);
|
||||
if *node_count > limit {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::TreeLimitExceeded { limit })
|
||||
.prepend(PathSegment::Object(path.to_owned())),
|
||||
);
|
||||
node.object.validate_at_path(path)?;
|
||||
|
||||
if depth == maximum_depth {
|
||||
if node.children.is_some() {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::ChildrenAtDepthBoundary { depth })
|
||||
.prepend(PathSegment::Object(path.to_owned())),
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
node.object.validate_at_path(path)?;
|
||||
let children = node.children.as_ref().ok_or_else(|| {
|
||||
ValidationError::new(ValidationErrorKind::ChildrenMissingBeforeDepth { depth })
|
||||
.prepend(PathSegment::Object(path.to_owned()))
|
||||
})?;
|
||||
let mut names = HashSet::new();
|
||||
for child in &node.children {
|
||||
for child in children {
|
||||
validate_object_name(&child.object.name, false)
|
||||
.map_err(|error| error.prepend(PathSegment::Child(child.object.name.clone())))?;
|
||||
if !names.insert(child.object.name.as_str()) {
|
||||
@@ -673,14 +711,7 @@ fn validate_tree_node(
|
||||
} else {
|
||||
format!("{path}/{}", child.object.name)
|
||||
};
|
||||
validate_tree_node(
|
||||
child,
|
||||
&child_path,
|
||||
depth.saturating_add(1),
|
||||
maximum_depth,
|
||||
limit,
|
||||
node_count,
|
||||
)?;
|
||||
validate_observation_node(child, &child_path, depth + 1, maximum_depth)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -689,11 +720,13 @@ pub(crate) fn validate_fetch_interface_response(
|
||||
response: &FetchInterfaceResponse,
|
||||
request: &FetchInterfaceRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
request.validate()?;
|
||||
response.interface.validate()?;
|
||||
if response.interface != request.interface {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::InterfaceResponseMismatch {
|
||||
expected: request.interface.clone(),
|
||||
actual: response.interface.clone(),
|
||||
expected: Box::new(request.interface.clone()),
|
||||
actual: Box::new(response.interface.clone()),
|
||||
})
|
||||
.prepend(PathSegment::Field("interface".into())),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::collections::BTreeMap;
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
||||
InterfaceReference, InterfaceTarget, Object, ObjectObservation, ObserveRequest,
|
||||
OperationDeclaration, ReturnDeclaration, Target, TypeExpr, ValidationErrorKind,
|
||||
};
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(path: &str, interfaces: Vec<InterfaceReference>) -> Object {
|
||||
Object {
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
description: None,
|
||||
interfaces,
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: wip_protocol::INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "run".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_is_segment_based_ancestor_or_self_not_indexability() {
|
||||
for (scope, path) in [
|
||||
("/", "/"),
|
||||
("/", "/a/b"),
|
||||
("/a", "/a"),
|
||||
("/a", "/a/b"),
|
||||
("/a/b", "/a/b/c"),
|
||||
] {
|
||||
reference(scope, "read").validate_for_path(path).unwrap();
|
||||
object(path, vec![reference(scope, "read")])
|
||||
.validate_at_path(path)
|
||||
.unwrap();
|
||||
}
|
||||
for (scope, path) in [
|
||||
("/a", "/ab"),
|
||||
("/a", "/ab/c"),
|
||||
("/a/b", "/a/c"),
|
||||
("/a/b", "/a"),
|
||||
("/a", "/"),
|
||||
] {
|
||||
assert!(matches!(
|
||||
reference(scope, "read")
|
||||
.validate_for_path(path)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
// Without the placement context, the Object/reference shape is valid.
|
||||
let object = object(path, vec![reference(scope, "read")]);
|
||||
object.validate().unwrap();
|
||||
assert!(matches!(
|
||||
object.validate_at_path(path).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_validation_does_not_normalize_or_parse_fields() {
|
||||
for scope in ["", "relative", "//a", "/a/", "/a//b", "/a/./b", "/a/../b"] {
|
||||
let reference = reference(scope, "read");
|
||||
assert!(matches!(
|
||||
reference.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::InvalidPath { .. }
|
||||
));
|
||||
assert!(
|
||||
FetchInterfaceRequest {
|
||||
interface: reference.clone()
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(object("/a", vec![reference]).validate().is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
reference("/", "").validate().unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
for name in [".", "..", "a/b", "::", "#", "読み::書き#λ", "e\u{301}"] {
|
||||
let reference = reference("/世::界/#/%2F", name);
|
||||
reference.validate().unwrap();
|
||||
assert_eq!(reference.name, name);
|
||||
assert_eq!(reference.scope, "/世::界/#/%2F");
|
||||
}
|
||||
assert_ne!(reference("/", "é"), reference("/", "e\u{301}"));
|
||||
assert_ne!(reference("/A", "read"), reference("/a", "read"));
|
||||
assert_ne!(reference("/%61", "read"), reference("/a", "read"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_membership_and_correlation_use_complete_pair() {
|
||||
let root = reference("/", "read");
|
||||
let scoped = reference("/a", "read");
|
||||
let mut object = object("/a", vec![root.clone(), scoped.clone()]);
|
||||
object.validate_at_path("/a").unwrap();
|
||||
assert!(object.interfaces.contains(&scoped));
|
||||
assert!(!object.interfaces.contains(&reference("/b", "read")));
|
||||
object.interfaces.push(root.clone());
|
||||
assert_eq!(
|
||||
object.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateInterface {
|
||||
reference: root.clone()
|
||||
}
|
||||
);
|
||||
let request = FetchInterfaceRequest { interface: root };
|
||||
let mut response = FetchInterfaceResponse {
|
||||
interface: scoped,
|
||||
scope_ref: None,
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
response.validate_for(&request).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceResponseMismatch { .. }
|
||||
));
|
||||
response.interface = request.interface.clone();
|
||||
for scope_ref in [None, Some(String::new()), Some("opaque::世界#/%".into())] {
|
||||
response.scope_ref = scope_ref;
|
||||
response.validate_for(&request).unwrap();
|
||||
}
|
||||
response.interface.name.clear();
|
||||
assert_eq!(
|
||||
response.validate_for(&request).unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_checks_scope_at_every_node_including_depth_boundary() {
|
||||
let request = ObserveRequest {
|
||||
path: "/a".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let mut response = ObjectObservation {
|
||||
object: object("/a", vec![reference("/a", "read")]),
|
||||
children: Some(vec![ObjectObservation {
|
||||
object: object("/a/b", vec![reference("/a/b", "read")]),
|
||||
children: None,
|
||||
}]),
|
||||
};
|
||||
request.validate_response(&response).unwrap();
|
||||
response.children.as_mut().unwrap()[0].object.interfaces[0].scope = "/a/c".into();
|
||||
assert!(matches!(
|
||||
request.validate_response(&response).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_needs_no_target_path_and_call_separates_shape_from_scope_selection() {
|
||||
let reference = reference("/some/unrelated/scope", "read");
|
||||
let fetch = FetchInterfaceRequest {
|
||||
interface: reference.clone(),
|
||||
};
|
||||
fetch.validate().unwrap();
|
||||
FetchInterfaceResponse {
|
||||
interface: reference.clone(),
|
||||
scope_ref: None,
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
}
|
||||
.validate_for(&fetch)
|
||||
.unwrap();
|
||||
let mut call = CallOperationRequest {
|
||||
target: Target {
|
||||
path: "/a".into(),
|
||||
validator: None,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference,
|
||||
scope_ref: Some("opaque".into()),
|
||||
validator: None,
|
||||
},
|
||||
operation: "run".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
};
|
||||
call.validate().unwrap();
|
||||
call.validate_with(&descriptor()).unwrap();
|
||||
// This stage is Host InterfaceMismatch, after NotFound, not shape InvalidRequest.
|
||||
assert!(matches!(
|
||||
call.interface
|
||||
.reference
|
||||
.validate_for_path(&call.target.path)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
call.interface.reference.name.clear();
|
||||
assert_eq!(
|
||||
call.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
assert_eq!(
|
||||
call.validate_with(&descriptor()).unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,20 @@ use std::collections::BTreeMap;
|
||||
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, CallOperationResponse, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
|
||||
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace,
|
||||
Object, ObjectTreeNode, OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError,
|
||||
ProtocolErrorCode, ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr,
|
||||
UnionCase, ValidationErrorKind, Value, ValueKind,
|
||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace, Object,
|
||||
ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration, PathSegment,
|
||||
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ProtocolResult, ReturnDeclaration,
|
||||
Target, TypeDeclaration, TypeExpr, UnionCase, ValidationErrorKind, Value, ValueKind,
|
||||
};
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||
Value::Record(
|
||||
entries
|
||||
@@ -135,7 +142,7 @@ fn object(name: &str) -> Object {
|
||||
Object {
|
||||
name: name.into(),
|
||||
description: Some(format!("Object {name}")),
|
||||
interfaces: vec!["catalog-v1".into(), "search-v2".into()],
|
||||
interfaces: vec![reference("/", "catalog-v1"), reference("/", "search-v2")],
|
||||
r#ref: Some("opaque-object-ref".into()),
|
||||
validator: Some(vec![1, 2, 3]),
|
||||
}
|
||||
@@ -146,16 +153,19 @@ fn object_fields_have_canonical_identity_and_ordered_set_semantics() {
|
||||
let object = object("article");
|
||||
object.validate().unwrap();
|
||||
object.validate_at_path("/articles/article").unwrap();
|
||||
assert_eq!(object.interfaces, ["catalog-v1", "search-v2"]);
|
||||
assert_eq!(
|
||||
object.interfaces,
|
||||
[reference("/", "catalog-v1"), reference("/", "search-v2")]
|
||||
);
|
||||
|
||||
let duplicate = Object {
|
||||
interfaces: vec!["catalog-v1".into(), "catalog-v1".into()],
|
||||
interfaces: vec![reference("/", "catalog-v1"), reference("/", "catalog-v1")],
|
||||
..object.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
duplicate.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateInterface {
|
||||
reference: "catalog-v1".into()
|
||||
reference: reference("/", "catalog-v1")
|
||||
}
|
||||
);
|
||||
|
||||
@@ -574,7 +584,8 @@ fn calls_validate_canonical_paths_named_arguments_and_unit_results() {
|
||||
validator: Some(vec![1]),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: "catalog-v1".into(),
|
||||
scope_ref: None,
|
||||
reference: reference("/", "catalog-v1"),
|
||||
validator: Some(vec![2]),
|
||||
},
|
||||
operation: "publish".into(),
|
||||
@@ -617,13 +628,26 @@ fn calls_validate_canonical_paths_named_arguments_and_unit_results() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
let fetch = FetchRequest {
|
||||
fn observe_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
let observe = ObserveRequest {
|
||||
path: "/articles/one".into(),
|
||||
depth: 0,
|
||||
};
|
||||
fetch.validate().unwrap();
|
||||
fetch.validate_response(&object("one")).unwrap();
|
||||
assert!(fetch.validate_response(&object("two")).is_err());
|
||||
observe.validate().unwrap();
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("one"),
|
||||
children: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("two"),
|
||||
children: None,
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
"",
|
||||
@@ -634,8 +658,9 @@ fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
"/a/../b",
|
||||
] {
|
||||
assert!(matches!(
|
||||
FetchRequest {
|
||||
path: invalid.into()
|
||||
ObserveRequest {
|
||||
path: invalid.into(),
|
||||
depth: 0,
|
||||
}
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
@@ -645,17 +670,18 @@ fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
}
|
||||
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: "catalog-v1".into(),
|
||||
interface: reference("/", "catalog-v1"),
|
||||
};
|
||||
let response = FetchInterfaceResponse {
|
||||
interface: "catalog-v1".into(),
|
||||
scope_ref: None,
|
||||
interface: reference("/", "catalog-v1"),
|
||||
descriptor: descriptor(),
|
||||
validator: Some(vec![9]),
|
||||
};
|
||||
response.validate_for(&request).unwrap();
|
||||
assert!(matches!(
|
||||
FetchInterfaceResponse {
|
||||
interface: "other".into(),
|
||||
interface: reference("/", "other"),
|
||||
..response
|
||||
}
|
||||
.validate_for(&request)
|
||||
@@ -666,61 +692,51 @@ fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_tree_dtos_validate_names_depth_limit_and_siblings() {
|
||||
let request = FetchTreeRequest {
|
||||
fn observe_response_validates_complete_children_and_depth_boundary() {
|
||||
let request = ObserveRequest {
|
||||
path: "/articles".into(),
|
||||
depth: 1,
|
||||
limit: 3,
|
||||
};
|
||||
let leaf = |name: &str| ObjectTreeNode {
|
||||
let leaf = |name: &str| ObjectObservation {
|
||||
object: object(name),
|
||||
children: vec![],
|
||||
children: None,
|
||||
};
|
||||
let response = FetchTreeResponse {
|
||||
root: ObjectTreeNode {
|
||||
object: object("articles"),
|
||||
children: vec![leaf("one"), leaf("two")],
|
||||
},
|
||||
truncated: false,
|
||||
let response = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![leaf("one"), leaf("two")]),
|
||||
};
|
||||
response.validate_for(&request).unwrap();
|
||||
request.validate_response(&response).unwrap();
|
||||
|
||||
let zero = FetchTreeRequest {
|
||||
limit: 0,
|
||||
..request.clone()
|
||||
let empty = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![]),
|
||||
};
|
||||
assert_eq!(
|
||||
zero.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::ZeroTreeLimit
|
||||
);
|
||||
request.validate_response(&empty).unwrap();
|
||||
|
||||
let shallow = FetchTreeRequest {
|
||||
let missing = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
request.validate_response(&missing).unwrap_err().kind,
|
||||
ValidationErrorKind::ChildrenMissingBeforeDepth { depth: 0 }
|
||||
));
|
||||
|
||||
let boundary = ObserveRequest {
|
||||
depth: 0,
|
||||
..request.clone()
|
||||
};
|
||||
assert!(matches!(
|
||||
response.validate_for(&shallow).unwrap_err().kind,
|
||||
ValidationErrorKind::TreeDepthExceeded { .. }
|
||||
boundary.validate_response(&response).unwrap_err().kind,
|
||||
ValidationErrorKind::ChildrenAtDepthBoundary { depth: 0 }
|
||||
));
|
||||
|
||||
let small = FetchTreeRequest {
|
||||
limit: 2,
|
||||
..request.clone()
|
||||
let duplicate = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![leaf("one"), leaf("one")]),
|
||||
};
|
||||
assert!(matches!(
|
||||
response.validate_for(&small).unwrap_err().kind,
|
||||
ValidationErrorKind::TreeLimitExceeded { .. }
|
||||
));
|
||||
|
||||
let duplicate = FetchTreeResponse {
|
||||
root: ObjectTreeNode {
|
||||
object: object("articles"),
|
||||
children: vec![leaf("one"), leaf("one")],
|
||||
},
|
||||
truncated: false,
|
||||
};
|
||||
assert!(matches!(
|
||||
duplicate.validate_for(&request).unwrap_err().kind,
|
||||
request.validate_response(&duplicate).unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::ChildObject,
|
||||
..
|
||||
@@ -729,24 +745,26 @@ fn fetch_tree_dtos_validate_names_depth_limit_and_siblings() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_result_and_every_canonical_error_code_are_available() {
|
||||
let codes = [
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::NotFound,
|
||||
ProtocolErrorCode::InterfaceNotFound,
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
ProtocolErrorCode::OperationNotFound,
|
||||
ProtocolErrorCode::InvalidArguments,
|
||||
ProtocolErrorCode::InvalidResult,
|
||||
ProtocolErrorCode::ValidatorRequired,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::PermissionDenied,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
];
|
||||
assert_eq!(codes.len(), 14);
|
||||
fn protocol_result_exposes_the_exact_canonical_wire_error_codes() {
|
||||
assert_eq!(
|
||||
ProtocolErrorCode::ALL,
|
||||
[
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::NotFound,
|
||||
ProtocolErrorCode::InterfaceNotFound,
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
ProtocolErrorCode::OperationNotFound,
|
||||
ProtocolErrorCode::InvalidArguments,
|
||||
ProtocolErrorCode::ValidatorRequired,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::PermissionDenied,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
]
|
||||
);
|
||||
|
||||
let failure: ProtocolResult<()> = ProtocolResult::Failure(ProtocolError {
|
||||
code: ProtocolErrorCode::InvalidArguments,
|
||||
@@ -758,3 +776,122 @@ fn protocol_result_and_every_canonical_error_code_are_available() {
|
||||
ProtocolResult::Success(Value::Unit)
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_allowed_codes(interaction: ProtocolInteraction, expected: &[ProtocolErrorCode]) {
|
||||
let actual: Vec<_> = ProtocolErrorCode::ALL
|
||||
.into_iter()
|
||||
.filter(|code| code.is_allowed_for(interaction))
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
for code in ProtocolErrorCode::ALL {
|
||||
assert_eq!(
|
||||
code.is_allowed_for(interaction),
|
||||
expected.contains(&code),
|
||||
"unexpected {code:?} validity for {interaction:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_error_codes_are_exhaustive() {
|
||||
assert_allowed_codes(
|
||||
ProtocolInteraction::Observe,
|
||||
&[
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::NotFound,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_interface_error_codes_are_exhaustive() {
|
||||
assert_allowed_codes(
|
||||
ProtocolInteraction::FetchInterface,
|
||||
&[
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::InterfaceNotFound,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_operation_error_codes_are_exhaustive() {
|
||||
assert_allowed_codes(
|
||||
ProtocolInteraction::CallOperation,
|
||||
&[
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::NotFound,
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
ProtocolErrorCode::OperationNotFound,
|
||||
ProtocolErrorCode::InvalidArguments,
|
||||
ProtocolErrorCode::ValidatorRequired,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::PermissionDenied,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_success_payloads_remain_client_local_validation_failures() {
|
||||
let observe = ObserveRequest {
|
||||
path: "/articles/one".into(),
|
||||
depth: 0,
|
||||
};
|
||||
assert!(matches!(
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("other"),
|
||||
children: None,
|
||||
})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::ObjectNameMismatch { .. }
|
||||
));
|
||||
|
||||
let interface_request = FetchInterfaceRequest {
|
||||
interface: reference("/", "catalog-v1"),
|
||||
};
|
||||
let mut invalid_descriptor = descriptor();
|
||||
invalid_descriptor
|
||||
.operations
|
||||
.push(invalid_descriptor.operations[0].clone());
|
||||
assert!(matches!(
|
||||
FetchInterfaceResponse {
|
||||
interface: interface_request.interface.clone(),
|
||||
scope_ref: None,
|
||||
descriptor: invalid_descriptor,
|
||||
validator: None,
|
||||
}
|
||||
.validate_for(&interface_request)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Operation,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
CallOperationResponse {
|
||||
result: Value::String("not a boolean".into()),
|
||||
validator: None,
|
||||
}
|
||||
.validate_for(&descriptor(), "publish")
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::TypeMismatch {
|
||||
expected: ValueKind::Boolean,
|
||||
actual: ValueKind::String,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "wip-public-api-example"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
wip-host.workspace = true
|
||||
wip-interface.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
wip-client.workspace = true
|
||||
wip-http.workspace = true
|
||||
@@ -0,0 +1,604 @@
|
||||
//! 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. Its dev-only conformance
|
||||
//! suite also uses the public Client and HTTP crates over real TCP HTTP to test
|
||||
//! scope replacement/deletion, optional refs, principal visibility and precondition
|
||||
//! precedence. Those dependencies are not required by the example executable.
|
||||
//!
|
||||
//! # 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. This demo registers explicit `catalog`, `audit`
|
||||
//! and `diagnostics` names at the service Object self-scope. A private [`Scope`]
|
||||
//! lifetime and coherent [`ScopeObservation`] bind fetch and call to that Object;
|
||||
//! successful calls carry its optional `scope_ref` identity precondition.
|
||||
//! Interface references are structured scope/name 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, Scope, ScopeObservation,
|
||||
Target, Validator, WipObject,
|
||||
};
|
||||
use wip_interface as wip;
|
||||
use wip_interface::WipType;
|
||||
use wip_protocol::{InterfaceReference, 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>>,
|
||||
/// Structured interface references published by the object, in exposure order.
|
||||
pub published_interfaces: Vec<InterfaceReference>,
|
||||
/// Self-scoped reference assigned to the catalog descriptor.
|
||||
pub catalog_interface_reference: InterfaceReference,
|
||||
/// Self-scoped reference assigned to the audit descriptor.
|
||||
pub audit_interface_reference: InterfaceReference,
|
||||
/// 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,
|
||||
/// Scope Object ref observed together with the catalog Descriptor.
|
||||
pub catalog_scope_ref: Option<String>,
|
||||
/// Scope Object ref observed together with the audit Descriptor.
|
||||
pub audit_scope_ref: Option<String>,
|
||||
/// Membership rejection when the supplied scope Object ref is stale.
|
||||
pub scope_mismatch: ProtocolErrorCode,
|
||||
/// 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 scope = Scope::new(OBJECT_PATH)?;
|
||||
let catalog = registry.register(
|
||||
&scope,
|
||||
"catalog",
|
||||
CatalogDefinition,
|
||||
Some(Validator::new(CATALOG_VALIDATOR)),
|
||||
)?;
|
||||
let audit = registry.register(&scope, "audit", AuditDefinition, None)?;
|
||||
let diagnostics = registry.register(&scope, "diagnostics", DiagnosticsDefinition, None)?;
|
||||
let provider = ApplicationProvider {
|
||||
scope,
|
||||
catalog: catalog.clone(),
|
||||
audit: audit.clone(),
|
||||
};
|
||||
|
||||
let object = provider.observe_object(OBJECT_PATH)?;
|
||||
let catalog_response = provider
|
||||
.fetch_interface(
|
||||
®istry,
|
||||
object
|
||||
.interfaces
|
||||
.first()
|
||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
||||
)?
|
||||
.protocol_response()?;
|
||||
let audit_response = provider
|
||||
.fetch_interface(
|
||||
®istry,
|
||||
object
|
||||
.interfaces
|
||||
.get(1)
|
||||
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
|
||||
)?
|
||||
.protocol_response()?;
|
||||
|
||||
let published = dispatch_publish(
|
||||
&provider,
|
||||
&catalog_response,
|
||||
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_response,
|
||||
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_response.interface,
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
let audit_status = dispatch_string(
|
||||
&provider,
|
||||
request(
|
||||
OBJECT_PATH,
|
||||
&audit_response.interface,
|
||||
audit_response.scope_ref.as_deref(),
|
||||
None,
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
),
|
||||
)?;
|
||||
|
||||
let host_error = provider
|
||||
.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
&catalog_response.interface,
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
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_response.interface,
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
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_response.interface,
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
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 {
|
||||
scope_ref: None,
|
||||
reference: diagnostics.reference().protocol_reference(),
|
||||
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().protocol_reference(),
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
None,
|
||||
"diagnostics",
|
||||
BTreeMap::new(),
|
||||
))
|
||||
.expect_err("registered but unexposed interface must not dispatch")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let interface_not_found = provider
|
||||
.fetch_interface(
|
||||
®istry,
|
||||
&InterfaceReference {
|
||||
scope: OBJECT_PATH.into(),
|
||||
name: "missing-interface".into(),
|
||||
},
|
||||
)
|
||||
.expect_err("unknown interface references must not resolve")
|
||||
.code;
|
||||
|
||||
let mut stale_scope = request(
|
||||
OBJECT_PATH,
|
||||
&catalog_response.interface,
|
||||
catalog_response.scope_ref.as_deref(),
|
||||
Some(CATALOG_VALIDATOR),
|
||||
"status",
|
||||
BTreeMap::new(),
|
||||
);
|
||||
stale_scope.interface.scope_ref = Some("replaced-service-instance".into());
|
||||
let scope_mismatch = provider
|
||||
.call_operation(stale_scope)
|
||||
.expect_err("stale scope identity must reject before operation dispatch")
|
||||
.protocol_error()
|
||||
.code;
|
||||
|
||||
let precedence_failure = provider
|
||||
.call_operation(CallRequest {
|
||||
target: Target {
|
||||
path: "relative/path".into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
scope_ref: None,
|
||||
reference: diagnostics.reference().protocol_reference(),
|
||||
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().protocol_reference(),
|
||||
audit_interface_reference: audit.reference().protocol_reference(),
|
||||
catalog_descriptor_format: catalog_response.descriptor.format,
|
||||
audit_descriptor_format: audit_response.descriptor.format,
|
||||
catalog_scope_ref: catalog_response.scope_ref,
|
||||
audit_scope_ref: audit_response.scope_ref,
|
||||
scope_mismatch,
|
||||
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: &wip_protocol::FetchInterfaceResponse,
|
||||
request_value: PublishRequest,
|
||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
||||
let encoded_request = request_value.encode()?;
|
||||
let result = provider.call_operation(request(
|
||||
OBJECT_PATH,
|
||||
&catalog.interface,
|
||||
catalog.scope_ref.as_deref(),
|
||||
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: &InterfaceReference,
|
||||
scope_ref: Option<&str>,
|
||||
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 {
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
reference: interface.clone(),
|
||||
validator: interface_validator.map(<[u8]>::to_vec),
|
||||
},
|
||||
operation: operation.into(),
|
||||
arguments,
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplicationProvider {
|
||||
scope: Scope,
|
||||
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;
|
||||
}
|
||||
// The immutable demo has no mutable backend actors. A real backend
|
||||
// must retain its transaction/lock across association and operation.
|
||||
let service = ApplicationService::new();
|
||||
let current = ScopeObservation::new(&self.scope, &service);
|
||||
let publication = PublishedObject::new(service)
|
||||
.bind_scope(current)
|
||||
.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,300 @@
|
||||
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 scope/name references"
|
||||
);
|
||||
assert_eq!(report.catalog_interface_reference.scope, "/article-service");
|
||||
assert_eq!(report.catalog_interface_reference.name, "catalog");
|
||||
assert_eq!(report.audit_interface_reference.scope, "/article-service");
|
||||
assert_eq!(report.audit_interface_reference.name, "audit");
|
||||
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
|
||||
assert_eq!(
|
||||
report.catalog_scope_ref.as_deref(),
|
||||
Some("article-service-instance")
|
||||
);
|
||||
assert_eq!(report.audit_scope_ref, report.catalog_scope_ref);
|
||||
assert_eq!(report.scope_mismatch, ProtocolErrorCode::InterfaceMismatch);
|
||||
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![root_reference("catalog-ref"), root_reference("audit-ref")],
|
||||
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,
|
||||
[root_reference("catalog-ref"), root_reference("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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scoped_dtos_keep_identity_binding_and_validators_separate() {
|
||||
// Exact literals/destructuring guard the public Rust contract, including
|
||||
// omission of refs rather than requiring a fabricated identity.
|
||||
let reference = wip_protocol::InterfaceReference {
|
||||
scope: "/article-service".into(),
|
||||
name: "catalog::read#raw".into(),
|
||||
};
|
||||
let request = wip_protocol::FetchInterfaceRequest {
|
||||
interface: reference.clone(),
|
||||
};
|
||||
request.validate().unwrap();
|
||||
let wip_protocol::FetchInterfaceResponse {
|
||||
interface,
|
||||
scope_ref,
|
||||
descriptor,
|
||||
validator,
|
||||
} = wip_protocol::FetchInterfaceResponse {
|
||||
interface: reference.clone(),
|
||||
scope_ref: None,
|
||||
descriptor: CatalogDefinition::descriptor(),
|
||||
validator: None,
|
||||
};
|
||||
let target = wip_protocol::InterfaceTarget {
|
||||
reference: interface,
|
||||
scope_ref,
|
||||
validator,
|
||||
};
|
||||
assert_eq!(target.reference, reference);
|
||||
assert!(target.scope_ref.is_none());
|
||||
assert!(target.validator.is_none());
|
||||
assert_eq!(descriptor.format, INTERFACE_FORMAT_V1);
|
||||
}
|
||||
|
||||
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: "/".into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
//! External-style consumer: a transactional provider, real TCP HTTP, and Client.
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use wip_client::{
|
||||
CallOutcome, Client, ClientLimits, Completion, ObservationState, SecurityContext,
|
||||
};
|
||||
use wip_host::{
|
||||
ExecutionContext, InterfaceRegistry, ObjectProvider, ProviderResult, PublishedObject,
|
||||
RegisteredInterface, Scope, ScopeObservation, Validator, WipObject,
|
||||
};
|
||||
use wip_http::{http, *};
|
||||
use wip_interface as wip;
|
||||
use wip_protocol::{InterfaceReference, ObjectObservation, ProtocolErrorCode, ProtocolInteraction};
|
||||
|
||||
#[wip::interface]
|
||||
pub trait Status {
|
||||
fn status(&self) -> wip::OperationResult<String>;
|
||||
fn uncertain(&self) -> wip::OperationResult<String>;
|
||||
}
|
||||
|
||||
struct Service {
|
||||
name: String,
|
||||
reference: Option<String>,
|
||||
validator: Validator,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
impl WipObject for Service {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn reference(&self) -> Option<&str> {
|
||||
self.reference.as_deref()
|
||||
}
|
||||
fn validator(&self) -> Option<&Validator> {
|
||||
Some(&self.validator)
|
||||
}
|
||||
}
|
||||
impl Status for Service {
|
||||
fn status(&self) -> wip::OperationResult<String> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(self.name.clone())
|
||||
}
|
||||
fn uncertain(&self) -> wip::OperationResult<String> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
Err(wip::HostError::internal(
|
||||
"commit acknowledgement lost",
|
||||
wip::EffectGuarantee::Unknown,
|
||||
))
|
||||
}
|
||||
}
|
||||
struct Publication {
|
||||
scope: Scope,
|
||||
api: RegisteredInterface<StatusDefinition>,
|
||||
reference: Option<String>,
|
||||
}
|
||||
struct State {
|
||||
registry: InterfaceRegistry,
|
||||
root: Publication,
|
||||
service: Option<Publication>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
impl State {
|
||||
fn new(reference: Option<&str>) -> Self {
|
||||
let mut registry = InterfaceRegistry::new();
|
||||
let scope = Scope::new("/").unwrap();
|
||||
let root = Publication {
|
||||
api: registry
|
||||
.register(&scope, "status", StatusDefinition, None)
|
||||
.unwrap(),
|
||||
scope,
|
||||
reference: None,
|
||||
};
|
||||
let mut state = Self {
|
||||
registry,
|
||||
root,
|
||||
service: None,
|
||||
calls: Arc::default(),
|
||||
};
|
||||
state.republish(reference);
|
||||
state
|
||||
}
|
||||
fn remove(&mut self) {
|
||||
if let Some(old) = self.service.take() {
|
||||
self.registry.remove_scope(&old.scope);
|
||||
}
|
||||
}
|
||||
fn republish(&mut self, reference: Option<&str>) {
|
||||
self.remove();
|
||||
let scope = Scope::new("/service").unwrap();
|
||||
self.service = Some(Publication {
|
||||
api: self
|
||||
.registry
|
||||
.register(
|
||||
&scope,
|
||||
"status",
|
||||
StatusDefinition,
|
||||
Some(Validator::new(b"api-v1")),
|
||||
)
|
||||
.unwrap(),
|
||||
scope,
|
||||
reference: reference.map(str::to_owned),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The HTTP adapter holds the State lock across all provider lookups, preconditions
|
||||
// and dispatch. No separate scope prelookup can race a replacement.
|
||||
struct Provider<'a> {
|
||||
state: &'a State,
|
||||
visible: bool,
|
||||
}
|
||||
impl ObjectProvider for Provider<'_> {
|
||||
type Object = Service;
|
||||
fn with_object<R>(
|
||||
&self,
|
||||
_: &ExecutionContext,
|
||||
path: &str,
|
||||
operation: impl FnOnce(&PublishedObject<Service>) -> R,
|
||||
) -> ProviderResult<R> {
|
||||
let publication = match path {
|
||||
"/" => &self.state.root,
|
||||
"/service" if self.visible => match &self.state.service {
|
||||
Some(value) => value,
|
||||
None => return ProviderResult::NotFound,
|
||||
},
|
||||
_ => return ProviderResult::NotFound,
|
||||
};
|
||||
let object = Service {
|
||||
name: if path == "/" { "" } else { "service" }.into(),
|
||||
reference: publication.reference.clone(),
|
||||
validator: Validator::new(b"object-v1"),
|
||||
calls: self.state.calls.clone(),
|
||||
};
|
||||
let current = ScopeObservation::new(&publication.scope, &object);
|
||||
let mut object = PublishedObject::new(object)
|
||||
.bind_scope(current)
|
||||
.expose(&publication.api)
|
||||
.unwrap();
|
||||
if path == "/service" {
|
||||
let root_object = Service {
|
||||
name: "".into(),
|
||||
reference: None,
|
||||
validator: Validator::new(b"object-v1"),
|
||||
calls: self.state.calls.clone(),
|
||||
};
|
||||
object = object
|
||||
.bind_scope(ScopeObservation::new(&self.state.root.scope, &root_object))
|
||||
.expose(&self.state.root.api)
|
||||
.unwrap();
|
||||
}
|
||||
ProviderResult::Found(operation(&object))
|
||||
}
|
||||
}
|
||||
fn limits() -> Limits {
|
||||
Limits::new(65536, 65536, 64).unwrap()
|
||||
}
|
||||
fn reference(scope: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: "status".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(state: &State, path: &str, body: &[u8], visible: bool) -> http::Response<Vec<u8>> {
|
||||
let provider = Provider { state, visible };
|
||||
match path {
|
||||
"/wip/v1/observe" => {
|
||||
let request = decode_observe_request(body, limits()).unwrap();
|
||||
match provider.observe_object(&request.path) {
|
||||
Ok(object) => encode_observe_response(
|
||||
&request,
|
||||
&ObjectObservation {
|
||||
object,
|
||||
children: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
Err(error) => encode_protocol_error_response(
|
||||
ProtocolInteraction::Observe,
|
||||
&error.protocol_error(),
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
"/wip/v1/fetch_interface" => {
|
||||
let request = decode_fetch_interface_request(body, limits()).unwrap();
|
||||
match provider.fetch_interface(&state.registry, &request.interface) {
|
||||
Ok(observation) => encode_fetch_interface_response(
|
||||
&request,
|
||||
&observation.protocol_response().unwrap(),
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
Err(error) => encode_protocol_error_response(
|
||||
ProtocolInteraction::FetchInterface,
|
||||
&error,
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
"/wip/v1/call_operation" => {
|
||||
let metadata = decode_call_operation_metadata(body, limits()).unwrap();
|
||||
let decoded = Mutex::new(None);
|
||||
let result = provider.call_operation_with_context_and_decoder(
|
||||
&ExecutionContext::default(),
|
||||
metadata.target.clone(),
|
||||
metadata.interface.clone(),
|
||||
metadata.operation.clone(),
|
||||
|descriptor| {
|
||||
let request = metadata.decode_request(body, descriptor, limits())?;
|
||||
let arguments = request.arguments.clone();
|
||||
*decoded.lock().unwrap() = Some((request, descriptor.clone()));
|
||||
Ok::<_, CodecError>(arguments)
|
||||
},
|
||||
);
|
||||
match result {
|
||||
Ok(result) => {
|
||||
let (request, descriptor) = decoded.into_inner().unwrap().unwrap();
|
||||
encode_call_operation_response(&request, &descriptor, &result, limits())
|
||||
.unwrap()
|
||||
}
|
||||
Err(error) => encode_protocol_error_response(
|
||||
ProtocolInteraction::CallOperation,
|
||||
&error.protocol_error(),
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
_ => panic!("unexpected route {path}"),
|
||||
}
|
||||
}
|
||||
|
||||
// Small bounded test-only HTTP/1.1 listener. Production serving is deliberately
|
||||
// not an example dependency; both directions still cross an actual TCP socket.
|
||||
fn exchange(
|
||||
state: &Arc<Mutex<State>>,
|
||||
request: http::Request<Vec<u8>>,
|
||||
visible: bool,
|
||||
) -> http::Response<Vec<u8>> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let state = state.clone();
|
||||
let server = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut raw = Vec::new();
|
||||
let (split, length) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert!(count > 0);
|
||||
raw.extend_from_slice(&chunk[..count]);
|
||||
assert!(raw.len() <= 70000);
|
||||
if let Some(split) = raw.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let head = std::str::from_utf8(&raw[..split]).unwrap();
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("Content-Length: "))
|
||||
.unwrap()
|
||||
.parse::<usize>()
|
||||
.unwrap();
|
||||
if raw.len() >= split + 4 + length {
|
||||
break (split, length);
|
||||
}
|
||||
}
|
||||
};
|
||||
let path = std::str::from_utf8(&raw[..split])
|
||||
.unwrap()
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap();
|
||||
let response = handle(
|
||||
&state.lock().unwrap(),
|
||||
path,
|
||||
&raw[split + 4..split + 4 + length],
|
||||
visible,
|
||||
);
|
||||
write!(stream, "HTTP/1.1 {} OK\r\nConnection: close\r\nContent-Length: {}\r\nContent-Type: application/json\r\n\r\n", response.status().as_u16(), response.body().len()).unwrap();
|
||||
stream.write_all(response.body()).unwrap();
|
||||
});
|
||||
let mut stream = TcpStream::connect(address).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(stream, "POST {} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", request.uri().path(), request.body().len()).unwrap();
|
||||
stream.write_all(request.body()).unwrap();
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).unwrap();
|
||||
server.join().unwrap();
|
||||
let split = raw.windows(4).position(|part| part == b"\r\n\r\n").unwrap();
|
||||
let status = std::str::from_utf8(&raw[..split])
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.parse::<u16>()
|
||||
.unwrap();
|
||||
http::Response::builder()
|
||||
.status(status)
|
||||
.header("content-type", "application/json")
|
||||
.body(raw[split + 4..].to_vec())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn setup() -> (Client, wip_client::SessionId) {
|
||||
let mut client = Client::new(ClientLimits::new(1, 16, 16, 16, 16).unwrap(), limits());
|
||||
let session = client
|
||||
.open_session("http://localhost/wip", SecurityContext::new("alice"))
|
||||
.unwrap();
|
||||
(client, session)
|
||||
}
|
||||
fn observe(
|
||||
client: &mut Client,
|
||||
session: &wip_client::SessionId,
|
||||
state: &Arc<Mutex<State>>,
|
||||
path: &str,
|
||||
) {
|
||||
let request = client.refresh_object(session, path).unwrap();
|
||||
let response = exchange(state, request.request, true);
|
||||
client.complete(request.id, response).unwrap();
|
||||
}
|
||||
fn fetch(
|
||||
client: &mut Client,
|
||||
session: &wip_client::SessionId,
|
||||
state: &Arc<Mutex<State>>,
|
||||
reference: &InterfaceReference,
|
||||
) {
|
||||
let request = client
|
||||
.prepare_interface(session, reference.clone())
|
||||
.unwrap();
|
||||
let body = std::str::from_utf8(request.request.body()).unwrap();
|
||||
assert!(body.contains("\"scope\""));
|
||||
assert!(body.contains("\"name\""));
|
||||
let response = exchange(state, request.request, true);
|
||||
assert!(matches!(
|
||||
client.complete(request.id, response).unwrap(),
|
||||
Completion::Interface(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_http_root_self_same_name_and_optional_scope_refs() {
|
||||
for scope_ref in [Some("instance-a"), None] {
|
||||
let state = Arc::new(Mutex::new(State::new(scope_ref)));
|
||||
let (mut client, session) = setup();
|
||||
observe(&mut client, &session, &state, "/");
|
||||
let root = client.object(&session, "/").unwrap();
|
||||
assert_eq!(root.object.unwrap().name, "");
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
for scope in ["/", "/service"] {
|
||||
let selected = reference(scope);
|
||||
fetch(&mut client, &session, &state, &selected);
|
||||
let observation = client.interface(&session, &selected).unwrap().clone();
|
||||
assert_eq!(
|
||||
observation.scope_ref.as_deref(),
|
||||
if scope == "/" { None } else { scope_ref }
|
||||
);
|
||||
let request = client
|
||||
.prepare_call(&session, "/service", &selected, "status", BTreeMap::new())
|
||||
.unwrap();
|
||||
let logical = decode_call_operation_request(
|
||||
request.request.body(),
|
||||
observation.descriptor.as_ref().unwrap(),
|
||||
limits(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(logical.interface.reference, selected);
|
||||
assert_eq!(logical.interface.scope_ref, observation.scope_ref);
|
||||
let response = exchange(&state, request.request, true);
|
||||
assert!(matches!(
|
||||
client.complete(request.id, response).unwrap(),
|
||||
Completion::Call(record) if matches!(record.outcome, CallOutcome::Success(_))
|
||||
));
|
||||
}
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_scope_republication_and_ref_less_replacement_require_explicit_calls() {
|
||||
let selected = reference("/service");
|
||||
let state = Arc::new(Mutex::new(State::new(Some("instance-a"))));
|
||||
let (mut client, session) = setup();
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
fetch(&mut client, &session, &state, &selected);
|
||||
let request = client
|
||||
.prepare_call(&session, "/service", &selected, "status", BTreeMap::new())
|
||||
.unwrap();
|
||||
state.lock().unwrap().republish(Some("instance-b"));
|
||||
let response = exchange(&state, request.request, true);
|
||||
assert_eq!(response.status(), http::StatusCode::CONFLICT);
|
||||
assert!(matches!(client.complete(request.id, response).unwrap(),
|
||||
Completion::Call(record) if matches!(record.outcome,
|
||||
CallOutcome::ProtocolFailure(ref error) if error.code == ProtocolErrorCode::InterfaceMismatch)));
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 0);
|
||||
assert_ne!(
|
||||
client.interface(&session, &selected).unwrap().state,
|
||||
ObservationState::Fresh
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.prepare_call(&session, "/service", &selected, "status", BTreeMap::new())
|
||||
.is_err()
|
||||
);
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
fetch(&mut client, &session, &state, &selected);
|
||||
assert_eq!(
|
||||
client
|
||||
.interface(&session, &selected)
|
||||
.unwrap()
|
||||
.scope_ref
|
||||
.as_deref(),
|
||||
Some("instance-b")
|
||||
);
|
||||
assert_eq!(
|
||||
state.lock().unwrap().calls.load(Ordering::SeqCst),
|
||||
0,
|
||||
"re-observation is not execution"
|
||||
);
|
||||
|
||||
state.lock().unwrap().remove();
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
assert!(client.interface(&session, &selected).is_none());
|
||||
state.lock().unwrap().republish(None);
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
fetch(&mut client, &session, &state, &selected);
|
||||
let request = client
|
||||
.prepare_call(&session, "/service", &selected, "status", BTreeMap::new())
|
||||
.unwrap();
|
||||
// Ref-less replacement is intentionally not identity-trackable. Current
|
||||
// membership, live publication and both validators still apply at dispatch.
|
||||
state.lock().unwrap().republish(None);
|
||||
let response = exchange(&state, request.request, true);
|
||||
client.complete(request.id, response).unwrap();
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_http_unknown_outcome_is_never_automatically_retried() {
|
||||
let state = Arc::new(Mutex::new(State::new(Some("instance-a"))));
|
||||
let (mut client, session) = setup();
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
let selected = reference("/service");
|
||||
fetch(&mut client, &session, &state, &selected);
|
||||
let request = client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/service",
|
||||
&selected,
|
||||
"uncertain",
|
||||
BTreeMap::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let response = exchange(&state, request.request, true);
|
||||
let completion = client.complete(request.id, response).unwrap();
|
||||
assert!(
|
||||
matches!(completion, Completion::Call(record) if matches!(record.outcome, CallOutcome::Unknown { .. }))
|
||||
);
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 1);
|
||||
observe(&mut client, &session, &state, "/service");
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn principal_visibility_and_validator_precedence_cross_real_http() {
|
||||
let state = Arc::new(Mutex::new(State::new(Some("instance-a"))));
|
||||
let endpoint = Endpoint::parse("http://localhost/wip").unwrap();
|
||||
let selected = reference("/service");
|
||||
let fetch = wip_protocol::FetchInterfaceRequest {
|
||||
interface: selected.clone(),
|
||||
};
|
||||
let response = exchange(
|
||||
&state,
|
||||
encode_fetch_interface_request(&endpoint, &fetch, limits()).unwrap(),
|
||||
false,
|
||||
);
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&fetch, &response, limits()).unwrap(), DecodedResponse::ProtocolFailure { error, .. } if error.code == ProtocolErrorCode::InterfaceNotFound)
|
||||
);
|
||||
let descriptor = StatusDefinition::descriptor();
|
||||
let mut call = wip_protocol::CallOperationRequest {
|
||||
target: wip_protocol::Target {
|
||||
path: "/service".into(),
|
||||
validator: Some(b"stale-object".to_vec()),
|
||||
},
|
||||
interface: wip_protocol::InterfaceTarget {
|
||||
reference: selected,
|
||||
scope_ref: Some("stale-scope".into()),
|
||||
validator: Some(b"stale-api".to_vec()),
|
||||
},
|
||||
operation: "status".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
};
|
||||
for (visible, object_validator, scope_ref, interface_validator, expected) in [
|
||||
(
|
||||
false,
|
||||
b"stale-object".as_slice(),
|
||||
Some("stale-scope"),
|
||||
Some(b"stale-api".as_slice()),
|
||||
ProtocolErrorCode::NotFound,
|
||||
),
|
||||
(
|
||||
true,
|
||||
b"stale-object".as_slice(),
|
||||
Some("stale-scope"),
|
||||
Some(b"stale-api".as_slice()),
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
),
|
||||
(
|
||||
true,
|
||||
b"object-v1".as_slice(),
|
||||
Some("stale-scope"),
|
||||
Some(b"stale-api".as_slice()),
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
),
|
||||
(
|
||||
true,
|
||||
b"object-v1".as_slice(),
|
||||
Some("instance-a"),
|
||||
None,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
),
|
||||
(
|
||||
true,
|
||||
b"object-v1".as_slice(),
|
||||
None,
|
||||
Some(b"stale-api".as_slice()),
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
),
|
||||
] {
|
||||
call.target.validator = Some(object_validator.to_vec());
|
||||
call.interface.scope_ref = scope_ref.map(str::to_owned);
|
||||
call.interface.validator = interface_validator.map(<[u8]>::to_vec);
|
||||
let response = exchange(
|
||||
&state,
|
||||
encode_call_operation_request(&endpoint, &call, &descriptor, limits()).unwrap(),
|
||||
visible,
|
||||
);
|
||||
assert!(
|
||||
matches!(decode_call_operation_response(&call, &descriptor, &response, limits()).unwrap(), DecodedResponse::ProtocolFailure { error, .. } if error.code == expected)
|
||||
);
|
||||
}
|
||||
assert_eq!(state.lock().unwrap().calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "wip-tui"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
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.workspace = true
|
||||
wip-http.workspace = true
|
||||
wip-protocol.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
wip-fs-server.workspace = true
|
||||
@@ -0,0 +1,219 @@
|
||||
# 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.
|
||||
|
||||
## Scoped reference formatting
|
||||
|
||||
`wip_tui::reference::{format_interface_reference, format_qualified_operation}`
|
||||
provides labels for the existing UI from `InterfaceReference` and a separate
|
||||
operation name, following `4.2-text-view.md` reference notation (`6086f3c`).
|
||||
|
||||
```rust
|
||||
use wip_protocol::InterfaceReference;
|
||||
use wip_tui::reference::{format_interface_reference, format_qualified_operation};
|
||||
|
||||
let reference = InterfaceReference { scope: "/github".into(), name: "issue#read".into() };
|
||||
assert_eq!(format_interface_reference(&reference)?, "/github::\"issue#read\"");
|
||||
assert_eq!(format_qualified_operation(&reference, "read#raw")?,
|
||||
"/github::\"issue#read\"#\"read#raw\"");
|
||||
# Ok::<(), wip_protocol::ValidationError>(())
|
||||
```
|
||||
|
||||
Both return `Result<String, ValidationError>` and reject invalid reference shape,
|
||||
including relative/omitted scope. Root is explicit `/`. Non-simple components use
|
||||
JSON string quoting with additional DEL/C1, Unicode line/paragraph separator and
|
||||
bidi-control escapes. Input values are borrowed and never normalized, case-folded,
|
||||
URL-encoded or split on delimiters. Ref, validators and `scope_ref` do not enter
|
||||
these labels. The output has no extra outer signature string quoting.
|
||||
|
||||
Keep selection, cache and calls keyed by structured references and operation
|
||||
names, never display text. No parser, scope inference, identity reconstruction,
|
||||
Object/Interface signature renderer or new crate is introduced. Membership,
|
||||
ancestry, authorization and freshness remain runtime concerns. Normal Entry,
|
||||
Interface/Operation, editor, confirmation and operation-history screens use these
|
||||
qualified labels with existing bounded layout. Shortened labels never feed back
|
||||
into identity or calls.
|
||||
|
||||
### Rust API and wire migration
|
||||
|
||||
Interface identities in the presentation map, action/selection rows, in-flight
|
||||
subjects and editors are now `InterfaceReference { scope, name }`, not strings.
|
||||
This is a breaking Rust API change; consumers must construct an explicit canonical
|
||||
absolute scope rather than parse a label or infer a scope from a target Entry.
|
||||
`ArgumentEditor` also retains its Entry `path`; `new` defaults to `/`, and
|
||||
`for_target(path)` fixes the chosen target before editing. Normal UI selection
|
||||
sets it automatically. Confirmation never retargets an existing editor.
|
||||
`App::operation_selection` retains the Entry and structured row through temporary
|
||||
loading gaps; the numeric cursor is only a layout position. Retaining this subject
|
||||
does not expose stale operations or authorize execution.
|
||||
|
||||
The TUI uses the scoped Protocol/HTTP Client wire: Interface references are
|
||||
structured, and calls use an Interface target carrying the reference and optional
|
||||
`scope_ref`/validator preconditions. The optional identity is copied by the Client,
|
||||
not invented by the UI; no additional required ref is introduced. This wire is not
|
||||
compatible with the former string-reference request/response shape.
|
||||
|
||||
## 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 structured `(scope,
|
||||
interface name, operation name)`, displaying `scope::interface#operation` with
|
||||
explicit absolute scope and safely quoted components. Structured references
|
||||
remain intact in selection, acquisition, and call state; display labels are
|
||||
never parsed back into references. 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.
|
||||
|
||||
Every Client transition is mirrored into retained UI Object, tree and Interface
|
||||
state, including scope retirement and cache removal. An open editor/confirmation
|
||||
is bound to private Object/Interface snapshots (not displayed refs/validators).
|
||||
Changed, stale, loading, removed or retargeted observations retire the editor;
|
||||
reobservation never recreates or executes it. Descriptor rows remain identified
|
||||
by the structured reference when another Interface gains or loses operation rows.
|
||||
Explicitly select/load an Interface header to refresh a retained stale descriptor,
|
||||
then select an operation and confirm a new call. Client calls already dispatched
|
||||
retain their original immutable context and are never moved to a new scope.
|
||||
|
||||
Without refs, a same-path replacement with indistinguishable public metadata
|
||||
cannot always be detected; the UI does not synthesize identity or infer deletion
|
||||
from missing tree edges. Optional refs remain optional. Typed `Entry` results are
|
||||
only observed when individually selected; the UI neither bulk-fetches result
|
||||
paths nor adds guessed parent/indexable edges.
|
||||
|
||||
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.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,646 @@
|
||||
//! 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, InterfaceReference, 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 {
|
||||
/// Exact Entry target selected when editing began; never read from display text.
|
||||
pub path: String,
|
||||
/// Structured interface reference selected for the call.
|
||||
pub interface: InterfaceReference,
|
||||
/// 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: InterfaceReference,
|
||||
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 {
|
||||
path: "/".into(),
|
||||
interface,
|
||||
operation,
|
||||
descriptor,
|
||||
fields,
|
||||
cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixes the Entry target for the editor and subsequent confirmation.
|
||||
#[must_use]
|
||||
pub fn for_target(mut self, path: impl Into<String>) -> Self {
|
||||
self.path = path.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: "/".into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
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(root_reference("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(root_reference("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,19 @@
|
||||
//! Presentation and terminal interaction for stateful WIP client sessions.
|
||||
//!
|
||||
//! Interface identity is a structured `wip_protocol::InterfaceReference` with an
|
||||
//! explicit absolute scope. Display-only [`mod@reference`] labels safely quote
|
||||
//! `scope::interface#operation`; shortened labels are never parsed for calls.
|
||||
//! This breaks the former string-reference Rust API and follows the scoped HTTP
|
||||
//! wire format. Ref and validator preconditions remain private Client metadata.
|
||||
//! Editors retain their selected Entry target and are retired when the Client's
|
||||
//! Object/Interface snapshots change; reobservation never executes an operation.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
pub mod app;
|
||||
pub mod config;
|
||||
pub mod editor;
|
||||
pub mod reference;
|
||||
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,107 @@
|
||||
//! Scoped Interface/Operation labels for the existing TUI.
|
||||
//!
|
||||
//! Follows the reference notation and safety escapes in WIP `4.2-text-view.md`.
|
||||
//! These are display labels, not wire values, cache keys or call targets. Keep
|
||||
//! [`InterfaceReference`] and operation names structured for selection and calls;
|
||||
//! do not split or reparse labels. No Object/Interface signature renderer or
|
||||
//! shorthand input parser is provided. Screen integration and bounded layout
|
||||
//! remain separate from formatting.
|
||||
//!
|
||||
//! Scope is always explicit and canonical absolute. Adapters accepting omitted
|
||||
//! scope must resolve it with an explicit context at their input boundary, never
|
||||
//! default to root, infer from a target path or search ancestors. Membership,
|
||||
//! ancestry and authorization are separate checks, not claims made by a label.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use wip_protocol::{InterfaceReference, ValidationError};
|
||||
|
||||
/// Formats a complete `scope::interface` label from structured values.
|
||||
///
|
||||
/// Validates reference shape (including canonical absolute scope), then quotes
|
||||
/// components as needed. There is no outer signature JSON string layer. The
|
||||
/// exact input is preserved without normalization, case conversion or URL
|
||||
/// encoding. Ref, validators and `scope_ref` are not inputs and cannot leak into
|
||||
/// the label. This does not validate membership, freshness or authorization.
|
||||
///
|
||||
/// ```
|
||||
/// use wip_protocol::InterfaceReference;
|
||||
/// use wip_tui::reference::format_interface_reference;
|
||||
/// let reference = InterfaceReference {
|
||||
/// scope: "/github::archive".into(), name: "issue#read".into(),
|
||||
/// };
|
||||
/// assert_eq!(format_interface_reference(&reference)?,
|
||||
/// "\"/github::archive\"::\"issue#read\"");
|
||||
/// # Ok::<(), wip_protocol::ValidationError>(())
|
||||
/// ```
|
||||
pub fn format_interface_reference(
|
||||
reference: &InterfaceReference,
|
||||
) -> Result<String, ValidationError> {
|
||||
reference.validate()?;
|
||||
Ok(format!(
|
||||
"{}::{}",
|
||||
component(&reference.scope, true),
|
||||
component(&reference.name, false)
|
||||
))
|
||||
}
|
||||
|
||||
/// Formats a complete `scope::interface#operation` display designation.
|
||||
///
|
||||
/// Operation remains a separate exact Unicode name, not an input expression.
|
||||
/// Delimiters inside it are quoted rather than split. This checks reference
|
||||
/// shape, not operation existence, and adds no operation-name restrictions to
|
||||
/// the Protocol. The output is plain text, without ANSI or Markdown; the UI
|
||||
/// remains responsible for bounded screen layout, not identity reconstruction.
|
||||
///
|
||||
/// ```
|
||||
/// use wip_protocol::InterfaceReference;
|
||||
/// use wip_tui::reference::format_qualified_operation;
|
||||
/// let reference = InterfaceReference { scope: "/".into(), name: "issue.read".into() };
|
||||
/// assert_eq!(format_qualified_operation(&reference, "read#raw")?,
|
||||
/// "/::issue.read#\"read#raw\"");
|
||||
/// # Ok::<(), wip_protocol::ValidationError>(())
|
||||
/// ```
|
||||
pub fn format_qualified_operation(
|
||||
reference: &InterfaceReference,
|
||||
operation: &str,
|
||||
) -> Result<String, ValidationError> {
|
||||
let mut output = format_interface_reference(reference)?;
|
||||
output.push('#');
|
||||
output.push_str(&component(operation, false));
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn component(value: &str, scope: bool) -> String {
|
||||
if !value.is_empty()
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b) || (scope && b == b'/'))
|
||||
{
|
||||
return value.to_owned();
|
||||
}
|
||||
let mut output = String::from("\"");
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'\\' => output.push_str("\\\\"),
|
||||
'"' => output.push_str("\\\""),
|
||||
'\u{08}' => output.push_str("\\b"),
|
||||
'\u{0c}' => output.push_str("\\f"),
|
||||
'\n' => output.push_str("\\n"),
|
||||
'\r' => output.push_str("\\r"),
|
||||
'\t' => output.push_str("\\t"),
|
||||
'\u{00}'..='\u{1f}'
|
||||
| '\u{7f}'..='\u{9f}'
|
||||
| '\u{2028}'
|
||||
| '\u{2029}'
|
||||
| '\u{061c}'
|
||||
| '\u{200e}'..='\u{200f}'
|
||||
| '\u{202a}'..='\u{202e}'
|
||||
| '\u{2066}'..='\u{2069}' => {
|
||||
// String's fmt::Write implementation is infallible.
|
||||
write!(output, "\\u{:04x}", ch as u32).expect("String write");
|
||||
}
|
||||
_ => output.push(ch),
|
||||
}
|
||||
}
|
||||
output.push('"');
|
||||
output
|
||||
}
|
||||
@@ -0,0 +1,980 @@
|
||||
//! 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;
|
||||
|
||||
/// Bounded presentation only; invalid references are never repaired or inferred.
|
||||
pub(crate) fn interface_label(reference: &wip_protocol::InterfaceReference) -> String {
|
||||
sanitize(
|
||||
&crate::reference::format_interface_reference(reference)
|
||||
.unwrap_or_else(|_| "(invalid interface reference)".into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// The exact structured subject remains separate from this shortened label.
|
||||
pub(crate) fn operation_label(
|
||||
reference: &wip_protocol::InterfaceReference,
|
||||
operation: &str,
|
||||
) -> String {
|
||||
sanitize(
|
||||
&crate::reference::format_qualified_operation(reference, operation)
|
||||
.unwrap_or_else(|_| "(invalid operation reference)".into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// 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(interface_label)
|
||||
.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!(" {}", operation_label(&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}) -> {}{}",
|
||||
operation_label(&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 {} [{}]{}",
|
||||
interface_label(&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(&editor.path),
|
||||
operation_label(&editor.interface, &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(&editor.path))),
|
||||
Line::from(format!("Interface: {}", interface_label(&editor.interface))),
|
||||
Line::from(format!(
|
||||
"Operation: {}",
|
||||
operation_label(&editor.interface, &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 {
|
||||
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: "/".into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
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![root_reference("demo-interface")],
|
||||
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 {
|
||||
scope_ref: None,
|
||||
reference: root_reference("demo-interface"),
|
||||
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(
|
||||
root_reference("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![root_reference("many")],
|
||||
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 {
|
||||
scope_ref: None,
|
||||
reference: root_reference("many"),
|
||||
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 interface_labels_show_scope_and_name_without_parsing() {
|
||||
let reference = wip_protocol::InterfaceReference {
|
||||
scope: "/nested".into(),
|
||||
name: "#::操作".into(),
|
||||
};
|
||||
assert_eq!(interface_label(&reference), "/nested::\"#::操作\"");
|
||||
assert_ne!(
|
||||
interface_label(&reference),
|
||||
interface_label(&root_reference(&reference.name))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qualified_labels_are_safely_quoted_on_normal_screens_and_modals() {
|
||||
let mut app = App::new("https://example.test/wip/");
|
||||
let local = wip_protocol::InterfaceReference {
|
||||
scope: "/a::b".into(),
|
||||
name: "same#name".into(),
|
||||
};
|
||||
let root = root_reference(&local.name);
|
||||
let operation = "run#\n\u{202e}";
|
||||
let descriptor = InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: operation.into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
};
|
||||
app.apply_object(ObjectObservation {
|
||||
path: "/".into(),
|
||||
object: Some(Object {
|
||||
name: String::new(),
|
||||
description: None,
|
||||
interfaces: vec![root.clone(), local.clone()],
|
||||
r#ref: Some("hidden-object-ref".into()),
|
||||
validator: Some(b"hidden-object-validator".to_vec()),
|
||||
}),
|
||||
validator: Some(b"hidden-object-validator".to_vec()),
|
||||
state: ObservationState::Fresh,
|
||||
});
|
||||
for reference in [&root, &local] {
|
||||
app.apply_interface(InterfaceObservation {
|
||||
reference: reference.clone(),
|
||||
descriptor: Some(descriptor.clone()),
|
||||
validator: Some(b"hidden-interface-validator".to_vec()),
|
||||
scope_ref: Some("hidden-scope-ref".into()),
|
||||
state: ObservationState::Fresh,
|
||||
});
|
||||
}
|
||||
let root_label = "/::\"same#name\"";
|
||||
let local_label = "\"/a::b\"::\"same#name\"";
|
||||
let operation_label = "\"/a::b\"::\"same#name\"#\"run#\\n\\u202e\"";
|
||||
let normal = rendered(&app, 220, 55);
|
||||
assert!(normal.contains(root_label));
|
||||
assert!(normal.contains(local_label));
|
||||
assert!(normal.contains(operation_label));
|
||||
app.focus = Focus::Operations;
|
||||
app.operation_cursor = 3;
|
||||
app.reduce(crate::app::InputKey::Enter);
|
||||
let editor = rendered(&app, 220, 55);
|
||||
assert!(editor.contains(operation_label));
|
||||
assert!(editor.contains("Argument editor"));
|
||||
app.reduce(crate::app::InputKey::Enter);
|
||||
let confirmation = rendered(&app, 220, 55);
|
||||
assert!(confirmation.contains(operation_label));
|
||||
assert!(confirmation.contains("EXPLICIT EXECUTION CONFIRMATION"));
|
||||
for snapshot in [normal, editor, confirmation] {
|
||||
assert!(!snapshot.contains("hidden-"));
|
||||
assert!(!snapshot.contains('\u{202e}'));
|
||||
}
|
||||
assert!(matches!(
|
||||
app.reduce(crate::app::InputKey::Enter).as_slice(),
|
||||
[crate::app::Action::Execute { interface, operation: name, .. }]
|
||||
if interface == &local && name == operation
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortened_and_invalid_labels_never_infer_a_reference() {
|
||||
let reference = root_reference(&"x".repeat(1000));
|
||||
assert!(interface_label(&reference).ends_with('…'));
|
||||
assert_eq!(reference.name.len(), 1000);
|
||||
let invalid = wip_protocol::InterfaceReference {
|
||||
scope: "relative".into(),
|
||||
name: "name".into(),
|
||||
};
|
||||
assert_eq!(interface_label(&invalid), "(invalid interface reference)");
|
||||
assert_eq!(
|
||||
operation_label(&invalid, "run"),
|
||||
"(invalid operation reference)"
|
||||
);
|
||||
}
|
||||
|
||||
#[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,567 @@
|
||||
//! UI lifetime regressions driven by real Client/HTTP codec completions.
|
||||
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
use wip_client::ObservationState;
|
||||
use wip_http::{
|
||||
decode_call_operation_request, encode_fetch_interface_response, encode_observe_response,
|
||||
encode_protocol_error_response,
|
||||
};
|
||||
use wip_protocol::{
|
||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceReference, Object,
|
||||
ObjectObservation, ObserveRequest, OperationDeclaration, ProtocolError, ProtocolErrorCode,
|
||||
ProtocolInteraction, ReturnDeclaration,
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct RecordingTransport(Arc<Mutex<Vec<Request<Vec<u8>>>>>);
|
||||
|
||||
impl Transport for RecordingTransport {
|
||||
type Prepared = Request<Vec<u8>>;
|
||||
|
||||
fn prepare(&self, request: Request<Vec<u8>>) -> Result<Self::Prepared, TransportError> {
|
||||
self.0.lock().unwrap().push(request);
|
||||
Err(TransportError {
|
||||
kind: TransportErrorKind::Disconnect,
|
||||
detail: "deliberate pre-dispatch failure".into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn execute(&self, _: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError> {
|
||||
panic!("test transport must never dispatch");
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(scope: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: "same#::名前".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "run#::\n\u{202e}".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime() -> Runtime<RecordingTransport> {
|
||||
let config = Config::parse(["https://example.test/wip"], None, None, |_| None).unwrap();
|
||||
Runtime::new(&config, RecordingTransport::default()).unwrap()
|
||||
}
|
||||
|
||||
fn observe(runtime: &mut Runtime<RecordingTransport>, identity: Option<&str>) {
|
||||
let request = runtime
|
||||
.client
|
||||
.refresh_object(&runtime.session, "/item")
|
||||
.unwrap();
|
||||
let response = encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: "/item".into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: Object {
|
||||
name: "item".into(),
|
||||
description: None,
|
||||
interfaces: vec![reference("/"), reference("/item")],
|
||||
r#ref: identity.map(str::to_owned),
|
||||
validator: None,
|
||||
},
|
||||
children: None,
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap();
|
||||
runtime
|
||||
.app
|
||||
.request_started(request.id.get(), InFlightKind::Object("/item".into()));
|
||||
// Mirror the actual dispatch-time loading transition before the response.
|
||||
runtime.reconcile_authoritative();
|
||||
runtime.finish(WorkerEvent {
|
||||
id: request.id,
|
||||
response: Ok(response),
|
||||
});
|
||||
}
|
||||
|
||||
fn fetch(runtime: &mut Runtime<RecordingTransport>, scope: &str, identity: Option<&str>) {
|
||||
let request = runtime
|
||||
.client
|
||||
.prepare_interface(&runtime.session, reference(scope))
|
||||
.unwrap();
|
||||
runtime
|
||||
.app
|
||||
.request_started(request.id.get(), InFlightKind::Interface(reference(scope)));
|
||||
runtime.finish(WorkerEvent {
|
||||
id: request.id,
|
||||
response: Ok(interface_response(scope, identity)),
|
||||
});
|
||||
}
|
||||
|
||||
fn interface_response(scope: &str, identity: Option<&str>) -> Response<Vec<u8>> {
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: reference(scope),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
interface: reference(scope),
|
||||
scope_ref: identity.map(str::to_owned),
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn populated() -> Runtime<RecordingTransport> {
|
||||
let mut runtime = runtime();
|
||||
observe(&mut runtime, Some("old-scope"));
|
||||
fetch(&mut runtime, "/", Some("root-scope"));
|
||||
fetch(&mut runtime, "/item", Some("old-scope"));
|
||||
runtime.app.navigate_entry("/item");
|
||||
runtime.app.focus = crate::app::Focus::Operations;
|
||||
runtime.app.operation_cursor = 3;
|
||||
runtime
|
||||
}
|
||||
|
||||
fn confirm_local(runtime: &mut Runtime<RecordingTransport>) {
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
assert!(matches!(&runtime.app.modal, Modal::Editor(editor)
|
||||
if editor.interface == reference("/item") && editor.path == "/item"));
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
assert!(matches!(runtime.app.modal, Modal::Confirm { .. }));
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_names_dispatch_exact_structured_scope_only_after_confirmation() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
let requests = runtime.transport.0.lock().unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
let call =
|
||||
decode_call_operation_request(requests[0].body(), &descriptor(), default_wire_limits())
|
||||
.unwrap();
|
||||
assert_eq!(call.target.path, "/item");
|
||||
assert_eq!(call.interface.reference, reference("/item"));
|
||||
assert_eq!(call.interface.scope_ref.as_deref(), Some("old-scope"));
|
||||
assert_eq!(call.operation, descriptor().operations[0].name);
|
||||
assert!(
|
||||
runtime.app.history[0]
|
||||
.title
|
||||
.contains("/item::\"same#::名前\"#")
|
||||
);
|
||||
assert!(runtime.app.history[0].title.contains("\\n\\u202e"));
|
||||
assert!(!runtime.app.history[0].title.contains("old-scope"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_loading_preserves_scoped_operation_selection_until_reobservation() {
|
||||
let mut runtime = populated();
|
||||
observe(&mut runtime, Some("old-scope"));
|
||||
let selected = &runtime.app.operation_rows()[runtime.app.operation_cursor];
|
||||
assert_eq!(selected.interface, reference("/item"));
|
||||
assert_eq!(
|
||||
selected.operation.as_deref(),
|
||||
Some(descriptor().operations[0].name.as_str())
|
||||
);
|
||||
assert!(matches!(&runtime.app.operation_selection, Some((path, row))
|
||||
if path == "/item" && row == selected));
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_replacement_retires_confirmation_and_requires_explicit_reobservation() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
observe(&mut runtime, Some("new-scope"));
|
||||
let local = &runtime.app.interfaces[&reference("/item")];
|
||||
assert_eq!(local.state, crate::app::ViewState::Stale);
|
||||
assert!(local.descriptor.is_none());
|
||||
assert_eq!(
|
||||
runtime.app.interfaces[&reference("/")].state,
|
||||
crate::app::ViewState::Fresh
|
||||
);
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
assert!(runtime.app.status.contains("editor retired"));
|
||||
assert_eq!(
|
||||
runtime.app.operation_rows()[runtime.app.operation_cursor].interface,
|
||||
reference("/item")
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.client
|
||||
.ensure_interface(&runtime.session, reference("/item"))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
// Refetch without any execution; selecting and confirming again is required.
|
||||
fetch(&mut runtime, "/item", Some("new-scope"));
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
runtime.app.operation_cursor = 3;
|
||||
confirm_local(&mut runtime);
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
let requests = runtime.transport.0.lock().unwrap();
|
||||
let call =
|
||||
decode_call_operation_request(requests[0].body(), &descriptor(), default_wire_limits())
|
||||
.unwrap();
|
||||
assert_eq!(call.interface.scope_ref.as_deref(), Some("new-scope"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_old_fetch_cannot_revive_retired_editor_or_descriptor() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
let request = runtime
|
||||
.client
|
||||
.prepare_interface(&runtime.session, reference("/item"))
|
||||
.unwrap();
|
||||
runtime.app.request_started(
|
||||
request.id.get(),
|
||||
InFlightKind::Interface(reference("/item")),
|
||||
);
|
||||
observe(&mut runtime, Some("new-scope"));
|
||||
runtime.finish(WorkerEvent {
|
||||
id: request.id,
|
||||
response: Ok(interface_response("/item", Some("old-scope"))),
|
||||
});
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
assert_ne!(
|
||||
runtime.app.interfaces[&reference("/item")].state,
|
||||
crate::app::ViewState::Fresh
|
||||
);
|
||||
assert!(
|
||||
runtime.app.interfaces[&reference("/item")]
|
||||
.descriptor
|
||||
.is_none()
|
||||
);
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_deletion_and_republication_remove_ui_cache_without_switching_to_root() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
let request = runtime
|
||||
.client
|
||||
.refresh_object(&runtime.session, "/item")
|
||||
.unwrap();
|
||||
runtime
|
||||
.app
|
||||
.request_started(request.id.get(), InFlightKind::Object("/item".into()));
|
||||
runtime.finish(WorkerEvent {
|
||||
id: request.id,
|
||||
response: Ok(encode_protocol_error_response(
|
||||
ProtocolInteraction::Observe,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::NotFound,
|
||||
message: "scope deleted".into(),
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap()),
|
||||
});
|
||||
assert!(!runtime.app.interfaces.contains_key(&reference("/item")));
|
||||
assert!(runtime.app.interfaces.contains_key(&reference("/")));
|
||||
assert!(runtime.app.operation_rows().is_empty());
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
observe(&mut runtime, Some("republished-scope"));
|
||||
fetch(&mut runtime, "/item", Some("republished-scope"));
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lost_ref_and_retained_stale_descriptor_are_mirrored_without_synthetic_binding() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
observe(&mut runtime, None);
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
assert_eq!(
|
||||
runtime.app.interfaces[&reference("/item")].state,
|
||||
crate::app::ViewState::Stale
|
||||
);
|
||||
fetch(&mut runtime, "/item", None);
|
||||
runtime.app.operation_cursor = 3;
|
||||
confirm_local(&mut runtime);
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
let requests = runtime.transport.0.lock().unwrap();
|
||||
let call =
|
||||
decode_call_operation_request(requests[0].body(), &descriptor(), default_wire_limits())
|
||||
.unwrap();
|
||||
assert_eq!(call.interface.scope_ref, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_mirrors_retained_state_and_preserves_selected_reference_as_rows_shift() {
|
||||
let mut runtime = populated();
|
||||
// Fetch of the first Interface temporarily removes its Operation row. The
|
||||
// selected operation on the second Interface must stay selected by identity.
|
||||
let request = runtime
|
||||
.client
|
||||
.prepare_interface(&runtime.session, reference("/"))
|
||||
.unwrap();
|
||||
runtime.reconcile_authoritative();
|
||||
assert_eq!(
|
||||
runtime.app.operation_rows()[runtime.app.operation_cursor].interface,
|
||||
reference("/item")
|
||||
);
|
||||
assert!(
|
||||
runtime.app.operation_rows()[runtime.app.operation_cursor]
|
||||
.operation
|
||||
.is_some()
|
||||
);
|
||||
let error = runtime
|
||||
.client
|
||||
.fail_transport(request.id, "test failure")
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ClientErrorKind::Transport);
|
||||
runtime.reconcile_authoritative();
|
||||
assert!(matches!(
|
||||
runtime.app.interfaces[&reference("/")].state,
|
||||
crate::app::ViewState::Error(_)
|
||||
));
|
||||
assert_eq!(
|
||||
runtime.app.operation_rows()[runtime.app.operation_cursor].interface,
|
||||
reference("/item")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn already_dispatched_call_keeps_original_context_across_scope_republication() {
|
||||
let mut runtime = populated();
|
||||
let call = runtime
|
||||
.client
|
||||
.prepare_call(
|
||||
&runtime.session,
|
||||
"/item",
|
||||
&reference("/item"),
|
||||
&descriptor().operations[0].name,
|
||||
std::collections::BTreeMap::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let logical =
|
||||
decode_call_operation_request(call.request.body(), &descriptor(), default_wire_limits())
|
||||
.unwrap();
|
||||
runtime.client.mark_dispatched(call.id).unwrap();
|
||||
runtime.app.request_started(
|
||||
call.id.get(),
|
||||
InFlightKind::Operation {
|
||||
path: "/item".into(),
|
||||
interface: reference("/item"),
|
||||
operation: logical.operation.clone(),
|
||||
dispatched: true,
|
||||
},
|
||||
);
|
||||
observe(&mut runtime, Some("new-scope"));
|
||||
let mut new_descriptor = descriptor();
|
||||
new_descriptor.operations[0].returns.r#type = TypeExpr::String;
|
||||
let fetch = runtime
|
||||
.client
|
||||
.prepare_interface(&runtime.session, reference("/item"))
|
||||
.unwrap();
|
||||
runtime
|
||||
.app
|
||||
.request_started(fetch.id.get(), InFlightKind::Interface(reference("/item")));
|
||||
runtime.finish(WorkerEvent {
|
||||
id: fetch.id,
|
||||
response: Ok(encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: reference("/item"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
interface: reference("/item"),
|
||||
scope_ref: Some("new-scope".into()),
|
||||
validator: None,
|
||||
descriptor: new_descriptor.clone(),
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap()),
|
||||
});
|
||||
runtime.finish(WorkerEvent {
|
||||
id: call.id,
|
||||
response: Ok(wip_http::encode_call_operation_response(
|
||||
&logical,
|
||||
&descriptor(),
|
||||
&wip_protocol::CallOperationResponse {
|
||||
result: Value::Unit,
|
||||
validator: None,
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap()),
|
||||
});
|
||||
assert_eq!(runtime.app.history[0].kind, HistoryKind::Success);
|
||||
assert_eq!(runtime.app.history[0].detail, "null");
|
||||
assert_eq!(
|
||||
runtime.app.interfaces[&reference("/item")]
|
||||
.descriptor
|
||||
.as_ref(),
|
||||
Some(&new_descriptor)
|
||||
);
|
||||
assert_eq!(logical.interface.scope_ref.as_deref(), Some("old-scope"));
|
||||
assert!(
|
||||
runtime.transport.0.lock().unwrap().is_empty(),
|
||||
"no redispatch or retry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_entry_results_are_only_observed_on_selection_without_guessed_edges() {
|
||||
let mut runtime = populated();
|
||||
// The original no-validator descriptor is immutable within its scope
|
||||
// lifetime. Republish the scope before testing a different result schema.
|
||||
observe(&mut runtime, Some("entry-result-scope"));
|
||||
let mut descriptor = descriptor();
|
||||
descriptor.operations[0].returns.r#type = TypeExpr::Record {
|
||||
fields: vec![
|
||||
wip_protocol::FieldDeclaration {
|
||||
name: "entries".into(),
|
||||
required: true,
|
||||
documentation: None,
|
||||
r#type: TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Entry),
|
||||
},
|
||||
},
|
||||
wip_protocol::FieldDeclaration {
|
||||
name: "ordinary".into(),
|
||||
required: true,
|
||||
documentation: None,
|
||||
r#type: TypeExpr::String,
|
||||
},
|
||||
],
|
||||
};
|
||||
let fetch = runtime
|
||||
.client
|
||||
.prepare_interface(&runtime.session, reference("/item"))
|
||||
.unwrap();
|
||||
let completion = runtime
|
||||
.client
|
||||
.complete(
|
||||
fetch.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: reference("/item"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
interface: reference("/item"),
|
||||
scope_ref: Some("entry-result-scope".into()),
|
||||
validator: None,
|
||||
descriptor: descriptor.clone(),
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
runtime.apply_completion(completion, None);
|
||||
let call = runtime
|
||||
.client
|
||||
.prepare_call(
|
||||
&runtime.session,
|
||||
"/item",
|
||||
&reference("/item"),
|
||||
&descriptor.operations[0].name,
|
||||
std::collections::BTreeMap::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let logical =
|
||||
decode_call_operation_request(call.request.body(), &descriptor, default_wire_limits())
|
||||
.unwrap();
|
||||
runtime.client.mark_dispatched(call.id).unwrap();
|
||||
runtime.app.request_started(
|
||||
call.id.get(),
|
||||
InFlightKind::Operation {
|
||||
path: "/item".into(),
|
||||
interface: reference("/item"),
|
||||
operation: descriptor.operations[0].name.clone(),
|
||||
dispatched: true,
|
||||
},
|
||||
);
|
||||
runtime.finish(WorkerEvent {
|
||||
id: call.id,
|
||||
response: Ok(wip_http::encode_call_operation_response(
|
||||
&logical,
|
||||
&descriptor,
|
||||
&wip_protocol::CallOperationResponse {
|
||||
result: Value::Record(std::collections::BTreeMap::from([
|
||||
(
|
||||
"entries".into(),
|
||||
Value::List(vec![
|
||||
Value::String("/hidden/a".into()),
|
||||
Value::String("/hidden/b".into()),
|
||||
]),
|
||||
),
|
||||
("ordinary".into(), Value::String("/not-an-entry".into())),
|
||||
])),
|
||||
validator: None,
|
||||
},
|
||||
default_wire_limits(),
|
||||
)
|
||||
.unwrap()),
|
||||
});
|
||||
assert_eq!(
|
||||
runtime
|
||||
.app
|
||||
.history
|
||||
.iter()
|
||||
.filter(|item| item.entry_target.is_some())
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert!(!runtime.app.entries.contains_key("/hidden/a"));
|
||||
assert!(!runtime.app.entries.contains_key("/hidden/b"));
|
||||
assert!(!runtime.app.entries.contains_key("/not-an-entry"));
|
||||
assert!(runtime.app.entries["/"].children.is_empty());
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
runtime.app.focus = crate::app::Focus::History;
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
let requests = runtime.transport.0.lock().unwrap();
|
||||
assert_eq!(
|
||||
requests.len(),
|
||||
1,
|
||||
"only the selected typed Entry is observed"
|
||||
);
|
||||
let observe =
|
||||
wip_http::decode_observe_request(requests[0].body(), default_wire_limits()).unwrap();
|
||||
assert_eq!(observe.path, "/hidden/b");
|
||||
assert_eq!(observe.depth, 0);
|
||||
assert!(
|
||||
!runtime.app.entries.contains_key("/hidden"),
|
||||
"no inferred indexable parent"
|
||||
);
|
||||
assert!(!runtime.app.entries.contains_key("/hidden/a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_change_during_confirmation_never_retargets_the_old_editor() {
|
||||
let mut runtime = populated();
|
||||
confirm_local(&mut runtime);
|
||||
runtime.app.selected_path = "/".into();
|
||||
runtime.handle_key(InputKey::Enter);
|
||||
assert!(matches!(runtime.app.modal, Modal::None));
|
||||
assert!(runtime.transport.0.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
runtime
|
||||
.client
|
||||
.interface(&runtime.session, &reference("/item"))
|
||||
.unwrap()
|
||||
.state,
|
||||
ObservationState::Fresh
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user