Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d58809bdbc | ||
|
|
84cb5904df | ||
|
|
fc52d72a01 | ||
|
|
a7186173b4 | ||
|
|
827bef8478 | ||
|
|
b2be41d540 | ||
|
|
cc0ec0ccc8 | ||
|
|
755e6aeb88 | ||
|
|
fe6dccda83 | ||
|
|
8b8041cba1 | ||
|
|
4544bc0d8b | ||
|
|
8ecc307fc9 | ||
|
|
bf5fa54f44 | ||
|
|
c6528c2887 | ||
|
|
b196047b57 | ||
|
|
ea49cb0586 | ||
|
|
da559de912 | ||
|
|
193ca89d93 |
@@ -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
+4
-2
@@ -1301,7 +1301,9 @@ version = "0.1.0"
|
|||||||
name = "wip-public-api-example"
|
name = "wip-public-api-example"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"wip-client",
|
||||||
"wip-host",
|
"wip-host",
|
||||||
|
"wip-http",
|
||||||
"wip-interface",
|
"wip-interface",
|
||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
@@ -1341,9 +1343,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yoke-derive"
|
name = "yoke-derive"
|
||||||
version = "0.8.3"
|
version = "0.8.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
|
|||||||
+16
@@ -1,3 +1,19 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
|
[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"
|
||||||
|
|
||||||
|
[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.
|
||||||
@@ -13,29 +13,36 @@ repository root is not itself a package.
|
|||||||
## Crate graph and responsibilities
|
## Crate graph and responsibilities
|
||||||
|
|
||||||
```text
|
```text
|
||||||
wip-tui (interactive Worldspace explorer and operation editor)
|
Published libraries
|
||||||
├── wip-client Known Space, request identity, validators, and calls
|
|
||||||
├── wip-http framework-neutral HTTP request/response messages
|
|
||||||
└── wip-protocol descriptors and logical values
|
|
||||||
|
|
||||||
wip-fs-server (request-time filesystem projection and loopback listener)
|
wip-client
|
||||||
├── wip-http standard routes/codecs/envelopes
|
├── wip-http
|
||||||
├── wip-host request-scoped publication and dispatch
|
│ └── wip-protocol
|
||||||
└── wip-interface macro-generated filesystem capabilities
|
└── wip-protocol
|
||||||
|
|
||||||
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
wip-host
|
||||||
├── wip-protocol logical declarations, values, calls, and validation
|
├── wip-interface
|
||||||
├── wip-http standard HTTP v1 routes, JSON codecs, and envelopes
|
│ ├── wip-interface-macros
|
||||||
│ └── wip-protocol
|
│ └── wip-protocol
|
||||||
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
|
└── wip-protocol
|
||||||
│ ├── wip-http
|
|
||||||
│ └── wip-protocol
|
Workspace-only applications and conformance consumers
|
||||||
├── wip-interface application DTO codecs and interface authoring facade
|
|
||||||
│ ├── wip-protocol
|
wip-tui
|
||||||
│ └── wip-interface-macros proc-macro implementation detail
|
├── wip-client
|
||||||
└── wip-host descriptor registry, publication, and qualified dispatch
|
├── wip-http
|
||||||
├── wip-interface
|
└── wip-protocol
|
||||||
└── 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 |
|
| Crate | Responsibility | Does not own |
|
||||||
@@ -50,6 +57,21 @@ wip-public-api-example (workspace-only executable, integration tests, doctest)
|
|||||||
| `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-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. |
|
| `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
|
The boundary is intentional: protocol types describe what can cross a
|
||||||
transport; application DTOs opt into that model with `WipType`; a host-private
|
transport; application DTOs opt into that model with `WipType`; a host-private
|
||||||
implementation owns credentials, handles, and backend state; and `wip-http`
|
implementation owns credentials, handles, and backend state; and `wip-http`
|
||||||
@@ -57,6 +79,20 @@ maps standard routes/envelopes to `CallOperationRequest` and
|
|||||||
`CallOperationResponse` without placing transport-specific types in descriptors
|
`CallOperationResponse` without placing transport-specific types in descriptors
|
||||||
or application traits.
|
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
|
## End-to-end example
|
||||||
|
|
||||||
[`crates/wip-public-api-example/src/lib.rs`](crates/wip-public-api-example/src/lib.rs)
|
[`crates/wip-public-api-example/src/lib.rs`](crates/wip-public-api-example/src/lib.rs)
|
||||||
@@ -69,7 +105,7 @@ runs it. It demonstrates all of the following:
|
|||||||
2. two public traits declared with `#[wip::interface]`;
|
2. two public traits declared with `#[wip::interface]`;
|
||||||
3. a private host struct implementing both traits;
|
3. a private host struct implementing both traits;
|
||||||
4. explicit publication of both interfaces as an ordered set on one object;
|
4. explicit publication of both interfaces as an ordered set on one object;
|
||||||
5. separate observation of opaque interface references, descriptors, and
|
5. separate observation of structured interface references, descriptors, and
|
||||||
descriptor validators;
|
descriptor validators;
|
||||||
6. calls qualified by `target.path`, object validator, interface reference and
|
6. calls qualified by `target.path`, object validator, interface reference and
|
||||||
validator, operation, and schema-neutral `Value` arguments;
|
validator, operation, and schema-neutral `Value` arguments;
|
||||||
@@ -197,25 +233,44 @@ choose the ordered interface set for each object publication:
|
|||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
let mut interfaces = wip_host::InterfaceRegistry::new();
|
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)
|
let published = wip_host::PublishedObject::new(request_scoped_object)
|
||||||
.expose(&messenger)?;
|
.expose(&messenger)?
|
||||||
let protocol_object = published.protocol_object();
|
.bind_scope(current);
|
||||||
|
let protocol_object = published.protocol_object_at("/service/item")?;
|
||||||
```
|
```
|
||||||
|
|
||||||
`expose` compiles only when the object implements the generated definition's
|
`expose` compiles only when the object implements the generated definition's
|
||||||
interface trait. Implementing a trait does not expose it automatically, empty
|
interface trait. Implementing a trait does not expose it automatically, empty
|
||||||
interface sets are valid, insertion order is preserved, and duplicate
|
interface sets are valid, insertion order is preserved, and duplicate
|
||||||
references are rejected. Registry references are opaque and remain outside the
|
references are rejected. Registry collisions use exact `(scope, name)` pairs,
|
||||||
descriptor; generated descriptors contain neither those references nor Rust
|
not Rust Definition identity; the same Definition may be registered at multiple
|
||||||
trait identity.
|
coordinates. Structured references remain outside the Descriptor.
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
Dispatch is qualified by interface reference and operation name and targets a
|
Dispatch is qualified by interface reference and operation name and targets a
|
||||||
canonical Worldspace path. An `ObjectProvider` validates that path before
|
canonical Worldspace path. An `ObjectProvider` validates that path before
|
||||||
resolution, maps malformed paths to `InvalidRequest`, then resolves a valid path
|
resolution, maps malformed paths to `InvalidRequest`, then resolves a valid path
|
||||||
exactly once inside `with_object`; the host checks the supplied object validator,
|
exactly once inside `with_object`; the host checks the supplied object validator,
|
||||||
current interface membership, interface validator, descriptor operation,
|
current scope lifetime/optional scope_ref and interface membership, Interface
|
||||||
|
validator, Descriptor operation,
|
||||||
operation-specific object-validator policy, arguments, and authorization in
|
operation-specific object-validator policy, arguments, and authorization in
|
||||||
canonical precedence. Path and children remain provider resolution context and
|
canonical precedence. Path and children remain provider resolution context and
|
||||||
are never projected by `WipObject`; host-private fields and backend handles are
|
are never projected by `WipObject`; host-private fields and backend handles are
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-client"
|
name = "wip-client"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Presentation-independent stateful WIP client runtime"
|
description = "Presentation-independent stateful WIP client runtime"
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme = "README.md"
|
||||||
|
documentation = "https://docs.rs/wip-client"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
wip-http = { path = "../wip-http" }
|
wip-http.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
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.
|
||||||
+220
-26
@@ -21,8 +21,8 @@ use wip_http::{
|
|||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, InterfaceDescriptor,
|
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, InterfaceDescriptor,
|
||||||
InterfaceTarget, Object, ObjectObservation as ProtocolObjectObservation, ObserveRequest,
|
InterfaceReference, InterfaceTarget, Object, ObjectObservation as ProtocolObjectObservation,
|
||||||
OperationDeclaration, ProtocolError, ProtocolErrorCode, Target, Value,
|
ObserveRequest, OperationDeclaration, ProtocolError, ProtocolErrorCode, Target, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Monotonic identity assigned to one logical request.
|
/// Monotonic identity assigned to one logical request.
|
||||||
@@ -223,15 +223,23 @@ pub struct TreeObservation {
|
|||||||
pub state: ObservationState,
|
pub state: ObservationState,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cached interface descriptor observation.
|
/// Cached interface descriptor observation for one structured `(scope, name)` pair.
|
||||||
|
///
|
||||||
|
/// A known lost scope binding retires the descriptor rather than replacing only
|
||||||
|
/// its [`Self::scope_ref`]. A direct scope `observe` returning `NotFound` may remove
|
||||||
|
/// this cache entry; edge omission and local Object eviction do not prove deletion.
|
||||||
|
/// Prepared calls retain their own snapshot until result validation completes.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct InterfaceObservation {
|
pub struct InterfaceObservation {
|
||||||
/// Opaque interface reference.
|
/// Structured interface reference.
|
||||||
pub reference: String,
|
pub reference: InterfaceReference,
|
||||||
/// Last accepted descriptor, if one has been received.
|
/// Last accepted descriptor, if one has been received.
|
||||||
pub descriptor: Option<InterfaceDescriptor>,
|
pub descriptor: Option<InterfaceDescriptor>,
|
||||||
/// Optional interface validator. Absence makes the reference immutable.
|
/// Optional interface validator. Absence makes the descriptor immutable only
|
||||||
|
/// while the scope binding remains valid.
|
||||||
pub validator: Option<Vec<u8>>,
|
pub validator: Option<Vec<u8>>,
|
||||||
|
/// Optional opaque identity of the interface scope Object.
|
||||||
|
pub scope_ref: Option<String>,
|
||||||
/// Current observation lifecycle.
|
/// Current observation lifecycle.
|
||||||
pub state: ObservationState,
|
pub state: ObservationState,
|
||||||
}
|
}
|
||||||
@@ -243,6 +251,7 @@ pub struct CallContext {
|
|||||||
object_key: u64,
|
object_key: u64,
|
||||||
object: ObjectObservation,
|
object: ObjectObservation,
|
||||||
interface: InterfaceObservation,
|
interface: InterfaceObservation,
|
||||||
|
interface_revision: RequestId,
|
||||||
descriptor: InterfaceDescriptor,
|
descriptor: InterfaceDescriptor,
|
||||||
operation: OperationDeclaration,
|
operation: OperationDeclaration,
|
||||||
request: CallOperationRequest,
|
request: CallOperationRequest,
|
||||||
@@ -388,6 +397,9 @@ struct EntryRecord {
|
|||||||
object_key: Option<u64>,
|
object_key: Option<u64>,
|
||||||
revision: RequestId,
|
revision: RequestId,
|
||||||
state: ObservationState,
|
state: ObservationState,
|
||||||
|
// Retrieval state can change without losing the last accepted binding.
|
||||||
|
// Only confirmed unavailability ends that path's lifetime evidence.
|
||||||
|
confirmed_missing: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -404,7 +416,7 @@ struct Session {
|
|||||||
objects: BTreeMap<u64, ObjectRecord>,
|
objects: BTreeMap<u64, ObjectRecord>,
|
||||||
refs: BTreeMap<String, u64>,
|
refs: BTreeMap<String, u64>,
|
||||||
trees: BTreeMap<String, TreeObservation>,
|
trees: BTreeMap<String, TreeObservation>,
|
||||||
interfaces: BTreeMap<String, InterfaceRecord>,
|
interfaces: BTreeMap<InterfaceReference, InterfaceRecord>,
|
||||||
calls: VecDeque<CallRecord>,
|
calls: VecDeque<CallRecord>,
|
||||||
diagnostics: VecDeque<Diagnostic>,
|
diagnostics: VecDeque<Diagnostic>,
|
||||||
next_object_key: u64,
|
next_object_key: u64,
|
||||||
@@ -414,9 +426,28 @@ struct Session {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct InterfaceRecord {
|
struct InterfaceRecord {
|
||||||
observation: InterfaceObservation,
|
observation: InterfaceObservation,
|
||||||
|
// Ownership of this exact fetch/observation, not a Protocol identity.
|
||||||
|
revision: RequestId,
|
||||||
|
// Starting a refresh does not rebind its retained Descriptor. Scope evidence
|
||||||
|
// must still be able to retire that old lifetime while the refresh loads.
|
||||||
|
accepted_revision: RequestId,
|
||||||
|
// Scope evidence is shared across names and can also come from Observe.
|
||||||
|
// This private corroboration is never substituted for wire scope_ref and is
|
||||||
|
// retained only with the bounded Interface record, not as a new identity/key.
|
||||||
|
scope_binding: Option<String>,
|
||||||
|
binding_revision: RequestId,
|
||||||
touched: u64,
|
touched: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl InterfaceRecord {
|
||||||
|
fn retire(&mut self, revision: RequestId) {
|
||||||
|
self.revision = self.revision.max(revision);
|
||||||
|
self.observation.descriptor = None;
|
||||||
|
self.observation.validator = None;
|
||||||
|
self.observation.state = ObservationState::Stale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -594,9 +625,14 @@ impl Client {
|
|||||||
self.sessions.get(session)?.trees.get(path)
|
self.sessions.get(session)?.trees.get(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the current interface observation.
|
/// Returns the current interface observation, isolated by session and the
|
||||||
|
/// complete structured reference (never by display text or serialized JSON).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn interface(&self, session: &SessionId, reference: &str) -> Option<&InterfaceObservation> {
|
pub fn interface(
|
||||||
|
&self,
|
||||||
|
session: &SessionId,
|
||||||
|
reference: &InterfaceReference,
|
||||||
|
) -> Option<&InterfaceObservation> {
|
||||||
self.sessions
|
self.sessions
|
||||||
.get(session)?
|
.get(session)?
|
||||||
.interfaces
|
.interfaces
|
||||||
@@ -718,6 +754,7 @@ impl Client {
|
|||||||
object_key: None,
|
object_key: None,
|
||||||
revision: id,
|
revision: id,
|
||||||
state: ObservationState::Loading(id),
|
state: ObservationState::Loading(id),
|
||||||
|
confirmed_missing: false,
|
||||||
});
|
});
|
||||||
entry.revision = id;
|
entry.revision = id;
|
||||||
entry.state = ObservationState::Loading(id);
|
entry.state = ObservationState::Loading(id);
|
||||||
@@ -762,9 +799,8 @@ impl Client {
|
|||||||
pub fn ensure_interface(
|
pub fn ensure_interface(
|
||||||
&mut self,
|
&mut self,
|
||||||
session: &SessionId,
|
session: &SessionId,
|
||||||
reference: impl Into<String>,
|
reference: InterfaceReference,
|
||||||
) -> Result<Option<PreparedRequest>, ClientError> {
|
) -> Result<Option<PreparedRequest>, ClientError> {
|
||||||
let reference = reference.into();
|
|
||||||
let state = self.session(session)?;
|
let state = self.session(session)?;
|
||||||
if state.interfaces.contains_key(&reference)
|
if state.interfaces.contains_key(&reference)
|
||||||
|| state.interfaces.len() >= self.limits.interfaces_per_session
|
|| state.interfaces.len() >= self.limits.interfaces_per_session
|
||||||
@@ -782,11 +818,11 @@ impl Client {
|
|||||||
pub fn prepare_interface(
|
pub fn prepare_interface(
|
||||||
&mut self,
|
&mut self,
|
||||||
session: &SessionId,
|
session: &SessionId,
|
||||||
reference: impl Into<String>,
|
reference: InterfaceReference,
|
||||||
) -> Result<PreparedRequest, ClientError> {
|
) -> Result<PreparedRequest, ClientError> {
|
||||||
self.ensure_capacity()?;
|
self.ensure_capacity()?;
|
||||||
let request = FetchInterfaceRequest {
|
let request = FetchInterfaceRequest {
|
||||||
interface: reference.into(),
|
interface: reference,
|
||||||
};
|
};
|
||||||
let endpoint = session_endpoint(session)?;
|
let endpoint = session_endpoint(session)?;
|
||||||
let encoded = encode_fetch_interface_request(&endpoint, &request, self.wire_limits)
|
let encoded = encode_fetch_interface_request(&endpoint, &request, self.wire_limits)
|
||||||
@@ -797,6 +833,8 @@ impl Client {
|
|||||||
let maximum = self.limits.interfaces_per_session;
|
let maximum = self.limits.interfaces_per_session;
|
||||||
let state = self.session_mut(session)?;
|
let state = self.session_mut(session)?;
|
||||||
ensure_interface_slot(state, &request.interface, maximum)?;
|
ensure_interface_slot(state, &request.interface, maximum)?;
|
||||||
|
let (scope_binding, binding_revision) =
|
||||||
|
latest_scope_binding(state, &request.interface.scope);
|
||||||
let touched = state.tick();
|
let touched = state.tick();
|
||||||
let record = state
|
let record = state
|
||||||
.interfaces
|
.interfaces
|
||||||
@@ -804,12 +842,18 @@ impl Client {
|
|||||||
.or_insert(InterfaceRecord {
|
.or_insert(InterfaceRecord {
|
||||||
observation: InterfaceObservation {
|
observation: InterfaceObservation {
|
||||||
reference: request.interface.clone(),
|
reference: request.interface.clone(),
|
||||||
|
scope_ref: None,
|
||||||
descriptor: None,
|
descriptor: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
state: ObservationState::Loading(id),
|
state: ObservationState::Loading(id),
|
||||||
},
|
},
|
||||||
|
revision: id,
|
||||||
|
accepted_revision: RequestId(0),
|
||||||
|
scope_binding,
|
||||||
|
binding_revision,
|
||||||
touched,
|
touched,
|
||||||
});
|
});
|
||||||
|
record.revision = id;
|
||||||
record.observation.state = ObservationState::Loading(id);
|
record.observation.state = ObservationState::Loading(id);
|
||||||
record.touched = touched;
|
record.touched = touched;
|
||||||
self.pending.insert(
|
self.pending.insert(
|
||||||
@@ -827,13 +871,16 @@ impl Client {
|
|||||||
|
|
||||||
/// Constructs an operation from fresh object and interface observations.
|
/// Constructs an operation from fresh object and interface observations.
|
||||||
///
|
///
|
||||||
/// Membership, both validators, the descriptor, and the operation declaration
|
/// Membership, scope binding, both validators, the descriptor, and the operation
|
||||||
/// are fixed in the returned request's immutable [`CallContext`].
|
/// declaration are fixed in the returned request's immutable [`CallContext`].
|
||||||
|
/// The descriptor's optional `scope_ref` is copied unchanged, never substituted
|
||||||
|
/// from a separate Object observation. No ancestor fetch is required. Without
|
||||||
|
/// a scope ref, same-path replacement cannot always be detected.
|
||||||
pub fn prepare_call(
|
pub fn prepare_call(
|
||||||
&mut self,
|
&mut self,
|
||||||
session: &SessionId,
|
session: &SessionId,
|
||||||
path: &str,
|
path: &str,
|
||||||
interface: &str,
|
interface: &InterfaceReference,
|
||||||
operation: impl Into<String>,
|
operation: impl Into<String>,
|
||||||
arguments: BTreeMap<String, Value>,
|
arguments: BTreeMap<String, Value>,
|
||||||
) -> Result<PreparedRequest, ClientError> {
|
) -> Result<PreparedRequest, ClientError> {
|
||||||
@@ -879,6 +926,7 @@ impl Client {
|
|||||||
"interface observation is not fresh",
|
"interface observation is not fresh",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
let interface_revision = state.interfaces[interface].revision;
|
||||||
let descriptor = interface_observation
|
let descriptor = interface_observation
|
||||||
.descriptor
|
.descriptor
|
||||||
.clone()
|
.clone()
|
||||||
@@ -900,7 +948,8 @@ impl Client {
|
|||||||
validator: object.validator.clone(),
|
validator: object.validator.clone(),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: interface.to_owned(),
|
reference: interface.clone(),
|
||||||
|
scope_ref: interface_observation.scope_ref.clone(),
|
||||||
validator: interface_observation.validator.clone(),
|
validator: interface_observation.validator.clone(),
|
||||||
},
|
},
|
||||||
operation,
|
operation,
|
||||||
@@ -914,6 +963,7 @@ impl Client {
|
|||||||
object_key,
|
object_key,
|
||||||
object: object_observation,
|
object: object_observation,
|
||||||
interface: interface_observation,
|
interface: interface_observation,
|
||||||
|
interface_revision,
|
||||||
descriptor,
|
descriptor,
|
||||||
operation: operation_declaration,
|
operation: operation_declaration,
|
||||||
request,
|
request,
|
||||||
@@ -1131,6 +1181,11 @@ impl Client {
|
|||||||
error.to_string(),
|
error.to_string(),
|
||||||
))
|
))
|
||||||
};
|
};
|
||||||
|
if error.code == ProtocolErrorCode::NotFound {
|
||||||
|
let state = self.session_mut(session)?;
|
||||||
|
retire_scope_subtree(state, &request.path, id);
|
||||||
|
mark_subtree_stale(state, &request.path, id);
|
||||||
|
}
|
||||||
set_observe_subject_state(
|
set_observe_subject_state(
|
||||||
self.session_mut(session)?,
|
self.session_mut(session)?,
|
||||||
&request,
|
&request,
|
||||||
@@ -1158,8 +1213,37 @@ impl Client {
|
|||||||
match decode_fetch_interface_response(&request, &response, self.wire_limits) {
|
match decode_fetch_interface_response(&request, &response, self.wire_limits) {
|
||||||
Ok(DecodedResponse::Success(value)) => {
|
Ok(DecodedResponse::Success(value)) => {
|
||||||
let state = self.session_mut(session)?;
|
let state = self.session_mut(session)?;
|
||||||
let existing = &state.interfaces[&request.interface].observation;
|
// Newer scope evidence (Observe or another Interface name) can
|
||||||
|
// supersede even the first fetch for this pair.
|
||||||
|
let (scope_binding, binding_revision) =
|
||||||
|
latest_scope_binding(state, &request.interface.scope);
|
||||||
|
if binding_revision > id
|
||||||
|
&& value.scope_ref.is_some()
|
||||||
|
&& value.scope_ref != scope_binding
|
||||||
|
{
|
||||||
|
state
|
||||||
|
.interfaces
|
||||||
|
.get_mut(&request.interface)
|
||||||
|
.expect("interface exists")
|
||||||
|
.retire(binding_revision);
|
||||||
|
return self.reject_stale(session, id);
|
||||||
|
}
|
||||||
|
let existing_record = &state.interfaces[&request.interface];
|
||||||
|
let existing = &existing_record.observation;
|
||||||
|
let lost_wire_binding = existing.scope_ref.is_some() && value.scope_ref.is_none();
|
||||||
|
// Omission stays omission in the public observation and call. A
|
||||||
|
// known Object/sibling binding can still supply private lifetime
|
||||||
|
// evidence unless this response explicitly lost its prior ref.
|
||||||
|
let current_binding = if lost_wire_binding || value.scope_ref.is_some() {
|
||||||
|
value.scope_ref.clone()
|
||||||
|
} else {
|
||||||
|
scope_binding
|
||||||
|
};
|
||||||
|
let same_lifetime = existing.scope_ref == value.scope_ref
|
||||||
|
|| (current_binding.is_some()
|
||||||
|
&& existing_record.scope_binding == current_binding);
|
||||||
if let Some(descriptor) = &existing.descriptor
|
if let Some(descriptor) = &existing.descriptor
|
||||||
|
&& same_lifetime
|
||||||
&& ((existing.validator.is_none()
|
&& ((existing.validator.is_none()
|
||||||
&& (value.validator.is_some() || descriptor != &value.descriptor))
|
&& (value.validator.is_some() || descriptor != &value.descriptor))
|
||||||
|| (existing.validator.is_some()
|
|| (existing.validator.is_some()
|
||||||
@@ -1179,9 +1263,18 @@ impl Client {
|
|||||||
self.push_failure_diagnostic(session, id, &error)?;
|
self.push_failure_diagnostic(session, id, &error)?;
|
||||||
return Err(error);
|
return Err(error);
|
||||||
}
|
}
|
||||||
|
update_scope_binding(
|
||||||
|
state,
|
||||||
|
&request.interface.scope,
|
||||||
|
current_binding.clone(),
|
||||||
|
id,
|
||||||
|
false,
|
||||||
|
Some(&request.interface),
|
||||||
|
);
|
||||||
let touched = state.tick();
|
let touched = state.tick();
|
||||||
let observation = InterfaceObservation {
|
let observation = InterfaceObservation {
|
||||||
reference: value.interface,
|
reference: value.interface,
|
||||||
|
scope_ref: value.scope_ref,
|
||||||
descriptor: Some(value.descriptor),
|
descriptor: Some(value.descriptor),
|
||||||
validator: value.validator,
|
validator: value.validator,
|
||||||
state: ObservationState::Fresh,
|
state: ObservationState::Fresh,
|
||||||
@@ -1191,6 +1284,9 @@ impl Client {
|
|||||||
.get_mut(&request.interface)
|
.get_mut(&request.interface)
|
||||||
.expect("interface exists");
|
.expect("interface exists");
|
||||||
record.observation = observation.clone();
|
record.observation = observation.clone();
|
||||||
|
record.accepted_revision = id;
|
||||||
|
record.scope_binding = current_binding;
|
||||||
|
record.binding_revision = id;
|
||||||
record.touched = touched;
|
record.touched = touched;
|
||||||
Ok(Completion::Interface(observation))
|
Ok(Completion::Interface(observation))
|
||||||
}
|
}
|
||||||
@@ -1277,14 +1373,28 @@ impl Client {
|
|||||||
match error.code {
|
match error.code {
|
||||||
ProtocolErrorCode::ValidatorRequired
|
ProtocolErrorCode::ValidatorRequired
|
||||||
| ProtocolErrorCode::ValidatorMismatch
|
| ProtocolErrorCode::ValidatorMismatch
|
||||||
| ProtocolErrorCode::InterfaceMismatch => {
|
| ProtocolErrorCode::NotFound => {
|
||||||
state.mark_object_stale(context.object_key, id);
|
state.mark_object_stale(context.object_key, id);
|
||||||
}
|
}
|
||||||
|
ProtocolErrorCode::InterfaceMismatch => {
|
||||||
|
state.mark_object_stale(context.object_key, id);
|
||||||
|
if let Some(interface) =
|
||||||
|
state.interfaces.get_mut(&context.interface.reference)
|
||||||
|
&& interface.revision == context.interface_revision
|
||||||
|
{
|
||||||
|
// The call cannot reuse this observation, but mismatch
|
||||||
|
// alone does not prove the scope lifetime ended. Retain
|
||||||
|
// its Descriptor for same-binding consistency checks.
|
||||||
|
interface.revision = interface.revision.max(id);
|
||||||
|
interface.observation.state = ObservationState::Stale;
|
||||||
|
}
|
||||||
|
}
|
||||||
ProtocolErrorCode::InterfaceValidatorRequired
|
ProtocolErrorCode::InterfaceValidatorRequired
|
||||||
| ProtocolErrorCode::InterfaceValidatorMismatch => {
|
| ProtocolErrorCode::InterfaceValidatorMismatch => {
|
||||||
if let Some(interface) = state
|
if let Some(interface) = state
|
||||||
.interfaces
|
.interfaces
|
||||||
.get_mut(&context.request.interface.reference)
|
.get_mut(&context.request.interface.reference)
|
||||||
|
&& interface.revision == context.interface_revision
|
||||||
{
|
{
|
||||||
interface.observation.state = ObservationState::Stale;
|
interface.observation.state = ObservationState::Stale;
|
||||||
}
|
}
|
||||||
@@ -1466,7 +1576,7 @@ impl Client {
|
|||||||
fn interface_request_is_current(
|
fn interface_request_is_current(
|
||||||
&self,
|
&self,
|
||||||
session: &SessionId,
|
session: &SessionId,
|
||||||
reference: &str,
|
reference: &InterfaceReference,
|
||||||
id: RequestId,
|
id: RequestId,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
@@ -1511,7 +1621,7 @@ impl Client {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum RetrievalSubject {
|
enum RetrievalSubject {
|
||||||
Observe(ObserveRequest),
|
Observe(ObserveRequest),
|
||||||
Interface(String),
|
Interface(InterfaceReference),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -1617,7 +1727,7 @@ fn set_observe_subject_state(
|
|||||||
|
|
||||||
fn ensure_interface_slot(
|
fn ensure_interface_slot(
|
||||||
state: &mut Session,
|
state: &mut Session,
|
||||||
reference: &str,
|
reference: &InterfaceReference,
|
||||||
maximum: usize,
|
maximum: usize,
|
||||||
) -> Result<(), ClientError> {
|
) -> Result<(), ClientError> {
|
||||||
if state.interfaces.contains_key(reference) || state.interfaces.len() < maximum {
|
if state.interfaces.contains_key(reference) || state.interfaces.len() < maximum {
|
||||||
@@ -1754,6 +1864,12 @@ fn insert_object(
|
|||||||
let existing_path_key = existing_path_entry
|
let existing_path_key = existing_path_entry
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|entry| entry.object_key);
|
.and_then(|entry| entry.object_key);
|
||||||
|
let previous_scope_ref = existing_path_entry
|
||||||
|
.as_ref()
|
||||||
|
.filter(|entry| !entry.confirmed_missing)
|
||||||
|
.and_then(|entry| entry.object_key)
|
||||||
|
.and_then(|key| state.objects.get(&key))
|
||||||
|
.and_then(|record| record.object.r#ref.clone());
|
||||||
let replaceable_key = existing_path_key.filter(|key| {
|
let replaceable_key = existing_path_key.filter(|key| {
|
||||||
state
|
state
|
||||||
.objects
|
.objects
|
||||||
@@ -1831,6 +1947,7 @@ fn insert_object(
|
|||||||
object_key: Some(key),
|
object_key: Some(key),
|
||||||
revision: ownership_revision,
|
revision: ownership_revision,
|
||||||
state: ObservationState::Stale,
|
state: ObservationState::Stale,
|
||||||
|
confirmed_missing: false,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -1838,9 +1955,15 @@ fn insert_object(
|
|||||||
object_key: Some(key),
|
object_key: Some(key),
|
||||||
revision,
|
revision,
|
||||||
state: ObservationState::Fresh,
|
state: ObservationState::Fresh,
|
||||||
|
confirmed_missing: false,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
state.entries.insert(path.to_owned(), entry);
|
state.entries.insert(path.to_owned(), entry);
|
||||||
|
if !suppressed {
|
||||||
|
let scope_ref = state.objects[&key].object.r#ref.clone();
|
||||||
|
let changed = previous_scope_ref.is_some() && previous_scope_ref != scope_ref;
|
||||||
|
update_scope_binding(state, path, scope_ref, revision, changed, None);
|
||||||
|
}
|
||||||
Ok(key)
|
Ok(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1989,15 +2112,86 @@ fn reserve_observation_metadata(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mark_subtree_stale(state: &mut Session, root: &str, request_id: RequestId) {
|
// Only retained observations contribute scope evidence. No unbounded scope
|
||||||
let prefix = format!("{root}/");
|
// tombstones or synthetic identity are needed: evidence is kept with bounded
|
||||||
|
// Interface records, survives Object eviction, and disappears with cache cleanup.
|
||||||
|
fn latest_scope_binding(state: &Session, scope: &str) -> (Option<String>, RequestId) {
|
||||||
|
let object_binding = state
|
||||||
|
.entries
|
||||||
|
.get(scope)
|
||||||
|
.filter(|entry| !entry.confirmed_missing)
|
||||||
|
.and_then(|entry| entry.object_key)
|
||||||
|
.and_then(|key| state.objects.get(&key))
|
||||||
|
.map(|record| (record.object.r#ref.clone(), record.revision));
|
||||||
|
state
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.filter(|(reference, _)| reference.scope == scope)
|
||||||
|
.map(|(_, record)| (record.scope_binding.clone(), record.binding_revision))
|
||||||
|
.chain(object_binding)
|
||||||
|
.max_by_key(|(_, revision)| *revision)
|
||||||
|
.unwrap_or((None, RequestId(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_scope_binding(
|
||||||
|
state: &mut Session,
|
||||||
|
scope: &str,
|
||||||
|
scope_ref: Option<String>,
|
||||||
|
revision: RequestId,
|
||||||
|
confirmed_change: bool,
|
||||||
|
except: Option<&InterfaceReference>,
|
||||||
|
) {
|
||||||
|
for (reference, interface) in &mut state.interfaces {
|
||||||
|
if reference.scope != scope
|
||||||
|
|| except == Some(reference)
|
||||||
|
|| interface.accepted_revision > revision
|
||||||
|
|| interface.binding_revision > revision
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if confirmed_change
|
||||||
|
|| (interface.scope_binding.is_some() && interface.scope_binding != scope_ref)
|
||||||
|
{
|
||||||
|
interface.retire(revision);
|
||||||
|
}
|
||||||
|
// Corroboration is not wire metadata: never update observation.scope_ref
|
||||||
|
// on a retained Descriptor, even when the first known ref is learned.
|
||||||
|
interface.scope_binding = scope_ref.clone();
|
||||||
|
interface.binding_revision = revision;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_subtree_path(root: &str, path: &str) -> bool {
|
||||||
|
root == "/"
|
||||||
|
|| path == root
|
||||||
|
|| path
|
||||||
|
.strip_prefix(root)
|
||||||
|
.is_some_and(|suffix| suffix.starts_with('/'))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Direct NotFound confirms that this scope path is no longer available. Edge
|
||||||
|
// omission and local eviction deliberately do not call this function.
|
||||||
|
fn retire_scope_subtree(state: &mut Session, root: &str, revision: RequestId) {
|
||||||
for (path, entry) in &mut state.entries {
|
for (path, entry) in &mut state.entries {
|
||||||
if (path == root || path.starts_with(&prefix)) && entry.revision <= request_id {
|
if is_subtree_path(root, path) && entry.revision <= revision {
|
||||||
|
entry.confirmed_missing = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.interfaces.retain(|reference, record| {
|
||||||
|
!is_subtree_path(root, &reference.scope) || record.accepted_revision > revision
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mark_subtree_stale(state: &mut Session, root: &str, request_id: RequestId) {
|
||||||
|
for (path, entry) in &mut state.entries {
|
||||||
|
if is_subtree_path(root, path) && entry.revision <= request_id {
|
||||||
|
entry.revision = request_id;
|
||||||
entry.state = ObservationState::Stale;
|
entry.state = ObservationState::Stale;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (path, tree) in &mut state.trees {
|
for (path, tree) in &mut state.trees {
|
||||||
if (path == root || path.starts_with(&prefix)) && tree.revision <= request_id {
|
if is_subtree_path(root, path) && tree.revision <= request_id {
|
||||||
|
tree.revision = request_id;
|
||||||
tree.state = ObservationState::Stale;
|
tree.state = ObservationState::Stale;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||||
|
wip_protocol::InterfaceReference {
|
||||||
|
scope: "/".into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use wip_client::{
|
use wip_client::{
|
||||||
@@ -6,13 +13,14 @@ use wip_client::{
|
|||||||
};
|
};
|
||||||
use wip_http::http::{Response, StatusCode};
|
use wip_http::http::{Response, StatusCode};
|
||||||
use wip_http::{
|
use wip_http::{
|
||||||
Limits, encode_fetch_interface_response, encode_observe_response,
|
Limits, decode_call_operation_request, decode_fetch_interface_request,
|
||||||
encode_protocol_error_response,
|
encode_fetch_interface_response, encode_observe_response, encode_protocol_error_response,
|
||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1,
|
||||||
Object, ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration,
|
InterfaceDescriptor, InterfaceReference, InterfaceTarget, Object, ObjectObservation,
|
||||||
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ReturnDeclaration, TypeExpr, Value,
|
ObserveRequest, OperationDeclaration, ParameterDeclaration, ProtocolError, ProtocolErrorCode,
|
||||||
|
ProtocolInteraction, ReturnDeclaration, Target, TypeExpr, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
@@ -39,7 +47,7 @@ fn object() -> Object {
|
|||||||
Object {
|
Object {
|
||||||
name: "item".into(),
|
name: "item".into(),
|
||||||
description: None,
|
description: None,
|
||||||
interfaces: vec!["math".into()],
|
interfaces: vec![root_reference("math")],
|
||||||
r#ref: None,
|
r#ref: None,
|
||||||
validator: Some(b"object-v1".to_vec()),
|
validator: Some(b"object-v1".to_vec()),
|
||||||
}
|
}
|
||||||
@@ -67,12 +75,358 @@ fn descriptor(format: &str) -> InterfaceDescriptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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]
|
#[test]
|
||||||
fn malformed_json_unknown_fields_duplicates_and_invalid_success_are_invalid_response() {
|
fn malformed_json_unknown_fields_duplicates_and_invalid_success_are_invalid_response() {
|
||||||
let cases: &[&[u8]] = &[
|
let cases: &[&[u8]] = &[
|
||||||
b"{not json",
|
b"{not json",
|
||||||
br#"{"name":"item","interfaces":[],"unknown":true}"#,
|
br#"{"name":"item","interfaces":[],"unknown":true}"#,
|
||||||
br#"{"name":"item","interfaces":["math","math"]}"#,
|
br#"{"name":"item","interfaces":[{"scope":"/","name":"math"},{"scope":"/","name":"math"}]}"#,
|
||||||
br#"{"name":"wrong","interfaces":[]}"#,
|
br#"{"name":"wrong","interfaces":[]}"#,
|
||||||
];
|
];
|
||||||
for body in cases {
|
for body in cases {
|
||||||
@@ -181,12 +535,15 @@ fn non_success_without_valid_envelope_remains_transport_failure() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn unsupported_descriptor_format_is_distinct_from_invalid_response() {
|
fn unsupported_descriptor_format_is_distinct_from_invalid_response() {
|
||||||
let (mut client, session) = setup();
|
let (mut client, session) = setup();
|
||||||
let request = client.prepare_interface(&session, "math").unwrap();
|
let request = client
|
||||||
|
.prepare_interface(&session, root_reference("math"))
|
||||||
|
.unwrap();
|
||||||
let logical = FetchInterfaceRequest {
|
let logical = FetchInterfaceRequest {
|
||||||
interface: "math".into(),
|
interface: root_reference("math"),
|
||||||
};
|
};
|
||||||
let value = FetchInterfaceResponse {
|
let value = FetchInterfaceResponse {
|
||||||
interface: "math".into(),
|
scope_ref: None,
|
||||||
|
interface: root_reference("math"),
|
||||||
descriptor: descriptor("future-format/2"),
|
descriptor: descriptor("future-format/2"),
|
||||||
validator: Some(b"v2".to_vec()),
|
validator: Some(b"v2".to_vec()),
|
||||||
};
|
};
|
||||||
@@ -216,16 +573,19 @@ fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object()
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let interface = client.prepare_interface(&session, "math").unwrap();
|
let interface = client
|
||||||
|
.prepare_interface(&session, root_reference("math"))
|
||||||
|
.unwrap();
|
||||||
client
|
client
|
||||||
.complete(
|
.complete(
|
||||||
interface.id,
|
interface.id,
|
||||||
encode_fetch_interface_response(
|
encode_fetch_interface_response(
|
||||||
&FetchInterfaceRequest {
|
&FetchInterfaceRequest {
|
||||||
interface: "math".into(),
|
interface: root_reference("math"),
|
||||||
},
|
},
|
||||||
&FetchInterfaceResponse {
|
&FetchInterfaceResponse {
|
||||||
interface: "math".into(),
|
scope_ref: None,
|
||||||
|
interface: root_reference("math"),
|
||||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
@@ -238,7 +598,7 @@ fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object()
|
|||||||
.prepare_call(
|
.prepare_call(
|
||||||
&session,
|
&session,
|
||||||
"/item",
|
"/item",
|
||||||
"math",
|
&root_reference("math"),
|
||||||
"calculate",
|
"calculate",
|
||||||
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||||
)
|
)
|
||||||
@@ -293,16 +653,19 @@ fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let interface = client.prepare_interface(&session, "math").unwrap();
|
let interface = client
|
||||||
|
.prepare_interface(&session, root_reference("math"))
|
||||||
|
.unwrap();
|
||||||
client
|
client
|
||||||
.complete(
|
.complete(
|
||||||
interface.id,
|
interface.id,
|
||||||
encode_fetch_interface_response(
|
encode_fetch_interface_response(
|
||||||
&FetchInterfaceRequest {
|
&FetchInterfaceRequest {
|
||||||
interface: "math".into(),
|
interface: root_reference("math"),
|
||||||
},
|
},
|
||||||
&FetchInterfaceResponse {
|
&FetchInterfaceResponse {
|
||||||
interface: "math".into(),
|
scope_ref: None,
|
||||||
|
interface: root_reference("math"),
|
||||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
@@ -315,7 +678,7 @@ fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
|||||||
.prepare_call(
|
.prepare_call(
|
||||||
&session,
|
&session,
|
||||||
"/item",
|
"/item",
|
||||||
"math",
|
&root_reference("math"),
|
||||||
"calculate",
|
"calculate",
|
||||||
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||||
)
|
)
|
||||||
|
|||||||
+1568
-55
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,21 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-fs-server"
|
name = "wip-fs-server"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
description = "Request-time filesystem projection server for WIP over HTTP"
|
rust-version.workspace = true
|
||||||
license = "MIT OR Apache-2.0"
|
description = "Extensible request-time filesystem projection library and WIP over HTTP server"
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
http = "1"
|
http = "1"
|
||||||
rustix = { version = "1.1", features = ["fs"] }
|
rustix = { version = "1.1", features = ["fs"] }
|
||||||
wip-host = { path = "../wip-host" }
|
wip-host.workspace = true
|
||||||
wip-http = { path = "../wip-http" }
|
wip-http.workspace = true
|
||||||
wip-interface = { path = "../wip-interface" }
|
wip-interface.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@@ -6,6 +6,169 @@ 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,
|
operation dispatch and uses the standard `wip-http` routes, JSON codecs,
|
||||||
envelopes, and HTTP status mapping.
|
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
|
## Security model
|
||||||
|
|
||||||
- The effective root is opened once as a directory capability. Root path
|
- The effective root is opened once as a directory capability. Root path
|
||||||
@@ -82,13 +245,17 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/observe \
|
|||||||
--data '{"path":"/","depth":2}'
|
--data '{"path":"/","depth":2}'
|
||||||
```
|
```
|
||||||
|
|
||||||
A regular-file observation returns the opaque read interface reference and an object
|
A regular-file observation returns a structured read interface reference and an
|
||||||
validator. Retrieve that descriptor with:
|
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
|
```console
|
||||||
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_interface \
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_interface \
|
||||||
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
--data '{"interface":"<read-interface-from-observation>"}'
|
--data '{"interface":{"scope":"/","name":"file.read"}}'
|
||||||
```
|
```
|
||||||
|
|
||||||
Then call a bounded range read:
|
Then call a bounded range read:
|
||||||
@@ -98,7 +265,7 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
|||||||
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
--data '{
|
--data '{
|
||||||
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
"interface":{"reference":"<read-interface>"},
|
"interface":{"reference":{"scope":"/","name":"file.read"}},
|
||||||
"operation":"read",
|
"operation":"read",
|
||||||
"arguments":{"offset":0,"length":4096}
|
"arguments":{"offset":0,"length":4096}
|
||||||
}'
|
}'
|
||||||
@@ -112,7 +279,7 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
|||||||
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
--data '{
|
--data '{
|
||||||
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
"interface":{"reference":"<write-interface>"},
|
"interface":{"reference":{"scope":"/","name":"file.write"}},
|
||||||
"operation":"replace",
|
"operation":"replace",
|
||||||
"arguments":{"contents":"dXBkYXRlZA=="}
|
"arguments":{"contents":"dXBkYXRlZA=="}
|
||||||
}'
|
}'
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,12 +7,59 @@
|
|||||||
//! - [`wip_http`] owns routes, JSON, envelopes, and status mapping;
|
//! - [`wip_http`] owns routes, JSON, envelopes, and status mapping;
|
||||||
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
//! - 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,
|
//! The built-in HTTP listener is intentionally loopback-only. TLS termination,
|
||||||
//! certificates, authentication, and externally visible schemes are independent
|
//! certificates, authentication, and externally visible schemes are independent
|
||||||
//! deployment concerns rather than WIP transport profiles.
|
//! deployment concerns rather than WIP transport profiles.
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
mod defaults;
|
||||||
|
mod engine;
|
||||||
|
mod http_adapter;
|
||||||
mod interfaces;
|
mod interfaces;
|
||||||
mod projection;
|
mod projection;
|
||||||
mod server;
|
mod server;
|
||||||
@@ -21,7 +68,17 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
pub use interfaces::{FileRead, FileWrite, SymlinkInspect};
|
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};
|
pub use server::{BoundServer, ServerBuildError, WipFsServer};
|
||||||
|
|
||||||
/// Filesystem capabilities published by regular files.
|
/// Filesystem capabilities published by regular files.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -5,26 +5,20 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use http::header::ALLOW;
|
|
||||||
use http::{Request, Response, StatusCode};
|
use http::{Request, Response, StatusCode};
|
||||||
use wip_host::{ExecutionContext, ObjectProvider};
|
use wip_host::ExecutionContext;
|
||||||
use wip_http::{
|
use wip_http::Endpoint;
|
||||||
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::projection::Projection;
|
use crate::engine::Projection;
|
||||||
use crate::{ConfigError, ServerConfig};
|
use crate::http_adapter::HttpAdapter;
|
||||||
|
use crate::{ConfigError, DefaultComposition, DefaultPolicy, LinuxBackend, ServerConfig};
|
||||||
|
|
||||||
/// Filesystem projection and framework-neutral standard WIP request adapter.
|
/// Default Linux filesystem projection and bounded loopback HTTP listener.
|
||||||
pub struct WipFsServer {
|
pub struct WipFsServer {
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
endpoint: Endpoint,
|
endpoint: Endpoint,
|
||||||
effective_root: std::path::PathBuf,
|
effective_root: std::path::PathBuf,
|
||||||
projection: Arc<Projection>,
|
projection: Arc<Projection<LinuxBackend, DefaultComposition, DefaultPolicy>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WipFsServer {
|
impl WipFsServer {
|
||||||
@@ -32,8 +26,8 @@ impl WipFsServer {
|
|||||||
pub fn new(config: ServerConfig) -> Result<Self, ServerBuildError> {
|
pub fn new(config: ServerConfig) -> Result<Self, ServerBuildError> {
|
||||||
config.validate()?;
|
config.validate()?;
|
||||||
let endpoint = config.endpoint()?;
|
let endpoint = config.endpoint()?;
|
||||||
let projection = Projection::open(&config.root, config.access, config.limits)?;
|
let projection = crate::default_projection(&config.root, config.access, config.limits)?;
|
||||||
let effective_root = projection.effective_root()?;
|
let effective_root = projection.backend().effective_root()?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
config,
|
config,
|
||||||
endpoint,
|
endpoint,
|
||||||
@@ -67,25 +61,12 @@ impl WipFsServer {
|
|||||||
request: Request<Vec<u8>>,
|
request: Request<Vec<u8>>,
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
) -> Response<Vec<u8>> {
|
) -> 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 context = ExecutionContext::new()
|
let context = ExecutionContext::new()
|
||||||
.with_deadline(deadline)
|
.with_deadline(deadline)
|
||||||
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
||||||
let response = match route {
|
let view = self.projection.view(&());
|
||||||
Route::Observe => self.observe(request.body(), &context),
|
HttpAdapter::new(&view, &self.endpoint, self.config.limits)
|
||||||
Route::FetchInterface => self.fetch_interface(request.body()),
|
.handle_http_with_context(request, &context)
|
||||||
Route::CallOperation => self.call_operation(request.body(), &context),
|
|
||||||
};
|
|
||||||
if Instant::now() >= deadline {
|
|
||||||
empty_response(StatusCode::GATEWAY_TIMEOUT)
|
|
||||||
} else {
|
|
||||||
response
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Binds the built-in bounded loopback HTTP listener.
|
/// Binds the built-in bounded loopback HTTP listener.
|
||||||
@@ -108,171 +89,6 @@ impl WipFsServer {
|
|||||||
listener: Arc::new(listener),
|
listener: Arc::new(listener),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::Observe, error),
|
|
||||||
};
|
|
||||||
match self.projection.observe(context, &request) {
|
|
||||||
Ok(tree) => encode_observe_response(&request, &tree, self.config.limits.wire)
|
|
||||||
.unwrap_or_else(|error| {
|
|
||||||
self.read_encode_error(ProtocolInteraction::Observe, error)
|
|
||||||
}),
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fetch_interface(&self, body: &[u8]) -> Response<Vec<u8>> {
|
|
||||||
let request = match decode_fetch_interface_request(body, self.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::FetchInterface, error),
|
|
||||||
};
|
|
||||||
match self.projection.fetch_interface(&request) {
|
|
||||||
Ok(interface) => {
|
|
||||||
encode_fetch_interface_response(&request, &interface, self.config.limits.wire)
|
|
||||||
.unwrap_or_else(|error| {
|
|
||||||
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call_operation(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
|
||||||
let metadata = match decode_call_operation_metadata(body, self.config.limits.wire) {
|
|
||||||
Ok(metadata) => metadata,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::CallOperation, error),
|
|
||||||
};
|
|
||||||
let may_commit = metadata.operation == "replace";
|
|
||||||
let decoded = std::sync::Mutex::new(None);
|
|
||||||
let execution = self.projection.call_operation_with_context_and_decoder(
|
|
||||||
context,
|
|
||||||
metadata.target.clone(),
|
|
||||||
metadata.interface.clone(),
|
|
||||||
metadata.operation.clone(),
|
|
||||||
|descriptor| {
|
|
||||||
let request = metadata.decode_request(body, descriptor, self.config.limits.wire)?;
|
|
||||||
let arguments = request.arguments.clone();
|
|
||||||
*decoded.lock().unwrap_or_else(|error| error.into_inner()) =
|
|
||||||
Some((request, descriptor.clone()));
|
|
||||||
Ok::<_, CodecError>(arguments)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
match execution.map_err(|error| error.protocol_error()) {
|
|
||||||
Ok(result) => {
|
|
||||||
let Some((request, descriptor)) = decoded
|
|
||||||
.into_inner()
|
|
||||||
.unwrap_or_else(|error| error.into_inner())
|
|
||||||
else {
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: if may_commit {
|
|
||||||
ProtocolErrorCode::OperationOutcomeUnknown
|
|
||||||
} else {
|
|
||||||
ProtocolErrorCode::Internal
|
|
||||||
},
|
|
||||||
message: "operation completed without response metadata".into(),
|
|
||||||
};
|
|
||||||
return self.protocol_error(ProtocolInteraction::CallOperation, &error);
|
|
||||||
};
|
|
||||||
encode_call_operation_response(
|
|
||||||
&request,
|
|
||||||
&descriptor,
|
|
||||||
&result,
|
|
||||||
self.config.limits.wire,
|
|
||||||
)
|
|
||||||
.unwrap_or_else(|encode_error| {
|
|
||||||
if matches!(
|
|
||||||
&encode_error,
|
|
||||||
EncodeHttpError::Codec(codec) if is_transport_limit(codec)
|
|
||||||
) {
|
|
||||||
return empty_response(StatusCode::INTERNAL_SERVER_ERROR);
|
|
||||||
}
|
|
||||||
if !may_commit {
|
|
||||||
return self
|
|
||||||
.read_encode_error(ProtocolInteraction::CallOperation, encode_error);
|
|
||||||
}
|
|
||||||
// Replacement may already be committed, so a response
|
|
||||||
// encoding failure cannot carry a non-commit guarantee.
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
|
||||||
message: "operation completed but its response could not be encoded".into(),
|
|
||||||
};
|
|
||||||
self.protocol_error(ProtocolInteraction::CallOperation, &error)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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, &internal_error()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn protocol_error(
|
|
||||||
&self,
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: &ProtocolError,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
encode_protocol_error_response(interaction, error, self.config.limits.wire)
|
|
||||||
.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bound real HTTP listener for a [`WipFsServer`].
|
/// Bound real HTTP listener for a [`WipFsServer`].
|
||||||
@@ -560,20 +376,6 @@ fn write_all_with_deadline(
|
|||||||
stream.flush()
|
stream.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_transport_limit(error: &CodecError) -> bool {
|
|
||||||
matches!(
|
|
||||||
error,
|
|
||||||
CodecError::BodyTooLarge { .. } | CodecError::NestingTooDeep { .. }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn internal_error() -> ProtocolError {
|
|
||||||
ProtocolError {
|
|
||||||
code: ProtocolErrorCode::Internal,
|
|
||||||
message: "filesystem server failed".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||||
Response::builder()
|
Response::builder()
|
||||||
.status(status)
|
.status(status)
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ fn real_listener_serves_three_core_interactions_and_write() {
|
|||||||
validator: file.validator.clone(),
|
validator: file.validator.clone(),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
|
scope_ref: None,
|
||||||
reference: file.interfaces[0].clone(),
|
reference: file.interfaces[0].clone(),
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
@@ -141,6 +142,7 @@ fn real_listener_serves_three_core_interactions_and_write() {
|
|||||||
validator: file.validator,
|
validator: file.validator,
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
|
scope_ref: None,
|
||||||
reference: file.interfaces[1].clone(),
|
reference: file.interfaces[1].clone(),
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
@@ -412,7 +414,7 @@ fn call_argument_decoding_does_not_mask_missing_target() {
|
|||||||
let config = ServerConfig::for_root(temporary.path());
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":{"scope":"/","name":"unknown"}},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
||||||
let request = http::Request::builder()
|
let request = http::Request::builder()
|
||||||
.method(http::Method::POST)
|
.method(http::Method::POST)
|
||||||
.uri(endpoint.route(Route::CallOperation).as_str())
|
.uri(endpoint.route(Route::CallOperation).as_str())
|
||||||
@@ -490,6 +492,7 @@ fn read_response_size_failure_is_transport_local() {
|
|||||||
validator: file.validator,
|
validator: file.validator,
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
|
scope_ref: None,
|
||||||
reference: file.interfaces[0].clone(),
|
reference: file.interfaces[0].clone(),
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
|
|||||||
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]
|
[package]
|
||||||
name = "wip-host"
|
name = "wip-host"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Host-side object publication and operation dispatch for WIP"
|
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]
|
[dependencies]
|
||||||
wip-interface = { path = "../wip-interface" }
|
wip-interface.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
trybuild = "1"
|
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.
|
||||||
+528
-106
@@ -3,7 +3,7 @@
|
|||||||
//! # Responsibility boundaries
|
//! # Responsibility boundaries
|
||||||
//!
|
//!
|
||||||
//! [`InterfaceRegistry::register`] validates and freezes a generated interface
|
//! [`InterfaceRegistry::register`] validates and freezes a generated interface
|
||||||
//! descriptor, assigns an opaque [`InterfaceRef`], and leaves that reference
|
//! descriptor at an explicit scope and local name, and leaves that reference
|
||||||
//! outside the descriptor. [`PublishedObject::expose`] explicitly combines a
|
//! outside the descriptor. [`PublishedObject::expose`] explicitly combines a
|
||||||
//! request-scoped Rust object with a registered interface; its
|
//! request-scoped Rust object with a registered interface; its
|
||||||
//! [`InterfaceImplementation`] bound proves at compile time that the object
|
//! [`InterfaceImplementation`] bound proves at compile time that the object
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
//! and a publication with no interfaces is valid.
|
//! and a publication with no interfaces is valid.
|
||||||
//!
|
//!
|
||||||
//! [`ObjectProvider::call_operation`] resolves `target.path` exactly once and
|
//! [`ObjectProvider::call_operation`] resolves `target.path` exactly once and
|
||||||
//! keeps the resulting object, interface membership, descriptor, implementation,
|
//! keeps the resulting object, current scope Object association/ref, interface
|
||||||
|
//! membership, descriptor, implementation,
|
||||||
//! and backend target fixed within the provider's [`ObjectProvider::with_object`]
|
//! and backend target fixed within the provider's [`ObjectProvider::with_object`]
|
||||||
//! callback. Dispatch is qualified by `(interface reference, operation name)`.
|
//! callback. Dispatch is qualified by `(interface reference, operation name)`.
|
||||||
//! The same frozen operation declaration validates both arguments and results.
|
//! The same frozen operation declaration validates both arguments and results.
|
||||||
@@ -29,14 +30,13 @@
|
|||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
use std::any::TypeId;
|
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use wip_interface::DispatchError;
|
use wip_interface::DispatchError;
|
||||||
@@ -49,8 +49,8 @@ pub use wip_protocol::{
|
|||||||
Target,
|
Target,
|
||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor, Object, ProtocolError,
|
FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor, InterfaceReference, Object,
|
||||||
ProtocolErrorCode, ValidationError, Value,
|
ProtocolError, ProtocolErrorCode, ValidationError, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Opaque bytes used as a conditional execution precondition.
|
/// Opaque bytes used as a conditional execution precondition.
|
||||||
@@ -187,30 +187,120 @@ impl ExecutionContext {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opaque host-assigned reference to one registered interface artifact.
|
/// One publication lifetime of the Object at a canonical scope path.
|
||||||
|
///
|
||||||
|
/// Clone while the same Object remains published, including state updates. Create
|
||||||
|
/// a new handle after deletion, replacement or movement, even with the same ref.
|
||||||
|
/// This private lifetime is not a Protocol identity component or generated ref.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Scope {
|
||||||
|
path: String,
|
||||||
|
lifetime: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scope {
|
||||||
|
/// Creates a fresh lifetime without implicitly publishing an Object.
|
||||||
|
pub fn new(path: impl Into<String>) -> Result<Self, ValidationError> {
|
||||||
|
let path = path.into();
|
||||||
|
wip_protocol::validate_path(&path)?;
|
||||||
|
Ok(Self {
|
||||||
|
path,
|
||||||
|
lifetime: Arc::new(AtomicBool::new(true)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the client-facing canonical scope path.
|
||||||
|
#[must_use]
|
||||||
|
pub fn path(&self) -> &str {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_lifetime(&self, other: &Self) -> bool {
|
||||||
|
self.path == other.path && Arc::ptr_eq(&self.lifetime, &other.lifetime)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active(&self) -> bool {
|
||||||
|
self.lifetime.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Provider-attested current scope Object association.
|
||||||
|
///
|
||||||
|
/// Construct only inside a coherent boundary that proves this lifetime belongs
|
||||||
|
/// to the Object at `scope.path()`. A prelookup or matching ref alone is not proof.
|
||||||
|
/// The Object need not expose interfaces. Its validator is not scope identity.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ScopeObservation {
|
||||||
|
scope: Scope,
|
||||||
|
reference: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScopeObservation {
|
||||||
|
/// Attests the association and captures the current Object's optional ref.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(scope: &Scope, object: &impl WipObject) -> Self {
|
||||||
|
Self {
|
||||||
|
scope: scope.clone(),
|
||||||
|
reference: object.reference().map(str::to_owned),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the observed optional ref.
|
||||||
|
#[must_use]
|
||||||
|
pub fn reference(&self) -> Option<&str> {
|
||||||
|
self.reference.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the associated scope publication lifetime.
|
||||||
|
#[must_use]
|
||||||
|
pub fn scope(&self) -> &Scope {
|
||||||
|
&self.scope
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structured client-facing reference to a scoped Interface publication.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct InterfaceRef(String);
|
pub struct InterfaceRef(InterfaceReference);
|
||||||
|
|
||||||
impl InterfaceRef {
|
impl InterfaceRef {
|
||||||
/// Returns the opaque reference for a protocol transport.
|
/// Returns the local name without parsing or adding display delimiters.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_str(&self) -> &str {
|
pub fn as_str(&self) -> &str {
|
||||||
&self.0
|
&self.0.name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the structured Protocol reference.
|
||||||
|
#[must_use]
|
||||||
|
pub fn protocol_reference(&self) -> InterfaceReference {
|
||||||
|
self.0.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One atomic observation of an interface reference, descriptor, and validator.
|
/// One atomic observation of an interface reference, descriptor, and validator.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct InterfaceObservation {
|
pub struct InterfaceObservation {
|
||||||
/// Opaque reference selected by published objects and operation calls.
|
/// Structured reference selected by published objects and operation calls.
|
||||||
pub reference: InterfaceRef,
|
pub reference: InterfaceRef,
|
||||||
/// Canonical descriptor frozen when the interface was registered.
|
/// Canonical descriptor frozen when the interface was registered.
|
||||||
pub descriptor: InterfaceDescriptor,
|
pub descriptor: InterfaceDescriptor,
|
||||||
|
/// Optional ref of the scope Object from this same observation.
|
||||||
|
pub scope_ref: Option<String>,
|
||||||
/// Optional validator. Its presence makes it a required call precondition.
|
/// Optional validator. Its presence makes it a required call precondition.
|
||||||
pub validator: Option<Validator>,
|
pub validator: Option<Validator>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InterfaceObservation {
|
impl InterfaceObservation {
|
||||||
|
/// Restricts this effective view to visible operations and reachable types.
|
||||||
|
///
|
||||||
|
/// Registry artifacts are unchanged. When operations are removed, interface-
|
||||||
|
/// wide documentation is omitted because it may describe hidden operations.
|
||||||
|
/// Providers must use the same predicate for publication and fetch.
|
||||||
|
#[must_use]
|
||||||
|
pub fn project_operations(mut self, visible: impl Fn(&str) -> bool) -> Self {
|
||||||
|
restrict_descriptor(&mut self.descriptor, visible);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Converts this host observation to a validated canonical protocol response.
|
/// Converts this host observation to a validated canonical protocol response.
|
||||||
///
|
///
|
||||||
/// A Host-side response construction failure is returned as `Internal`; it is
|
/// A Host-side response construction failure is returned as `Internal`; it is
|
||||||
@@ -218,13 +308,14 @@ impl InterfaceObservation {
|
|||||||
/// local validation error.
|
/// local validation error.
|
||||||
pub fn protocol_response(&self) -> Result<FetchInterfaceResponse, ProtocolError> {
|
pub fn protocol_response(&self) -> Result<FetchInterfaceResponse, ProtocolError> {
|
||||||
let response = FetchInterfaceResponse {
|
let response = FetchInterfaceResponse {
|
||||||
interface: self.reference.0.clone(),
|
interface: self.reference.protocol_reference(),
|
||||||
descriptor: self.descriptor.clone(),
|
descriptor: self.descriptor.clone(),
|
||||||
|
scope_ref: self.scope_ref.clone(),
|
||||||
validator: self.validator.as_ref().map(|validator| validator.0.clone()),
|
validator: self.validator.as_ref().map(|validator| validator.0.clone()),
|
||||||
};
|
};
|
||||||
response
|
response
|
||||||
.validate_for(&FetchInterfaceRequest {
|
.validate_for(&FetchInterfaceRequest {
|
||||||
interface: self.reference.0.clone(),
|
interface: self.reference.protocol_reference(),
|
||||||
})
|
})
|
||||||
.map_err(|_| ProtocolError {
|
.map_err(|_| ProtocolError {
|
||||||
code: ProtocolErrorCode::Internal,
|
code: ProtocolErrorCode::Internal,
|
||||||
@@ -236,6 +327,7 @@ impl InterfaceObservation {
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct InterfaceArtifact {
|
struct InterfaceArtifact {
|
||||||
|
scope: Scope,
|
||||||
reference: InterfaceRef,
|
reference: InterfaceRef,
|
||||||
descriptor: InterfaceDescriptor,
|
descriptor: InterfaceDescriptor,
|
||||||
validator: Option<Validator>,
|
validator: Option<Validator>,
|
||||||
@@ -244,7 +336,7 @@ struct InterfaceArtifact {
|
|||||||
/// A typed registration token for a generated interface definition.
|
/// A typed registration token for a generated interface definition.
|
||||||
///
|
///
|
||||||
/// Tokens can be reused by any number of request-scoped objects. They expose an
|
/// Tokens can be reused by any number of request-scoped objects. They expose an
|
||||||
/// opaque reference, not the Rust type name or an address.
|
/// scoped reference and a private publication lifetime, not a Rust address.
|
||||||
pub struct RegisteredInterface<D> {
|
pub struct RegisteredInterface<D> {
|
||||||
artifact: Arc<InterfaceArtifact>,
|
artifact: Arc<InterfaceArtifact>,
|
||||||
definition: PhantomData<fn() -> D>,
|
definition: PhantomData<fn() -> D>,
|
||||||
@@ -260,158 +352,161 @@ impl<D> Clone for RegisteredInterface<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<D> RegisteredInterface<D> {
|
impl<D> RegisteredInterface<D> {
|
||||||
/// Returns the opaque protocol reference assigned by the registry.
|
/// Returns the explicit scope/name reference.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn reference(&self) -> &InterfaceRef {
|
pub fn reference(&self) -> &InterfaceRef {
|
||||||
&self.artifact.reference
|
&self.artifact.reference
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registry of validated, immutable interface artifacts.
|
/// Registry of frozen definition artifacts and explicitly scoped registrations.
|
||||||
///
|
///
|
||||||
/// Generated descriptors are never rewritten to contain their assigned
|
/// Artifact retention is not proof of current publication. Fetch requires a live
|
||||||
/// references. A validator-free artifact is immutable for the lifetime of its
|
/// provider-attested ScopeObservation; execution requires the same lifetime in
|
||||||
/// reference. A validator-bearing artifact requires that exact validator on a
|
/// the target's atomic boundary. Collision keys are exact (scope, name) pairs,
|
||||||
/// call. Re-registering a definition is rejected rather than silently changing
|
/// not Rust TypeId: the same Definition can be registered at multiple coordinates.
|
||||||
/// the observation associated with an existing reference.
|
#[derive(Debug, Default)]
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct InterfaceRegistry {
|
pub struct InterfaceRegistry {
|
||||||
namespace: u64,
|
|
||||||
next_reference: u64,
|
|
||||||
definitions: HashSet<TypeId>,
|
|
||||||
artifacts: HashMap<InterfaceRef, Arc<InterfaceArtifact>>,
|
artifacts: HashMap<InterfaceRef, Arc<InterfaceArtifact>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
static NEXT_REGISTRY_NAMESPACE: AtomicU64 = AtomicU64::new(1);
|
|
||||||
|
|
||||||
impl Default for InterfaceRegistry {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
namespace: NEXT_REGISTRY_NAMESPACE.fetch_add(1, Ordering::Relaxed),
|
|
||||||
next_reference: 0,
|
|
||||||
definitions: HashSet::new(),
|
|
||||||
artifacts: HashMap::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl InterfaceRegistry {
|
impl InterfaceRegistry {
|
||||||
/// Creates an empty interface registry.
|
/// Creates an empty artifact registry without publishing any Object.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers and freezes one generated interface definition.
|
/// Freezes a Definition at an explicit scope and local name.
|
||||||
pub fn register<D>(
|
pub fn register<D>(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
scope: &Scope,
|
||||||
|
name: impl Into<String>,
|
||||||
_definition: D,
|
_definition: D,
|
||||||
validator: Option<Validator>,
|
validator: Option<Validator>,
|
||||||
) -> Result<RegisteredInterface<D>, RegistrationError>
|
) -> Result<RegisteredInterface<D>, RegistrationError>
|
||||||
where
|
where
|
||||||
D: InterfaceDefinition + 'static,
|
D: InterfaceDefinition + 'static,
|
||||||
{
|
{
|
||||||
let definition = TypeId::of::<D>();
|
let reference = InterfaceRef(InterfaceReference {
|
||||||
if self.definitions.contains(&definition) {
|
scope: scope.path.clone(),
|
||||||
|
name: name.into(),
|
||||||
|
});
|
||||||
|
reference
|
||||||
|
.0
|
||||||
|
.validate()
|
||||||
|
.map_err(RegistrationError::InvalidReference)?;
|
||||||
|
if !scope.active() {
|
||||||
|
return Err(RegistrationError::RetiredScope);
|
||||||
|
}
|
||||||
|
if self.artifacts.contains_key(&reference) {
|
||||||
return Err(RegistrationError::AlreadyRegistered);
|
return Err(RegistrationError::AlreadyRegistered);
|
||||||
}
|
}
|
||||||
|
|
||||||
let descriptor = D::descriptor();
|
let descriptor = D::descriptor();
|
||||||
descriptor
|
descriptor
|
||||||
.validate()
|
.validate()
|
||||||
.map_err(RegistrationError::InvalidDescriptor)?;
|
.map_err(RegistrationError::InvalidDescriptor)?;
|
||||||
|
|
||||||
let reference = InterfaceRef(format!(
|
|
||||||
"wip-interface:{}:{}",
|
|
||||||
self.namespace, self.next_reference
|
|
||||||
));
|
|
||||||
self.next_reference = self
|
|
||||||
.next_reference
|
|
||||||
.checked_add(1)
|
|
||||||
.ok_or(RegistrationError::ReferenceSpaceExhausted)?;
|
|
||||||
let artifact = Arc::new(InterfaceArtifact {
|
let artifact = Arc::new(InterfaceArtifact {
|
||||||
|
scope: scope.clone(),
|
||||||
reference: reference.clone(),
|
reference: reference.clone(),
|
||||||
descriptor,
|
descriptor,
|
||||||
validator,
|
validator,
|
||||||
});
|
});
|
||||||
self.definitions.insert(definition);
|
|
||||||
self.artifacts.insert(reference, Arc::clone(&artifact));
|
self.artifacts.insert(reference, Arc::clone(&artifact));
|
||||||
|
|
||||||
Ok(RegisteredInterface {
|
Ok(RegisteredInterface {
|
||||||
artifact,
|
artifact,
|
||||||
definition: PhantomData,
|
definition: PhantomData,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves a transport-provided opaque reference string in this registry.
|
/// Ends a scope lifetime and releases its registry entries.
|
||||||
|
///
|
||||||
|
/// Retained tokens cannot start new calls/fetches. Started calls retain their
|
||||||
|
/// frozen Descriptor. Re-publication requires a fresh Scope.
|
||||||
|
pub fn remove_scope(&mut self, scope: &Scope) {
|
||||||
|
scope.lifetime.store(false, Ordering::Release);
|
||||||
|
self.artifacts
|
||||||
|
.retain(|_, artifact| !artifact.scope.same_lifetime(scope));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a stored artifact, not evidence of current publication.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn resolve(&self, reference: &str) -> Option<InterfaceRef> {
|
pub fn resolve(&self, reference: &InterfaceReference) -> Option<InterfaceRef> {
|
||||||
let reference = InterfaceRef(reference.to_owned());
|
let reference = InterfaceRef(reference.clone());
|
||||||
self.artifacts.contains_key(&reference).then_some(reference)
|
self.artifacts.contains_key(&reference).then_some(reference)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Observes a registered interface by its host-side reference.
|
/// Iterates registered scope handles, possibly repeated for multiple names.
|
||||||
#[must_use]
|
pub fn scopes(&self) -> impl Iterator<Item = &Scope> {
|
||||||
pub fn observe_object(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
|
self.artifacts.values().map(|artifact| &artifact.scope)
|
||||||
self.artifacts.get(reference).map(Self::observation)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Implements canonical `fetch_interface` semantics for an opaque reference.
|
/// Fetches only with a coherent current scope Object attestation.
|
||||||
///
|
pub fn fetch_interface(
|
||||||
/// Unknown and currently unpublished references map to `InterfaceNotFound`,
|
&self,
|
||||||
/// not object membership errors or authorization failures.
|
reference: &InterfaceReference,
|
||||||
pub fn fetch_interface(&self, reference: &str) -> Result<InterfaceObservation, ProtocolError> {
|
current: &ScopeObservation,
|
||||||
let reference = InterfaceRef(reference.to_owned());
|
) -> Result<InterfaceObservation, ProtocolError> {
|
||||||
|
reference.validate().map_err(|error| ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: error.to_string(),
|
||||||
|
})?;
|
||||||
self.artifacts
|
self.artifacts
|
||||||
.get(&reference)
|
.get(&InterfaceRef(reference.clone()))
|
||||||
.map(Self::observation)
|
.filter(|artifact| {
|
||||||
.ok_or_else(|| ProtocolError {
|
artifact.scope.active() && artifact.scope.same_lifetime(¤t.scope)
|
||||||
code: ProtocolErrorCode::InterfaceNotFound,
|
|
||||||
message: "interface reference is not currently published".into(),
|
|
||||||
})
|
})
|
||||||
}
|
.map(|artifact| InterfaceObservation {
|
||||||
|
reference: artifact.reference.clone(),
|
||||||
fn observation(artifact: &Arc<InterfaceArtifact>) -> InterfaceObservation {
|
descriptor: artifact.descriptor.clone(),
|
||||||
InterfaceObservation {
|
scope_ref: current.reference.clone(),
|
||||||
reference: artifact.reference.clone(),
|
validator: artifact.validator.clone(),
|
||||||
descriptor: artifact.descriptor.clone(),
|
})
|
||||||
validator: artifact.validator.clone(),
|
.ok_or_else(interface_not_found)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Failure while registering a generated interface definition.
|
fn interface_not_found() -> ProtocolError {
|
||||||
|
ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "interface is not currently published".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure while registering a generated interface Definition.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum RegistrationError {
|
pub enum RegistrationError {
|
||||||
/// The same generated definition was already assigned a reference.
|
/// The exact scope/name coordinate is already occupied.
|
||||||
AlreadyRegistered,
|
AlreadyRegistered,
|
||||||
/// The generated descriptor is structurally invalid.
|
/// The generated Descriptor is invalid.
|
||||||
InvalidDescriptor(ValidationError),
|
InvalidDescriptor(ValidationError),
|
||||||
/// The registry cannot assign another opaque reference.
|
/// The scope or local name is invalid.
|
||||||
ReferenceSpaceExhausted,
|
InvalidReference(ValidationError),
|
||||||
|
/// The lifetime ended; re-publication needs a fresh Scope.
|
||||||
|
RetiredScope,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for RegistrationError {
|
impl Display for RegistrationError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::AlreadyRegistered => {
|
Self::AlreadyRegistered => {
|
||||||
formatter.write_str("interface definition already registered")
|
formatter.write_str("interface scope/name already registered")
|
||||||
}
|
}
|
||||||
Self::InvalidDescriptor(error) => {
|
Self::InvalidDescriptor(error) => {
|
||||||
write!(formatter, "invalid interface descriptor: {error}")
|
write!(formatter, "invalid interface descriptor: {error}")
|
||||||
}
|
}
|
||||||
Self::ReferenceSpaceExhausted => {
|
Self::InvalidReference(error) => {
|
||||||
formatter.write_str("interface reference space exhausted")
|
write!(formatter, "invalid interface reference: {error}")
|
||||||
}
|
}
|
||||||
|
Self::RetiredScope => formatter.write_str("scope publication lifetime has ended"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for RegistrationError {
|
impl Error for RegistrationError {
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidDescriptor(error) => Some(error),
|
Self::InvalidDescriptor(error) | Self::InvalidReference(error) => Some(error),
|
||||||
Self::AlreadyRegistered | Self::ReferenceSpaceExhausted => None,
|
Self::AlreadyRegistered | Self::RetiredScope => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -449,6 +544,60 @@ pub trait WipObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn restrict_descriptor(descriptor: &mut InterfaceDescriptor, visible: impl Fn(&str) -> bool) {
|
||||||
|
let count = descriptor.operations.len();
|
||||||
|
descriptor
|
||||||
|
.operations
|
||||||
|
.retain(|operation| visible(&operation.name));
|
||||||
|
if descriptor.operations.len() == count {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
descriptor.documentation = None;
|
||||||
|
let mut used = HashSet::new();
|
||||||
|
fn references(expression: &wip_protocol::TypeExpr, used: &mut HashSet<String>) {
|
||||||
|
use wip_protocol::TypeExpr;
|
||||||
|
match expression {
|
||||||
|
TypeExpr::Named { name } => {
|
||||||
|
used.insert(name.clone());
|
||||||
|
}
|
||||||
|
TypeExpr::Record { fields } => {
|
||||||
|
for field in fields {
|
||||||
|
references(&field.r#type, used);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TypeExpr::List { items } => references(items, used),
|
||||||
|
TypeExpr::Union { cases } => {
|
||||||
|
for case in cases {
|
||||||
|
if let Some(payload) = &case.payload {
|
||||||
|
references(payload, used);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for operation in &descriptor.operations {
|
||||||
|
for parameter in &operation.parameters {
|
||||||
|
references(¶meter.r#type, &mut used);
|
||||||
|
}
|
||||||
|
references(&operation.returns.r#type, &mut used);
|
||||||
|
}
|
||||||
|
loop {
|
||||||
|
let before = used.len();
|
||||||
|
for declaration in &descriptor.types {
|
||||||
|
if used.contains(&declaration.name) {
|
||||||
|
references(&declaration.definition, &mut used);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if before == used.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
descriptor
|
||||||
|
.types
|
||||||
|
.retain(|declaration| used.contains(&declaration.name));
|
||||||
|
}
|
||||||
|
|
||||||
type DispatchFn<T> = fn(&T, &str, BTreeMap<String, Value>) -> Result<Value, DispatchError>;
|
type DispatchFn<T> = fn(&T, &str, BTreeMap<String, Value>) -> Result<Value, DispatchError>;
|
||||||
|
|
||||||
struct BoundInterface<T> {
|
struct BoundInterface<T> {
|
||||||
@@ -464,6 +613,7 @@ struct BoundInterface<T> {
|
|||||||
pub struct PublishedObject<T: WipObject> {
|
pub struct PublishedObject<T: WipObject> {
|
||||||
implementation: T,
|
implementation: T,
|
||||||
interfaces: Vec<BoundInterface<T>>,
|
interfaces: Vec<BoundInterface<T>>,
|
||||||
|
scopes: Vec<ScopeObservation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: WipObject> PublishedObject<T> {
|
impl<T: WipObject> PublishedObject<T> {
|
||||||
@@ -473,13 +623,45 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
Self {
|
Self {
|
||||||
implementation,
|
implementation,
|
||||||
interfaces: Vec::new(),
|
interfaces: Vec::new(),
|
||||||
|
scopes: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Attaches a current scope snapshot inside the provider's atomic boundary.
|
||||||
|
///
|
||||||
|
/// Never populate this from a stale prelookup. Target, scope association,
|
||||||
|
/// Descriptor and backend handles must remain coherent through dispatch and
|
||||||
|
/// commit. A later same-path binding replaces the earlier snapshot.
|
||||||
|
#[must_use]
|
||||||
|
pub fn bind_scope(mut self, current: ScopeObservation) -> Self {
|
||||||
|
self.scopes
|
||||||
|
.retain(|old| old.scope.path != current.scope.path);
|
||||||
|
self.scopes.push(current);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_scope(&self, scope: &Scope) -> Option<&ScopeObservation> {
|
||||||
|
self.scopes
|
||||||
|
.iter()
|
||||||
|
.find(|current| scope.active() && scope.same_lifetime(¤t.scope))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scopes_valid_at(&self, path: &str) -> bool {
|
||||||
|
self.interfaces.iter().all(|bound| {
|
||||||
|
bound.artifact.reference.0.validate_for_path(path).is_ok()
|
||||||
|
&& self
|
||||||
|
.current_scope(&bound.artifact.scope)
|
||||||
|
.is_some_and(|current| {
|
||||||
|
current.scope.path != path
|
||||||
|
|| current.reference() == self.implementation.reference()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Explicitly exposes a registered generated interface in insertion order.
|
/// Explicitly exposes a registered generated interface in insertion order.
|
||||||
///
|
///
|
||||||
/// The `InterfaceImplementation<T>` bound is generated only when `T`
|
/// The `InterfaceImplementation<T>` bound is generated only when `T`
|
||||||
/// implements the corresponding Rust interface trait. Duplicate opaque
|
/// implements the corresponding Rust interface trait. Duplicate scoped
|
||||||
/// references are rejected.
|
/// references are rejected.
|
||||||
pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
|
pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
|
||||||
where
|
where
|
||||||
@@ -502,15 +684,60 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Restricts a publication to an ordered interface/operation view.
|
||||||
|
///
|
||||||
|
/// This never adds implementations or changes codecs. The provider must use
|
||||||
|
/// the identical operation predicate for `fetch_interface`, and keep the
|
||||||
|
/// effective view stable for the lifetime of its references. Filtered
|
||||||
|
/// descriptors are scoped to that view, not mutations of registry artifacts.
|
||||||
|
pub fn project(
|
||||||
|
mut self,
|
||||||
|
interfaces: &[InterfaceRef],
|
||||||
|
visible: impl Fn(&InterfaceRef, &str) -> bool,
|
||||||
|
) -> Result<Self, PublicationError> {
|
||||||
|
let mut projected = Vec::with_capacity(interfaces.len());
|
||||||
|
for reference in interfaces {
|
||||||
|
if projected
|
||||||
|
.iter()
|
||||||
|
.any(|bound: &BoundInterface<T>| &bound.artifact.reference == reference)
|
||||||
|
{
|
||||||
|
return Err(PublicationError::DuplicateInterface(reference.clone()));
|
||||||
|
}
|
||||||
|
let Some(index) = self
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.position(|bound| &bound.artifact.reference == reference)
|
||||||
|
else {
|
||||||
|
return Err(PublicationError::UnexposedInterface(reference.clone()));
|
||||||
|
};
|
||||||
|
let mut bound = self.interfaces.remove(index);
|
||||||
|
let mut descriptor = bound.artifact.descriptor.clone();
|
||||||
|
restrict_descriptor(&mut descriptor, |operation| visible(reference, operation));
|
||||||
|
bound.artifact = Arc::new(InterfaceArtifact {
|
||||||
|
scope: bound.artifact.scope.clone(),
|
||||||
|
reference: reference.clone(),
|
||||||
|
descriptor,
|
||||||
|
validator: bound.artifact.validator.clone(),
|
||||||
|
});
|
||||||
|
projected.push(bound);
|
||||||
|
}
|
||||||
|
self.interfaces = projected;
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the host-private implementation without projecting its fields.
|
/// Returns the host-private implementation without projecting its fields.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn implementation(&self) -> &T {
|
pub fn implementation(&self) -> &T {
|
||||||
&self.implementation
|
&self.implementation
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds canonical protocol object metadata in interface insertion order.
|
/// Builds metadata from the explicit exposure set in insertion order.
|
||||||
///
|
///
|
||||||
/// The observation contains no path, children, descriptor, backend handle,
|
/// This path-free projection is useful while composing a publication, but is
|
||||||
|
/// not proof that its scopes are currently published. Use
|
||||||
|
/// [`ObjectProvider::observe_object`] for a validated current observation, or
|
||||||
|
/// [`Self::protocol_object_at`] inside a provider's coherent boundary.
|
||||||
|
/// The metadata contains no path, children, descriptor, backend handle,
|
||||||
/// credential, or provider resolution state.
|
/// credential, or provider resolution state.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn protocol_object(&self) -> Object {
|
pub fn protocol_object(&self) -> Object {
|
||||||
@@ -520,7 +747,7 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
interfaces: self
|
interfaces: self
|
||||||
.interfaces
|
.interfaces
|
||||||
.iter()
|
.iter()
|
||||||
.map(|bound| bound.artifact.reference.0.clone())
|
.map(|bound| bound.artifact.reference.protocol_reference())
|
||||||
.collect(),
|
.collect(),
|
||||||
r#ref: self.implementation.reference().map(str::to_owned),
|
r#ref: self.implementation.reference().map(str::to_owned),
|
||||||
validator: self
|
validator: self
|
||||||
@@ -530,6 +757,30 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates a current Object observation inside the provider's boundary.
|
||||||
|
///
|
||||||
|
/// All exposed interfaces must have compatible, live scope associations. The
|
||||||
|
/// provider must still establish those associations atomically; this method
|
||||||
|
/// cannot verify backend lifetime assertions or lock external writers.
|
||||||
|
pub fn protocol_object_at(&self, path: &str) -> Result<Object, CallError> {
|
||||||
|
wip_protocol::validate_path(path)
|
||||||
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
|
if !self.scopes_valid_at(path) {
|
||||||
|
return Err(CallError::new(
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
"Host published interfaces without current compatible scope Objects",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let object = self.protocol_object();
|
||||||
|
object.validate_at_path(path).map_err(|_| {
|
||||||
|
CallError::new(
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
"Host produced an invalid object response",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(object)
|
||||||
|
}
|
||||||
|
|
||||||
fn dispatch_resolved(
|
fn dispatch_resolved(
|
||||||
&self,
|
&self,
|
||||||
context: &ExecutionContext,
|
context: &ExecutionContext,
|
||||||
@@ -573,10 +824,17 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if interface.reference.validate_for_path(&target.path).is_err() {
|
||||||
|
return pre_dispatch_failure(
|
||||||
|
CallErrorKind::InterfaceMismatch,
|
||||||
|
"interface scope is not an ancestor of the target path",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
let Some(bound) = self
|
let Some(bound) = self
|
||||||
.interfaces
|
.interfaces
|
||||||
.iter()
|
.iter()
|
||||||
.find(|bound| bound.artifact.reference.as_str() == interface.reference.as_str())
|
.find(|bound| bound.artifact.reference.protocol_reference() == interface.reference)
|
||||||
else {
|
else {
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::InterfaceMismatch,
|
CallErrorKind::InterfaceMismatch,
|
||||||
@@ -584,6 +842,31 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let Some(current_scope) = self.current_scope(&bound.artifact.scope) else {
|
||||||
|
return pre_dispatch_failure(
|
||||||
|
CallErrorKind::InterfaceMismatch,
|
||||||
|
"interface scope Object is not currently associated with this publication",
|
||||||
|
);
|
||||||
|
};
|
||||||
|
if current_scope.scope.path == target.path
|
||||||
|
&& current_scope.reference() != self.implementation.reference()
|
||||||
|
{
|
||||||
|
return pre_dispatch_failure(
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
"provider produced inconsistent self-scope metadata",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if interface
|
||||||
|
.scope_ref
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|supplied| current_scope.reference() != Some(supplied))
|
||||||
|
{
|
||||||
|
return pre_dispatch_failure(
|
||||||
|
CallErrorKind::InterfaceMismatch,
|
||||||
|
"scope Object ref does not match the current association",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
match (
|
match (
|
||||||
bound.artifact.validator.as_ref(),
|
bound.artifact.validator.as_ref(),
|
||||||
interface.validator.as_deref(),
|
interface.validator.as_deref(),
|
||||||
@@ -782,6 +1065,15 @@ pub enum OperationAttempt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl OperationAttempt {
|
impl OperationAttempt {
|
||||||
|
/// Rejects a provider precondition before typed implementation invocation.
|
||||||
|
///
|
||||||
|
/// Only use this before dispatch starts; post-invocation failures require
|
||||||
|
/// an explicit effect disposition. The diagnostic is intentionally generic.
|
||||||
|
#[must_use]
|
||||||
|
pub fn reject(kind: CallErrorKind) -> Self {
|
||||||
|
Self::NotStarted(CallError::new(kind, "provider precondition failed"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Marks a post-invocation failure as fully rolled back.
|
/// Marks a post-invocation failure as fully rolled back.
|
||||||
///
|
///
|
||||||
/// Successful attempts and pre-dispatch failures are returned unchanged.
|
/// Successful attempts and pre-dispatch failures are returned unchanged.
|
||||||
@@ -813,7 +1105,12 @@ pub enum ProviderResult<T> {
|
|||||||
///
|
///
|
||||||
/// `with_object` must resolve the current object at `path` exactly once and pass
|
/// `with_object` must resolve the current object at `path` exactly once and pass
|
||||||
/// a publication that pins its current interface set, implementations, and
|
/// a publication that pins its current interface set, implementations, and
|
||||||
/// backend target for the duration of `operation`. The execution context is the
|
/// backend target and all current scope Object associations for the duration of
|
||||||
|
/// `operation`. Attach them with PublishedObject::bind_scope inside this same
|
||||||
|
/// boundary, never via an independent scope prelookup. A new Object at the same
|
||||||
|
/// path needs a fresh Scope; ordinary state changes retain the handle. Providers
|
||||||
|
/// own lifetime/atomicity enforcement, including external writers and backend
|
||||||
|
/// commit/rollback. The execution context is the
|
||||||
/// runtime-neutral carrier for cancellation, deadline, and resource controls.
|
/// runtime-neutral carrier for cancellation, deadline, and resource controls.
|
||||||
/// The borrowed publication cannot escape the callback.
|
/// The borrowed publication cannot escape the callback.
|
||||||
///
|
///
|
||||||
@@ -877,7 +1174,9 @@ pub trait ObjectProvider {
|
|||||||
wip_protocol::validate_path(path)
|
wip_protocol::validate_path(path)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
let resolved = catch_unwind(AssertUnwindSafe(|| {
|
let resolved = catch_unwind(AssertUnwindSafe(|| {
|
||||||
self.with_object(context, path, PublishedObject::protocol_object)
|
self.with_object(context, path, |publication| {
|
||||||
|
publication.protocol_object_at(path)
|
||||||
|
})
|
||||||
}))
|
}))
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
CallError::new(
|
CallError::new(
|
||||||
@@ -886,7 +1185,7 @@ pub trait ObjectProvider {
|
|||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let object = match resolved {
|
let object = match resolved {
|
||||||
ProviderResult::Found(object) => object,
|
ProviderResult::Found(object) => object?,
|
||||||
ProviderResult::NotFound => {
|
ProviderResult::NotFound => {
|
||||||
return Err(CallError::new(
|
return Err(CallError::new(
|
||||||
CallErrorKind::NotFound,
|
CallErrorKind::NotFound,
|
||||||
@@ -895,15 +1194,58 @@ pub trait ObjectProvider {
|
|||||||
}
|
}
|
||||||
ProviderResult::Failure(error) => return Err(CallError::from_read_failure(error)),
|
ProviderResult::Failure(error) => return Err(CallError::from_read_failure(error)),
|
||||||
};
|
};
|
||||||
object.validate_at_path(path).map_err(|_| {
|
|
||||||
CallError::new(
|
|
||||||
CallErrorKind::Internal,
|
|
||||||
"Host produced an invalid object response",
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
Ok(object)
|
Ok(object)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fetches Descriptor, scope Object ref and Interface validator atomically.
|
||||||
|
///
|
||||||
|
/// The scope Object may expose no interfaces. Its publication must still
|
||||||
|
/// bind the live ScopeObservation. Registry retention is not publication.
|
||||||
|
fn fetch_interface(
|
||||||
|
&self,
|
||||||
|
registry: &InterfaceRegistry,
|
||||||
|
reference: &InterfaceReference,
|
||||||
|
) -> Result<InterfaceObservation, ProtocolError> {
|
||||||
|
reference.validate().map_err(|error| ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: error.to_string(),
|
||||||
|
})?;
|
||||||
|
let observed = catch_unwind(AssertUnwindSafe(|| {
|
||||||
|
self.with_object(
|
||||||
|
&ExecutionContext::default(),
|
||||||
|
&reference.scope,
|
||||||
|
|publication| {
|
||||||
|
publication
|
||||||
|
.scopes
|
||||||
|
.iter()
|
||||||
|
.find(|current| current.scope.path == reference.scope)
|
||||||
|
.ok_or_else(interface_not_found)
|
||||||
|
.and_then(|current| {
|
||||||
|
if current.reference() != publication.implementation.reference() {
|
||||||
|
return Err(ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "provider produced inconsistent scope Object metadata"
|
||||||
|
.into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
registry.fetch_interface(reference, current)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
.map_err(|_| ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "provider panicked while observing an interface".into(),
|
||||||
|
})?;
|
||||||
|
match observed {
|
||||||
|
ProviderResult::Found(observation) => observation,
|
||||||
|
ProviderResult::NotFound => Err(interface_not_found()),
|
||||||
|
ProviderResult::Failure(error) => {
|
||||||
|
Err(CallError::from_read_failure(error).protocol_error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves and executes a canonical path-targeted operation request.
|
/// Resolves and executes a canonical path-targeted operation request.
|
||||||
///
|
///
|
||||||
/// Structural path validation precedes provider resolution. For a valid
|
/// Structural path validation precedes provider resolution. For a valid
|
||||||
@@ -925,6 +1267,11 @@ pub trait ObjectProvider {
|
|||||||
) -> Result<CallResult, CallError> {
|
) -> Result<CallResult, CallError> {
|
||||||
wip_protocol::validate_path(&request.target.path)
|
wip_protocol::validate_path(&request.target.path)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
|
request
|
||||||
|
.interface
|
||||||
|
.reference
|
||||||
|
.validate()
|
||||||
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
let path = request.target.path.clone();
|
let path = request.target.path.clone();
|
||||||
let execution = catch_unwind(AssertUnwindSafe(|| {
|
let execution = catch_unwind(AssertUnwindSafe(|| {
|
||||||
self.execute_operation(context, &path, |publication| {
|
self.execute_operation(context, &path, |publication| {
|
||||||
@@ -974,6 +1321,10 @@ pub trait ObjectProvider {
|
|||||||
) -> Result<CallResult, CallError> {
|
) -> Result<CallResult, CallError> {
|
||||||
wip_protocol::validate_path(&target.path)
|
wip_protocol::validate_path(&target.path)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
|
interface
|
||||||
|
.reference
|
||||||
|
.validate()
|
||||||
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
let path = target.path.clone();
|
let path = target.path.clone();
|
||||||
let execution = catch_unwind(AssertUnwindSafe(|| {
|
let execution = catch_unwind(AssertUnwindSafe(|| {
|
||||||
self.execute_operation(context, &path, |publication| {
|
self.execute_operation(context, &path, |publication| {
|
||||||
@@ -1014,13 +1365,20 @@ pub trait ObjectProvider {
|
|||||||
/// Failure to construct an explicit object publication.
|
/// Failure to construct an explicit object publication.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum PublicationError {
|
pub enum PublicationError {
|
||||||
/// The same opaque interface reference was exposed more than once.
|
/// The same scope/name Interface reference was exposed more than once.
|
||||||
DuplicateInterface(InterfaceRef),
|
DuplicateInterface(InterfaceRef),
|
||||||
|
/// Projection attempted to add an interface without an implementation.
|
||||||
|
UnexposedInterface(InterfaceRef),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for PublicationError {
|
impl Display for PublicationError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
Self::UnexposedInterface(reference) => write!(
|
||||||
|
formatter,
|
||||||
|
"interface `{}` has no implementation",
|
||||||
|
reference.as_str()
|
||||||
|
),
|
||||||
Self::DuplicateInterface(reference) => write!(
|
Self::DuplicateInterface(reference) => write!(
|
||||||
formatter,
|
formatter,
|
||||||
"interface `{}` is already exposed by this object",
|
"interface `{}` is already exposed by this object",
|
||||||
@@ -1032,6 +1390,70 @@ impl Display for PublicationError {
|
|||||||
|
|
||||||
impl Error for PublicationError {}
|
impl Error for PublicationError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod projection_tests {
|
||||||
|
use super::*;
|
||||||
|
use wip_protocol::{
|
||||||
|
Documentation, OperationDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn operation_views_prune_hidden_types_and_documentation_without_mutating_registry() {
|
||||||
|
let named = |name: &str| TypeExpr::Named { name: name.into() };
|
||||||
|
let operation = |name: &str, returns| OperationDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: Vec::new(),
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: returns,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let declaration = |name: &str, definition| TypeDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
documentation: None,
|
||||||
|
definition,
|
||||||
|
};
|
||||||
|
let descriptor = InterfaceDescriptor {
|
||||||
|
format: "wip/1".into(),
|
||||||
|
documentation: Some(Documentation {
|
||||||
|
summary: "contains hidden operation details".into(),
|
||||||
|
details: None,
|
||||||
|
}),
|
||||||
|
operations: vec![
|
||||||
|
operation("visible", named("Public")),
|
||||||
|
operation("secret", named("Secret")),
|
||||||
|
],
|
||||||
|
types: vec![
|
||||||
|
declaration(
|
||||||
|
"Public",
|
||||||
|
TypeExpr::List {
|
||||||
|
items: Box::new(named("Shared")),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
declaration("Shared", TypeExpr::String),
|
||||||
|
declaration("Secret", TypeExpr::Bytes),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let mut projected = descriptor.clone();
|
||||||
|
restrict_descriptor(&mut projected, |operation| operation == "visible");
|
||||||
|
assert_eq!(projected.operations.len(), 1);
|
||||||
|
assert!(projected.documentation.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
projected
|
||||||
|
.types
|
||||||
|
.iter()
|
||||||
|
.map(|declaration| declaration.name.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec!["Public", "Shared"]
|
||||||
|
);
|
||||||
|
assert_eq!(descriptor.types.len(), 3);
|
||||||
|
restrict_descriptor(&mut projected, |_| false);
|
||||||
|
assert!(projected.types.is_empty());
|
||||||
|
assert!(projected.operations.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Stable Host dispatch failure kind.
|
/// Stable Host dispatch failure kind.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum CallErrorKind {
|
pub enum CallErrorKind {
|
||||||
|
|||||||
+227
-17
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
|||||||
use wip_host::{
|
use wip_host::{
|
||||||
CallError, CallErrorKind, CallRequest, CancellationToken, ExecutionContext, InterfaceRef,
|
CallError, CallErrorKind, CallRequest, CancellationToken, ExecutionContext, InterfaceRef,
|
||||||
InterfaceRegistry, InterfaceTarget, ObjectProvider, OperationAttempt, ProviderResult,
|
InterfaceRegistry, InterfaceTarget, ObjectProvider, OperationAttempt, ProviderResult,
|
||||||
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
PublishedObject, RegisteredInterface, Scope, ScopeObservation, Target, Validator, WipObject,
|
||||||
};
|
};
|
||||||
use wip_interface::{
|
use wip_interface::{
|
||||||
CodecError, EffectGuarantee, HostError, OperationResult, TypeDeclaration, TypeExpr, Value,
|
CodecError, EffectGuarantee, HostError, OperationResult, TypeDeclaration, TypeExpr, Value,
|
||||||
@@ -14,6 +14,77 @@ use wip_interface::{
|
|||||||
};
|
};
|
||||||
use wip_protocol::ProtocolErrorCode;
|
use wip_protocol::ProtocolErrorCode;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn principal_projection_orders_subsets_and_rejects_unimplemented_or_duplicate_tokens() {
|
||||||
|
let mut registry = InterfaceRegistry::new();
|
||||||
|
let root = Scope::new("/").unwrap();
|
||||||
|
let read = registry
|
||||||
|
.register(&root, "reader", ReaderDefinition, None)
|
||||||
|
.unwrap();
|
||||||
|
let write = registry
|
||||||
|
.register(&root, "writer::#日本語", WriterDefinition, None)
|
||||||
|
.unwrap();
|
||||||
|
let hidden = registry
|
||||||
|
.register(&root, "hidden", HiddenDefinition, None)
|
||||||
|
.unwrap();
|
||||||
|
let publication = || {
|
||||||
|
PublishedObject::new(Document::open("document", None, Rc::new(Cell::new(0))))
|
||||||
|
.expose(&read)
|
||||||
|
.unwrap()
|
||||||
|
.expose(&write)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let projected = publication()
|
||||||
|
.project(
|
||||||
|
&[write.reference().clone(), read.reference().clone()],
|
||||||
|
|_, operation| operation == "label",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
projected.protocol_object().interfaces,
|
||||||
|
vec![
|
||||||
|
write.reference().protocol_reference(),
|
||||||
|
read.reference().protocol_reference()
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
publication()
|
||||||
|
.project(&[hidden.reference().clone()], |_, _| true)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
publication()
|
||||||
|
.project(
|
||||||
|
&[read.reference().clone(), read.reference().clone()],
|
||||||
|
|_, _| true
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
publication()
|
||||||
|
.project(&[], |_, _| true)
|
||||||
|
.unwrap()
|
||||||
|
.protocol_object()
|
||||||
|
.interfaces
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
let current = ScopeObservation::new(&root, &Document::open("", None, Rc::new(Cell::new(0))));
|
||||||
|
let full = registry
|
||||||
|
.fetch_interface(&read.reference().protocol_reference(), ¤t)
|
||||||
|
.unwrap();
|
||||||
|
let filtered = full
|
||||||
|
.clone()
|
||||||
|
.project_operations(|operation| operation == "label");
|
||||||
|
assert_eq!(filtered.descriptor.operations.len(), 1);
|
||||||
|
assert_eq!(full.descriptor.operations.len(), 3);
|
||||||
|
assert_eq!(
|
||||||
|
registry
|
||||||
|
.fetch_interface(&read.reference().protocol_reference(), ¤t)
|
||||||
|
.unwrap(),
|
||||||
|
full
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[interface]
|
#[interface]
|
||||||
pub trait Reader {
|
pub trait Reader {
|
||||||
/// Returns the reader-qualified label.
|
/// Returns the reader-qualified label.
|
||||||
@@ -246,6 +317,7 @@ impl Broken for Document {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct TestProvider {
|
struct TestProvider {
|
||||||
|
root: Scope,
|
||||||
reader: RegisteredInterface<ReaderDefinition>,
|
reader: RegisteredInterface<ReaderDefinition>,
|
||||||
writer: RegisteredInterface<WriterDefinition>,
|
writer: RegisteredInterface<WriterDefinition>,
|
||||||
broken: RegisteredInterface<BrokenDefinition>,
|
broken: RegisteredInterface<BrokenDefinition>,
|
||||||
@@ -263,11 +335,13 @@ struct TestProvider {
|
|||||||
|
|
||||||
impl TestProvider {
|
impl TestProvider {
|
||||||
fn new(
|
fn new(
|
||||||
|
root: Scope,
|
||||||
reader: RegisteredInterface<ReaderDefinition>,
|
reader: RegisteredInterface<ReaderDefinition>,
|
||||||
writer: RegisteredInterface<WriterDefinition>,
|
writer: RegisteredInterface<WriterDefinition>,
|
||||||
broken: RegisteredInterface<BrokenDefinition>,
|
broken: RegisteredInterface<BrokenDefinition>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
root,
|
||||||
reader,
|
reader,
|
||||||
writer,
|
writer,
|
||||||
broken,
|
broken,
|
||||||
@@ -299,7 +373,10 @@ impl ObjectProvider for TestProvider {
|
|||||||
self.observed_cancelled
|
self.observed_cancelled
|
||||||
.set(context.cancellation().is_cancelled());
|
.set(context.cancellation().is_cancelled());
|
||||||
self.resolutions.set(self.resolutions.get() + 1);
|
self.resolutions.set(self.resolutions.get() + 1);
|
||||||
|
let scope_object = Document::open("", None, Rc::clone(&self.calls));
|
||||||
|
let current_scope = ScopeObservation::new(&self.root, &scope_object);
|
||||||
let (document, interfaces) = match path {
|
let (document, interfaces) = match path {
|
||||||
|
"/" => (scope_object, 0),
|
||||||
"/document" => (
|
"/document" => (
|
||||||
Document::strict(
|
Document::strict(
|
||||||
"document",
|
"document",
|
||||||
@@ -357,6 +434,7 @@ impl ObjectProvider for TestProvider {
|
|||||||
3 => publication.expose(&self.broken).unwrap(),
|
3 => publication.expose(&self.broken).unwrap(),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
|
let publication = publication.bind_scope(current_scope);
|
||||||
ProviderResult::Found(operation(&publication))
|
ProviderResult::Found(operation(&publication))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,13 +476,25 @@ fn registry_and_provider() -> (
|
|||||||
RegisteredInterface<HiddenDefinition>,
|
RegisteredInterface<HiddenDefinition>,
|
||||||
) {
|
) {
|
||||||
let mut registry = InterfaceRegistry::new();
|
let mut registry = InterfaceRegistry::new();
|
||||||
|
let root = Scope::new("/").unwrap();
|
||||||
let reader = registry
|
let reader = registry
|
||||||
.register(ReaderDefinition, Some(Validator::new(b"schema-v1")))
|
.register(
|
||||||
|
&root,
|
||||||
|
"reader",
|
||||||
|
ReaderDefinition,
|
||||||
|
Some(Validator::new(b"schema-v1")),
|
||||||
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let writer = registry.register(WriterDefinition, None).unwrap();
|
let writer = registry
|
||||||
let hidden = registry.register(HiddenDefinition, None).unwrap();
|
.register(&root, "writer::#日本語", WriterDefinition, None)
|
||||||
let broken = registry.register(BrokenDefinition, None).unwrap();
|
.unwrap();
|
||||||
let provider = TestProvider::new(reader, writer, broken);
|
let hidden = registry
|
||||||
|
.register(&root, "hidden", HiddenDefinition, None)
|
||||||
|
.unwrap();
|
||||||
|
let broken = registry
|
||||||
|
.register(&root, "broken", BrokenDefinition, None)
|
||||||
|
.unwrap();
|
||||||
|
let provider = TestProvider::new(root, reader, writer, broken);
|
||||||
(registry, provider, hidden)
|
(registry, provider, hidden)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -422,7 +512,8 @@ fn request(
|
|||||||
validator: object_validator.map(<[u8]>::to_vec),
|
validator: object_validator.map(<[u8]>::to_vec),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: reference.as_str().to_owned(),
|
reference: reference.protocol_reference(),
|
||||||
|
scope_ref: None,
|
||||||
validator: interface_validator.map(<[u8]>::to_vec),
|
validator: interface_validator.map(<[u8]>::to_vec),
|
||||||
},
|
},
|
||||||
operation: operation.into(),
|
operation: operation.into(),
|
||||||
@@ -441,17 +532,22 @@ fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor()
|
|||||||
let reference = provider.reader.reference();
|
let reference = provider.reader.reference();
|
||||||
|
|
||||||
assert_ne!(reference.as_str(), "Reader");
|
assert_ne!(reference.as_str(), "Reader");
|
||||||
let observation = registry.fetch_interface(reference.as_str()).unwrap();
|
let observation = provider
|
||||||
|
.fetch_interface(®istry, &reference.protocol_reference())
|
||||||
|
.unwrap();
|
||||||
assert_eq!(observation.reference, *reference);
|
assert_eq!(observation.reference, *reference);
|
||||||
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
|
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
|
||||||
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
|
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
|
||||||
let response = observation.protocol_response().unwrap();
|
let response = observation.protocol_response().unwrap();
|
||||||
assert_eq!(response.interface, reference.as_str());
|
assert_eq!(response.interface, reference.protocol_reference());
|
||||||
|
assert_eq!(response.scope_ref, None);
|
||||||
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
|
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
|
||||||
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
|
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
|
||||||
response.descriptor.validate().unwrap();
|
response.descriptor.validate().unwrap();
|
||||||
|
|
||||||
let mut invalid_observation = registry.fetch_interface(reference.as_str()).unwrap();
|
let mut invalid_observation = provider
|
||||||
|
.fetch_interface(®istry, &reference.protocol_reference())
|
||||||
|
.unwrap();
|
||||||
let duplicate_operation = invalid_observation.descriptor.operations[0].clone();
|
let duplicate_operation = invalid_observation.descriptor.operations[0].clone();
|
||||||
invalid_observation
|
invalid_observation
|
||||||
.descriptor
|
.descriptor
|
||||||
@@ -460,7 +556,15 @@ fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor()
|
|||||||
let invalid_response = invalid_observation.protocol_response().unwrap_err();
|
let invalid_response = invalid_observation.protocol_response().unwrap_err();
|
||||||
assert_eq!(invalid_response.code, ProtocolErrorCode::Internal);
|
assert_eq!(invalid_response.code, ProtocolErrorCode::Internal);
|
||||||
|
|
||||||
let error = registry.fetch_interface("unknown").unwrap_err();
|
let error = provider
|
||||||
|
.fetch_interface(
|
||||||
|
®istry,
|
||||||
|
&wip_protocol::InterfaceReference {
|
||||||
|
scope: "/".into(),
|
||||||
|
name: "unknown".into(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
|
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,8 +580,8 @@ fn canonical_object_projection_supports_optional_metadata_and_ordered_sets() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
object.interfaces,
|
object.interfaces,
|
||||||
vec![
|
vec![
|
||||||
provider.writer.reference().as_str().to_owned(),
|
provider.writer.reference().protocol_reference(),
|
||||||
provider.reader.reference().as_str().to_owned(),
|
provider.reader.reference().protocol_reference(),
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
assert!(!format!("{object:?}").contains("secret-handle"));
|
assert!(!format!("{object:?}").contains("secret-handle"));
|
||||||
@@ -758,7 +862,8 @@ fn descriptor_guided_decoder_runs_inside_canonical_resolution_boundary() {
|
|||||||
validator: Some(b"stale".to_vec()),
|
validator: Some(b"stale".to_vec()),
|
||||||
},
|
},
|
||||||
InterfaceTarget {
|
InterfaceTarget {
|
||||||
reference: hidden.reference().as_str().into(),
|
reference: hidden.reference().protocol_reference(),
|
||||||
|
scope_ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
"missing".into(),
|
"missing".into(),
|
||||||
@@ -776,7 +881,8 @@ fn descriptor_guided_decoder_runs_inside_canonical_resolution_boundary() {
|
|||||||
validator: Some(b"stale".to_vec()),
|
validator: Some(b"stale".to_vec()),
|
||||||
},
|
},
|
||||||
InterfaceTarget {
|
InterfaceTarget {
|
||||||
reference: hidden.reference().as_str().into(),
|
reference: hidden.reference().protocol_reference(),
|
||||||
|
scope_ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
"hidden".into(),
|
"hidden".into(),
|
||||||
@@ -794,7 +900,8 @@ fn descriptor_guided_decoder_runs_inside_canonical_resolution_boundary() {
|
|||||||
validator: Some(b"object-v1".to_vec()),
|
validator: Some(b"object-v1".to_vec()),
|
||||||
},
|
},
|
||||||
InterfaceTarget {
|
InterfaceTarget {
|
||||||
reference: hidden.reference().as_str().into(),
|
reference: hidden.reference().protocol_reference(),
|
||||||
|
scope_ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
},
|
},
|
||||||
"hidden".into(),
|
"hidden".into(),
|
||||||
@@ -812,7 +919,8 @@ fn descriptor_guided_decoder_runs_inside_canonical_resolution_boundary() {
|
|||||||
validator: Some(b"object-v1".to_vec()),
|
validator: Some(b"object-v1".to_vec()),
|
||||||
},
|
},
|
||||||
InterfaceTarget {
|
InterfaceTarget {
|
||||||
reference: provider.reader.reference().as_str().into(),
|
reference: provider.reader.reference().protocol_reference(),
|
||||||
|
scope_ref: None,
|
||||||
validator: Some(b"schema-v1".to_vec()),
|
validator: Some(b"schema-v1".to_vec()),
|
||||||
},
|
},
|
||||||
"add".into(),
|
"add".into(),
|
||||||
@@ -1066,3 +1174,105 @@ fn execution_context_is_propagated_and_preflight_prevents_invocation() {
|
|||||||
);
|
);
|
||||||
assert_eq!(provider.calls.get(), calls);
|
assert_eq!(provider.calls.get(), calls);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn registry_boundaries_preserve_names_verbatim_and_match_exact_scope() {
|
||||||
|
let (registry, provider, _) = registry_and_provider();
|
||||||
|
let legacy = provider.writer.reference();
|
||||||
|
let reference = legacy.protocol_reference();
|
||||||
|
assert_eq!(reference.scope, "/");
|
||||||
|
assert_eq!(reference.name, legacy.as_str());
|
||||||
|
assert_eq!(reference.name, "writer::#日本語");
|
||||||
|
assert_eq!(registry.resolve(&reference).as_ref(), Some(legacy));
|
||||||
|
let nested = wip_protocol::InterfaceReference {
|
||||||
|
scope: "/open".into(),
|
||||||
|
name: reference.name.clone(),
|
||||||
|
};
|
||||||
|
assert!(registry.resolve(&nested).is_none());
|
||||||
|
assert_eq!(
|
||||||
|
provider
|
||||||
|
.fetch_interface(®istry, &nested)
|
||||||
|
.unwrap_err()
|
||||||
|
.code,
|
||||||
|
ProtocolErrorCode::InterfaceNotFound
|
||||||
|
);
|
||||||
|
let malformed = wip_protocol::InterfaceReference {
|
||||||
|
scope: "relative".into(),
|
||||||
|
name: reference.name,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
provider
|
||||||
|
.fetch_interface(®istry, &malformed)
|
||||||
|
.unwrap_err()
|
||||||
|
.code,
|
||||||
|
ProtocolErrorCode::InvalidRequest
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn call_reference_shape_precedes_resolution_and_scope_membership_is_exact() {
|
||||||
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
for (scope, name) in [("relative", "valid"), ("/", ""), ("/bad/", "valid")] {
|
||||||
|
let mut call = request(
|
||||||
|
"/open",
|
||||||
|
None,
|
||||||
|
provider.writer.reference(),
|
||||||
|
None,
|
||||||
|
"label",
|
||||||
|
BTreeMap::new(),
|
||||||
|
);
|
||||||
|
call.interface.reference = wip_protocol::InterfaceReference {
|
||||||
|
scope: scope.into(),
|
||||||
|
name: name.into(),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
provider.call_operation(call.clone()).unwrap_err().kind(),
|
||||||
|
CallErrorKind::InvalidRequest
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
call.target,
|
||||||
|
call.interface,
|
||||||
|
call.operation,
|
||||||
|
|_| Ok::<_, ()>(BTreeMap::new()),
|
||||||
|
)
|
||||||
|
.unwrap_err()
|
||||||
|
.kind(),
|
||||||
|
CallErrorKind::InvalidRequest
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(provider.resolutions.get(), 0);
|
||||||
|
// /other is outside the target scope; /open is self but has no legacy artifact.
|
||||||
|
for scope in ["/other", "/open"] {
|
||||||
|
let mut call = request(
|
||||||
|
"/open",
|
||||||
|
None,
|
||||||
|
provider.writer.reference(),
|
||||||
|
None,
|
||||||
|
"label",
|
||||||
|
BTreeMap::new(),
|
||||||
|
);
|
||||||
|
call.interface.reference.scope = scope.into();
|
||||||
|
assert_eq!(
|
||||||
|
provider.call_operation(call.clone()).unwrap_err().kind(),
|
||||||
|
CallErrorKind::InterfaceMismatch
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
call.target,
|
||||||
|
call.interface,
|
||||||
|
call.operation,
|
||||||
|
|_| -> Result<BTreeMap<String, Value>, ()> { panic!("must not decode") },
|
||||||
|
)
|
||||||
|
.unwrap_err()
|
||||||
|
.kind(),
|
||||||
|
CallErrorKind::InterfaceMismatch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(provider.calls.get(), 0);
|
||||||
|
assert_eq!(provider.authorization_checks.get(), 0);
|
||||||
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -16,6 +16,6 @@ impl WipObject for Object {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut registry = InterfaceRegistry::new();
|
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();
|
let _published = PublishedObject::new(Object).expose(&search).unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-http"
|
name = "wip-http"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Framework-independent standard WIP over HTTP v1 binding"
|
description = "Framework-independent standard WIP over HTTP v1 binding"
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme = "README.md"
|
||||||
|
documentation = "https://docs.rs/wip-http"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
@@ -11,4 +15,4 @@ http = "1"
|
|||||||
serde = "1"
|
serde = "1"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
url = "2"
|
url = "2"
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
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.
|
||||||
@@ -296,11 +296,14 @@ pub fn decode_observe_request(body: &[u8], limits: Limits) -> Result<ObserveRequ
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Encodes a `fetch_interface` HTTP request.
|
/// Encodes a `fetch_interface` HTTP request.
|
||||||
|
///
|
||||||
|
/// Validates reference shape without requiring a target Object path.
|
||||||
pub fn encode_fetch_interface_request(
|
pub fn encode_fetch_interface_request(
|
||||||
endpoint: &Endpoint,
|
endpoint: &Endpoint,
|
||||||
value: &FetchInterfaceRequest,
|
value: &FetchInterfaceRequest,
|
||||||
limits: Limits,
|
limits: Limits,
|
||||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
value.interface.validate().map_err(CodecError::from)?;
|
||||||
let body = json::serialize(
|
let body = json::serialize(
|
||||||
&json::fetch_interface_request_to_json(value),
|
&json::fetch_interface_request_to_json(value),
|
||||||
BodyKind::Request,
|
BodyKind::Request,
|
||||||
@@ -358,6 +361,10 @@ impl CallOperationMetadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Decodes descriptor-independent `call_operation` routing metadata.
|
/// 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(
|
pub fn decode_call_operation_metadata(
|
||||||
body: &[u8],
|
body: &[u8],
|
||||||
limits: Limits,
|
limits: Limits,
|
||||||
|
|||||||
+49
-14
@@ -8,9 +8,9 @@ use serde_json::{Map, Number, Value as Json};
|
|||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
InterfaceTarget, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
|
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, Object,
|
||||||
ObserveResponse, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
|
ObjectObservation, ObserveRequest, ObserveResponse, OperationDeclaration, ParameterDeclaration,
|
||||||
TypeDeclaration, TypeExpr, UnionCase, Value,
|
ReturnDeclaration, Target, TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{BodyKind, CodecError, Limits};
|
use crate::{BodyKind, CodecError, Limits};
|
||||||
@@ -285,8 +285,25 @@ pub(crate) fn observe_request_from_json(value: &Json) -> Result<ObserveRequest,
|
|||||||
Ok(request)
|
Ok(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn interface_reference_to_json(reference: &InterfaceReference) -> Json {
|
||||||
|
serde_json::json!({"scope": reference.scope, "name": reference.name})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interface_reference_from_json(
|
||||||
|
value: &Json,
|
||||||
|
field: &str,
|
||||||
|
) -> Result<InterfaceReference, CodecError> {
|
||||||
|
let fields = exact_object(value, field, &["scope", "name"])?;
|
||||||
|
let reference = InterfaceReference {
|
||||||
|
scope: string(required(fields, "scope")?, &qualified(field, "scope"))?,
|
||||||
|
name: string(required(fields, "name")?, &qualified(field, "name"))?,
|
||||||
|
};
|
||||||
|
reference.validate()?;
|
||||||
|
Ok(reference)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn fetch_interface_request_to_json(request: &FetchInterfaceRequest) -> Json {
|
pub(crate) fn fetch_interface_request_to_json(request: &FetchInterfaceRequest) -> Json {
|
||||||
serde_json::json!({"interface": request.interface})
|
serde_json::json!({"interface": interface_reference_to_json(&request.interface)})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn fetch_interface_request_from_json(
|
pub(crate) fn fetch_interface_request_from_json(
|
||||||
@@ -294,7 +311,7 @@ pub(crate) fn fetch_interface_request_from_json(
|
|||||||
) -> Result<FetchInterfaceRequest, CodecError> {
|
) -> Result<FetchInterfaceRequest, CodecError> {
|
||||||
let fields = exact_object(value, "request", &["interface"])?;
|
let fields = exact_object(value, "request", &["interface"])?;
|
||||||
Ok(FetchInterfaceRequest {
|
Ok(FetchInterfaceRequest {
|
||||||
interface: string(required(fields, "interface")?, "interface")?,
|
interface: interface_reference_from_json(required(fields, "interface")?, "interface")?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,8 +325,7 @@ pub(crate) fn object_to_json(object: &Object) -> Json {
|
|||||||
object
|
object
|
||||||
.interfaces
|
.interfaces
|
||||||
.iter()
|
.iter()
|
||||||
.cloned()
|
.map(interface_reference_to_json)
|
||||||
.map(Json::String)
|
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -327,7 +343,7 @@ pub(crate) fn object_from_json(value: &Json, field: &str) -> Result<Object, Code
|
|||||||
let interfaces = array(required(fields, "interfaces")?, "interfaces")?
|
let interfaces = array(required(fields, "interfaces")?, "interfaces")?
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(index, value)| string(value, &format!("interfaces[{index}]")))
|
.map(|(index, value)| interface_reference_from_json(value, &format!("interfaces[{index}]")))
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
let object = Object {
|
let object = Object {
|
||||||
name: string(required(fields, "name")?, "name")?,
|
name: string(required(fields, "name")?, "name")?,
|
||||||
@@ -745,7 +761,11 @@ pub(crate) fn descriptor_from_json(
|
|||||||
|
|
||||||
pub(crate) fn fetch_interface_response_to_json(response: &FetchInterfaceResponse) -> Json {
|
pub(crate) fn fetch_interface_response_to_json(response: &FetchInterfaceResponse) -> Json {
|
||||||
let mut fields = Map::new();
|
let mut fields = Map::new();
|
||||||
fields.insert("interface".into(), Json::String(response.interface.clone()));
|
fields.insert(
|
||||||
|
"interface".into(),
|
||||||
|
interface_reference_to_json(&response.interface),
|
||||||
|
);
|
||||||
|
insert_optional_string(&mut fields, "scope_ref", &response.scope_ref);
|
||||||
fields.insert(
|
fields.insert(
|
||||||
"descriptor".into(),
|
"descriptor".into(),
|
||||||
descriptor_to_json(&response.descriptor),
|
descriptor_to_json(&response.descriptor),
|
||||||
@@ -757,8 +777,15 @@ pub(crate) fn fetch_interface_response_to_json(response: &FetchInterfaceResponse
|
|||||||
pub(crate) fn fetch_interface_response_from_json(
|
pub(crate) fn fetch_interface_response_from_json(
|
||||||
value: &Json,
|
value: &Json,
|
||||||
) -> Result<FetchInterfaceResponse, CodecError> {
|
) -> Result<FetchInterfaceResponse, CodecError> {
|
||||||
let fields = exact_object(value, "response", &["interface", "descriptor", "validator"])?;
|
let fields = exact_object(
|
||||||
let interface = string(required(fields, "interface")?, "interface")?;
|
value,
|
||||||
|
"response",
|
||||||
|
&["interface", "scope_ref", "descriptor", "validator"],
|
||||||
|
)?;
|
||||||
|
let interface = interface_reference_from_json(required(fields, "interface")?, "interface")?;
|
||||||
|
let scope_ref = optional(fields, "scope_ref")?
|
||||||
|
.map(|value| string(value, "scope_ref"))
|
||||||
|
.transpose()?;
|
||||||
let validator = optional(fields, "validator")?
|
let validator = optional(fields, "validator")?
|
||||||
.map(|value| base64_decode(value, "validator"))
|
.map(|value| base64_decode(value, "validator"))
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
@@ -780,6 +807,7 @@ pub(crate) fn fetch_interface_response_from_json(
|
|||||||
};
|
};
|
||||||
Ok(FetchInterfaceResponse {
|
Ok(FetchInterfaceResponse {
|
||||||
interface,
|
interface,
|
||||||
|
scope_ref,
|
||||||
descriptor,
|
descriptor,
|
||||||
validator,
|
validator,
|
||||||
})
|
})
|
||||||
@@ -1121,18 +1149,25 @@ fn target_from_json(value: &Json, field: &str) -> Result<Target, CodecError> {
|
|||||||
|
|
||||||
fn interface_target_to_json(target: &InterfaceTarget) -> Json {
|
fn interface_target_to_json(target: &InterfaceTarget) -> Json {
|
||||||
let mut fields = Map::new();
|
let mut fields = Map::new();
|
||||||
fields.insert("reference".into(), Json::String(target.reference.clone()));
|
fields.insert(
|
||||||
|
"reference".into(),
|
||||||
|
interface_reference_to_json(&target.reference),
|
||||||
|
);
|
||||||
|
insert_optional_string(&mut fields, "scope_ref", &target.scope_ref);
|
||||||
insert_optional_bytes(&mut fields, "validator", &target.validator);
|
insert_optional_bytes(&mut fields, "validator", &target.validator);
|
||||||
Json::Object(fields)
|
Json::Object(fields)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn interface_target_from_json(value: &Json, field: &str) -> Result<InterfaceTarget, CodecError> {
|
fn interface_target_from_json(value: &Json, field: &str) -> Result<InterfaceTarget, CodecError> {
|
||||||
let fields = exact_object(value, field, &["reference", "validator"])?;
|
let fields = exact_object(value, field, &["reference", "scope_ref", "validator"])?;
|
||||||
Ok(InterfaceTarget {
|
Ok(InterfaceTarget {
|
||||||
reference: string(
|
reference: interface_reference_from_json(
|
||||||
required(fields, "reference")?,
|
required(fields, "reference")?,
|
||||||
&qualified(field, "reference"),
|
&qualified(field, "reference"),
|
||||||
)?,
|
)?,
|
||||||
|
scope_ref: optional(fields, "scope_ref")?
|
||||||
|
.map(|value| string(value, &qualified(field, "scope_ref")))
|
||||||
|
.transpose()?,
|
||||||
validator: optional(fields, "validator")?
|
validator: optional(fields, "validator")?
|
||||||
.map(|value| base64_decode(value, &qualified(field, "validator")))
|
.map(|value| base64_decode(value, &qualified(field, "validator")))
|
||||||
.transpose()?,
|
.transpose()?,
|
||||||
|
|||||||
@@ -12,6 +12,14 @@
|
|||||||
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
||||||
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
//! 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_http::{Endpoint, Limits, encode_observe_request};
|
||||||
//! use wip_protocol::ObserveRequest;
|
//! use wip_protocol::ObserveRequest;
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ use wip_http::http::StatusCode;
|
|||||||
use wip_http::wip_protocol::{
|
use wip_http::wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
|
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation,
|
||||||
OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target, TypeDeclaration,
|
ObserveRequest, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
|
||||||
TypeExpr, UnionCase, Value,
|
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||||
};
|
};
|
||||||
use wip_http::{
|
use wip_http::{
|
||||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||||
@@ -25,11 +25,18 @@ fn endpoint() -> Endpoint {
|
|||||||
Endpoint::parse("https://example.test/wip").unwrap()
|
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 {
|
fn object(name: &str, validator: &[u8]) -> Object {
|
||||||
Object {
|
Object {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
description: Some("description".into()),
|
description: Some("description".into()),
|
||||||
interfaces: vec!["interface-v1".into()],
|
interfaces: vec![reference("/", "interface-v1")],
|
||||||
r#ref: Some(format!("object:{name}")),
|
r#ref: Some(format!("object:{name}")),
|
||||||
validator: Some(validator.to_vec()),
|
validator: Some(validator.to_vec()),
|
||||||
}
|
}
|
||||||
@@ -152,7 +159,8 @@ fn call_request() -> CallOperationRequest {
|
|||||||
validator: Some(vec![0, 1, 2, 255]),
|
validator: Some(vec![0, 1, 2, 255]),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: "interface-v1".into(),
|
reference: reference("/", "interface-v1"),
|
||||||
|
scope_ref: None,
|
||||||
validator: Some(vec![9, 8, 7]),
|
validator: Some(vec![9, 8, 7]),
|
||||||
},
|
},
|
||||||
operation: "everything".into(),
|
operation: "everything".into(),
|
||||||
@@ -206,7 +214,7 @@ fn every_single_interaction_request_accepts_json() {
|
|||||||
let fetch_interface = encode_fetch_interface_request(
|
let fetch_interface = encode_fetch_interface_request(
|
||||||
&endpoint(),
|
&endpoint(),
|
||||||
&FetchInterfaceRequest {
|
&FetchInterfaceRequest {
|
||||||
interface: "interface-v1".into(),
|
interface: reference("/", "interface-v1"),
|
||||||
},
|
},
|
||||||
limits(),
|
limits(),
|
||||||
)
|
)
|
||||||
@@ -286,7 +294,7 @@ fn observe_and_interface_round_trip_nested_logical_models() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let interface_request = FetchInterfaceRequest {
|
let interface_request = FetchInterfaceRequest {
|
||||||
interface: "interface-v1".into(),
|
interface: reference("/", "interface-v1"),
|
||||||
};
|
};
|
||||||
let encoded_request =
|
let encoded_request =
|
||||||
encode_fetch_interface_request(&endpoint(), &interface_request, limits()).unwrap();
|
encode_fetch_interface_request(&endpoint(), &interface_request, limits()).unwrap();
|
||||||
@@ -296,6 +304,7 @@ fn observe_and_interface_round_trip_nested_logical_models() {
|
|||||||
);
|
);
|
||||||
let interface = FetchInterfaceResponse {
|
let interface = FetchInterfaceResponse {
|
||||||
interface: interface_request.interface.clone(),
|
interface: interface_request.interface.clone(),
|
||||||
|
scope_ref: None,
|
||||||
descriptor: descriptor(),
|
descriptor: descriptor(),
|
||||||
validator: Some(vec![4, 5, 6, 255]),
|
validator: Some(vec![4, 5, 6, 255]),
|
||||||
};
|
};
|
||||||
@@ -383,7 +392,7 @@ fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
|
|||||||
let descriptor = descriptor();
|
let descriptor = descriptor();
|
||||||
let body = serde_json::to_vec(&serde_json::json!({
|
let body = serde_json::to_vec(&serde_json::json!({
|
||||||
"target": {"path": "/items/123", "validator": null},
|
"target": {"path": "/items/123", "validator": null},
|
||||||
"interface": {"reference": "interface-v1"},
|
"interface": {"reference": {"scope": "/", "name": "interface-v1"}},
|
||||||
"operation": "everything",
|
"operation": "everything",
|
||||||
"arguments": {}
|
"arguments": {}
|
||||||
}))
|
}))
|
||||||
@@ -443,10 +452,11 @@ fn caller_limits_remain_local_codec_failures() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn unsupported_descriptor_format_is_client_local() {
|
fn unsupported_descriptor_format_is_client_local() {
|
||||||
let request = FetchInterfaceRequest {
|
let request = FetchInterfaceRequest {
|
||||||
interface: "interface-v1".into(),
|
interface: reference("/", "interface-v1"),
|
||||||
};
|
};
|
||||||
let mut interface = FetchInterfaceResponse {
|
let mut interface = FetchInterfaceResponse {
|
||||||
interface: request.interface.clone(),
|
interface: request.interface.clone(),
|
||||||
|
scope_ref: None,
|
||||||
descriptor: descriptor(),
|
descriptor: descriptor(),
|
||||||
validator: None,
|
validator: None,
|
||||||
};
|
};
|
||||||
@@ -462,7 +472,7 @@ fn unsupported_descriptor_format_is_client_local() {
|
|||||||
.status(StatusCode::OK)
|
.status(StatusCode::OK)
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
.body(
|
.body(
|
||||||
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future_shape":true}}"#
|
br#"{"interface":{"scope":"/","name":"interface-v1"},"descriptor":{"format":"wip-interface/2","future_shape":true}}"#
|
||||||
.to_vec(),
|
.to_vec(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -473,8 +483,8 @@ fn unsupported_descriptor_format_is_client_local() {
|
|||||||
));
|
));
|
||||||
|
|
||||||
for malformed in [
|
for malformed in [
|
||||||
br#"{"interface":"wrong","descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
br#"{"interface":{"scope":"/","name":"wrong"},"descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
||||||
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
br#"{"interface":{"scope":"/","name":"interface-v1"},"descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
||||||
.as_slice(),
|
.as_slice(),
|
||||||
] {
|
] {
|
||||||
let response = wip_http::http::Response::builder()
|
let response = wip_http::http::Response::builder()
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-interface-macros"
|
name = "wip-interface-macros"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Procedural macros for WIP interface declarations and DTO codecs"
|
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]
|
[lib]
|
||||||
proc-macro = true
|
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,13 +1,17 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-interface"
|
name = "wip-interface"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Public Rust authoring API for WIP interfaces and operation value codecs"
|
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]
|
[dependencies]
|
||||||
wip-interface-macros = { path = "../wip-interface-macros" }
|
wip-interface-macros.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
trybuild = "1"
|
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.
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-protocol"
|
name = "wip-protocol"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Transport-independent logical model and validation for WIP"
|
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]
|
[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.
|
||||||
@@ -143,8 +143,17 @@ pub enum ValidationErrorKind {
|
|||||||
},
|
},
|
||||||
/// An object's ordered interface set contains a duplicate.
|
/// An object's ordered interface set contains a duplicate.
|
||||||
DuplicateInterface {
|
DuplicateInterface {
|
||||||
/// Duplicate opaque interface reference.
|
/// Duplicate structured interface reference.
|
||||||
reference: String,
|
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.
|
/// A string is not a canonical absolute Worldspace path.
|
||||||
InvalidPath {
|
InvalidPath {
|
||||||
@@ -175,10 +184,10 @@ pub enum ValidationErrorKind {
|
|||||||
},
|
},
|
||||||
/// A response refers to a different interface than its request.
|
/// A response refers to a different interface than its request.
|
||||||
InterfaceResponseMismatch {
|
InterfaceResponseMismatch {
|
||||||
/// Requested opaque reference.
|
/// Requested structured reference (boxed to keep validation errors small).
|
||||||
expected: String,
|
expected: Box<crate::InterfaceReference>,
|
||||||
/// Returned opaque reference.
|
/// Returned structured reference (boxed to keep validation errors small).
|
||||||
actual: String,
|
actual: Box<crate::InterfaceReference>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,7 +235,7 @@ impl Error for ValidationError {}
|
|||||||
pub enum ProtocolInteraction {
|
pub enum ProtocolInteraction {
|
||||||
/// Observe one object and its indexable descendants to a requested depth.
|
/// Observe one object and its indexable descendants to a requested depth.
|
||||||
Observe,
|
Observe,
|
||||||
/// Fetch one interface descriptor by its opaque reference.
|
/// Fetch one interface descriptor by its structured reference.
|
||||||
FetchInterface,
|
FetchInterface,
|
||||||
/// Invoke one operation on a path-targeted object.
|
/// Invoke one operation on a path-targeted object.
|
||||||
CallOperation,
|
CallOperation,
|
||||||
|
|||||||
@@ -31,7 +31,7 @@
|
|||||||
//! guarantee; Clients must not automatically retry it.
|
//! guarantee; Clients must not automatically retry it.
|
||||||
//!
|
//!
|
||||||
//! Paths, object refs, interface refs, and validators remain separate concepts.
|
//! 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
|
//! fields. In particular, object refs are optional, operation targeting uses a
|
||||||
//! path, and this crate defines no interaction that fetches an object by ref.
|
//! path, and this crate defines no interaction that fetches an object by ref.
|
||||||
//!
|
//!
|
||||||
@@ -52,9 +52,10 @@ pub use error::{
|
|||||||
};
|
};
|
||||||
pub use model::{
|
pub use model::{
|
||||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object,
|
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceReference,
|
||||||
ObjectObservation, ObserveRequest, ObserveResponse, OperationDeclaration, ParameterDeclaration,
|
InterfaceTarget, Object, ObjectObservation, ObserveRequest, ObserveResponse,
|
||||||
ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr, UnionCase, Value,
|
OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
|
||||||
|
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Validates a canonical absolute Worldspace path.
|
/// Validates a canonical absolute Worldspace path.
|
||||||
|
|||||||
@@ -11,9 +11,49 @@ pub struct Documentation {
|
|||||||
pub details: Option<String>,
|
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.
|
/// 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
|
/// references, `r#ref` is optional object identity, and `validator` is an
|
||||||
/// independent optional observation precondition. In particular, neither the
|
/// independent optional observation precondition. In particular, neither the
|
||||||
/// path nor `r#ref` is a mandatory object identifier.
|
/// path nor `r#ref` is a mandatory object identifier.
|
||||||
@@ -23,8 +63,8 @@ pub struct Object {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
/// Short public description of the object.
|
/// Short public description of the object.
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
/// Opaque interface references in host publication order.
|
/// Structured interface references in host publication order.
|
||||||
pub interfaces: Vec<String>,
|
pub interfaces: Vec<InterfaceReference>,
|
||||||
/// Optional opaque identity within one client-facing Worldspace.
|
/// Optional opaque identity within one client-facing Worldspace.
|
||||||
pub r#ref: Option<String>,
|
pub r#ref: Option<String>,
|
||||||
/// Optional opaque validator for the object's observed state.
|
/// Optional opaque validator for the object's observed state.
|
||||||
@@ -239,18 +279,20 @@ pub struct ObjectObservation {
|
|||||||
/// Successful `observe` response.
|
/// Successful `observe` response.
|
||||||
pub type ObserveResponse = ObjectObservation;
|
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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct FetchInterfaceRequest {
|
pub struct FetchInterfaceRequest {
|
||||||
/// Opaque interface reference obtained from an object.
|
/// Structured interface reference obtained from an object.
|
||||||
pub interface: String,
|
pub interface: InterfaceReference,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Successful `fetch_interface` response.
|
/// Successful `fetch_interface` response.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct FetchInterfaceResponse {
|
pub struct FetchInterfaceResponse {
|
||||||
/// Opaque interface reference corresponding to the request.
|
/// Structured interface reference corresponding to the request.
|
||||||
pub interface: String,
|
pub interface: InterfaceReference,
|
||||||
|
/// Optional opaque ref of the scope Object, not part of interface identity.
|
||||||
|
pub scope_ref: Option<String>,
|
||||||
/// Current validated descriptor.
|
/// Current validated descriptor.
|
||||||
pub descriptor: InterfaceDescriptor,
|
pub descriptor: InterfaceDescriptor,
|
||||||
/// Optional opaque validator for this descriptor observation.
|
/// Optional opaque validator for this descriptor observation.
|
||||||
@@ -269,8 +311,10 @@ pub struct Target {
|
|||||||
/// Interface portion of an operation target.
|
/// Interface portion of an operation target.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct InterfaceTarget {
|
pub struct InterfaceTarget {
|
||||||
/// Opaque interface reference selected from the object's interface set.
|
/// Structured reference selected from the object's interface set.
|
||||||
pub reference: String,
|
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.
|
/// Optional validator copied from the interface observation.
|
||||||
pub validator: Option<Vec<u8>>,
|
pub validator: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
@@ -369,6 +413,13 @@ impl ObserveRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl FetchInterfaceRequest {
|
||||||
|
/// Validates reference shape; fetching an interface needs no target path.
|
||||||
|
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||||
|
self.interface.validate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FetchInterfaceResponse {
|
impl FetchInterfaceResponse {
|
||||||
/// Validates request correspondence and descriptor semantics.
|
/// Validates request correspondence and descriptor semantics.
|
||||||
///
|
///
|
||||||
@@ -382,7 +433,16 @@ impl FetchInterfaceResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CallOperationRequest {
|
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> {
|
pub fn validate_with(&self, descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||||
descriptor.validate_call(self)
|
descriptor.validate_call(self)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,22 @@ use std::collections::{BTreeMap, HashMap, HashSet};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
||||||
MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace, Object, ObjectObservation, ObserveRequest,
|
InterfaceReference, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace, Object,
|
||||||
PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, ValidationError,
|
ObjectObservation, ObserveRequest, PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD,
|
||||||
ValidationErrorKind, Value, ValueKind,
|
UNION_VALUE_FIELD, ValidationError, ValidationErrorKind, Value, ValueKind,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub(crate) fn validate_object(object: &Object) -> Result<(), ValidationError> {
|
pub(crate) fn validate_object(object: &Object) -> Result<(), ValidationError> {
|
||||||
validate_object_name(&object.name, true)?;
|
validate_object_name(&object.name, true)?;
|
||||||
|
|
||||||
let mut seen = HashSet::new();
|
let mut seen = HashSet::new();
|
||||||
for interface in &object.interfaces {
|
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||||
if !seen.insert(interface.as_str()) {
|
interface.validate().map_err(|error| {
|
||||||
|
error
|
||||||
|
.prepend(PathSegment::Index(index))
|
||||||
|
.prepend(PathSegment::Field("interfaces".into()))
|
||||||
|
})?;
|
||||||
|
if !seen.insert(interface) {
|
||||||
return Err(
|
return Err(
|
||||||
ValidationError::new(ValidationErrorKind::DuplicateInterface {
|
ValidationError::new(ValidationErrorKind::DuplicateInterface {
|
||||||
reference: interface.clone(),
|
reference: interface.clone(),
|
||||||
@@ -51,6 +56,14 @@ pub(crate) fn validate_object_at_path(object: &Object, path: &str) -> Result<(),
|
|||||||
.next()
|
.next()
|
||||||
.expect("non-root path has a segment")
|
.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 {
|
if object.name == expected {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} 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> {
|
pub(crate) fn validate_descriptor(descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||||
let declarations = declaration_map(descriptor)?;
|
let declarations = declaration_map(descriptor)?;
|
||||||
|
|
||||||
@@ -582,8 +643,7 @@ pub(crate) fn validate_call(
|
|||||||
descriptor: &InterfaceDescriptor,
|
descriptor: &InterfaceDescriptor,
|
||||||
request: &CallOperationRequest,
|
request: &CallOperationRequest,
|
||||||
) -> Result<(), ValidationError> {
|
) -> Result<(), ValidationError> {
|
||||||
validate_path(&request.target.path)
|
request.validate()?;
|
||||||
.map_err(|error| error.prepend(PathSegment::Field("target".into())))?;
|
|
||||||
validate_arguments(descriptor, &request.operation, &request.arguments)
|
validate_arguments(descriptor, &request.operation, &request.arguments)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,11 +720,13 @@ pub(crate) fn validate_fetch_interface_response(
|
|||||||
response: &FetchInterfaceResponse,
|
response: &FetchInterfaceResponse,
|
||||||
request: &FetchInterfaceRequest,
|
request: &FetchInterfaceRequest,
|
||||||
) -> Result<(), ValidationError> {
|
) -> Result<(), ValidationError> {
|
||||||
|
request.validate()?;
|
||||||
|
response.interface.validate()?;
|
||||||
if response.interface != request.interface {
|
if response.interface != request.interface {
|
||||||
return Err(
|
return Err(
|
||||||
ValidationError::new(ValidationErrorKind::InterfaceResponseMismatch {
|
ValidationError::new(ValidationErrorKind::InterfaceResponseMismatch {
|
||||||
expected: request.interface.clone(),
|
expected: Box::new(request.interface.clone()),
|
||||||
actual: response.interface.clone(),
|
actual: Box::new(response.interface.clone()),
|
||||||
})
|
})
|
||||||
.prepend(PathSegment::Field("interface".into())),
|
.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
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,12 +3,19 @@ use std::collections::BTreeMap;
|
|||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, EnumCase, FetchInterfaceRequest,
|
||||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace, Object, ObjectObservation, ObserveRequest,
|
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace, Object,
|
||||||
OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError, ProtocolErrorCode,
|
ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration, PathSegment,
|
||||||
ProtocolInteraction, ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr,
|
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ProtocolResult, ReturnDeclaration,
|
||||||
UnionCase, ValidationErrorKind, Value, ValueKind,
|
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 {
|
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||||
Value::Record(
|
Value::Record(
|
||||||
entries
|
entries
|
||||||
@@ -135,7 +142,7 @@ fn object(name: &str) -> Object {
|
|||||||
Object {
|
Object {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
description: Some(format!("Object {name}")),
|
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()),
|
r#ref: Some("opaque-object-ref".into()),
|
||||||
validator: Some(vec![1, 2, 3]),
|
validator: Some(vec![1, 2, 3]),
|
||||||
}
|
}
|
||||||
@@ -146,16 +153,19 @@ fn object_fields_have_canonical_identity_and_ordered_set_semantics() {
|
|||||||
let object = object("article");
|
let object = object("article");
|
||||||
object.validate().unwrap();
|
object.validate().unwrap();
|
||||||
object.validate_at_path("/articles/article").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 {
|
let duplicate = Object {
|
||||||
interfaces: vec!["catalog-v1".into(), "catalog-v1".into()],
|
interfaces: vec![reference("/", "catalog-v1"), reference("/", "catalog-v1")],
|
||||||
..object.clone()
|
..object.clone()
|
||||||
};
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
duplicate.validate().unwrap_err().kind,
|
duplicate.validate().unwrap_err().kind,
|
||||||
ValidationErrorKind::DuplicateInterface {
|
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]),
|
validator: Some(vec![1]),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: "catalog-v1".into(),
|
scope_ref: None,
|
||||||
|
reference: reference("/", "catalog-v1"),
|
||||||
validator: Some(vec![2]),
|
validator: Some(vec![2]),
|
||||||
},
|
},
|
||||||
operation: "publish".into(),
|
operation: "publish".into(),
|
||||||
@@ -659,17 +670,18 @@ fn observe_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let request = FetchInterfaceRequest {
|
let request = FetchInterfaceRequest {
|
||||||
interface: "catalog-v1".into(),
|
interface: reference("/", "catalog-v1"),
|
||||||
};
|
};
|
||||||
let response = FetchInterfaceResponse {
|
let response = FetchInterfaceResponse {
|
||||||
interface: "catalog-v1".into(),
|
scope_ref: None,
|
||||||
|
interface: reference("/", "catalog-v1"),
|
||||||
descriptor: descriptor(),
|
descriptor: descriptor(),
|
||||||
validator: Some(vec![9]),
|
validator: Some(vec![9]),
|
||||||
};
|
};
|
||||||
response.validate_for(&request).unwrap();
|
response.validate_for(&request).unwrap();
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
FetchInterfaceResponse {
|
FetchInterfaceResponse {
|
||||||
interface: "other".into(),
|
interface: reference("/", "other"),
|
||||||
..response
|
..response
|
||||||
}
|
}
|
||||||
.validate_for(&request)
|
.validate_for(&request)
|
||||||
@@ -847,7 +859,7 @@ fn invalid_success_payloads_remain_client_local_validation_failures() {
|
|||||||
));
|
));
|
||||||
|
|
||||||
let interface_request = FetchInterfaceRequest {
|
let interface_request = FetchInterfaceRequest {
|
||||||
interface: "catalog-v1".into(),
|
interface: reference("/", "catalog-v1"),
|
||||||
};
|
};
|
||||||
let mut invalid_descriptor = descriptor();
|
let mut invalid_descriptor = descriptor();
|
||||||
invalid_descriptor
|
invalid_descriptor
|
||||||
@@ -856,6 +868,7 @@ fn invalid_success_payloads_remain_client_local_validation_failures() {
|
|||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
FetchInterfaceResponse {
|
FetchInterfaceResponse {
|
||||||
interface: interface_request.interface.clone(),
|
interface: interface_request.interface.clone(),
|
||||||
|
scope_ref: None,
|
||||||
descriptor: invalid_descriptor,
|
descriptor: invalid_descriptor,
|
||||||
validator: None,
|
validator: None,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-public-api-example"
|
name = "wip-public-api-example"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
wip-host = { path = "../wip-host" }
|
wip-host.workspace = true
|
||||||
wip-interface = { path = "../wip-interface" }
|
wip-interface.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
wip-client.workspace = true
|
||||||
|
wip-http.workspace = true
|
||||||
|
|||||||
@@ -10,13 +10,20 @@
|
|||||||
//! request-scoped implementation, backend handle, authorization policy, and
|
//! request-scoped implementation, backend handle, authorization policy, and
|
||||||
//! publication wiring remain host-private. A transport binding would translate
|
//! 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
|
//! its own wire routes and envelopes to the protocol call DTOs; no HTTP type is
|
||||||
//! part of an application trait or interface descriptor.
|
//! 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
|
//! # Breaking migration exercised here
|
||||||
//!
|
//!
|
||||||
//! The canonical API targets operations by `target.path` rather than a mandatory
|
//! The canonical API targets operations by `target.path` rather than a mandatory
|
||||||
//! object identifier. Object `ref` and object/interface validators are separate,
|
//! object identifier. Object `ref` and object/interface validators are separate,
|
||||||
//! optional observation fields. Interface references are opaque values observed
|
//! 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
|
//! separately from descriptors, and descriptors contain neither a Rust trait
|
||||||
//! name nor an opaque-reference `name` field. Application records, enums,
|
//! name nor an opaque-reference `name` field. Application records, enums,
|
||||||
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
|
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
|
||||||
@@ -41,12 +48,12 @@ use std::io;
|
|||||||
|
|
||||||
use wip_host::{
|
use wip_host::{
|
||||||
CallErrorKind, CallRequest, ExecutionContext, InterfaceRef, InterfaceRegistry, InterfaceTarget,
|
CallErrorKind, CallRequest, ExecutionContext, InterfaceRef, InterfaceRegistry, InterfaceTarget,
|
||||||
ObjectProvider, ProviderResult, PublishedObject, RegisteredInterface, Target, Validator,
|
ObjectProvider, ProviderResult, PublishedObject, RegisteredInterface, Scope, ScopeObservation,
|
||||||
WipObject,
|
Target, Validator, WipObject,
|
||||||
};
|
};
|
||||||
use wip_interface as wip;
|
use wip_interface as wip;
|
||||||
use wip_interface::WipType;
|
use wip_interface::WipType;
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, Value};
|
use wip_protocol::{InterfaceReference, ProtocolError, ProtocolErrorCode, Value};
|
||||||
|
|
||||||
const OBJECT_PATH: &str = "/article-service";
|
const OBJECT_PATH: &str = "/article-service";
|
||||||
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
||||||
@@ -134,16 +141,22 @@ pub struct DemoReport {
|
|||||||
pub object_reference: Option<String>,
|
pub object_reference: Option<String>,
|
||||||
/// Optional object-state validator.
|
/// Optional object-state validator.
|
||||||
pub object_validator: Option<Vec<u8>>,
|
pub object_validator: Option<Vec<u8>>,
|
||||||
/// Opaque interface references published by the object, in exposure order.
|
/// Structured interface references published by the object, in exposure order.
|
||||||
pub published_interfaces: Vec<String>,
|
pub published_interfaces: Vec<InterfaceReference>,
|
||||||
/// Opaque reference assigned to the catalog descriptor.
|
/// Self-scoped reference assigned to the catalog descriptor.
|
||||||
pub catalog_interface_reference: String,
|
pub catalog_interface_reference: InterfaceReference,
|
||||||
/// Opaque reference assigned to the audit descriptor.
|
/// Self-scoped reference assigned to the audit descriptor.
|
||||||
pub audit_interface_reference: String,
|
pub audit_interface_reference: InterfaceReference,
|
||||||
/// Descriptor format observed separately for the catalog reference.
|
/// Descriptor format observed separately for the catalog reference.
|
||||||
pub catalog_descriptor_format: String,
|
pub catalog_descriptor_format: String,
|
||||||
/// Descriptor format observed separately for the audit reference.
|
/// Descriptor format observed separately for the audit reference.
|
||||||
pub audit_descriptor_format: String,
|
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`].
|
/// Typed successful application result decoded from a validated [`Value`].
|
||||||
pub published: PublishOutcome,
|
pub published: PublishOutcome,
|
||||||
/// Typed application-domain rejection decoded from a validated [`Value`].
|
/// Typed application-domain rejection decoded from a validated [`Value`].
|
||||||
@@ -182,25 +195,34 @@ pub struct DemoReport {
|
|||||||
/// application-value decoding fails unexpectedly.
|
/// application-value decoding fails unexpectedly.
|
||||||
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
||||||
let mut registry = InterfaceRegistry::new();
|
let mut registry = InterfaceRegistry::new();
|
||||||
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
|
let scope = Scope::new(OBJECT_PATH)?;
|
||||||
let audit = registry.register(AuditDefinition, None)?;
|
let catalog = registry.register(
|
||||||
let diagnostics = registry.register(DiagnosticsDefinition, None)?;
|
&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 {
|
let provider = ApplicationProvider {
|
||||||
|
scope,
|
||||||
catalog: catalog.clone(),
|
catalog: catalog.clone(),
|
||||||
audit: audit.clone(),
|
audit: audit.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let object = provider.observe_object(OBJECT_PATH)?;
|
let object = provider.observe_object(OBJECT_PATH)?;
|
||||||
let catalog_response = registry
|
let catalog_response = provider
|
||||||
.fetch_interface(
|
.fetch_interface(
|
||||||
|
®istry,
|
||||||
object
|
object
|
||||||
.interfaces
|
.interfaces
|
||||||
.first()
|
.first()
|
||||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
||||||
)?
|
)?
|
||||||
.protocol_response()?;
|
.protocol_response()?;
|
||||||
let audit_response = registry
|
let audit_response = provider
|
||||||
.fetch_interface(
|
.fetch_interface(
|
||||||
|
®istry,
|
||||||
object
|
object
|
||||||
.interfaces
|
.interfaces
|
||||||
.get(1)
|
.get(1)
|
||||||
@@ -210,7 +232,7 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
|
|
||||||
let published = dispatch_publish(
|
let published = dispatch_publish(
|
||||||
&provider,
|
&provider,
|
||||||
catalog.reference(),
|
&catalog_response,
|
||||||
PublishRequest {
|
PublishRequest {
|
||||||
title: "Public APIs".into(),
|
title: "Public APIs".into(),
|
||||||
body: Some("protocol values in, validated values out".into()),
|
body: Some("protocol values in, validated values out".into()),
|
||||||
@@ -224,7 +246,7 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
)?;
|
)?;
|
||||||
let rejected = dispatch_publish(
|
let rejected = dispatch_publish(
|
||||||
&provider,
|
&provider,
|
||||||
catalog.reference(),
|
&catalog_response,
|
||||||
PublishRequest {
|
PublishRequest {
|
||||||
title: String::new(),
|
title: String::new(),
|
||||||
body: None,
|
body: None,
|
||||||
@@ -237,7 +259,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
&provider,
|
&provider,
|
||||||
request(
|
request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
catalog.reference(),
|
&catalog_response.interface,
|
||||||
|
catalog_response.scope_ref.as_deref(),
|
||||||
Some(CATALOG_VALIDATOR),
|
Some(CATALOG_VALIDATOR),
|
||||||
"status",
|
"status",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -247,7 +270,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
&provider,
|
&provider,
|
||||||
request(
|
request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
audit.reference(),
|
&audit_response.interface,
|
||||||
|
audit_response.scope_ref.as_deref(),
|
||||||
None,
|
None,
|
||||||
"status",
|
"status",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -257,7 +281,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
let host_error = provider
|
let host_error = provider
|
||||||
.call_operation(request(
|
.call_operation(request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
catalog.reference(),
|
&catalog_response.interface,
|
||||||
|
catalog_response.scope_ref.as_deref(),
|
||||||
Some(CATALOG_VALIDATOR),
|
Some(CATALOG_VALIDATOR),
|
||||||
"backend_status",
|
"backend_status",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -269,7 +294,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
let unknown_protocol_failure = provider
|
let unknown_protocol_failure = provider
|
||||||
.call_operation(request(
|
.call_operation(request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
catalog.reference(),
|
&catalog_response.interface,
|
||||||
|
catalog_response.scope_ref.as_deref(),
|
||||||
Some(CATALOG_VALIDATOR),
|
Some(CATALOG_VALIDATOR),
|
||||||
"uncertain_backend_status",
|
"uncertain_backend_status",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -280,7 +306,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
let permission_failure = provider
|
let permission_failure = provider
|
||||||
.call_operation(request(
|
.call_operation(request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
catalog.reference(),
|
&catalog_response.interface,
|
||||||
|
catalog_response.scope_ref.as_deref(),
|
||||||
Some(CATALOG_VALIDATOR),
|
Some(CATALOG_VALIDATOR),
|
||||||
"restricted_status",
|
"restricted_status",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -296,7 +323,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
validator: Some(b"stale-object".to_vec()),
|
validator: Some(b"stale-object".to_vec()),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: diagnostics.reference().as_str().to_owned(),
|
scope_ref: None,
|
||||||
|
reference: diagnostics.reference().protocol_reference(),
|
||||||
validator: Some(b"stale-interface".to_vec()),
|
validator: Some(b"stale-interface".to_vec()),
|
||||||
},
|
},
|
||||||
operation: "missing".into(),
|
operation: "missing".into(),
|
||||||
@@ -309,7 +337,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
let interface_mismatch = provider
|
let interface_mismatch = provider
|
||||||
.call_operation(request(
|
.call_operation(request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
diagnostics.reference(),
|
&diagnostics.reference().protocol_reference(),
|
||||||
|
catalog_response.scope_ref.as_deref(),
|
||||||
None,
|
None,
|
||||||
"diagnostics",
|
"diagnostics",
|
||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
@@ -318,11 +347,32 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
.protocol_error()
|
.protocol_error()
|
||||||
.code;
|
.code;
|
||||||
|
|
||||||
let interface_not_found = registry
|
let interface_not_found = provider
|
||||||
.fetch_interface("missing-interface")
|
.fetch_interface(
|
||||||
|
®istry,
|
||||||
|
&InterfaceReference {
|
||||||
|
scope: OBJECT_PATH.into(),
|
||||||
|
name: "missing-interface".into(),
|
||||||
|
},
|
||||||
|
)
|
||||||
.expect_err("unknown interface references must not resolve")
|
.expect_err("unknown interface references must not resolve")
|
||||||
.code;
|
.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
|
let precedence_failure = provider
|
||||||
.call_operation(CallRequest {
|
.call_operation(CallRequest {
|
||||||
target: Target {
|
target: Target {
|
||||||
@@ -330,7 +380,8 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
validator: Some(b"stale-object".to_vec()),
|
validator: Some(b"stale-object".to_vec()),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: diagnostics.reference().as_str().to_owned(),
|
scope_ref: None,
|
||||||
|
reference: diagnostics.reference().protocol_reference(),
|
||||||
validator: Some(b"stale-interface".to_vec()),
|
validator: Some(b"stale-interface".to_vec()),
|
||||||
},
|
},
|
||||||
operation: "missing".into(),
|
operation: "missing".into(),
|
||||||
@@ -345,10 +396,13 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|||||||
object_reference: object.r#ref,
|
object_reference: object.r#ref,
|
||||||
object_validator: object.validator,
|
object_validator: object.validator,
|
||||||
published_interfaces: object.interfaces,
|
published_interfaces: object.interfaces,
|
||||||
catalog_interface_reference: catalog.reference().as_str().to_owned(),
|
catalog_interface_reference: catalog.reference().protocol_reference(),
|
||||||
audit_interface_reference: audit.reference().as_str().to_owned(),
|
audit_interface_reference: audit.reference().protocol_reference(),
|
||||||
catalog_descriptor_format: catalog_response.descriptor.format,
|
catalog_descriptor_format: catalog_response.descriptor.format,
|
||||||
audit_descriptor_format: audit_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,
|
published,
|
||||||
rejected,
|
rejected,
|
||||||
catalog_status,
|
catalog_status,
|
||||||
@@ -377,13 +431,14 @@ fn ensure_kind(error: &wip_host::CallError, expected: CallErrorKind) -> Result<(
|
|||||||
|
|
||||||
fn dispatch_publish(
|
fn dispatch_publish(
|
||||||
provider: &ApplicationProvider,
|
provider: &ApplicationProvider,
|
||||||
catalog: &InterfaceRef,
|
catalog: &wip_protocol::FetchInterfaceResponse,
|
||||||
request_value: PublishRequest,
|
request_value: PublishRequest,
|
||||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
) -> Result<PublishOutcome, Box<dyn Error>> {
|
||||||
let encoded_request = request_value.encode()?;
|
let encoded_request = request_value.encode()?;
|
||||||
let result = provider.call_operation(request(
|
let result = provider.call_operation(request(
|
||||||
OBJECT_PATH,
|
OBJECT_PATH,
|
||||||
catalog,
|
&catalog.interface,
|
||||||
|
catalog.scope_ref.as_deref(),
|
||||||
Some(CATALOG_VALIDATOR),
|
Some(CATALOG_VALIDATOR),
|
||||||
"publish",
|
"publish",
|
||||||
BTreeMap::from([("request".into(), encoded_request)]),
|
BTreeMap::from([("request".into(), encoded_request)]),
|
||||||
@@ -401,7 +456,8 @@ fn dispatch_string(
|
|||||||
|
|
||||||
fn request(
|
fn request(
|
||||||
path: &str,
|
path: &str,
|
||||||
interface: &InterfaceRef,
|
interface: &InterfaceReference,
|
||||||
|
scope_ref: Option<&str>,
|
||||||
interface_validator: Option<&[u8]>,
|
interface_validator: Option<&[u8]>,
|
||||||
operation: &str,
|
operation: &str,
|
||||||
arguments: BTreeMap<String, Value>,
|
arguments: BTreeMap<String, Value>,
|
||||||
@@ -412,7 +468,8 @@ fn request(
|
|||||||
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
||||||
},
|
},
|
||||||
interface: InterfaceTarget {
|
interface: InterfaceTarget {
|
||||||
reference: interface.as_str().to_owned(),
|
scope_ref: scope_ref.map(str::to_owned),
|
||||||
|
reference: interface.clone(),
|
||||||
validator: interface_validator.map(<[u8]>::to_vec),
|
validator: interface_validator.map(<[u8]>::to_vec),
|
||||||
},
|
},
|
||||||
operation: operation.into(),
|
operation: operation.into(),
|
||||||
@@ -421,6 +478,7 @@ fn request(
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct ApplicationProvider {
|
struct ApplicationProvider {
|
||||||
|
scope: Scope,
|
||||||
catalog: RegisteredInterface<CatalogDefinition>,
|
catalog: RegisteredInterface<CatalogDefinition>,
|
||||||
audit: RegisteredInterface<AuditDefinition>,
|
audit: RegisteredInterface<AuditDefinition>,
|
||||||
}
|
}
|
||||||
@@ -437,7 +495,12 @@ impl ObjectProvider for ApplicationProvider {
|
|||||||
if path != OBJECT_PATH {
|
if path != OBJECT_PATH {
|
||||||
return ProviderResult::NotFound;
|
return ProviderResult::NotFound;
|
||||||
}
|
}
|
||||||
let publication = PublishedObject::new(ApplicationService::new())
|
// 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)
|
.expose(&self.catalog)
|
||||||
.expect("ApplicationService implements Catalog")
|
.expect("ApplicationService implements Catalog")
|
||||||
.expose(&self.audit)
|
.expose(&self.audit)
|
||||||
|
|||||||
@@ -28,10 +28,20 @@ fn public_crates_support_the_complete_qualified_end_to_end_scenario() {
|
|||||||
);
|
);
|
||||||
assert_ne!(
|
assert_ne!(
|
||||||
report.catalog_interface_reference, report.audit_interface_reference,
|
report.catalog_interface_reference, report.audit_interface_reference,
|
||||||
"interfaces form an ordered set of distinct opaque references"
|
"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.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
||||||
assert_eq!(report.audit_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!(
|
assert_eq!(
|
||||||
report.published,
|
report.published,
|
||||||
PublishOutcome::Published("article-1".into())
|
PublishOutcome::Published("article-1".into())
|
||||||
@@ -97,7 +107,7 @@ fn object_fields_keep_path_context_and_optional_ref_separate() {
|
|||||||
let object = Object {
|
let object = Object {
|
||||||
name: "article".into(),
|
name: "article".into(),
|
||||||
description: None,
|
description: None,
|
||||||
interfaces: vec!["catalog-ref".into(), "audit-ref".into()],
|
interfaces: vec![root_reference("catalog-ref"), root_reference("audit-ref")],
|
||||||
r#ref: None,
|
r#ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
};
|
};
|
||||||
@@ -105,7 +115,10 @@ fn object_fields_keep_path_context_and_optional_ref_separate() {
|
|||||||
object.validate_at_path("/library/article").unwrap();
|
object.validate_at_path("/library/article").unwrap();
|
||||||
assert_eq!(object.name, "article");
|
assert_eq!(object.name, "article");
|
||||||
assert_eq!(object.r#ref, None);
|
assert_eq!(object.r#ref, None);
|
||||||
assert_eq!(object.interfaces, ["catalog-ref", "audit-ref"]);
|
assert_eq!(
|
||||||
|
object.interfaces,
|
||||||
|
[root_reference("catalog-ref"), root_reference("audit-ref")]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -244,3 +257,44 @@ fn assert_schema_neutral(value: &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);
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-tui"
|
name = "wip-tui"
|
||||||
version = "0.1.0"
|
version.workspace = true
|
||||||
edition = "2024"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
|
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
@@ -13,10 +15,10 @@ crossterm = "0.28.1"
|
|||||||
ratatui = "0.29.0"
|
ratatui = "0.29.0"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
ureq = "3.1.2"
|
ureq = "3.1.2"
|
||||||
wip-client = { path = "../wip-client" }
|
wip-client.workspace = true
|
||||||
wip-http = { path = "../wip-http" }
|
wip-http.workspace = true
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
wip-fs-server = { path = "../wip-fs-server" }
|
wip-fs-server.workspace = true
|
||||||
|
|||||||
@@ -64,6 +64,57 @@ enter `contents` as RFC 4648 base64—for example, `dXBkYXRlZA==` for
|
|||||||
`updated`—then review the target Entry, interface reference, operation, and value
|
`updated`—then review the target Entry, interface reference, operation, and value
|
||||||
on the confirmation screen before pressing Enter again.
|
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
|
## Keyboard bindings
|
||||||
|
|
||||||
All required actions are keyboard-accessible.
|
All required actions are keyboard-accessible.
|
||||||
@@ -96,8 +147,12 @@ a second explicit Enter (or `e`) to execute once. There is no operation auto-ret
|
|||||||
interfaces, and freshness. Validators, credentials, Host internals, and backend
|
interfaces, and freshness. Validators, credentials, Host internals, and backend
|
||||||
paths are deliberately hidden. If current metadata disappears, old text is not
|
paths are deliberately hidden. If current metadata disappears, old text is not
|
||||||
presented as current.
|
presented as current.
|
||||||
- **Interfaces / Operations** identifies every operation by `(interface reference,
|
- **Interfaces / Operations** identifies every operation by structured `(scope,
|
||||||
operation name)`. Descriptor lookahead follows fresh visible Objects, shares the
|
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.
|
client's in-flight/cache bounds, and never retries retained failures implicitly.
|
||||||
The pane shows descriptor documentation, ordered parameters, required/optional
|
The pane shows descriptor documentation, ordered parameters, required/optional
|
||||||
status, and result types.
|
status, and result types.
|
||||||
@@ -124,6 +179,22 @@ Validator mismatch, interface mismatch, `OperationOutcomeUnknown`, undecodable
|
|||||||
post-dispatch responses, and post-dispatch timeout/disconnect are displayed using
|
post-dispatch responses, and post-dispatch timeout/disconnect are displayed using
|
||||||
the runtime's authoritative transition.
|
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
|
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
|
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,
|
does not recreate the call: the user must select the operation, review fresh input,
|
||||||
|
|||||||
+120
-22
@@ -3,7 +3,7 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
|
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
|
||||||
use wip_protocol::{InterfaceDescriptor, Object, Value};
|
use wip_protocol::{InterfaceDescriptor, InterfaceReference, Object, Value};
|
||||||
|
|
||||||
use crate::editor::ArgumentEditor;
|
use crate::editor::ArgumentEditor;
|
||||||
|
|
||||||
@@ -139,8 +139,8 @@ impl EntryView {
|
|||||||
/// Cached interface descriptor state used by presentation.
|
/// Cached interface descriptor state used by presentation.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct InterfaceView {
|
pub struct InterfaceView {
|
||||||
/// Opaque interface reference.
|
/// Structured interface reference.
|
||||||
pub reference: String,
|
pub reference: InterfaceReference,
|
||||||
/// Descriptor when accepted by the client runtime.
|
/// Descriptor when accepted by the client runtime.
|
||||||
pub descriptor: Option<InterfaceDescriptor>,
|
pub descriptor: Option<InterfaceDescriptor>,
|
||||||
/// Descriptor observation state.
|
/// Descriptor observation state.
|
||||||
@@ -187,13 +187,13 @@ pub enum InFlightKind {
|
|||||||
/// Tree expansion or refresh.
|
/// Tree expansion or refresh.
|
||||||
Tree(String),
|
Tree(String),
|
||||||
/// Descriptor fetch.
|
/// Descriptor fetch.
|
||||||
Interface(String),
|
Interface(InterfaceReference),
|
||||||
/// Explicit operation call.
|
/// Explicit operation call.
|
||||||
Operation {
|
Operation {
|
||||||
/// Target path.
|
/// Target path.
|
||||||
path: String,
|
path: String,
|
||||||
/// Interface reference.
|
/// Interface reference.
|
||||||
interface: String,
|
interface: InterfaceReference,
|
||||||
/// Operation name.
|
/// Operation name.
|
||||||
operation: String,
|
operation: String,
|
||||||
/// Whether the transport dispatch boundary was crossed.
|
/// Whether the transport dispatch boundary was crossed.
|
||||||
@@ -241,13 +241,13 @@ pub enum Action {
|
|||||||
path: String,
|
path: String,
|
||||||
},
|
},
|
||||||
/// Retrieve one interface descriptor.
|
/// Retrieve one interface descriptor.
|
||||||
FetchInterface(String),
|
FetchInterface(InterfaceReference),
|
||||||
/// Execute only after explicit confirmation.
|
/// Execute only after explicit confirmation.
|
||||||
Execute {
|
Execute {
|
||||||
/// Entry target.
|
/// Entry target.
|
||||||
path: String,
|
path: String,
|
||||||
/// Interface reference.
|
/// Interface reference.
|
||||||
interface: String,
|
interface: InterfaceReference,
|
||||||
/// Operation name.
|
/// Operation name.
|
||||||
operation: String,
|
operation: String,
|
||||||
/// Descriptor-validated arguments.
|
/// Descriptor-validated arguments.
|
||||||
@@ -276,10 +276,13 @@ pub struct App {
|
|||||||
pub selected_path: String,
|
pub selected_path: String,
|
||||||
/// Focused pane.
|
/// Focused pane.
|
||||||
pub focus: Focus,
|
pub focus: Focus,
|
||||||
/// Interface descriptor views by opaque reference.
|
/// Interface descriptor views by structured reference.
|
||||||
pub interfaces: BTreeMap<String, InterfaceView>,
|
pub interfaces: BTreeMap<InterfaceReference, InterfaceView>,
|
||||||
/// Selected row in the flattened interface/operation view.
|
/// Selected row in the flattened interface/operation view.
|
||||||
pub operation_cursor: usize,
|
pub operation_cursor: usize,
|
||||||
|
/// Retained Entry and structured row while current operation rows are hidden.
|
||||||
|
/// This is selection identity only, never authority to execute a stale row.
|
||||||
|
pub operation_selection: Option<(String, OperationRow)>,
|
||||||
/// Selected recent-history row.
|
/// Selected recent-history row.
|
||||||
pub history_cursor: usize,
|
pub history_cursor: usize,
|
||||||
/// Active overlay.
|
/// Active overlay.
|
||||||
@@ -310,6 +313,7 @@ impl App {
|
|||||||
focus: Focus::Tree,
|
focus: Focus::Tree,
|
||||||
interfaces: BTreeMap::new(),
|
interfaces: BTreeMap::new(),
|
||||||
operation_cursor: 0,
|
operation_cursor: 0,
|
||||||
|
operation_selection: None,
|
||||||
history_cursor: 0,
|
history_cursor: 0,
|
||||||
modal: Modal::None,
|
modal: Modal::None,
|
||||||
in_flight: BTreeMap::new(),
|
in_flight: BTreeMap::new(),
|
||||||
@@ -362,7 +366,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
InputKey::Enter | InputKey::Character('e') => {
|
InputKey::Enter | InputKey::Character('e') => {
|
||||||
let action = Action::Execute {
|
let action = Action::Execute {
|
||||||
path: self.selected_path.clone(),
|
path: editor.path.clone(),
|
||||||
interface: editor.interface.clone(),
|
interface: editor.interface.clone(),
|
||||||
operation: editor.operation.name.clone(),
|
operation: editor.operation.name.clone(),
|
||||||
arguments,
|
arguments,
|
||||||
@@ -464,17 +468,21 @@ impl App {
|
|||||||
if let Some(row) = rows.get(self.operation_cursor) {
|
if let Some(row) = rows.get(self.operation_cursor) {
|
||||||
if let Some(operation_name) = &row.operation {
|
if let Some(operation_name) = &row.operation {
|
||||||
if let Some(interface) = self.interfaces.get(&row.interface)
|
if let Some(interface) = self.interfaces.get(&row.interface)
|
||||||
|
&& interface.state == ViewState::Fresh
|
||||||
&& let Some(descriptor) = &interface.descriptor
|
&& let Some(descriptor) = &interface.descriptor
|
||||||
&& let Some(operation) = descriptor
|
&& let Some(operation) = descriptor
|
||||||
.operations
|
.operations
|
||||||
.iter()
|
.iter()
|
||||||
.find(|operation| operation.name == *operation_name)
|
.find(|operation| operation.name == *operation_name)
|
||||||
{
|
{
|
||||||
self.modal = Modal::Editor(ArgumentEditor::new(
|
self.modal = Modal::Editor(
|
||||||
row.interface.clone(),
|
ArgumentEditor::new(
|
||||||
descriptor.clone(),
|
row.interface.clone(),
|
||||||
operation.clone(),
|
descriptor.clone(),
|
||||||
));
|
operation.clone(),
|
||||||
|
)
|
||||||
|
.for_target(self.selected_path.clone()),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return vec![Action::FetchInterface(row.interface.clone())];
|
return vec![Action::FetchInterface(row.interface.clone())];
|
||||||
@@ -515,6 +523,10 @@ impl App {
|
|||||||
|
|
||||||
/// Records a pending request separately by interaction type.
|
/// Records a pending request separately by interaction type.
|
||||||
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
|
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
|
||||||
|
// Object/Interface loading can remove all rows before completion. Keep
|
||||||
|
// the exact subject now rather than recovering identity from a cursor.
|
||||||
|
let selected = self.operation_rows().get(self.operation_cursor).cloned();
|
||||||
|
self.restore_operation_selection(selected);
|
||||||
match &kind {
|
match &kind {
|
||||||
InFlightKind::Object(path) => {
|
InFlightKind::Object(path) => {
|
||||||
self.ensure_entry(path).state = ViewState::Loading(id);
|
self.ensure_entry(path).state = ViewState::Loading(id);
|
||||||
@@ -615,7 +627,7 @@ impl App {
|
|||||||
/// Returns interface references advertised by fresh visible Objects in display
|
/// Returns interface references advertised by fresh visible Objects in display
|
||||||
/// and per-Object declaration order, with duplicates removed.
|
/// and per-Object declaration order, with duplicates removed.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn visible_interface_references(&self) -> Vec<String> {
|
pub fn visible_interface_references(&self) -> Vec<InterfaceReference> {
|
||||||
let mut references = Vec::new();
|
let mut references = Vec::new();
|
||||||
let mut seen = BTreeSet::new();
|
let mut seen = BTreeSet::new();
|
||||||
for path in self.visible_paths() {
|
for path in self.visible_paths() {
|
||||||
@@ -683,6 +695,37 @@ impl App {
|
|||||||
rows
|
rows
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Preserves a selected structured subject across descriptor/row movement.
|
||||||
|
pub(crate) fn restore_operation_selection(&mut self, selected: Option<OperationRow>) {
|
||||||
|
if let Some(selected) = selected {
|
||||||
|
self.operation_selection = Some((self.selected_path.clone(), selected));
|
||||||
|
} else if self
|
||||||
|
.operation_selection
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(path, _)| path != &self.selected_path)
|
||||||
|
{
|
||||||
|
self.operation_selection = None;
|
||||||
|
}
|
||||||
|
let rows = self.operation_rows();
|
||||||
|
self.operation_cursor = self
|
||||||
|
.operation_selection
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|(_, selected)| {
|
||||||
|
rows.iter().position(|row| row == selected).or_else(|| {
|
||||||
|
rows.iter().position(|row| {
|
||||||
|
row.interface == selected.interface && row.operation.is_none()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
// Keep identity through a temporarily empty (loading/stale) view. Once
|
||||||
|
// rows are current, the retained identity follows the actual selection,
|
||||||
|
// falling back to its own Interface header if the Operation was retired.
|
||||||
|
if let Some(row) = rows.get(self.operation_cursor) {
|
||||||
|
self.operation_selection = Some((self.selected_path.clone(), row.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
|
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
|
||||||
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
|
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
|
||||||
let candidate = self
|
let candidate = self
|
||||||
@@ -716,7 +759,7 @@ impl App {
|
|||||||
.or_insert_with(|| EntryView::placeholder(path))
|
.or_insert_with(|| EntryView::placeholder(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ensure_interface(&mut self, reference: &str) -> &mut InterfaceView {
|
fn ensure_interface(&mut self, reference: &InterfaceReference) -> &mut InterfaceView {
|
||||||
if !self.interfaces.contains_key(reference)
|
if !self.interfaces.contains_key(reference)
|
||||||
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
|
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
|
||||||
{
|
{
|
||||||
@@ -757,7 +800,7 @@ impl App {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct OperationRow {
|
pub struct OperationRow {
|
||||||
/// Interface reference, which participates in operation identity.
|
/// Interface reference, which participates in operation identity.
|
||||||
pub interface: String,
|
pub interface: InterfaceReference,
|
||||||
/// Operation name, or `None` for the interface heading.
|
/// Operation name, or `None` for the interface heading.
|
||||||
pub operation: Option<String>,
|
pub operation: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -773,6 +816,12 @@ pub fn parent_path(path: &str) -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||||
|
wip_protocol::InterfaceReference {
|
||||||
|
scope: "/".into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
use super::*;
|
use super::*;
|
||||||
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
|
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
|
||||||
|
|
||||||
@@ -780,7 +829,10 @@ mod tests {
|
|||||||
Object {
|
Object {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
description: Some(format!("{name} description")),
|
description: Some(format!("{name} description")),
|
||||||
interfaces: interfaces.iter().map(|value| (*value).into()).collect(),
|
interfaces: interfaces
|
||||||
|
.iter()
|
||||||
|
.map(|value| root_reference(value))
|
||||||
|
.collect(),
|
||||||
r#ref: None,
|
r#ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
}
|
}
|
||||||
@@ -846,7 +898,51 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
app.visible_interface_references(),
|
app.visible_interface_references(),
|
||||||
["root", "shared", "child"]
|
[
|
||||||
|
root_reference("root"),
|
||||||
|
root_reference("shared"),
|
||||||
|
root_reference("child")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presentation_retains_equal_names_in_distinct_scopes() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
let root = root_reference("shared#::操作");
|
||||||
|
let local = InterfaceReference {
|
||||||
|
scope: "/a".into(),
|
||||||
|
name: root.name.clone(),
|
||||||
|
};
|
||||||
|
let mut value = object("a", &[]);
|
||||||
|
value.interfaces = vec![root.clone(), local.clone()];
|
||||||
|
app.navigate_entry("/a");
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/a".into(),
|
||||||
|
object: Some(value),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
for reference in [&root, &local] {
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: reference.clone(),
|
||||||
|
descriptor: None,
|
||||||
|
validator: None,
|
||||||
|
scope_ref: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert_eq!(app.interfaces.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
app.visible_interface_references(),
|
||||||
|
vec![root.clone(), local.clone()]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
app.operation_rows()
|
||||||
|
.iter()
|
||||||
|
.map(|row| row.interface.clone())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![root, local]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -874,7 +970,8 @@ mod tests {
|
|||||||
}],
|
}],
|
||||||
};
|
};
|
||||||
app.apply_interface(InterfaceObservation {
|
app.apply_interface(InterfaceObservation {
|
||||||
reference: "iface".into(),
|
scope_ref: None,
|
||||||
|
reference: root_reference("iface"),
|
||||||
descriptor: Some(descriptor),
|
descriptor: Some(descriptor),
|
||||||
validator: None,
|
validator: None,
|
||||||
state: ObservationState::Fresh,
|
state: ObservationState::Fresh,
|
||||||
@@ -903,7 +1000,8 @@ mod tests {
|
|||||||
|
|
||||||
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
|
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
|
||||||
app.apply_interface(InterfaceObservation {
|
app.apply_interface(InterfaceObservation {
|
||||||
reference: format!("interface-{index}"),
|
scope_ref: None,
|
||||||
|
reference: root_reference(&format!("interface-{index}")),
|
||||||
descriptor: None,
|
descriptor: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
state: ObservationState::Fresh,
|
state: ObservationState::Fresh,
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ use std::collections::BTreeMap;
|
|||||||
|
|
||||||
use base64::Engine as _;
|
use base64::Engine as _;
|
||||||
use base64::engine::general_purpose::STANDARD;
|
use base64::engine::general_purpose::STANDARD;
|
||||||
use wip_protocol::{InterfaceDescriptor, OperationDeclaration, TypeExpr, Value};
|
use wip_protocol::{
|
||||||
|
InterfaceDescriptor, InterfaceReference, OperationDeclaration, TypeExpr, Value,
|
||||||
|
};
|
||||||
|
|
||||||
const MAX_FIELD_INPUT_BYTES: usize = 256 * 1024;
|
const MAX_FIELD_INPUT_BYTES: usize = 256 * 1024;
|
||||||
|
|
||||||
@@ -30,8 +32,10 @@ pub struct InvalidArguments;
|
|||||||
/// Pure, terminal-independent editor built from an operation descriptor.
|
/// Pure, terminal-independent editor built from an operation descriptor.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ArgumentEditor {
|
pub struct ArgumentEditor {
|
||||||
/// Opaque interface reference selected for the call.
|
/// Exact Entry target selected when editing began; never read from display text.
|
||||||
pub interface: String,
|
pub path: String,
|
||||||
|
/// Structured interface reference selected for the call.
|
||||||
|
pub interface: InterfaceReference,
|
||||||
/// Selected operation declaration.
|
/// Selected operation declaration.
|
||||||
pub operation: OperationDeclaration,
|
pub operation: OperationDeclaration,
|
||||||
/// Complete descriptor used to resolve named types.
|
/// Complete descriptor used to resolve named types.
|
||||||
@@ -46,7 +50,7 @@ impl ArgumentEditor {
|
|||||||
/// Builds an editor whose fields preserve descriptor order.
|
/// Builds an editor whose fields preserve descriptor order.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
interface: impl Into<String>,
|
interface: InterfaceReference,
|
||||||
descriptor: InterfaceDescriptor,
|
descriptor: InterfaceDescriptor,
|
||||||
operation: OperationDeclaration,
|
operation: OperationDeclaration,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
@@ -66,7 +70,8 @@ impl ArgumentEditor {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
Self {
|
Self {
|
||||||
interface: interface.into(),
|
path: "/".into(),
|
||||||
|
interface,
|
||||||
operation,
|
operation,
|
||||||
descriptor,
|
descriptor,
|
||||||
fields,
|
fields,
|
||||||
@@ -74,6 +79,13 @@ impl ArgumentEditor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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.
|
/// Moves to the preceding field without wrapping.
|
||||||
pub fn previous_field(&mut self) {
|
pub fn previous_field(&mut self) {
|
||||||
self.cursor = self.cursor.saturating_sub(1);
|
self.cursor = self.cursor.saturating_sub(1);
|
||||||
@@ -466,6 +478,12 @@ fn json_to_untyped(json: &serde_json::Value, field: &str) -> Result<Value, Strin
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||||
|
wip_protocol::InterfaceReference {
|
||||||
|
scope: "/".into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
use super::*;
|
use super::*;
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
EnumCase, FieldDeclaration, INTERFACE_FORMAT_V1, ParameterDeclaration, ReturnDeclaration,
|
EnumCase, FieldDeclaration, INTERFACE_FORMAT_V1, ParameterDeclaration, ReturnDeclaration,
|
||||||
@@ -560,7 +578,7 @@ mod tests {
|
|||||||
}],
|
}],
|
||||||
);
|
);
|
||||||
let operation = descriptor.operations[0].clone();
|
let operation = descriptor.operations[0].clone();
|
||||||
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
let mut editor = ArgumentEditor::new(root_reference("test"), descriptor, operation);
|
||||||
let inputs = [
|
let inputs = [
|
||||||
"null",
|
"null",
|
||||||
"true",
|
"true",
|
||||||
@@ -595,7 +613,7 @@ mod tests {
|
|||||||
vec![],
|
vec![],
|
||||||
);
|
);
|
||||||
let operation = descriptor.operations[0].clone();
|
let operation = descriptor.operations[0].clone();
|
||||||
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
let mut editor = ArgumentEditor::new(root_reference("test"), descriptor, operation);
|
||||||
editor.fields[1].input = "not-a-bool".into();
|
editor.fields[1].input = "not-a-bool".into();
|
||||||
assert_eq!(editor.validate(), Err(InvalidArguments));
|
assert_eq!(editor.validate(), Err(InvalidArguments));
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
//! Presentation and terminal interaction for stateful WIP client sessions.
|
//! 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)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod editor;
|
pub mod editor;
|
||||||
|
pub mod reference;
|
||||||
pub mod render;
|
pub mod render;
|
||||||
pub mod runtime;
|
pub mod runtime;
|
||||||
pub mod terminal;
|
pub mod terminal;
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
+149
-20
@@ -11,6 +11,25 @@ use crate::editor::type_name;
|
|||||||
|
|
||||||
const MAX_RENDER_TEXT: usize = 512;
|
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.
|
/// Draws the complete application without mutating it.
|
||||||
pub fn draw(frame: &mut Frame<'_>, app: &App) {
|
pub fn draw(frame: &mut Frame<'_>, app: &App) {
|
||||||
let area = frame.area();
|
let area = frame.area();
|
||||||
@@ -162,7 +181,7 @@ fn render_selected(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
|||||||
object
|
object
|
||||||
.interfaces
|
.interfaces
|
||||||
.iter()
|
.iter()
|
||||||
.map(|value| sanitize(value))
|
.map(interface_label)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
}
|
}
|
||||||
@@ -224,7 +243,7 @@ fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
|
|||||||
.find(|operation| operation.name == *name)
|
.find(|operation| operation.name == *name)
|
||||||
});
|
});
|
||||||
let signature = declaration.map_or_else(
|
let signature = declaration.map_or_else(
|
||||||
|| format!(" ({}, {})", row.interface, name),
|
|| format!(" {}", operation_label(&row.interface, name)),
|
||||||
|operation| {
|
|operation| {
|
||||||
let parameters = operation
|
let parameters = operation
|
||||||
.parameters
|
.parameters
|
||||||
@@ -245,9 +264,8 @@ fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
|
|||||||
.map(|documentation| format!(" — {}", documentation.summary))
|
.map(|documentation| format!(" — {}", documentation.summary))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
format!(
|
format!(
|
||||||
" ({}, {}) ({parameters}) -> {}{}",
|
" {} ({parameters}) -> {}{}",
|
||||||
row.interface,
|
operation_label(&row.interface, name),
|
||||||
name,
|
|
||||||
type_name(&operation.returns.r#type),
|
type_name(&operation.returns.r#type),
|
||||||
documentation
|
documentation
|
||||||
)
|
)
|
||||||
@@ -266,7 +284,7 @@ fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
|
|||||||
(
|
(
|
||||||
Line::from(format!(
|
Line::from(format!(
|
||||||
"Interface {} [{}]{}",
|
"Interface {} [{}]{}",
|
||||||
sanitize(&row.interface),
|
interface_label(&row.interface),
|
||||||
state,
|
state,
|
||||||
documentation
|
documentation
|
||||||
)),
|
)),
|
||||||
@@ -353,10 +371,9 @@ fn render_modal(frame: &mut Frame<'_>, app: &App) {
|
|||||||
let area = centered(frame.area(), 86, 78);
|
let area = centered(frame.area(), 86, 78);
|
||||||
frame.render_widget(Clear, area);
|
frame.render_widget(Clear, area);
|
||||||
let mut lines = vec![Line::from(format!(
|
let mut lines = vec![Line::from(format!(
|
||||||
"Target: {} Operation: ({}, {})",
|
"Target: {} Operation: {}",
|
||||||
sanitize(&app.selected_path),
|
sanitize(&editor.path),
|
||||||
sanitize(&editor.interface),
|
operation_label(&editor.interface, &editor.operation.name)
|
||||||
sanitize(&editor.operation.name)
|
|
||||||
))];
|
))];
|
||||||
if editor.fields.is_empty() {
|
if editor.fields.is_empty() {
|
||||||
lines.push(Line::from("(no parameters)"));
|
lines.push(Line::from("(no parameters)"));
|
||||||
@@ -404,9 +421,12 @@ fn render_modal(frame: &mut Frame<'_>, app: &App) {
|
|||||||
.fg(Color::Yellow)
|
.fg(Color::Yellow)
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
Line::from(format!("Entry: {}", sanitize(&app.selected_path))),
|
Line::from(format!("Entry: {}", sanitize(&editor.path))),
|
||||||
Line::from(format!("Interface: {}", sanitize(&editor.interface))),
|
Line::from(format!("Interface: {}", interface_label(&editor.interface))),
|
||||||
Line::from(format!("Operation: {}", sanitize(&editor.operation.name))),
|
Line::from(format!(
|
||||||
|
"Operation: {}",
|
||||||
|
operation_label(&editor.interface, &editor.operation.name)
|
||||||
|
)),
|
||||||
Line::from("Input values:"),
|
Line::from("Input values:"),
|
||||||
];
|
];
|
||||||
for (name, value) in arguments {
|
for (name, value) in arguments {
|
||||||
@@ -579,6 +599,12 @@ fn bounded_value_at(value: &wip_protocol::Value, depth: usize) -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||||
|
wip_protocol::InterfaceReference {
|
||||||
|
scope: "/".into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
use ratatui::Terminal;
|
use ratatui::Terminal;
|
||||||
use ratatui::backend::TestBackend;
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
@@ -664,7 +690,7 @@ mod tests {
|
|||||||
object: Some(Object {
|
object: Some(Object {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
description: Some("public root description".into()),
|
description: Some("public root description".into()),
|
||||||
interfaces: vec!["demo-interface".into()],
|
interfaces: vec![root_reference("demo-interface")],
|
||||||
r#ref: None,
|
r#ref: None,
|
||||||
validator: Some(b"must-not-render".to_vec()),
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
}),
|
}),
|
||||||
@@ -691,7 +717,8 @@ mod tests {
|
|||||||
}],
|
}],
|
||||||
};
|
};
|
||||||
app.apply_interface(InterfaceObservation {
|
app.apply_interface(InterfaceObservation {
|
||||||
reference: "demo-interface".into(),
|
scope_ref: None,
|
||||||
|
reference: root_reference("demo-interface"),
|
||||||
descriptor: Some(descriptor.clone()),
|
descriptor: Some(descriptor.clone()),
|
||||||
validator: Some(b"must-not-render".to_vec()),
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
state: ObservationState::Fresh,
|
state: ObservationState::Fresh,
|
||||||
@@ -711,7 +738,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let snapshot = rendered(&app, 140, 40);
|
let snapshot = rendered(&app, 140, 40);
|
||||||
assert!(snapshot.contains("public root description"));
|
assert!(snapshot.contains("public root description"));
|
||||||
assert!(snapshot.contains("(demo-interface, run)"));
|
assert!(snapshot.contains("/::demo-interface#run"));
|
||||||
assert!(snapshot.contains("SUCCESS"));
|
assert!(snapshot.contains("SUCCESS"));
|
||||||
assert!(snapshot.contains("PROTOCOL ERROR"));
|
assert!(snapshot.contains("PROTOCOL ERROR"));
|
||||||
assert!(snapshot.contains("TRANSPORT FAILURE"));
|
assert!(snapshot.contains("TRANSPORT FAILURE"));
|
||||||
@@ -719,7 +746,7 @@ mod tests {
|
|||||||
assert!(!snapshot.contains("must-not-render"));
|
assert!(!snapshot.contains("must-not-render"));
|
||||||
|
|
||||||
let mut editor = ArgumentEditor::new(
|
let mut editor = ArgumentEditor::new(
|
||||||
"demo-interface",
|
root_reference("demo-interface"),
|
||||||
descriptor.clone(),
|
descriptor.clone(),
|
||||||
descriptor.operations[0].clone(),
|
descriptor.operations[0].clone(),
|
||||||
);
|
);
|
||||||
@@ -774,7 +801,7 @@ mod tests {
|
|||||||
object: Some(Object {
|
object: Some(Object {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
description: None,
|
description: None,
|
||||||
interfaces: vec!["many".into()],
|
interfaces: vec![root_reference("many")],
|
||||||
r#ref: None,
|
r#ref: None,
|
||||||
validator: None,
|
validator: None,
|
||||||
}),
|
}),
|
||||||
@@ -793,7 +820,8 @@ mod tests {
|
|||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
app.apply_interface(InterfaceObservation {
|
app.apply_interface(InterfaceObservation {
|
||||||
reference: "many".into(),
|
scope_ref: None,
|
||||||
|
reference: root_reference("many"),
|
||||||
descriptor: Some(InterfaceDescriptor {
|
descriptor: Some(InterfaceDescriptor {
|
||||||
format: INTERFACE_FORMAT_V1.into(),
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
documentation: None,
|
documentation: None,
|
||||||
@@ -806,7 +834,7 @@ mod tests {
|
|||||||
app.focus = Focus::Operations;
|
app.focus = Focus::Operations;
|
||||||
app.operation_cursor = app.operation_rows().len() - 1;
|
app.operation_cursor = app.operation_rows().len() - 1;
|
||||||
let snapshot = rendered(&app, 100, 30);
|
let snapshot = rendered(&app, 100, 30);
|
||||||
assert!(snapshot.contains("(many, operation-19)"));
|
assert!(snapshot.contains("/::many#operation-19"));
|
||||||
|
|
||||||
for index in 0..20 {
|
for index in 0..20 {
|
||||||
app.push_history(HistoryItem {
|
app.push_history(HistoryItem {
|
||||||
@@ -828,6 +856,107 @@ mod tests {
|
|||||||
assert!(snapshot.contains("too small"));
|
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]
|
#[test]
|
||||||
fn control_characters_and_large_bytes_are_bounded() {
|
fn control_characters_and_large_bytes_are_bounded() {
|
||||||
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
|
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
|
||||||
|
|||||||
+144
-22
@@ -21,7 +21,7 @@ use crate::app::{
|
|||||||
Action, App, ConnectionState, HistoryItem, HistoryKind, InFlightKind, InputKey, Modal,
|
Action, App, ConnectionState, HistoryItem, HistoryKind, InFlightKind, InputKey, Modal,
|
||||||
};
|
};
|
||||||
use crate::config::{Config, ConfigError};
|
use crate::config::{Config, ConfigError};
|
||||||
use crate::render::{bounded_value, draw, sanitize};
|
use crate::render::{bounded_value, draw, interface_label, operation_label, sanitize};
|
||||||
use crate::terminal::{TerminalGuard, translate_key};
|
use crate::terminal::{TerminalGuard, translate_key};
|
||||||
|
|
||||||
/// Stable transport failure category.
|
/// Stable transport failure category.
|
||||||
@@ -205,6 +205,12 @@ pub struct Runtime<T: Transport> {
|
|||||||
sender: mpsc::Sender<WorkerEvent>,
|
sender: mpsc::Sender<WorkerEvent>,
|
||||||
receiver: mpsc::Receiver<WorkerEvent>,
|
receiver: mpsc::Receiver<WorkerEvent>,
|
||||||
ignored: BTreeSet<u64>,
|
ignored: BTreeSet<u64>,
|
||||||
|
// Private Client snapshots bind an open editor to the observed lifetime,
|
||||||
|
// including optional refs/validators that must never appear on normal screens.
|
||||||
|
editor_context: Option<(
|
||||||
|
wip_client::ObjectObservation,
|
||||||
|
wip_client::InterfaceObservation,
|
||||||
|
)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Transport> Runtime<T> {
|
impl<T: Transport> Runtime<T> {
|
||||||
@@ -231,6 +237,7 @@ impl<T: Transport> Runtime<T> {
|
|||||||
sender,
|
sender,
|
||||||
receiver,
|
receiver,
|
||||||
ignored: BTreeSet::new(),
|
ignored: BTreeSet::new(),
|
||||||
|
editor_context: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,7 +263,15 @@ impl<T: Transport> Runtime<T> {
|
|||||||
|
|
||||||
/// Applies a key through the reducer and starts any resulting effects.
|
/// Applies a key through the reducer and starts any resulting effects.
|
||||||
pub fn handle_key(&mut self, key: InputKey) -> bool {
|
pub fn handle_key(&mut self, key: InputKey) -> bool {
|
||||||
|
let was_editing = matches!(self.app.modal, Modal::Editor(_) | Modal::Confirm { .. });
|
||||||
|
self.reconcile_authoritative();
|
||||||
|
if was_editing && matches!(self.app.modal, Modal::None) {
|
||||||
|
// Do not reinterpret a stale confirmation keystroke as selection
|
||||||
|
// of another row/scope after the old editor has been retired.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
let actions = self.app.reduce(key);
|
let actions = self.app.reduce(key);
|
||||||
|
self.capture_editor_context();
|
||||||
let mut quit = false;
|
let mut quit = false;
|
||||||
for action in actions {
|
for action in actions {
|
||||||
quit |= self.perform(action);
|
quit |= self.perform(action);
|
||||||
@@ -303,7 +318,10 @@ impl<T: Transport> Runtime<T> {
|
|||||||
Err(error) => self.local_error("subtree refresh", error),
|
Err(error) => self.local_error("subtree refresh", error),
|
||||||
},
|
},
|
||||||
Action::FetchInterface(reference) => {
|
Action::FetchInterface(reference) => {
|
||||||
match self.client.prepare_interface(&self.session, &reference) {
|
match self
|
||||||
|
.client
|
||||||
|
.prepare_interface(&self.session, reference.clone())
|
||||||
|
{
|
||||||
Ok(request) => {
|
Ok(request) => {
|
||||||
self.dispatch(request, InFlightKind::Interface(reference), false)
|
self.dispatch(request, InFlightKind::Interface(reference), false)
|
||||||
}
|
}
|
||||||
@@ -367,7 +385,10 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for reference in references {
|
for reference in references {
|
||||||
match self.client.ensure_interface(&self.session, &reference) {
|
match self
|
||||||
|
.client
|
||||||
|
.ensure_interface(&self.session, reference.clone())
|
||||||
|
{
|
||||||
Ok(Some(request)) => {
|
Ok(Some(request)) => {
|
||||||
self.dispatch(request, InFlightKind::Interface(reference), false);
|
self.dispatch(request, InFlightKind::Interface(reference), false);
|
||||||
}
|
}
|
||||||
@@ -381,9 +402,14 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch(&mut self, request: PreparedRequest, kind: InFlightKind, operation: bool) {
|
fn dispatch(&mut self, request: PreparedRequest, kind: InFlightKind, operation: bool) {
|
||||||
|
let selected = self
|
||||||
|
.app
|
||||||
|
.operation_rows()
|
||||||
|
.get(self.app.operation_cursor)
|
||||||
|
.cloned();
|
||||||
let id = request.id;
|
let id = request.id;
|
||||||
self.app.request_started(id.get(), kind.clone());
|
self.app.request_started(id.get(), kind.clone());
|
||||||
self.reconcile_authoritative();
|
self.reconcile_authoritative_with_selection(selected);
|
||||||
let prepared = match self.transport.prepare(request.request) {
|
let prepared = match self.transport.prepare(request.request) {
|
||||||
Ok(prepared) => prepared,
|
Ok(prepared) => prepared,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -505,6 +531,11 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn finish(&mut self, event: WorkerEvent) {
|
fn finish(&mut self, event: WorkerEvent) {
|
||||||
|
let selected = self
|
||||||
|
.app
|
||||||
|
.operation_rows()
|
||||||
|
.get(self.app.operation_cursor)
|
||||||
|
.cloned();
|
||||||
let kind = self.app.in_flight.get(&event.id.get()).cloned();
|
let kind = self.app.in_flight.get(&event.id.get()).cloned();
|
||||||
if kind.is_none() {
|
if kind.is_none() {
|
||||||
return;
|
return;
|
||||||
@@ -543,7 +574,7 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.reconcile_authoritative();
|
self.reconcile_authoritative_with_selection(selected);
|
||||||
self.reconcile_visible_lookahead();
|
self.reconcile_visible_lookahead();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -574,9 +605,15 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Completion::ProtocolFailure(error) => {
|
Completion::ProtocolFailure(error) => {
|
||||||
|
let subject = match kind {
|
||||||
|
Some(InFlightKind::Interface(reference)) => {
|
||||||
|
format!(" for {}", interface_label(reference))
|
||||||
|
}
|
||||||
|
_ => String::new(),
|
||||||
|
};
|
||||||
self.app.push_history(HistoryItem {
|
self.app.push_history(HistoryItem {
|
||||||
kind: HistoryKind::DomainFailure,
|
kind: HistoryKind::DomainFailure,
|
||||||
title: format!("Host {:?}", error.code),
|
title: format!("Host {:?}{subject}", error.code),
|
||||||
detail: sanitize(&error.message),
|
detail: sanitize(&error.message),
|
||||||
entry_target: None,
|
entry_target: None,
|
||||||
});
|
});
|
||||||
@@ -599,10 +636,12 @@ impl<T: Transport> Runtime<T> {
|
|||||||
|
|
||||||
fn push_call_history(&mut self, record: &wip_client::CallRecord) {
|
fn push_call_history(&mut self, record: &wip_client::CallRecord) {
|
||||||
let key = format!(
|
let key = format!(
|
||||||
"({}, {}) on {}",
|
"{} on {}",
|
||||||
record.context.interface().reference,
|
operation_label(
|
||||||
record.context.operation().name,
|
&record.context.interface().reference,
|
||||||
record.context.object().path
|
&record.context.operation().name
|
||||||
|
),
|
||||||
|
sanitize(&record.context.object().path)
|
||||||
);
|
);
|
||||||
self.app.status = match &record.outcome {
|
self.app.status = match &record.outcome {
|
||||||
CallOutcome::Success(_) => "operation completed".into(),
|
CallOutcome::Success(_) => "operation completed".into(),
|
||||||
@@ -683,8 +722,14 @@ impl<T: Transport> Runtime<T> {
|
|||||||
let title = match kind {
|
let title = match kind {
|
||||||
Some(InFlightKind::Object(path)) => format!("observe {path}"),
|
Some(InFlightKind::Object(path)) => format!("observe {path}"),
|
||||||
Some(InFlightKind::Tree(path)) => format!("tree {path}"),
|
Some(InFlightKind::Tree(path)) => format!("tree {path}"),
|
||||||
Some(InFlightKind::Interface(reference)) => format!("interface {reference}"),
|
Some(InFlightKind::Interface(reference)) => {
|
||||||
Some(InFlightKind::Operation { operation, .. }) => operation.clone(),
|
format!("interface {}", interface_label(reference))
|
||||||
|
}
|
||||||
|
Some(InFlightKind::Operation {
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
..
|
||||||
|
}) => operation_label(interface, operation),
|
||||||
None => "request".into(),
|
None => "request".into(),
|
||||||
};
|
};
|
||||||
self.app.push_history(HistoryItem {
|
self.app.push_history(HistoryItem {
|
||||||
@@ -741,16 +786,87 @@ impl<T: Transport> Runtime<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn reconcile_authoritative(&mut self) {
|
fn reconcile_authoritative(&mut self) {
|
||||||
self.sync_all_objects();
|
let selected = self
|
||||||
let evicted_interfaces = self
|
|
||||||
.app
|
.app
|
||||||
.interfaces
|
.operation_rows()
|
||||||
.keys()
|
.get(self.app.operation_cursor)
|
||||||
.filter(|reference| self.client.interface(&self.session, reference).is_none())
|
.cloned();
|
||||||
.cloned()
|
self.reconcile_authoritative_with_selection(selected);
|
||||||
.collect::<Vec<_>>();
|
}
|
||||||
for reference in evicted_interfaces {
|
|
||||||
self.app.interfaces.remove(&reference);
|
fn reconcile_authoritative_with_selection(
|
||||||
|
&mut self,
|
||||||
|
selected: Option<crate::app::OperationRow>,
|
||||||
|
) {
|
||||||
|
self.sync_all_objects();
|
||||||
|
let references = self.app.interfaces.keys().cloned().collect::<Vec<_>>();
|
||||||
|
for reference in references {
|
||||||
|
match self.client.interface(&self.session, &reference).cloned() {
|
||||||
|
Some(observation) => self.app.apply_interface(observation),
|
||||||
|
None => {
|
||||||
|
self.app.interfaces.remove(&reference);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let paths = self.app.entries.keys().cloned().collect::<Vec<_>>();
|
||||||
|
for path in paths {
|
||||||
|
if let Some(tree) = self.client.tree(&self.session, &path).cloned() {
|
||||||
|
self.app.apply_tree(tree);
|
||||||
|
} else if let Some(entry) = self.app.entries.get_mut(&path)
|
||||||
|
&& !matches!(entry.tree_state, crate::app::ViewState::Unloaded)
|
||||||
|
{
|
||||||
|
entry.tree_state = crate::app::ViewState::Stale;
|
||||||
|
entry.children.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.app.restore_operation_selection(selected);
|
||||||
|
self.reconcile_editor_context();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_editor_context(&mut self) {
|
||||||
|
let editor = match &self.app.modal {
|
||||||
|
Modal::Editor(editor) | Modal::Confirm { editor, .. } => editor,
|
||||||
|
_ => {
|
||||||
|
self.editor_context = None;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if self.editor_context.is_none() {
|
||||||
|
self.editor_context = self.client.object(&self.session, &editor.path).zip(
|
||||||
|
self.client
|
||||||
|
.interface(&self.session, &editor.interface)
|
||||||
|
.cloned(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.reconcile_editor_context();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reconcile_editor_context(&mut self) {
|
||||||
|
let editor = match &self.app.modal {
|
||||||
|
Modal::Editor(editor) | Modal::Confirm { editor, .. } => editor,
|
||||||
|
_ => {
|
||||||
|
self.editor_context = None;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let valid = self
|
||||||
|
.editor_context
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(object, interface)| {
|
||||||
|
object.path == editor.path
|
||||||
|
&& self.app.selected_path == editor.path
|
||||||
|
&& interface.reference == editor.interface
|
||||||
|
&& interface.descriptor.as_ref() == Some(&editor.descriptor)
|
||||||
|
&& object.state == wip_client::ObservationState::Fresh
|
||||||
|
&& interface.state == wip_client::ObservationState::Fresh
|
||||||
|
&& self.client.object(&self.session, &editor.path).as_ref() == Some(object)
|
||||||
|
&& self.client.interface(&self.session, &editor.interface) == Some(interface)
|
||||||
|
});
|
||||||
|
if !valid {
|
||||||
|
self.app.modal = Modal::None;
|
||||||
|
self.editor_context = None;
|
||||||
|
self.app.status =
|
||||||
|
"editor retired: target or interface changed; reobserve and select again".into();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -760,7 +876,9 @@ impl<T: Transport> Runtime<T> {
|
|||||||
.entries
|
.entries
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, entry)| {
|
.filter(|(_, entry)| {
|
||||||
entry.object.is_some() || self.client.object(&self.session, &entry.path).is_some()
|
entry.object.is_some()
|
||||||
|
|| entry.state != crate::app::ViewState::Unloaded
|
||||||
|
|| self.client.object(&self.session, &entry.path).is_some()
|
||||||
})
|
})
|
||||||
.map(|(path, _)| path.clone())
|
.map(|(path, _)| path.clone())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -919,6 +1037,10 @@ impl Display for RuntimeError {
|
|||||||
|
|
||||||
impl Error for RuntimeError {}
|
impl Error for RuntimeError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "runtime_scoped_tests.rs"]
|
||||||
|
mod scoped_tests;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|||||||
@@ -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
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
use wip_protocol::{InterfaceReference, InterfaceTarget};
|
||||||
|
use wip_tui::reference::{format_interface_reference, format_qualified_operation};
|
||||||
|
|
||||||
|
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||||
|
InterfaceReference {
|
||||||
|
scope: scope.into(),
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn specification_reference_examples() {
|
||||||
|
for (scope, name, operation, expected) in [
|
||||||
|
("/github", "issue.read", "read", "/github::issue.read#read"),
|
||||||
|
("/", "issue.read", "read", "/::issue.read#read"),
|
||||||
|
(
|
||||||
|
"/github::archive",
|
||||||
|
"issue.read",
|
||||||
|
"read",
|
||||||
|
"\"/github::archive\"::issue.read#read",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/github",
|
||||||
|
"issue#read",
|
||||||
|
"read",
|
||||||
|
"/github::\"issue#read\"#read",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/github",
|
||||||
|
"issue.read",
|
||||||
|
"read#raw",
|
||||||
|
"/github::issue.read#\"read#raw\"",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/開発",
|
||||||
|
"課題.read",
|
||||||
|
"read",
|
||||||
|
"\"/開発\"::\"課題.read\"#read",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let input = reference(scope, name);
|
||||||
|
input.validate().unwrap();
|
||||||
|
let before = input.clone();
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, operation).unwrap(),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
assert_eq!(input, before);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn root_self_and_same_name_different_scope_stay_distinct() {
|
||||||
|
let root = reference("/", "read");
|
||||||
|
let parent = reference("/a", "read");
|
||||||
|
let self_scope = reference("/a/b", "read");
|
||||||
|
let labels: Vec<_> = [&root, &parent, &self_scope]
|
||||||
|
.into_iter()
|
||||||
|
.map(|input| {
|
||||||
|
input.validate_for_path("/a/b").unwrap();
|
||||||
|
format_interface_reference(input).unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(labels, ["/::read", "/a::read", "/a/b::read"]);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&self_scope, "read").unwrap(),
|
||||||
|
"/a/b::read#read"
|
||||||
|
);
|
||||||
|
assert_ne!(root, self_scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn components_not_declaration_identifiers_or_signatures() {
|
||||||
|
// Reference components follow their own ASCII rules, not identifier/keyword
|
||||||
|
// backtick quoting or the outer JSON string quoting used by full signatures.
|
||||||
|
let input = reference("/a-b/c_d.1", "1-name.entry");
|
||||||
|
assert_eq!(
|
||||||
|
format_interface_reference(&input).unwrap(),
|
||||||
|
"/a-b/c_d.1::1-name.entry"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, "operation").unwrap(),
|
||||||
|
"/a-b/c_d.1::1-name.entry#operation"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, "a/b").unwrap(),
|
||||||
|
"/a-b/c_d.1::1-name.entry#\"a/b\""
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, "").unwrap(),
|
||||||
|
"/a-b/c_d.1::1-name.entry#\"\""
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_interface_reference(&reference("/", "name`tick")).unwrap(),
|
||||||
|
"/::\"name`tick\""
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delimiters_quote_backslash_whitespace_and_newline_are_component_data() {
|
||||||
|
let input = reference("/a::b#c\"\\\n", "x::y#z\"\\\n");
|
||||||
|
let before = input.clone();
|
||||||
|
assert_eq!(
|
||||||
|
format_interface_reference(&input).unwrap(),
|
||||||
|
"\"/a::b#c\\\"\\\\\\n\"::\"x::y#z\\\"\\\\\\n\""
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, "read::raw# \"\\\n\t").unwrap(),
|
||||||
|
"\"/a::b#c\\\"\\\\\\n\"::\"x::y#z\\\"\\\\\\n\"#\"read::raw# \\\"\\\\\\n\\t\""
|
||||||
|
);
|
||||||
|
assert_eq!(input, before);
|
||||||
|
assert_eq!(
|
||||||
|
format_interface_reference(&reference("/space here", " name ")).unwrap(),
|
||||||
|
"\"/space here\"::\" name \""
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_required_safety_escape_in_each_component() {
|
||||||
|
let controls = (0..=0x1f)
|
||||||
|
.chain(0x7f..=0x9f)
|
||||||
|
.chain([0x061c, 0x200e, 0x200f, 0x2028, 0x2029])
|
||||||
|
.chain(0x202a..=0x202e)
|
||||||
|
.chain(0x2066..=0x2069);
|
||||||
|
for code in controls {
|
||||||
|
let ch = char::from_u32(code).unwrap();
|
||||||
|
let escape = match code {
|
||||||
|
8 => "\\b".into(),
|
||||||
|
9 => "\\t".into(),
|
||||||
|
10 => "\\n".into(),
|
||||||
|
12 => "\\f".into(),
|
||||||
|
13 => "\\r".into(),
|
||||||
|
_ => format!("\\u{code:04x}"),
|
||||||
|
};
|
||||||
|
let input = reference(&format!("/a{ch}z"), &format!("n{ch}z"));
|
||||||
|
let operation = format!("o{ch}z");
|
||||||
|
let before = (input.clone(), operation.clone());
|
||||||
|
let label = format_qualified_operation(&input, &operation).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
label,
|
||||||
|
format!("\"/a{escape}z\"::\"n{escape}z\"#\"o{escape}z\""),
|
||||||
|
"U+{code:04X}"
|
||||||
|
);
|
||||||
|
assert!(!label.contains(ch), "raw U+{code:04X} leaked");
|
||||||
|
assert_eq!((input, operation), before);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unicode_remains_exact_no_normalization_case_folding_or_url_encoding() {
|
||||||
|
for name in ["é", "e\u{301}", "課題", "λ😀", "%23"] {
|
||||||
|
let input = reference(&format!("/{name}"), name);
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&input, name).unwrap(),
|
||||||
|
format!("\"/{name}\"::\"{name}\"#\"{name}\"")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_ne!(
|
||||||
|
format_interface_reference(&reference("/", "é")).unwrap(),
|
||||||
|
format_interface_reference(&reference("/", "e\u{301}")).unwrap()
|
||||||
|
);
|
||||||
|
assert_ne!(
|
||||||
|
format_interface_reference(&reference("/", "Read")).unwrap(),
|
||||||
|
format_interface_reference(&reference("/", "read")).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_shape_instead_of_inferring_scope() {
|
||||||
|
for scope in [
|
||||||
|
"",
|
||||||
|
"github",
|
||||||
|
"../github",
|
||||||
|
"/a/../b",
|
||||||
|
"/a/./b",
|
||||||
|
"/a//b",
|
||||||
|
"/a/",
|
||||||
|
] {
|
||||||
|
let input = reference(scope, "read");
|
||||||
|
assert_eq!(
|
||||||
|
format_interface_reference(&input).unwrap_err(),
|
||||||
|
input.validate().unwrap_err()
|
||||||
|
);
|
||||||
|
assert!(format_qualified_operation(&input, "read").is_err());
|
||||||
|
}
|
||||||
|
assert!(format_interface_reference(&reference("/", "")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn runtime_metadata_and_call_identity_stay_separate_from_display() {
|
||||||
|
let mut target = InterfaceTarget {
|
||||||
|
reference: reference("/a", "read#raw"),
|
||||||
|
scope_ref: Some("secret-scope-ref".into()),
|
||||||
|
validator: Some(vec![27, 255]),
|
||||||
|
};
|
||||||
|
let before = target.clone();
|
||||||
|
let label = format_qualified_operation(&target.reference, "run").unwrap();
|
||||||
|
assert_eq!(label, "/a::\"read#raw\"#run");
|
||||||
|
assert_eq!(target, before);
|
||||||
|
target.scope_ref = None;
|
||||||
|
target.validator = None;
|
||||||
|
assert_eq!(
|
||||||
|
format_qualified_operation(&target.reference, "run").unwrap(),
|
||||||
|
label
|
||||||
|
);
|
||||||
|
// Selection/call keys are still exact protocol pairs; labels are disposable.
|
||||||
|
let mut selected = std::collections::BTreeMap::new();
|
||||||
|
selected.insert(target.reference.clone(), "run");
|
||||||
|
assert_eq!(selected.get(&before.reference), Some(&"run"));
|
||||||
|
assert!(!selected.contains_key(&reference("/", "read#raw")));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user