Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf5fa54f44 | ||
|
|
c6528c2887 | ||
|
|
b196047b57 | ||
|
|
ea49cb0586 | ||
|
|
da559de912 | ||
|
|
193ca89d93 | ||
|
|
dc9a7f0dbf | ||
|
|
3c4dbf3ad0 | ||
|
|
df006ee706 |
@@ -0,0 +1,16 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to the published WIP Rust crates are documented here.
|
||||||
|
|
||||||
|
## 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
+2
-2
@@ -1341,9 +1341,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.
|
||||||
@@ -13,43 +13,65 @@ 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/batching
|
├── 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, envelopes, and batching
|
│ ├── 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 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
||||||
| `wip-http` | Standard WIP over HTTP v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, URL scheme or TLS policy, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
| `wip-http` | Standard WIP over HTTP v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, and error/status classification. | HTTP I/O, URL scheme or TLS policy, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
||||||
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
||||||
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTP I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
|
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTP I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
|
||||||
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
||||||
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
||||||
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
|
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
|
||||||
| `wip-fs-server` | Linux directory-handle-confined request-time projection, complete depth-bounded observations and bounded file operations, standard `wip-http` dispatch/batch handling, and a loopback HTTP binary. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, TLS termination, or filesystem-wide preregistration. |
|
| `wip-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`
|
||||||
|
|||||||
@@ -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,16 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -16,7 +16,7 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setup() -> (Client, wip_client::SessionId) {
|
fn setup() -> (Client, wip_client::SessionId) {
|
||||||
@@ -145,16 +145,37 @@ fn valid_error_envelope_is_authoritative_and_status_mismatch_is_diagnostic() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn non_success_without_valid_envelope_remains_transport_failure() {
|
fn resource_envelope_on_413_uses_code_and_records_canonical_422_mismatch() {
|
||||||
let (mut client, session) = setup();
|
let (mut client, session) = setup();
|
||||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
let error = client
|
let error = ProtocolError {
|
||||||
.complete(
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
request.id,
|
message: "logical observation limit exceeded".into(),
|
||||||
response(StatusCode::BAD_GATEWAY, b"gateway html"),
|
};
|
||||||
)
|
let mut encoded =
|
||||||
.unwrap_err();
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
assert_eq!(error.kind, ClientErrorKind::Transport);
|
*encoded.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
client.complete(request.id, encoded).unwrap(),
|
||||||
|
Completion::ProtocolFailure(error)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||||
|
DiagnosticKind::HttpStatusMismatch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_success_without_valid_envelope_remains_transport_failure() {
|
||||||
|
for status in [StatusCode::BAD_GATEWAY, StatusCode::PAYLOAD_TOO_LARGE] {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
let error = client
|
||||||
|
.complete(request.id, response(status, b"infrastructure failure"))
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(error.kind, ClientErrorKind::Transport);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -250,3 +271,80 @@ fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object()
|
|||||||
);
|
);
|
||||||
assert_eq!(client.in_flight_len(), 0);
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
observation.id,
|
||||||
|
encode_observe_response(
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
&ObjectObservation {
|
||||||
|
object: object(),
|
||||||
|
children: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let interface = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
interface.id,
|
||||||
|
encode_fetch_interface_response(
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
},
|
||||||
|
&FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let call = client
|
||||||
|
.prepare_call(
|
||||||
|
&session,
|
||||||
|
"/item",
|
||||||
|
"math",
|
||||||
|
"calculate",
|
||||||
|
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.mark_dispatched(call.id).unwrap();
|
||||||
|
|
||||||
|
let completion = client
|
||||||
|
.complete(
|
||||||
|
call.id,
|
||||||
|
Response::builder()
|
||||||
|
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
completion,
|
||||||
|
Completion::Call(record)
|
||||||
|
if matches!(
|
||||||
|
&record.outcome,
|
||||||
|
CallOutcome::Unknown {
|
||||||
|
reason: OutcomeUnknownReason::ResponseDecode,
|
||||||
|
failure: Some(failure),
|
||||||
|
} if failure.kind == ClientErrorKind::Transport
|
||||||
|
)
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/item").unwrap().state,
|
||||||
|
ObservationState::Stale
|
||||||
|
);
|
||||||
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
fn wire_limits() -> Limits {
|
fn wire_limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -399,6 +399,67 @@ fn ensure_interface_waits_for_request_and_cache_capacity_without_evicting() {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn independent_retrievals_run_concurrently_and_complete_out_of_order() {
|
||||||
|
let mut client = client(8, 8, 8, 8);
|
||||||
|
let session = client
|
||||||
|
.open_session("https://example.test/wip", SecurityContext::new("subject"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let first = client.refresh_observed(&session, "/one", 0).unwrap();
|
||||||
|
let second = client.refresh_observed(&session, "/two", 0).unwrap();
|
||||||
|
let interface = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(first.request.uri().path(), "/wip/v1/observe");
|
||||||
|
assert_eq!(second.request.uri().path(), "/wip/v1/observe");
|
||||||
|
assert_eq!(interface.request.uri().path(), "/wip/v1/fetch_interface");
|
||||||
|
assert_eq!(client.in_flight_len(), 3);
|
||||||
|
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
second.id,
|
||||||
|
observation_response("/two", &object("two", None, b"two")),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
interface.id,
|
||||||
|
encode_fetch_interface_response(
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
},
|
||||||
|
&FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor(TypeExpr::Integer),
|
||||||
|
validator: Some(b"math-v1".to_vec()),
|
||||||
|
},
|
||||||
|
wire_limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
first.id,
|
||||||
|
observation_response("/one", &object("one", None, b"one")),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/one").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/two").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.interface(&session, "math").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn newer_refresh_rejects_out_of_order_response_for_the_same_subject() {
|
fn newer_refresh_rejects_out_of_order_response_for_the_same_subject() {
|
||||||
let mut client = client(8, 8, 8, 8);
|
let mut client = client(8, 8, 8, 8);
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -4,7 +4,120 @@
|
|||||||
Worldspace `/` at request time. It does not register the filesystem contents or
|
Worldspace `/` at request time. It does not register the filesystem contents or
|
||||||
keep one object instance per entry. It uses `wip-host` for publication and typed
|
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, batching, and HTTP status mapping.
|
envelopes, and HTTP status mapping.
|
||||||
|
|
||||||
|
## Library assembly and migration
|
||||||
|
|
||||||
|
The existing `ServerConfig`, `WipFsServer::new`, `handle_http`, CLI flags and wire
|
||||||
|
representation remain compatible. The formerly private projection has become a
|
||||||
|
public, generic library engine. No package version or publication policy changes
|
||||||
|
are required.
|
||||||
|
|
||||||
|
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. Register generated `#[wip_interface::interface]` definitions using the existing
|
||||||
|
`wip_host::InterfaceRegistry`. `DefaultInterfaces::register` optionally supplies
|
||||||
|
reusable built-in tokens; using those tokens does not force their publication.
|
||||||
|
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 still receive only the exact scoped target `Entry`.
|
||||||
|
|
||||||
|
`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
|
||||||
|
|
||||||
@@ -118,14 +231,11 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
|||||||
}'
|
}'
|
||||||
```
|
```
|
||||||
|
|
||||||
`observe` and `fetch_interface` can also be combined through the standard
|
|
||||||
`POST /wip/v1/batch` route. `call_operation` is never batchable.
|
|
||||||
|
|
||||||
## Resource and failure behavior
|
## Resource and failure behavior
|
||||||
|
|
||||||
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
||||||
nesting, batch items, file read/write bytes, tree depth/node count, pinned handles,
|
nesting, file read/write bytes, tree depth/node count, pinned handles, and active
|
||||||
and active connections/requests. One absolute request deadline covers header and
|
connections/requests. One absolute request deadline covers header and
|
||||||
body intake, dispatch, cooperative filesystem work, and response transmission;
|
body intake, dispatch, cooperative filesystem work, and response transmission;
|
||||||
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
||||||
accept connections directly, so the listener never moves more than the configured
|
accept connections directly, so the listener never moves more than the configured
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
//! 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, 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 default descriptors without publishing any objects.
|
||||||
|
pub fn register(registry: &mut InterfaceRegistry) -> Result<Self, RegistrationError> {
|
||||||
|
Ok(Self {
|
||||||
|
read: registry.register(FileReadDefinition, None)?,
|
||||||
|
symlink: registry.register(SymlinkInspectDefinition, None)?,
|
||||||
|
write: registry.register(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 interfaces = DefaultInterfaces::register(&mut registry).map_err(std::io::Error::other)?;
|
||||||
|
Ok(Projection::new(
|
||||||
|
backend,
|
||||||
|
registry,
|
||||||
|
DefaultComposition::new(interfaces),
|
||||||
|
DefaultPolicy,
|
||||||
|
limits,
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
//! Transport-independent projection, publication, and principal view boundaries.
|
||||||
|
|
||||||
|
use crate::ResourceLimits;
|
||||||
|
use wip_host::{
|
||||||
|
EffectGuarantee, ExecutionContext, HostError, InterfaceRef, InterfaceRegistry, ObjectProvider,
|
||||||
|
OperationAttempt, ProviderResult, PublishedObject, 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.
|
||||||
|
///
|
||||||
|
/// `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;
|
||||||
|
/// Build a request-scoped publication using this exact capability/context.
|
||||||
|
///
|
||||||
|
/// Publication and policy hooks must be side-effect-free with respect to the
|
||||||
|
/// backend. 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,
|
||||||
|
entry: B::Entry,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
) -> Result<PublishedObject<C::Object>, HostError> {
|
||||||
|
let publication = self
|
||||||
|
.projection
|
||||||
|
.composition
|
||||||
|
.publish(entry.clone(), context)?;
|
||||||
|
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| {
|
||||||
|
self.projection
|
||||||
|
.policy
|
||||||
|
.interface_visible(self.principal, reference)
|
||||||
|
});
|
||||||
|
publication
|
||||||
|
.project(&selected, |reference, operation| {
|
||||||
|
self.projection
|
||||||
|
.policy
|
||||||
|
.operation_visible(self.principal, reference, operation)
|
||||||
|
})
|
||||||
|
.map_err(|_| internal())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 = self
|
||||||
|
.projection
|
||||||
|
.registry
|
||||||
|
.fetch_interface(&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 (_ancestors, entry) = entry.into_parts();
|
||||||
|
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, 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,
|
||||||
|
entry: 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 = self
|
||||||
|
.publication(entry.clone(), context)
|
||||||
|
.map_err(read_error)?
|
||||||
|
.protocol_object();
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
for child in entries {
|
||||||
|
if self
|
||||||
|
.projection
|
||||||
|
.policy
|
||||||
|
.object_visible(self.principal, &child)
|
||||||
|
{
|
||||||
|
children.push(self.observe_entry(context, 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) => {
|
||||||
|
let (_ancestors, entry) = resolved.into_parts();
|
||||||
|
match self.publication(entry, context) {
|
||||||
|
Ok(publication) => ProviderResult::Found(operation(&publication)),
|
||||||
|
Err(error) => ProviderResult::Failure(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
let (_ancestors, entry) = resolved.into_parts();
|
||||||
|
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(entry, 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,15 +4,49 @@
|
|||||||
//!
|
//!
|
||||||
//! - [`wip_protocol`] owns logical requests and responses;
|
//! - [`wip_protocol`] owns logical requests and responses;
|
||||||
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
||||||
//! - [`wip_http`] owns routes, JSON, envelopes, batching, 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.
|
||||||
|
//!
|
||||||
|
//! 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 +55,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.
|
||||||
@@ -36,7 +80,7 @@ pub enum AccessMode {
|
|||||||
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct ResourceLimits {
|
pub struct ResourceLimits {
|
||||||
/// Standard JSON, body-size, nesting, and batch limits.
|
/// Standard JSON, body-size, and nesting limits.
|
||||||
pub wire: wip_http::Limits,
|
pub wire: wip_http::Limits,
|
||||||
/// Maximum bytes returned by one file read.
|
/// Maximum bytes returned by one file read.
|
||||||
pub max_file_read_bytes: usize,
|
pub max_file_read_bytes: usize,
|
||||||
@@ -59,7 +103,7 @@ pub struct ResourceLimits {
|
|||||||
impl Default for ResourceLimits {
|
impl Default for ResourceLimits {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
wire: wip_http::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
wire: wip_http::Limits::new(256 * 1024, 2 * 1024 * 1024, 64)
|
||||||
.expect("default wire limits are nonzero"),
|
.expect("default wire limits are nonzero"),
|
||||||
max_file_read_bytes: 1024 * 1024,
|
max_file_read_bytes: 1024 * 1024,
|
||||||
max_file_write_bytes: 1024 * 1024,
|
max_file_write_bytes: 1024 * 1024,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -6,26 +6,19 @@ use std::thread;
|
|||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
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;
|
||||||
BatchRequestKind, BatchResponse, BatchResponseItem, BatchSuccess, CodecError, EncodeHttpError,
|
|
||||||
Endpoint, RequestMetadataError, ResourceLimitKind, Route, decode_batch_request,
|
|
||||||
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
|
|
||||||
encode_batch_error_response, encode_batch_resource_limit_error_response, encode_batch_response,
|
|
||||||
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
|
|
||||||
encode_protocol_error_response, encode_resource_limit_error_response, validate_http_request,
|
|
||||||
};
|
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
|
||||||
|
|
||||||
use crate::projection::Projection;
|
use crate::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 {
|
||||||
@@ -33,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,
|
||||||
@@ -68,21 +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().path()) else {
|
|
||||||
return empty_response(StatusCode::NOT_FOUND);
|
|
||||||
};
|
|
||||||
if let Err(error) = validate_http_request(&self.endpoint, route, &request) {
|
|
||||||
return self.metadata_error(route, error);
|
|
||||||
}
|
|
||||||
let context = ExecutionContext::new()
|
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));
|
||||||
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),
|
|
||||||
Route::Batch => self.batch(request.body(), &context),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Binds the built-in bounded loopback HTTP listener.
|
/// Binds the built-in bounded loopback HTTP listener.
|
||||||
@@ -105,237 +89,6 @@ impl WipFsServer {
|
|||||||
listener: Arc::new(listener),
|
listener: Arc::new(listener),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn route(&self, path: &str) -> Option<Route> {
|
|
||||||
[
|
|
||||||
Route::Observe,
|
|
||||||
Route::FetchInterface,
|
|
||||||
Route::CallOperation,
|
|
||||||
Route::Batch,
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.find(|route| self.endpoint.route(*route).path() == path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
|
||||||
let request = match decode_observe_request(body, self.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::Observe, error),
|
|
||||||
};
|
|
||||||
match self.projection.observe(context, &request) {
|
|
||||||
Ok(tree) => encode_observe_response(&request, &tree, self.config.limits.wire)
|
|
||||||
.unwrap_or_else(|error| {
|
|
||||||
self.read_encode_error(ProtocolInteraction::Observe, error)
|
|
||||||
}),
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error, None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fetch_interface(&self, body: &[u8]) -> Response<Vec<u8>> {
|
|
||||||
let request = match decode_fetch_interface_request(body, self.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::FetchInterface, error),
|
|
||||||
};
|
|
||||||
match self.projection.fetch_interface(&request) {
|
|
||||||
Ok(interface) => {
|
|
||||||
encode_fetch_interface_response(&request, &interface, self.config.limits.wire)
|
|
||||||
.unwrap_or_else(|error| {
|
|
||||||
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error, None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call_operation(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
|
||||||
let metadata = match decode_call_operation_metadata(body, self.config.limits.wire) {
|
|
||||||
Ok(metadata) => metadata,
|
|
||||||
Err(error) => return self.codec_error(ProtocolInteraction::CallOperation, error),
|
|
||||||
};
|
|
||||||
let may_commit = metadata.operation == "replace";
|
|
||||||
let decoded = std::sync::Mutex::new(None);
|
|
||||||
let execution = self.projection.call_operation_with_context_and_decoder(
|
|
||||||
context,
|
|
||||||
metadata.target.clone(),
|
|
||||||
metadata.interface.clone(),
|
|
||||||
metadata.operation.clone(),
|
|
||||||
|descriptor| {
|
|
||||||
let request = metadata.decode_request(body, descriptor, self.config.limits.wire)?;
|
|
||||||
let arguments = request.arguments.clone();
|
|
||||||
*decoded.lock().unwrap_or_else(|error| error.into_inner()) =
|
|
||||||
Some((request, descriptor.clone()));
|
|
||||||
Ok::<_, CodecError>(arguments)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
match execution.map_err(|error| error.protocol_error()) {
|
|
||||||
Ok(result) => {
|
|
||||||
let Some((request, descriptor)) = decoded
|
|
||||||
.into_inner()
|
|
||||||
.unwrap_or_else(|error| error.into_inner())
|
|
||||||
else {
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: if may_commit {
|
|
||||||
ProtocolErrorCode::OperationOutcomeUnknown
|
|
||||||
} else {
|
|
||||||
ProtocolErrorCode::Internal
|
|
||||||
},
|
|
||||||
message: "operation completed without response metadata".into(),
|
|
||||||
};
|
|
||||||
return self.protocol_error(ProtocolInteraction::CallOperation, &error, None);
|
|
||||||
};
|
|
||||||
encode_call_operation_response(
|
|
||||||
&request,
|
|
||||||
&descriptor,
|
|
||||||
&result,
|
|
||||||
self.config.limits.wire,
|
|
||||||
)
|
|
||||||
.unwrap_or_else(|encode_error| {
|
|
||||||
if !may_commit {
|
|
||||||
return self
|
|
||||||
.read_encode_error(ProtocolInteraction::CallOperation, encode_error);
|
|
||||||
}
|
|
||||||
// Replacement may already be committed, so a response
|
|
||||||
// encoding failure cannot carry a non-commit guarantee.
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
|
||||||
message: "operation completed but its response could not be encoded".into(),
|
|
||||||
};
|
|
||||||
self.protocol_error(ProtocolInteraction::CallOperation, &error, None)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error, None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
|
||||||
let request = match decode_batch_request(body, self.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.batch_codec_error(error),
|
|
||||||
};
|
|
||||||
let responses = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| {
|
|
||||||
let outcome = match &item.request {
|
|
||||||
BatchRequestKind::Observe(request) => self
|
|
||||||
.projection
|
|
||||||
.observe(context, request)
|
|
||||||
.map(BatchSuccess::Observe),
|
|
||||||
BatchRequestKind::FetchInterface(request) => self
|
|
||||||
.projection
|
|
||||||
.fetch_interface(request)
|
|
||||||
.map(BatchSuccess::FetchInterface),
|
|
||||||
BatchRequestKind::Invalid { error, .. } => Err(error.clone()),
|
|
||||||
};
|
|
||||||
BatchResponseItem {
|
|
||||||
id: item.id.clone(),
|
|
||||||
outcome,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let response = BatchResponse { responses };
|
|
||||||
encode_batch_response(&request, &response, self.config.limits.wire).unwrap_or_else(
|
|
||||||
|error| match error {
|
|
||||||
EncodeHttpError::Codec(codec) => self.batch_codec_error(codec),
|
|
||||||
EncodeHttpError::Http(_) => self.batch_top_error(&internal_error(), None),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn metadata_error(&self, route: Route, error: RequestMetadataError) -> Response<Vec<u8>> {
|
|
||||||
match error {
|
|
||||||
RequestMetadataError::InvalidRequest(_) => self.protocol_error(
|
|
||||||
interaction(route),
|
|
||||||
&ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "invalid HTTP request metadata".into(),
|
|
||||||
},
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
RequestMetadataError::UnsupportedMediaType => {
|
|
||||||
empty_response(StatusCode::UNSUPPORTED_MEDIA_TYPE)
|
|
||||||
}
|
|
||||||
RequestMetadataError::NotAcceptable => empty_response(StatusCode::NOT_ACCEPTABLE),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn codec_error(
|
|
||||||
&self,
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: CodecError,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
if let Some(kind) = error.resource_limit_kind() {
|
|
||||||
self.protocol_error(interaction, &resource_error(), Some(kind))
|
|
||||||
} else {
|
|
||||||
self.protocol_error(
|
|
||||||
interaction,
|
|
||||||
&ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "malformed WIP request".into(),
|
|
||||||
},
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch_codec_error(&self, error: CodecError) -> Response<Vec<u8>> {
|
|
||||||
if let Some(kind) = error.resource_limit_kind() {
|
|
||||||
self.batch_top_error(&resource_error(), Some(kind))
|
|
||||||
} else {
|
|
||||||
self.batch_top_error(
|
|
||||||
&ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "malformed WIP batch request".into(),
|
|
||||||
},
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_encode_error(
|
|
||||||
&self,
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: EncodeHttpError,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
match error {
|
|
||||||
EncodeHttpError::Codec(codec) if codec.resource_limit_kind().is_some() => {
|
|
||||||
self.protocol_error(interaction, &resource_error(), codec.resource_limit_kind())
|
|
||||||
}
|
|
||||||
_ => self.protocol_error(interaction, &internal_error(), None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn protocol_error(
|
|
||||||
&self,
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: &ProtocolError,
|
|
||||||
resource_kind: Option<ResourceLimitKind>,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
let encoded = match resource_kind {
|
|
||||||
Some(kind) => encode_resource_limit_error_response(
|
|
||||||
interaction,
|
|
||||||
error,
|
|
||||||
kind,
|
|
||||||
self.config.limits.wire,
|
|
||||||
),
|
|
||||||
None => encode_protocol_error_response(interaction, error, self.config.limits.wire),
|
|
||||||
};
|
|
||||||
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch_top_error(
|
|
||||||
&self,
|
|
||||||
error: &ProtocolError,
|
|
||||||
resource_kind: Option<ResourceLimitKind>,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
let encoded = match resource_kind {
|
|
||||||
Some(kind) => {
|
|
||||||
encode_batch_resource_limit_error_response(error, kind, self.config.limits.wire)
|
|
||||||
}
|
|
||||||
None => encode_batch_error_response(error, self.config.limits.wire),
|
|
||||||
};
|
|
||||||
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bound real HTTP listener for a [`WipFsServer`].
|
/// Bound real HTTP listener for a [`WipFsServer`].
|
||||||
@@ -404,7 +157,7 @@ struct ParsedRequestHead {
|
|||||||
enum IntakeError {
|
enum IntakeError {
|
||||||
Timeout,
|
Timeout,
|
||||||
HeaderTooLarge,
|
HeaderTooLarge,
|
||||||
PayloadTooLarge { target: String },
|
PayloadTooLarge,
|
||||||
BadRequest,
|
BadRequest,
|
||||||
Socket,
|
Socket,
|
||||||
}
|
}
|
||||||
@@ -425,9 +178,7 @@ fn serve_connection(service: &WipFsServer, mut stream: TcpStream) {
|
|||||||
Err(IntakeError::HeaderTooLarge) => {
|
Err(IntakeError::HeaderTooLarge) => {
|
||||||
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
||||||
}
|
}
|
||||||
Err(IntakeError::PayloadTooLarge { target }) => {
|
Err(IntakeError::PayloadTooLarge) => Some(empty_response(StatusCode::PAYLOAD_TOO_LARGE)),
|
||||||
Some(payload_too_large_response(service, &target))
|
|
||||||
}
|
|
||||||
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
||||||
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
||||||
};
|
};
|
||||||
@@ -466,9 +217,7 @@ fn read_http_request(
|
|||||||
|
|
||||||
let parsed = parse_request_head(&received[..header_end])?;
|
let parsed = parse_request_head(&received[..header_end])?;
|
||||||
if parsed.content_length > maximum_body {
|
if parsed.content_length > maximum_body {
|
||||||
return Err(IntakeError::PayloadTooLarge {
|
return Err(IntakeError::PayloadTooLarge);
|
||||||
target: parsed.target,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
let mut body = Vec::with_capacity(parsed.content_length);
|
let mut body = Vec::with_capacity(parsed.content_length);
|
||||||
let buffered = &received[header_end..];
|
let buffered = &received[header_end..];
|
||||||
@@ -567,27 +316,6 @@ fn read_with_deadline(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn payload_too_large_response(service: &WipFsServer, target: &str) -> Response<Vec<u8>> {
|
|
||||||
let route = service.route(target.split('?').next().unwrap_or_default());
|
|
||||||
route.map_or_else(
|
|
||||||
|| empty_response(StatusCode::PAYLOAD_TOO_LARGE),
|
|
||||||
|route| {
|
|
||||||
if route == Route::Batch {
|
|
||||||
service.batch_top_error(
|
|
||||||
&resource_error(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
service.protocol_error(
|
|
||||||
interaction(route),
|
|
||||||
&resource_error(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_http_response(
|
fn write_http_response(
|
||||||
stream: &mut TcpStream,
|
stream: &mut TcpStream,
|
||||||
response: &Response<Vec<u8>>,
|
response: &Response<Vec<u8>>,
|
||||||
@@ -648,29 +376,6 @@ fn write_all_with_deadline(
|
|||||||
stream.flush()
|
stream.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn interaction(route: Route) -> ProtocolInteraction {
|
|
||||||
match route {
|
|
||||||
Route::Observe => ProtocolInteraction::Observe,
|
|
||||||
Route::FetchInterface => ProtocolInteraction::FetchInterface,
|
|
||||||
Route::CallOperation => ProtocolInteraction::CallOperation,
|
|
||||||
Route::Batch => ProtocolInteraction::Observe,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resource_error() -> ProtocolError {
|
|
||||||
ProtocolError {
|
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
|
||||||
message: "configured resource limit exceeded".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn internal_error() -> ProtocolError {
|
|
||||||
ProtocolError {
|
|
||||||
code: ProtocolErrorCode::Internal,
|
|
||||||
message: "filesystem server failed".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||||
Response::builder()
|
Response::builder()
|
||||||
.status(status)
|
.status(status)
|
||||||
|
|||||||
@@ -9,10 +9,9 @@ use std::time::{Duration, Instant};
|
|||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
use wip_http::{
|
use wip_http::{
|
||||||
BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse, BatchSuccess, DecodedResponse,
|
ClientResponseError, DecodedResponse, Endpoint, JSON_CONTENT_TYPE, Limits, Route,
|
||||||
Endpoint, JSON_CONTENT_TYPE, Limits, Route, decode_batch_request, decode_batch_response,
|
TransportFailureKind, decode_call_operation_response, decode_fetch_interface_response,
|
||||||
decode_call_operation_response, decode_fetch_interface_response, decode_observe_response,
|
decode_observe_response, encode_call_operation_request, encode_fetch_interface_request,
|
||||||
encode_batch_request, encode_call_operation_request, encode_fetch_interface_request,
|
|
||||||
encode_observe_request,
|
encode_observe_request,
|
||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
@@ -21,7 +20,7 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn real_listener_serves_three_core_interactions_batch_and_write() {
|
fn real_listener_serves_three_core_interactions_and_write() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
||||||
@@ -124,36 +123,6 @@ fn real_listener_serves_three_core_interactions_batch_and_write() {
|
|||||||
);
|
);
|
||||||
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
||||||
|
|
||||||
let batch_request = BatchRequest {
|
|
||||||
requests: vec![
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "root".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/".into(),
|
|
||||||
depth: 0,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "tree".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/nested".into(),
|
|
||||||
depth: 1,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(read_interface_request.clone()),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let response = exchange(
|
|
||||||
address,
|
|
||||||
encode_batch_request(&endpoint, &batch_request, limits).expect("encode batch"),
|
|
||||||
);
|
|
||||||
let batch =
|
|
||||||
success(decode_batch_response(&batch_request, &response, limits).expect("decode batch"));
|
|
||||||
assert_batch_successes(&batch);
|
|
||||||
|
|
||||||
let write_interface_request = FetchInterfaceRequest {
|
let write_interface_request = FetchInterfaceRequest {
|
||||||
interface: file.interfaces[1].clone(),
|
interface: file.interfaces[1].clone(),
|
||||||
};
|
};
|
||||||
@@ -210,6 +179,162 @@ fn real_listener_serves_three_core_interactions_batch_and_write() {
|
|||||||
.expect("listener exits cleanly");
|
.expect("listener exits cleanly");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_listener_keeps_route_method_and_malformed_body_boundaries_distinct() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(64, 4_096, 64).expect("wire limits");
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
|
||||||
|
for uri in [
|
||||||
|
"/wip/v1/unknown",
|
||||||
|
"/wip/v1/batch",
|
||||||
|
"/wip/v1/observe?unexpected=true",
|
||||||
|
"/wip/v1/observe/extra",
|
||||||
|
] {
|
||||||
|
let response = exchange(address, json_request(http::Method::POST, uri, b"{}"));
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
assert!(response.body().is_empty());
|
||||||
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
assert!(!response.headers().contains_key(http::header::ALLOW));
|
||||||
|
}
|
||||||
|
|
||||||
|
let wrong_method = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::GET, "/wip/v1/observe", b""),
|
||||||
|
);
|
||||||
|
assert_eq!(wrong_method.status(), http::StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
assert_eq!(wrong_method.headers()[http::header::ALLOW], "POST");
|
||||||
|
assert!(wrong_method.body().is_empty());
|
||||||
|
assert!(
|
||||||
|
!wrong_method
|
||||||
|
.headers()
|
||||||
|
.contains_key(http::header::CONTENT_TYPE)
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut unsupported_coding = json_request(
|
||||||
|
http::Method::POST,
|
||||||
|
"/wip/v1/observe",
|
||||||
|
br#"{"path":"/","depth":0}"#,
|
||||||
|
);
|
||||||
|
unsupported_coding
|
||||||
|
.headers_mut()
|
||||||
|
.insert(http::header::CONTENT_ENCODING, "gzip".parse().unwrap());
|
||||||
|
let unsupported_coding = exchange(address, unsupported_coding);
|
||||||
|
assert_eq!(
|
||||||
|
unsupported_coding.status(),
|
||||||
|
http::StatusCode::UNSUPPORTED_MEDIA_TYPE
|
||||||
|
);
|
||||||
|
assert!(unsupported_coding.body().is_empty());
|
||||||
|
assert!(
|
||||||
|
!unsupported_coding
|
||||||
|
.headers()
|
||||||
|
.contains_key(http::header::CONTENT_TYPE)
|
||||||
|
);
|
||||||
|
|
||||||
|
let malformed = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::POST, "/wip/v1/observe", b"{"),
|
||||||
|
);
|
||||||
|
assert_eq!(malformed.status(), http::StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(
|
||||||
|
malformed.headers()[http::header::CONTENT_TYPE],
|
||||||
|
JSON_CONTENT_TYPE
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(malformed.body())
|
||||||
|
.expect("UTF-8 error envelope")
|
||||||
|
.contains("\"invalid_request\"")
|
||||||
|
);
|
||||||
|
|
||||||
|
let oversized = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::POST, "/wip/v1/observe", &[b'x'; 65]),
|
||||||
|
);
|
||||||
|
assert_eq!(oversized.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
assert!(oversized.body().is_empty());
|
||||||
|
assert!(!oversized.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
|
||||||
|
let mut header_only = TcpStream::connect(address).expect("connect header-only client");
|
||||||
|
header_only
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.expect("set header-only timeout");
|
||||||
|
write!(
|
||||||
|
header_only,
|
||||||
|
"POST /wip/v1/observe HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: 65\r\n\r\n"
|
||||||
|
)
|
||||||
|
.expect("write oversized request head");
|
||||||
|
header_only.flush().expect("flush oversized request head");
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
header_only
|
||||||
|
.read_to_end(&mut raw)
|
||||||
|
.expect("read immediate limit response");
|
||||||
|
assert!(raw.starts_with(b"HTTP/1.1 413 "));
|
||||||
|
assert!(raw.ends_with(b"\r\n\r\n"));
|
||||||
|
assert!(
|
||||||
|
!raw.windows(b"resource_limit_exceeded".len())
|
||||||
|
.any(|window| { window == b"resource_limit_exceeded" })
|
||||||
|
);
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn raw_decoder_limits_are_transport_failures() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(4_096, 4_096, 8).expect("wire limits");
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
|
||||||
|
let nested = br#"{"path":[[[[[[[[["/"]]]]]]]]],"depth":0}"#;
|
||||||
|
let response = server.handle_http(json_request(http::Method::POST, "/wip/v1/observe", nested));
|
||||||
|
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
assert!(response.body().is_empty());
|
||||||
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn logical_observation_limit_remains_protocol_resource_failure() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.max_observation_depth = 0;
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
let request = ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_observe_request(&endpoint, &request, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request, &response, limits).expect("decode logical limit"),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: None,
|
||||||
|
} if error.code == ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
@@ -281,37 +406,6 @@ fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
|||||||
.expect("listener exits cleanly");
|
.expect("listener exits cleanly");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_keeps_known_malformed_arguments_item_local() {
|
|
||||||
let temporary = tempdir().expect("temporary root");
|
|
||||||
let config = ServerConfig::for_root(temporary.path());
|
|
||||||
let limits = config.limits.wire;
|
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
|
||||||
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
|
||||||
let body = br#"{"requests":[{"id":"ok","method":"observe","arguments":{"path":"/","depth":0}},{"id":"bad","method":"observe","arguments":{"path":"/","depth":"bad"}}]}"#;
|
|
||||||
let logical = decode_batch_request(body, limits).expect("decode item-local invalid request");
|
|
||||||
assert!(matches!(
|
|
||||||
logical.requests[1].request,
|
|
||||||
BatchRequestKind::Invalid { .. }
|
|
||||||
));
|
|
||||||
let request = http::Request::builder()
|
|
||||||
.method(http::Method::POST)
|
|
||||||
.uri(endpoint.route(Route::Batch).as_str())
|
|
||||||
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.header(http::header::ACCEPT, "application/json")
|
|
||||||
.body(body.to_vec())
|
|
||||||
.expect("build request");
|
|
||||||
let response = server.handle_http(request);
|
|
||||||
let batch = success(
|
|
||||||
decode_batch_response(&logical, &response, limits).expect("decode mixed batch response"),
|
|
||||||
);
|
|
||||||
assert!(matches!(
|
|
||||||
batch.responses[0].outcome,
|
|
||||||
Ok(BatchSuccess::Observe(_))
|
|
||||||
));
|
|
||||||
assert!(batch.responses[1].outcome.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn call_argument_decoding_does_not_mask_missing_target() {
|
fn call_argument_decoding_does_not_mask_missing_target() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
@@ -359,11 +453,11 @@ fn backend_invalid_unicode_path_is_not_found_not_internal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn read_response_size_failure_preserves_non_commit_guarantee() {
|
fn read_response_size_failure_is_transport_local() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
||||||
let mut config = ServerConfig::for_root(temporary.path());
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
config.limits.wire = Limits::new(4_096, 1_024, 64, 64).expect("wire limits");
|
config.limits.wire = Limits::new(4_096, 1_024, 64).expect("wire limits");
|
||||||
let limits = config.limits.wire;
|
let limits = config.limits.wire;
|
||||||
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");
|
||||||
@@ -406,30 +500,15 @@ fn read_response_size_failure_preserves_non_commit_guarantee() {
|
|||||||
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
||||||
.expect("encode read call"),
|
.expect("encode read call"),
|
||||||
);
|
);
|
||||||
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
match decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
assert!(response.body().is_empty());
|
||||||
.expect("decode resource failure")
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
{
|
|
||||||
DecodedResponse::ProtocolFailure { error, .. } => {
|
|
||||||
assert_eq!(error.code, ProtocolErrorCode::ResourceLimitExceeded);
|
|
||||||
}
|
|
||||||
DecodedResponse::Success(_) => panic!("oversized read response must fail"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_batch_successes(batch: &BatchResponse) {
|
|
||||||
assert_eq!(batch.responses.len(), 3);
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
batch.responses[0].outcome,
|
decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
||||||
Ok(BatchSuccess::Observe(_))
|
.expect_err("oversized representation is not a protocol failure"),
|
||||||
));
|
ClientResponseError::TransportBinding(failure)
|
||||||
assert!(matches!(
|
if failure.status == http::StatusCode::INTERNAL_SERVER_ERROR
|
||||||
batch.responses[1].outcome,
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
Ok(BatchSuccess::Observe(_))
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
batch.responses[2].outcome,
|
|
||||||
Ok(BatchSuccess::FetchInterface(_))
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -440,6 +519,16 @@ fn success<T>(response: DecodedResponse<T>) -> T {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn json_request(method: http::Method, uri: &str, body: &[u8]) -> http::Request<Vec<u8>> {
|
||||||
|
http::Request::builder()
|
||||||
|
.method(method)
|
||||||
|
.uri(uri)
|
||||||
|
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(http::header::ACCEPT, "application/json")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.expect("build JSON request")
|
||||||
|
}
|
||||||
|
|
||||||
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
||||||
let mut stream = TcpStream::connect(address).expect("connect listener");
|
let mut stream = TcpStream::connect(address).expect("connect listener");
|
||||||
stream
|
stream
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -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,15 @@
|
|||||||
|
# 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"
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -211,6 +211,17 @@ pub struct InterfaceObservation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -449,6 +460,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> {
|
||||||
@@ -502,6 +567,46 @@ 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 {
|
||||||
|
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 {
|
||||||
@@ -782,6 +887,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.
|
||||||
@@ -1016,11 +1130,18 @@ pub trait ObjectProvider {
|
|||||||
pub enum PublicationError {
|
pub enum PublicationError {
|
||||||
/// The same opaque interface reference was exposed more than once.
|
/// The same opaque 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 +1153,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 {
|
||||||
|
|||||||
@@ -14,6 +14,62 @@ 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 read = registry.register(ReaderDefinition, None).unwrap();
|
||||||
|
let write = registry.register(WriterDefinition, None).unwrap();
|
||||||
|
let hidden = registry.register(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().as_str(), read.reference().as_str()]
|
||||||
|
);
|
||||||
|
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 full = registry.fetch_interface(read.reference().as_str()).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().as_str()).unwrap(),
|
||||||
|
full
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[interface]
|
#[interface]
|
||||||
pub trait Reader {
|
pub trait Reader {
|
||||||
/// Returns the reader-qualified label.
|
/// Returns the reader-qualified label.
|
||||||
|
|||||||
@@ -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,31 @@
|
|||||||
|
# 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(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -1,570 +0,0 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
|
||||||
|
|
||||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
|
||||||
use http::{Method, Request, Response, StatusCode};
|
|
||||||
use serde_json::{Map, Value as Json};
|
|
||||||
use wip_protocol::{
|
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, ObserveRequest,
|
|
||||||
ObserveResponse, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::response::{self, DecodedResponse};
|
|
||||||
use crate::{
|
|
||||||
BodyKind, ClientResponseError, CodecError, EncodeHttpError, Endpoint, InvalidResponseKind,
|
|
||||||
JSON_CONTENT_TYPE, Limits, ResourceLimitKind, Route, is_json_content_type, json,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A retrieval method accepted by the standard v1 batch endpoint.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum BatchMethod {
|
|
||||||
/// Observe one object and its indexable descendants.
|
|
||||||
Observe,
|
|
||||||
/// Fetch one interface descriptor.
|
|
||||||
FetchInterface,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BatchMethod {
|
|
||||||
fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::Observe => "observe",
|
|
||||||
Self::FetchInterface => "fetch_interface",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn interaction(self) -> ProtocolInteraction {
|
|
||||||
match self {
|
|
||||||
Self::Observe => ProtocolInteraction::Observe,
|
|
||||||
Self::FetchInterface => ProtocolInteraction::FetchInterface,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One retrieval interaction accepted by the standard v1 batch endpoint.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum BatchRequestKind {
|
|
||||||
/// Observe one object and its indexable descendants.
|
|
||||||
Observe(ObserveRequest),
|
|
||||||
/// Fetch one interface descriptor.
|
|
||||||
FetchInterface(FetchInterfaceRequest),
|
|
||||||
/// A known method whose `arguments` are not a valid logical request.
|
|
||||||
Invalid {
|
|
||||||
/// Method that was successfully identified from the item envelope.
|
|
||||||
method: BatchMethod,
|
|
||||||
/// Item-local `invalid_request` to return without rejecting other items.
|
|
||||||
error: ProtocolError,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BatchRequestKind {
|
|
||||||
fn interaction(&self) -> ProtocolInteraction {
|
|
||||||
match self {
|
|
||||||
Self::Observe(_) => ProtocolInteraction::Observe,
|
|
||||||
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
|
|
||||||
Self::Invalid { method, .. } => method.interaction(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One uniquely identified batch subrequest.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct BatchRequestItem {
|
|
||||||
/// Identifier used only to correlate the corresponding subresponse.
|
|
||||||
pub id: String,
|
|
||||||
/// Retrieval interaction and arguments.
|
|
||||||
pub request: BatchRequestKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A standard v1 batch request.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct BatchRequest {
|
|
||||||
/// Independent subrequests. Identifiers must be unique.
|
|
||||||
pub requests: Vec<BatchRequestItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Successful result of one batch item.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum BatchSuccess {
|
|
||||||
/// Successful `observe` result.
|
|
||||||
Observe(ObserveResponse),
|
|
||||||
/// Successful `fetch_interface` result.
|
|
||||||
FetchInterface(FetchInterfaceResponse),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One batch subresponse, correlated by `id` rather than array position.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct BatchResponseItem {
|
|
||||||
/// Identifier copied from its subrequest.
|
|
||||||
pub id: String,
|
|
||||||
/// Direct interaction result or canonical item-local protocol failure.
|
|
||||||
pub outcome: Result<BatchSuccess, ProtocolError>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A valid standard v1 batch response.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct BatchResponse {
|
|
||||||
/// Exactly one response for each requested identifier, in any order.
|
|
||||||
pub responses: Vec<BatchResponseItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Result<(), CodecError> {
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
let mut count = 0;
|
|
||||||
for id in ids {
|
|
||||||
count += 1;
|
|
||||||
if !seen.insert(id) {
|
|
||||||
return Err(CodecError::DuplicateBatchId { id: id.into() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if count > maximum {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: count,
|
|
||||||
maximum,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
|
|
||||||
let (method, arguments) = match &item.request {
|
|
||||||
BatchRequestKind::Observe(value) => ("observe", json::observe_request_to_json(value)),
|
|
||||||
BatchRequestKind::FetchInterface(value) => (
|
|
||||||
"fetch_interface",
|
|
||||||
json::fetch_interface_request_to_json(value),
|
|
||||||
),
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "requests".into(),
|
|
||||||
reason: "item-local invalid requests cannot be encoded as client requests".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(serde_json::json!({"id": item.id, "method": method, "arguments": arguments}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, CodecError> {
|
|
||||||
validate_ids(
|
|
||||||
request.requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
for item in &request.requests {
|
|
||||||
match &item.request {
|
|
||||||
BatchRequestKind::Observe(value) => value.validate()?,
|
|
||||||
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let requests = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(request_item_to_json)
|
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
|
||||||
Ok(serde_json::json!({"requests": requests}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, CodecError> {
|
|
||||||
let fields = exact_object(value, "batch", &["requests"])?;
|
|
||||||
let values = array(required(fields, "requests")?, "requests")?;
|
|
||||||
if values.len() > limits.max_batch_items {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: values.len(),
|
|
||||||
maximum: limits.max_batch_items,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let mut requests = Vec::with_capacity(values.len());
|
|
||||||
for (index, value) in values.iter().enumerate() {
|
|
||||||
let field = format!("requests[{index}]");
|
|
||||||
let fields = exact_object(value, &field, &["id", "method", "arguments"])?;
|
|
||||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
|
||||||
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
|
|
||||||
let arguments = required(fields, "arguments")?;
|
|
||||||
let method = match method_name.as_str() {
|
|
||||||
"observe" => BatchMethod::Observe,
|
|
||||||
"fetch_interface" => BatchMethod::FetchInterface,
|
|
||||||
_ => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: format!("{field}.method"),
|
|
||||||
reason: "batch supports only observe and fetch_interface".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let decoded = match method {
|
|
||||||
BatchMethod::Observe => {
|
|
||||||
json::observe_request_from_json(arguments).map(BatchRequestKind::Observe)
|
|
||||||
}
|
|
||||||
BatchMethod::FetchInterface => json::fetch_interface_request_from_json(arguments)
|
|
||||||
.map(BatchRequestKind::FetchInterface),
|
|
||||||
};
|
|
||||||
let request = decoded.unwrap_or_else(|error| BatchRequestKind::Invalid {
|
|
||||||
method,
|
|
||||||
error: ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: format!("invalid {} arguments: {error}", method.name()),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
requests.push(BatchRequestItem { id, request });
|
|
||||||
}
|
|
||||||
validate_ids(
|
|
||||||
requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
Ok(BatchRequest { requests })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a batch request using `POST v1/batch`.
|
|
||||||
pub fn encode_batch_request(
|
|
||||||
endpoint: &Endpoint,
|
|
||||||
value: &BatchRequest,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
|
||||||
let body = json::serialize(&request_to_json(value, limits)?, BodyKind::Request, limits)?;
|
|
||||||
Ok(Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri(endpoint.route(Route::Batch).as_str())
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.header(ACCEPT, "application/json")
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes and validates a batch request body.
|
|
||||||
pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest, CodecError> {
|
|
||||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
|
||||||
request_from_json(&value, limits)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn success_to_json(success: &BatchSuccess) -> Json {
|
|
||||||
match success {
|
|
||||||
BatchSuccess::Observe(value) => json::observe_response_to_json(value),
|
|
||||||
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn response_to_json(
|
|
||||||
request: &BatchRequest,
|
|
||||||
response: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Json, CodecError> {
|
|
||||||
correlate(request, response, limits)?;
|
|
||||||
Ok(serde_json::json!({
|
|
||||||
"responses": response.responses.iter().map(|item| {
|
|
||||||
let mut fields = Map::new();
|
|
||||||
fields.insert("id".into(), Json::String(item.id.clone()));
|
|
||||||
match &item.outcome {
|
|
||||||
Ok(success) => { fields.insert("result".into(), success_to_json(success)); }
|
|
||||||
Err(error) => { fields.insert("error".into(), response::item_error_to_json(error)); }
|
|
||||||
}
|
|
||||||
Json::Object(fields)
|
|
||||||
}).collect::<Vec<_>>()
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn correlate(
|
|
||||||
request: &BatchRequest,
|
|
||||||
response: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<(), CodecError> {
|
|
||||||
validate_ids(
|
|
||||||
request.requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
validate_ids(
|
|
||||||
response.responses.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| (item.id.as_str(), &item.request))
|
|
||||||
.collect();
|
|
||||||
for item in &response.responses {
|
|
||||||
let Some(kind) = requested.get(item.id.as_str()) else {
|
|
||||||
return Err(CodecError::UnexpectedBatchId {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
match (&item.outcome, *kind) {
|
|
||||||
(Ok(BatchSuccess::Observe(value)), BatchRequestKind::Observe(request)) => {
|
|
||||||
request.validate_response(value)?;
|
|
||||||
}
|
|
||||||
(
|
|
||||||
Ok(BatchSuccess::FetchInterface(value)),
|
|
||||||
BatchRequestKind::FetchInterface(request),
|
|
||||||
) => {
|
|
||||||
value.validate_for(request)?;
|
|
||||||
}
|
|
||||||
(
|
|
||||||
Err(error),
|
|
||||||
BatchRequestKind::Invalid {
|
|
||||||
error: expected, ..
|
|
||||||
},
|
|
||||||
) if error == expected => {}
|
|
||||||
(Err(error), kind)
|
|
||||||
if !matches!(kind, BatchRequestKind::Invalid { .. })
|
|
||||||
&& error.code.is_allowed_for(kind.interaction()) => {}
|
|
||||||
_ => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for item in &request.requests {
|
|
||||||
if !response.responses.iter().any(|other| other.id == item.id) {
|
|
||||||
return Err(CodecError::MissingBatchId {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a valid batch response. Item failures remain inside HTTP 200.
|
|
||||||
pub fn encode_batch_response(
|
|
||||||
request: &BatchRequest,
|
|
||||||
value: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
let body = json::serialize(
|
|
||||||
&response_to_json(request, value, limits)?,
|
|
||||||
BodyKind::Response,
|
|
||||||
limits,
|
|
||||||
)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a top-level batch-envelope failure.
|
|
||||||
///
|
|
||||||
/// Item-local failures belong in [`BatchResponseItem`]. Only failures that can
|
|
||||||
/// reject the batch envelope before item execution are accepted here. A
|
|
||||||
/// resource-limit failure defaults to the logical-limit status; use
|
|
||||||
/// [`encode_batch_resource_limit_error_response`] when the concrete class is
|
|
||||||
/// known.
|
|
||||||
pub fn encode_batch_error_response(
|
|
||||||
error: &ProtocolError,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if !matches!(
|
|
||||||
error.code,
|
|
||||||
ProtocolErrorCode::InvalidRequest
|
|
||||||
| ProtocolErrorCode::ResourceLimitExceeded
|
|
||||||
| ProtocolErrorCode::Internal
|
|
||||||
) {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "code is not valid for a top-level batch failure".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(response::status_for_error(error.code))
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a class-specific top-level batch `resource_limit_exceeded` failure.
|
|
||||||
pub fn encode_batch_resource_limit_error_response(
|
|
||||||
error: &ProtocolError,
|
|
||||||
kind: ResourceLimitKind,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if error.code != ProtocolErrorCode::ResourceLimitExceeded {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(response::status_for_resource_limit(kind))
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn response_from_json(
|
|
||||||
value: &Json,
|
|
||||||
request: &BatchRequest,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<BatchResponse, CodecError> {
|
|
||||||
let fields = exact_object(value, "batch", &["responses"])?;
|
|
||||||
let values = array(required(fields, "responses")?, "responses")?;
|
|
||||||
if values.len() > limits.max_batch_items {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: values.len(),
|
|
||||||
maximum: limits.max_batch_items,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| (item.id.as_str(), &item.request))
|
|
||||||
.collect();
|
|
||||||
let mut responses = Vec::with_capacity(values.len());
|
|
||||||
for (index, value) in values.iter().enumerate() {
|
|
||||||
let field = format!("responses[{index}]");
|
|
||||||
let fields = object(value, &field)?;
|
|
||||||
for name in fields.keys() {
|
|
||||||
if !["id", "result", "error"].contains(&name.as_str()) {
|
|
||||||
return Err(CodecError::UnknownField {
|
|
||||||
field: format!("{field}.{name}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
|
||||||
let Some(kind) = requested.get(id.as_str()) else {
|
|
||||||
return Err(CodecError::UnexpectedBatchId { id });
|
|
||||||
};
|
|
||||||
let outcome = match (fields.get("result"), fields.get("error")) {
|
|
||||||
(Some(_), Some(_)) | (None, None) => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field,
|
|
||||||
reason: "batch item must contain exactly one of result or error".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
(None, Some(error)) => {
|
|
||||||
let error = response::item_error_from_json(error)?;
|
|
||||||
match kind {
|
|
||||||
BatchRequestKind::Invalid {
|
|
||||||
error: expected, ..
|
|
||||||
} if error == *expected => {}
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch { id });
|
|
||||||
}
|
|
||||||
kind if error.code.is_allowed_for(kind.interaction()) => {}
|
|
||||||
_ => return Err(CodecError::BatchInteractionMismatch { id }),
|
|
||||||
}
|
|
||||||
Err(error)
|
|
||||||
}
|
|
||||||
(Some(result), None) => Ok(match kind {
|
|
||||||
BatchRequestKind::Observe(request) => {
|
|
||||||
let value = json::observe_response_from_json(result)?;
|
|
||||||
request.validate_response(&value)?;
|
|
||||||
BatchSuccess::Observe(value)
|
|
||||||
}
|
|
||||||
BatchRequestKind::FetchInterface(request) => {
|
|
||||||
let value = json::fetch_interface_response_from_json(result)?;
|
|
||||||
value.validate_for(request)?;
|
|
||||||
BatchSuccess::FetchInterface(value)
|
|
||||||
}
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch { id });
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
responses.push(BatchResponseItem { id, outcome });
|
|
||||||
}
|
|
||||||
let response = BatchResponse { responses };
|
|
||||||
correlate(request, &response, limits)?;
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes a batch response, including item-local failures within HTTP 200.
|
|
||||||
pub fn decode_batch_response<B: AsRef<[u8]>>(
|
|
||||||
request: &BatchRequest,
|
|
||||||
value: &Response<B>,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<DecodedResponse<BatchResponse>, ClientResponseError> {
|
|
||||||
let valid_content_type = value
|
|
||||||
.headers()
|
|
||||||
.get(CONTENT_TYPE)
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.is_some_and(is_json_content_type);
|
|
||||||
if !valid_content_type {
|
|
||||||
if value.status().is_success() {
|
|
||||||
return Err(ClientResponseError::invalid(
|
|
||||||
InvalidResponseKind::InvalidBatch,
|
|
||||||
"missing or non-UTF-8 application/json Content-Type",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return Err(response::transport_failure(value.status()));
|
|
||||||
}
|
|
||||||
let decoded = response::decode(
|
|
||||||
value.status(),
|
|
||||||
value.body().as_ref(),
|
|
||||||
ProtocolInteraction::Observe,
|
|
||||||
limits,
|
|
||||||
|json| response_from_json(json, request, limits),
|
|
||||||
)
|
|
||||||
.map_err(|error| match error {
|
|
||||||
ClientResponseError::InvalidResponse { detail, .. } => {
|
|
||||||
ClientResponseError::invalid(InvalidResponseKind::InvalidBatch, detail)
|
|
||||||
}
|
|
||||||
other => other,
|
|
||||||
})?;
|
|
||||||
if let DecodedResponse::ProtocolFailure { error, .. } = &decoded
|
|
||||||
&& !matches!(
|
|
||||||
error.code,
|
|
||||||
ProtocolErrorCode::InvalidRequest
|
|
||||||
| ProtocolErrorCode::ResourceLimitExceeded
|
|
||||||
| ProtocolErrorCode::Internal
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return Err(ClientResponseError::invalid(
|
|
||||||
InvalidResponseKind::InvalidBatch,
|
|
||||||
"protocol code is not valid for a top-level batch failure",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let DecodedResponse::Success(success) = &decoded {
|
|
||||||
for item in &success.responses {
|
|
||||||
if let Ok(BatchSuccess::FetchInterface(interface)) = &item.outcome
|
|
||||||
&& interface.descriptor.format != INTERFACE_FORMAT_V1
|
|
||||||
{
|
|
||||||
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
|
||||||
format: interface.descriptor.format.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(decoded)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn object<'a>(value: &'a Json, field: &str) -> Result<&'a Map<String, Json>, CodecError> {
|
|
||||||
value.as_object().ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected object".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exact_object<'a>(
|
|
||||||
value: &'a Json,
|
|
||||||
field: &str,
|
|
||||||
allowed: &[&str],
|
|
||||||
) -> Result<&'a Map<String, Json>, CodecError> {
|
|
||||||
let fields = object(value, field)?;
|
|
||||||
for name in fields.keys() {
|
|
||||||
if !allowed.contains(&name.as_str()) {
|
|
||||||
return Err(CodecError::UnknownField {
|
|
||||||
field: format!("{field}.{name}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(fields)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn required<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a Json, CodecError> {
|
|
||||||
fields
|
|
||||||
.get(name)
|
|
||||||
.ok_or_else(|| CodecError::MissingField { field: name.into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn string(value: &Json, field: &str) -> Result<String, CodecError> {
|
|
||||||
value
|
|
||||||
.as_str()
|
|
||||||
.map(str::to_owned)
|
|
||||||
.ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected string".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn array<'a>(value: &'a Json, field: &str) -> Result<&'a [Json], CodecError> {
|
|
||||||
value
|
|
||||||
.as_array()
|
|
||||||
.map(Vec::as_slice)
|
|
||||||
.ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected array".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
use http::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE};
|
||||||
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
||||||
@@ -12,7 +12,7 @@ use wip_protocol::{
|
|||||||
use crate::response::{self, DecodedResponse};
|
use crate::response::{self, DecodedResponse};
|
||||||
use crate::{
|
use crate::{
|
||||||
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||||
Limits, ResourceLimitKind, Route, json,
|
Limits, Route, json,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn request(
|
fn request(
|
||||||
@@ -36,6 +36,9 @@ fn response(status: StatusCode, body: Vec<u8>) -> Result<Response<Vec<u8>>, http
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
||||||
|
if !has_supported_content_coding(response.headers()) {
|
||||||
|
return Err(response::unsupported_content_coding(response.status()));
|
||||||
|
}
|
||||||
let valid = response
|
let valid = response
|
||||||
.headers()
|
.headers()
|
||||||
.get(CONTENT_TYPE)
|
.get(CONTENT_TYPE)
|
||||||
@@ -181,9 +184,11 @@ fn accepts_json(headers: &HeaderMap) -> bool {
|
|||||||
/// A failure while validating inbound HTTP request metadata.
|
/// A failure while validating inbound HTTP request metadata.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum RequestMetadataError {
|
pub enum RequestMetadataError {
|
||||||
/// The method or route does not match the selected WIP interaction.
|
/// The request URI does not exactly identify the selected standard route.
|
||||||
InvalidRequest(CodecError),
|
NotFound,
|
||||||
/// The request body does not use UTF-8 `application/json`.
|
/// A known standard route was requested with a method other than `POST`.
|
||||||
|
MethodNotAllowed,
|
||||||
|
/// The request body does not use UTF-8 `application/json` or identity coding.
|
||||||
UnsupportedMediaType,
|
UnsupportedMediaType,
|
||||||
/// The request's `Accept` metadata excludes `application/json`.
|
/// The request's `Accept` metadata excludes `application/json`.
|
||||||
NotAcceptable,
|
NotAcceptable,
|
||||||
@@ -194,32 +199,47 @@ impl RequestMetadataError {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn status(&self) -> StatusCode {
|
pub const fn status(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidRequest(_) => StatusCode::BAD_REQUEST,
|
Self::NotFound => StatusCode::NOT_FOUND,
|
||||||
|
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
|
||||||
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||||
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the value for an `Allow` response header, when required.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn allow(&self) -> Option<&'static str> {
|
||||||
|
match self {
|
||||||
|
Self::MethodNotAllowed => Some("POST"),
|
||||||
|
Self::NotFound | Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for RequestMetadataError {
|
impl Display for RequestMetadataError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidRequest(error) => error.fmt(formatter),
|
Self::NotFound => formatter.write_str("request URI is not a standard WIP route"),
|
||||||
|
Self::MethodNotAllowed => formatter.write_str("standard WIP routes require POST"),
|
||||||
Self::UnsupportedMediaType => {
|
Self::UnsupportedMediaType => {
|
||||||
formatter.write_str("expected UTF-8 application/json Content-Type")
|
formatter.write_str("expected identity-coded UTF-8 application/json Content-Type")
|
||||||
}
|
}
|
||||||
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for RequestMetadataError {
|
impl Error for RequestMetadataError {}
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
match self {
|
pub(crate) fn has_supported_content_coding(headers: &HeaderMap) -> bool {
|
||||||
Self::InvalidRequest(error) => Some(error),
|
headers.get_all(CONTENT_ENCODING).iter().all(|value| {
|
||||||
Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
value.to_str().is_ok_and(|value| {
|
||||||
}
|
let mut codings = value.split(',').map(str::trim);
|
||||||
}
|
let first = codings.next();
|
||||||
|
first.is_some_and(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||||
|
&& codings.all(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||||
@@ -233,29 +253,19 @@ pub fn validate_http_request<B>(
|
|||||||
route: Route,
|
route: Route,
|
||||||
value: &Request<B>,
|
value: &Request<B>,
|
||||||
) -> Result<(), RequestMetadataError> {
|
) -> Result<(), RequestMetadataError> {
|
||||||
if value.method() != Method::POST {
|
|
||||||
return Err(RequestMetadataError::InvalidRequest(
|
|
||||||
CodecError::InvalidField {
|
|
||||||
field: "method".into(),
|
|
||||||
reason: "standard WIP routes require POST".into(),
|
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let expected = endpoint.route(route);
|
let expected = endpoint.route(route);
|
||||||
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||||
return Err(RequestMetadataError::InvalidRequest(
|
return Err(RequestMetadataError::NotFound);
|
||||||
CodecError::InvalidField {
|
}
|
||||||
field: "route".into(),
|
if value.method() != Method::POST {
|
||||||
reason: "request URI does not match the selected standard route".into(),
|
return Err(RequestMetadataError::MethodNotAllowed);
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let valid_content_type = value
|
let valid_content_type = value
|
||||||
.headers()
|
.headers()
|
||||||
.get(CONTENT_TYPE)
|
.get(CONTENT_TYPE)
|
||||||
.and_then(|value| value.to_str().ok())
|
.and_then(|value| value.to_str().ok())
|
||||||
.is_some_and(is_json_content_type);
|
.is_some_and(is_json_content_type);
|
||||||
if !valid_content_type {
|
if !valid_content_type || !has_supported_content_coding(value.headers()) {
|
||||||
return Err(RequestMetadataError::UnsupportedMediaType);
|
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||||
}
|
}
|
||||||
if !accepts_json(value.headers()) {
|
if !accepts_json(value.headers()) {
|
||||||
@@ -526,9 +536,8 @@ fn encode_protocol_error_with_status(
|
|||||||
/// The code must be allowed for `interaction`. This API accepts only
|
/// The code must be allowed for `interaction`. This API accepts only
|
||||||
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
||||||
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
||||||
/// error envelopes. Resource-limit errors use the logical-limit status; callers
|
/// error envelopes. Logical `resource_limit_exceeded` failures use HTTP 422;
|
||||||
/// that know the concrete limit class should use
|
/// representation and deployment limits are not protocol errors.
|
||||||
/// [`encode_resource_limit_error_response`].
|
|
||||||
pub fn encode_protocol_error_response(
|
pub fn encode_protocol_error_response(
|
||||||
interaction: ProtocolInteraction,
|
interaction: ProtocolInteraction,
|
||||||
error: &ProtocolError,
|
error: &ProtocolError,
|
||||||
@@ -542,28 +551,6 @@ pub fn encode_protocol_error_response(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encodes a `resource_limit_exceeded` envelope with its class-specific status.
|
|
||||||
pub fn encode_resource_limit_error_response(
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: &ProtocolError,
|
|
||||||
kind: ResourceLimitKind,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if error.code != wip_protocol::ProtocolErrorCode::ResourceLimitExceeded {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
encode_protocol_error_with_status(
|
|
||||||
interaction,
|
|
||||||
error,
|
|
||||||
response::status_for_resource_limit(kind),
|
|
||||||
limits,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Failure while building an outbound framework-neutral HTTP message.
|
/// Failure while building an outbound framework-neutral HTTP message.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum EncodeHttpError {
|
pub enum EncodeHttpError {
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ pub enum Route {
|
|||||||
FetchInterface,
|
FetchInterface,
|
||||||
/// Call one operation.
|
/// Call one operation.
|
||||||
CallOperation,
|
CallOperation,
|
||||||
/// Package independent retrieval interactions.
|
|
||||||
Batch,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Route {
|
impl Route {
|
||||||
@@ -27,7 +25,6 @@ impl Route {
|
|||||||
Self::Observe => "v1/observe",
|
Self::Observe => "v1/observe",
|
||||||
Self::FetchInterface => "v1/fetch_interface",
|
Self::FetchInterface => "v1/fetch_interface",
|
||||||
Self::CallOperation => "v1/call_operation",
|
Self::CallOperation => "v1/call_operation",
|
||||||
Self::Batch => "v1/batch",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,12 +79,7 @@ impl Endpoint {
|
|||||||
/// are not route components and therefore never match.
|
/// are not route components and therefore never match.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
||||||
const ROUTES: [Route; 4] = [
|
const ROUTES: [Route; 3] = [Route::Observe, Route::FetchInterface, Route::CallOperation];
|
||||||
Route::Observe,
|
|
||||||
Route::FetchInterface,
|
|
||||||
Route::CallOperation,
|
|
||||||
Route::Batch,
|
|
||||||
];
|
|
||||||
if candidate.query().is_some() || candidate.fragment().is_some() {
|
if candidate.query().is_some() || candidate.fragment().is_some() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ pub struct Limits {
|
|||||||
pub(crate) max_response_bytes: usize,
|
pub(crate) max_response_bytes: usize,
|
||||||
/// Largest accepted JSON container nesting depth.
|
/// Largest accepted JSON container nesting depth.
|
||||||
pub(crate) max_nesting: usize,
|
pub(crate) max_nesting: usize,
|
||||||
/// Largest accepted number of batch items.
|
|
||||||
pub(crate) max_batch_items: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Limits {
|
impl Limits {
|
||||||
@@ -20,7 +18,6 @@ impl Limits {
|
|||||||
max_request_bytes: usize,
|
max_request_bytes: usize,
|
||||||
max_response_bytes: usize,
|
max_response_bytes: usize,
|
||||||
max_nesting: usize,
|
max_nesting: usize,
|
||||||
max_batch_items: usize,
|
|
||||||
) -> Result<Self, LimitConfigurationError> {
|
) -> Result<Self, LimitConfigurationError> {
|
||||||
if max_request_bytes == 0 {
|
if max_request_bytes == 0 {
|
||||||
return Err(LimitConfigurationError::ZeroRequestBytes);
|
return Err(LimitConfigurationError::ZeroRequestBytes);
|
||||||
@@ -31,14 +28,10 @@ impl Limits {
|
|||||||
if max_nesting == 0 {
|
if max_nesting == 0 {
|
||||||
return Err(LimitConfigurationError::ZeroNesting);
|
return Err(LimitConfigurationError::ZeroNesting);
|
||||||
}
|
}
|
||||||
if max_batch_items == 0 {
|
|
||||||
return Err(LimitConfigurationError::ZeroBatchItems);
|
|
||||||
}
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
max_request_bytes,
|
max_request_bytes,
|
||||||
max_response_bytes,
|
max_response_bytes,
|
||||||
max_nesting,
|
max_nesting,
|
||||||
max_batch_items,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,12 +52,6 @@ impl Limits {
|
|||||||
pub const fn max_nesting(self) -> usize {
|
pub const fn max_nesting(self) -> usize {
|
||||||
self.max_nesting
|
self.max_nesting
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the batch item count limit.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn max_batch_items(self) -> usize {
|
|
||||||
self.max_batch_items
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why a [`Limits`] configuration is not bounded.
|
/// Why a [`Limits`] configuration is not bounded.
|
||||||
@@ -76,8 +63,6 @@ pub enum LimitConfigurationError {
|
|||||||
ZeroResponseBytes,
|
ZeroResponseBytes,
|
||||||
/// Nesting limit was zero.
|
/// Nesting limit was zero.
|
||||||
ZeroNesting,
|
ZeroNesting,
|
||||||
/// Batch-item limit was zero.
|
|
||||||
ZeroBatchItems,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for LimitConfigurationError {
|
impl Display for LimitConfigurationError {
|
||||||
@@ -86,7 +71,6 @@ impl Display for LimitConfigurationError {
|
|||||||
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
||||||
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
||||||
Self::ZeroNesting => "nesting limit must be nonzero",
|
Self::ZeroNesting => "nesting limit must be nonzero",
|
||||||
Self::ZeroBatchItems => "batch item limit must be nonzero",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -102,15 +86,6 @@ pub enum BodyKind {
|
|||||||
Response,
|
Response,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The class of a resource limit exceeded by a wire representation.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ResourceLimitKind {
|
|
||||||
/// A request or response representation exceeded its byte-size limit.
|
|
||||||
RepresentationBytes,
|
|
||||||
/// A logical limit such as nesting depth, batch count, or collection size was exceeded.
|
|
||||||
Logical,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A malformed or locally disallowed wire representation.
|
/// A malformed or locally disallowed wire representation.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum CodecError {
|
pub enum CodecError {
|
||||||
@@ -157,47 +132,6 @@ pub enum CodecError {
|
|||||||
},
|
},
|
||||||
/// Logical protocol validation rejected the decoded representation.
|
/// Logical protocol validation rejected the decoded representation.
|
||||||
ProtocolValidation(wip_protocol::ValidationError),
|
ProtocolValidation(wip_protocol::ValidationError),
|
||||||
/// The batch exceeds its configured item count.
|
|
||||||
TooManyBatchItems {
|
|
||||||
/// Actual item count.
|
|
||||||
actual: usize,
|
|
||||||
/// Configured maximum.
|
|
||||||
maximum: usize,
|
|
||||||
},
|
|
||||||
/// Batch item identifiers are not unique.
|
|
||||||
DuplicateBatchId {
|
|
||||||
/// Repeated identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A response contains a batch identifier that was not requested.
|
|
||||||
UnexpectedBatchId {
|
|
||||||
/// Unexpected identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A response omitted a requested batch identifier.
|
|
||||||
MissingBatchId {
|
|
||||||
/// Missing identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A batch item result does not match its requested interaction.
|
|
||||||
BatchInteractionMismatch {
|
|
||||||
/// Item identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CodecError {
|
|
||||||
/// Classifies this failure when it represents a canonical resource limit.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn resource_limit_kind(&self) -> Option<ResourceLimitKind> {
|
|
||||||
match self {
|
|
||||||
Self::BodyTooLarge { .. } => Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
Self::NestingTooDeep { .. } | Self::TooManyBatchItems { .. } => {
|
|
||||||
Some(ResourceLimitKind::Logical)
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for CodecError {
|
impl Display for CodecError {
|
||||||
@@ -225,15 +159,6 @@ impl Display for CodecError {
|
|||||||
write!(formatter, "field `{field}` is not canonical base64")
|
write!(formatter, "field `{field}` is not canonical base64")
|
||||||
}
|
}
|
||||||
Self::ProtocolValidation(error) => error.fmt(formatter),
|
Self::ProtocolValidation(error) => error.fmt(formatter),
|
||||||
Self::TooManyBatchItems { actual, maximum } => {
|
|
||||||
write!(formatter, "batch has {actual} items; maximum is {maximum}")
|
|
||||||
}
|
|
||||||
Self::DuplicateBatchId { id } => write!(formatter, "duplicate batch id `{id}`"),
|
|
||||||
Self::UnexpectedBatchId { id } => write!(formatter, "unexpected batch id `{id}`"),
|
|
||||||
Self::MissingBatchId { id } => write!(formatter, "missing batch id `{id}`"),
|
|
||||||
Self::BatchInteractionMismatch { id } => {
|
|
||||||
write!(formatter, "batch result does not match request `{id}`")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
//!
|
//!
|
||||||
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
||||||
//! success and error response handling, HTTP status mapping, descriptor-guided
|
//! success and error response handling, HTTP status mapping, descriptor-guided
|
||||||
//! operation-value conversion, and retrieval batching. It deliberately performs
|
//! operation-value conversion. It deliberately performs no I/O and depends on no
|
||||||
//! no I/O and depends on no server framework, TLS implementation, filesystem
|
//! server framework, TLS implementation, filesystem projection, client cache, or
|
||||||
//! projection, client cache, or presentation layer. URL schemes, TLS,
|
//! presentation layer. URL schemes, TLS, certificates, authentication mechanisms,
|
||||||
//! certificates, authentication mechanisms, proxies, and caches are selected by
|
//! proxies, and caches are selected by the HTTP implementation and deployment
|
||||||
//! the HTTP implementation and deployment rather than by WIP conformance.
|
//! rather than by WIP conformance.
|
||||||
//!
|
//!
|
||||||
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
||||||
//! 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
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
//! use wip_protocol::ObserveRequest;
|
//! use wip_protocol::ObserveRequest;
|
||||||
//!
|
//!
|
||||||
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
||||||
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
|
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64)?;
|
||||||
//! let request = encode_observe_request(
|
//! let request = encode_observe_request(
|
||||||
//! &endpoint,
|
//! &endpoint,
|
||||||
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
||||||
@@ -30,34 +30,25 @@
|
|||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
mod batch;
|
|
||||||
mod codec;
|
mod codec;
|
||||||
mod endpoint;
|
mod endpoint;
|
||||||
mod error;
|
mod error;
|
||||||
mod json;
|
mod json;
|
||||||
mod response;
|
mod response;
|
||||||
|
|
||||||
pub use batch::{
|
|
||||||
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
|
||||||
BatchResponseItem, BatchSuccess, decode_batch_request, decode_batch_response,
|
|
||||||
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
|
||||||
encode_batch_response,
|
|
||||||
};
|
|
||||||
pub use codec::{
|
pub use codec::{
|
||||||
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
||||||
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
||||||
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
||||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||||
encode_protocol_error_response, encode_resource_limit_error_response, is_json_content_type,
|
encode_protocol_error_response, is_json_content_type, validate_http_request,
|
||||||
validate_http_request,
|
|
||||||
};
|
};
|
||||||
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||||
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
|
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits};
|
||||||
pub use response::{
|
pub use response::{
|
||||||
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||||
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||||
status_for_resource_limit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Framework-neutral HTTP types used by this binding's public API.
|
/// Framework-neutral HTTP types used by this binding's public API.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use http::StatusCode;
|
|||||||
use serde_json::{Map, Value as Json};
|
use serde_json::{Map, Value as Json};
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
use crate::{BodyKind, CodecError, Limits, ResourceLimitKind, json};
|
use crate::{BodyKind, CodecError, Limits, json};
|
||||||
|
|
||||||
/// A successfully classified client response.
|
/// A successfully classified client response.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -37,6 +37,8 @@ pub enum TransportFailureKind {
|
|||||||
AuthenticationRequired,
|
AuthenticationRequired,
|
||||||
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
||||||
EndpointForbidden,
|
EndpointForbidden,
|
||||||
|
/// The response uses a content coding the client does not support.
|
||||||
|
UnsupportedContentCoding,
|
||||||
/// Another non-success HTTP response without a WIP error envelope.
|
/// Another non-success HTTP response without a WIP error envelope.
|
||||||
HttpStatus,
|
HttpStatus,
|
||||||
}
|
}
|
||||||
@@ -63,8 +65,6 @@ pub enum InvalidResponseKind {
|
|||||||
NonCanonicalSuccessStatus,
|
NonCanonicalSuccessStatus,
|
||||||
/// A 2xx body was malformed or semantically invalid.
|
/// A 2xx body was malformed or semantically invalid.
|
||||||
InvalidSuccessBody,
|
InvalidSuccessBody,
|
||||||
/// A batch response did not correlate exactly with its request.
|
|
||||||
InvalidBatch,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A local failure while classifying or validating a peer response.
|
/// A local failure while classifying or validating a peer response.
|
||||||
@@ -119,10 +119,6 @@ impl Display for ClientResponseError {
|
|||||||
impl Error for ClientResponseError {}
|
impl Error for ClientResponseError {}
|
||||||
|
|
||||||
/// Returns the canonical HTTP status for a wire-level protocol error.
|
/// Returns the canonical HTTP status for a wire-level protocol error.
|
||||||
///
|
|
||||||
/// [`ProtocolErrorCode::ResourceLimitExceeded`] defaults to the logical-limit
|
|
||||||
/// status. Use [`status_for_resource_limit`] when the concrete limit class is
|
|
||||||
/// known.
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
||||||
match code {
|
match code {
|
||||||
@@ -145,22 +141,8 @@ pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the canonical HTTP status for a concrete resource-limit class.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn status_for_resource_limit(kind: ResourceLimitKind) -> StatusCode {
|
|
||||||
match kind {
|
|
||||||
ResourceLimitKind::RepresentationBytes => StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
ResourceLimitKind::Logical => StatusCode::UNPROCESSABLE_ENTITY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||||
match code {
|
status == status_for_error(code)
|
||||||
ProtocolErrorCode::ResourceLimitExceeded => {
|
|
||||||
status == StatusCode::PAYLOAD_TOO_LARGE || status == StatusCode::UNPROCESSABLE_ENTITY
|
|
||||||
}
|
|
||||||
_ => status == status_for_error(code),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the stable snake-case wire spelling of a protocol code.
|
/// Returns the stable snake-case wire spelling of a protocol code.
|
||||||
@@ -213,14 +195,7 @@ pub(crate) fn error_to_json(error: &ProtocolError) -> Json {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn item_error_to_json(error: &ProtocolError) -> Json {
|
fn protocol_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
||||||
serde_json::json!({
|
|
||||||
"code": error_code_name(error.code),
|
|
||||||
"message": error.message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn item_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
|
||||||
let fields = value
|
let fields = value
|
||||||
.as_object()
|
.as_object()
|
||||||
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
||||||
@@ -239,7 +214,7 @@ fn envelope_error_from_json(value: &Json) -> Result<Option<ProtocolError>, Codec
|
|||||||
if fields.len() != 1 || !fields.contains_key("error") {
|
if fields.len() != 1 || !fields.contains_key("error") {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
item_error_from_json(&fields["error"]).map(Some)
|
protocol_error_from_json(&fields["error"]).map(Some)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
||||||
@@ -355,6 +330,13 @@ pub(crate) fn decode<T>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn unsupported_content_coding(status: StatusCode) -> ClientResponseError {
|
||||||
|
ClientResponseError::TransportBinding(TransportBindingFailure {
|
||||||
|
status,
|
||||||
|
kind: TransportFailureKind::UnsupportedContentCoding,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
||||||
let kind = match status {
|
let kind = match status {
|
||||||
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
||||||
|
|||||||
@@ -1,345 +0,0 @@
|
|||||||
use wip_http::http::StatusCode;
|
|
||||||
use wip_http::wip_protocol::{
|
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
|
||||||
Object, ObjectObservation, ObserveRequest, ProtocolError, ProtocolErrorCode,
|
|
||||||
};
|
|
||||||
use wip_http::{
|
|
||||||
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
|
||||||
BatchResponseItem, BatchSuccess, ClientResponseError, DecodedResponse, Endpoint,
|
|
||||||
InvalidResponseKind, Limits, ResourceLimitKind, decode_batch_request, decode_batch_response,
|
|
||||||
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
|
||||||
encode_batch_response,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn limits() -> Limits {
|
|
||||||
Limits::new(100_000, 100_000, 64, 4).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn observed_item(validator: Option<Vec<u8>>) -> ObjectObservation {
|
|
||||||
ObjectObservation {
|
|
||||||
object: Object {
|
|
||||||
name: "item".into(),
|
|
||||||
description: None,
|
|
||||||
interfaces: vec![],
|
|
||||||
r#ref: None,
|
|
||||||
validator,
|
|
||||||
},
|
|
||||||
children: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request() -> BatchRequest {
|
|
||||||
BatchRequest {
|
|
||||||
requests: vec![
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "object".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/item".into(),
|
|
||||||
depth: 0,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_round_trips_by_unique_id_with_item_failures_and_validators() {
|
|
||||||
let request = request();
|
|
||||||
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
|
||||||
let encoded_request = encode_batch_request(&endpoint, &request, limits()).unwrap();
|
|
||||||
assert_eq!(encoded_request.uri().path(), "/wip/v1/batch");
|
|
||||||
assert_eq!(encoded_request.headers()["accept"], "application/json");
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_request(encoded_request.body(), limits()).unwrap(),
|
|
||||||
request
|
|
||||||
);
|
|
||||||
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Err(ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InterfaceNotFound,
|
|
||||||
message: "gone".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(Some(vec![
|
|
||||||
0, 1, 2, 255,
|
|
||||||
])))),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), StatusCode::OK);
|
|
||||||
assert!(
|
|
||||||
std::str::from_utf8(encoded.body())
|
|
||||||
.unwrap()
|
|
||||||
.contains("AAEC/w==")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_interface_validator_round_trips_in_item_body() {
|
|
||||||
let request = BatchRequest {
|
|
||||||
requests: vec![BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Ok(BatchSuccess::FetchInterface(FetchInterfaceResponse {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
descriptor: InterfaceDescriptor {
|
|
||||||
format: INTERFACE_FORMAT_V1.into(),
|
|
||||||
documentation: None,
|
|
||||||
types: vec![],
|
|
||||||
operations: vec![],
|
|
||||||
},
|
|
||||||
validator: Some(vec![255, 254, 253]),
|
|
||||||
})),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
assert!(
|
|
||||||
std::str::from_utf8(encoded.body())
|
|
||||||
.unwrap()
|
|
||||||
.contains("//79")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn malformed_known_method_arguments_are_item_local() {
|
|
||||||
let body = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"valid","method":"observe","arguments":{"path":"/item","depth":0}},
|
|
||||||
{"id":"invalid","method":"observe","arguments":{"path":"/","depth":"deep"}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
let decoded = decode_batch_request(body, limits()).unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decoded.requests[0].request,
|
|
||||||
BatchRequestKind::Observe(_)
|
|
||||||
));
|
|
||||||
let invalid = match &decoded.requests[1].request {
|
|
||||||
BatchRequestKind::Invalid { method, error } => {
|
|
||||||
assert_eq!(*method, BatchMethod::Observe);
|
|
||||||
assert_eq!(error.code, ProtocolErrorCode::InvalidRequest);
|
|
||||||
error.clone()
|
|
||||||
}
|
|
||||||
other => panic!("expected item-local invalid request, got {other:?}"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "valid".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "invalid".into(),
|
|
||||||
outcome: Err(invalid),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&decoded, &response, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), StatusCode::OK);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&decoded, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_batch_envelopes_are_rejected_at_top_level() {
|
|
||||||
assert!(decode_batch_request(br#"{}"#, limits()).is_err());
|
|
||||||
|
|
||||||
let malformed_item = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"item","method":"observe","arguments":{"path":"/","depth":0},"extra":true}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(malformed_item, limits()).is_err());
|
|
||||||
|
|
||||||
let duplicate = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"same","method":"observe","arguments":{"path":"/a","depth":0}},
|
|
||||||
{"id":"same","method":"observe","arguments":{"path":"/b","depth":0}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(duplicate, limits()).is_err());
|
|
||||||
|
|
||||||
let operation = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"call","method":"call_operation","arguments":{}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(operation, limits()).is_err());
|
|
||||||
|
|
||||||
let too_many = Limits::new(100_000, 100_000, 64, 1).unwrap();
|
|
||||||
assert!(decode_batch_request(duplicate, too_many).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_resource_limits_use_413_or_422_and_never_429() {
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
|
||||||
message: "bounded".into(),
|
|
||||||
};
|
|
||||||
for (kind, status) in [
|
|
||||||
(
|
|
||||||
ResourceLimitKind::RepresentationBytes,
|
|
||||||
StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
),
|
|
||||||
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
|
||||||
] {
|
|
||||||
let encoded = encode_batch_resource_limit_error_response(&error, kind, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), status);
|
|
||||||
assert_ne!(encoded.status(), StatusCode::TOO_MANY_REQUESTS);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: error.clone(),
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_success_body_requires_exactly_http_200() {
|
|
||||||
let request = request();
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Err(ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InterfaceNotFound,
|
|
||||||
message: "gone".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
|
||||||
let mut noncanonical = encoded.clone();
|
|
||||||
*noncanonical.status_mut() = status;
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request, &noncanonical, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse { .. }
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn top_level_batch_errors_use_the_batch_allowed_code_set() {
|
|
||||||
let invalid = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "bad envelope".into(),
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_error_response(&invalid, limits()).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: invalid,
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
let not_found = wip_http::http::Response::builder()
|
|
||||||
.status(StatusCode::NOT_FOUND)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(br#"{"error":{"code":"not_found","message":"not a batch failure"}}"#.to_vec())
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), ¬_found, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
|
|
||||||
let duplicate = wip_http::http::Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(
|
|
||||||
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future":true}}},{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
|
||||||
.to_vec(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), &duplicate, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
let missing = wip_http::http::Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(
|
|
||||||
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
|
||||||
.to_vec(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), &missing, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
let request = BatchRequest {
|
|
||||||
requests: vec![BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request, &missing, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::UnsupportedDescriptorFormat { format }
|
|
||||||
if format == "wip-interface/2"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_response_must_have_exactly_the_requested_ids() {
|
|
||||||
let request = request();
|
|
||||||
let missing = BatchResponse {
|
|
||||||
responses: vec![BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
assert!(encode_batch_response(&request, &missing, limits()).is_err());
|
|
||||||
}
|
|
||||||
@@ -10,15 +10,15 @@ use wip_http::wip_protocol::{
|
|||||||
};
|
};
|
||||||
use wip_http::{
|
use wip_http::{
|
||||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||||
ResourceLimitKind, decode_call_operation_metadata, decode_call_operation_request,
|
decode_call_operation_metadata, decode_call_operation_request, decode_call_operation_response,
|
||||||
decode_call_operation_response, decode_fetch_interface_request,
|
decode_fetch_interface_request, decode_fetch_interface_response, decode_observe_request,
|
||||||
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
decode_observe_response, encode_call_operation_request, encode_call_operation_response,
|
||||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
encode_fetch_interface_request, encode_fetch_interface_response, encode_observe_request,
|
||||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
encode_observe_response,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(1_000_000, 1_000_000, 100, 100).unwrap()
|
Limits::new(1_000_000, 1_000_000, 100).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn endpoint() -> Endpoint {
|
fn endpoint() -> Endpoint {
|
||||||
@@ -404,25 +404,17 @@ fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn caller_limits_bound_bytes_and_nesting() {
|
fn caller_limits_remain_local_codec_failures() {
|
||||||
let tiny = Limits::new(8, 8, 2, 1).unwrap();
|
let tiny = Limits::new(8, 8, 2).unwrap();
|
||||||
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
||||||
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||||
assert_eq!(
|
|
||||||
too_large.resource_limit_kind(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes)
|
|
||||||
);
|
|
||||||
|
|
||||||
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
||||||
let nesting_limited = Limits::new(1024, 1024, 2, 1).unwrap();
|
let nesting_limited = Limits::new(1024, 1024, 2).unwrap();
|
||||||
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
||||||
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||||
assert_eq!(
|
|
||||||
too_deep.resource_limit_kind(),
|
|
||||||
Some(ResourceLimitKind::Logical)
|
|
||||||
);
|
|
||||||
|
|
||||||
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1, 10).unwrap();
|
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
encode_call_operation_request(
|
encode_call_operation_request(
|
||||||
&endpoint(),
|
&endpoint(),
|
||||||
|
|||||||
@@ -3,14 +3,13 @@ use wip_http::wip_protocol::{
|
|||||||
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
};
|
};
|
||||||
use wip_http::{
|
use wip_http::{
|
||||||
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, ResourceLimitKind,
|
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, TransportFailureKind,
|
||||||
TransportFailureKind, decode_observe_response, encode_protocol_error_response,
|
decode_observe_response, encode_protocol_error_response, error_code_name, is_json_content_type,
|
||||||
encode_resource_limit_error_response, error_code_name, is_json_content_type, status_for_error,
|
status_for_error,
|
||||||
status_for_resource_limit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 32, 16).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 32).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn request() -> ObserveRequest {
|
fn request() -> ObserveRequest {
|
||||||
@@ -120,41 +119,45 @@ fn every_protocol_code_has_stable_name_and_status() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
|
fn logical_resource_limit_uses_only_422_and_bare_413_is_transport_failure() {
|
||||||
let error = ProtocolError {
|
let error = ProtocolError {
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
message: "bounded".into(),
|
message: "logical observation limit exceeded".into(),
|
||||||
};
|
};
|
||||||
let cases = [
|
let encoded =
|
||||||
(
|
|
||||||
ResourceLimitKind::RepresentationBytes,
|
|
||||||
StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
),
|
|
||||||
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
|
||||||
];
|
|
||||||
for (kind, status) in cases {
|
|
||||||
assert_eq!(status_for_resource_limit(kind), status);
|
|
||||||
let encoded = encode_resource_limit_error_response(
|
|
||||||
ProtocolInteraction::Observe,
|
|
||||||
&error,
|
|
||||||
kind,
|
|
||||||
limits(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(encoded.status(), status);
|
|
||||||
assert_eq!(
|
|
||||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: error.clone(),
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let default =
|
|
||||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
assert_eq!(default.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
assert_eq!(encoded.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
assert_ne!(default.status(), StatusCode::TOO_MANY_REQUESTS);
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut noncanonical = encoded;
|
||||||
|
*noncanonical.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &noncanonical, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: Some(wip_http::StatusMismatch {
|
||||||
|
actual: StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
expected: StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let bare_413 = Response::builder()
|
||||||
|
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &bare_413, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::PAYLOAD_TOO_LARGE
|
||||||
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -171,6 +174,49 @@ fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_response_content_coding_is_transport_failure() {
|
||||||
|
let mut encoded = encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
encoded
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "gzip".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::NOT_FOUND
|
||||||
|
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||||
|
));
|
||||||
|
|
||||||
|
let success = response(StatusCode::OK, br#"{"object":{"name":"","interfaces":[]}}"#);
|
||||||
|
let mut identity = success.clone();
|
||||||
|
identity
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "identity".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &identity, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(_)
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut unsupported = success;
|
||||||
|
unsupported
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "br".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &unsupported, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::OK
|
||||||
|
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn valid_success_body_requires_exactly_http_200() {
|
fn valid_success_body_requires_exactly_http_200() {
|
||||||
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ fn endpoint_preserves_http_and_https_when_resolving_canonical_routes() {
|
|||||||
(Route::Observe, "v1/observe"),
|
(Route::Observe, "v1/observe"),
|
||||||
(Route::FetchInterface, "v1/fetch_interface"),
|
(Route::FetchInterface, "v1/fetch_interface"),
|
||||||
(Route::CallOperation, "v1/call_operation"),
|
(Route::CallOperation, "v1/call_operation"),
|
||||||
(Route::Batch, "v1/batch"),
|
|
||||||
];
|
];
|
||||||
for (route, suffix) in expected {
|
for (route, suffix) in expected {
|
||||||
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
|
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
|
||||||
@@ -61,7 +60,10 @@ fn inbound_http_metadata_enforces_post_route_and_json() {
|
|||||||
.header("content-type", "application/json")
|
.header("content-type", "application/json")
|
||||||
.body(Vec::<u8>::new())
|
.body(Vec::<u8>::new())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_method).is_err());
|
let error = validate_http_request(&endpoint, Route::Observe, &wrong_method).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::MethodNotAllowed));
|
||||||
|
assert_eq!(error.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
assert_eq!(error.allow(), Some("POST"));
|
||||||
|
|
||||||
let wrong_route = Request::builder()
|
let wrong_route = Request::builder()
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
@@ -69,7 +71,21 @@ fn inbound_http_metadata_enforces_post_route_and_json() {
|
|||||||
.header("content-type", "application/json")
|
.header("content-type", "application/json")
|
||||||
.body(Vec::<u8>::new())
|
.body(Vec::<u8>::new())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_route).is_err());
|
let error = validate_http_request(&endpoint, Route::Observe, &wrong_route).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::NotFound));
|
||||||
|
assert_eq!(error.status(), StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(error.allow(), None);
|
||||||
|
|
||||||
|
let query_and_wrong_method = Request::builder()
|
||||||
|
.method(Method::GET)
|
||||||
|
.uri("/wip/v1/observe?unexpected=true")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &query_and_wrong_method).unwrap_err(),
|
||||||
|
RequestMetadataError::NotFound
|
||||||
|
));
|
||||||
|
|
||||||
for accept in [
|
for accept in [
|
||||||
"text/plain, */*;q=1, application/json;q=0",
|
"text/plain, */*;q=1, application/json;q=0",
|
||||||
@@ -114,6 +130,29 @@ fn inbound_http_metadata_enforces_post_route_and_json() {
|
|||||||
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
||||||
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||||
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
|
||||||
|
for coding in ["gzip", "identity, gzip"] {
|
||||||
|
let unsupported_coding = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("content-encoding", coding)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &unsupported_coding).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||||
|
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
let identity_coding = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("content-encoding", "identity")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &identity_coding).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -130,6 +169,7 @@ fn invalid_endpoint_components_and_non_routes_are_rejected() {
|
|||||||
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
|
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
|
||||||
for outside in [
|
for outside in [
|
||||||
"http://example.test/wip/v1/unknown",
|
"http://example.test/wip/v1/unknown",
|
||||||
|
"http://example.test/wip/v1/batch",
|
||||||
"http://example.test/wip/v1/observe/extra",
|
"http://example.test/wip/v1/observe/extra",
|
||||||
"https://example.test/wip/v1/observe",
|
"https://example.test/wip/v1/observe",
|
||||||
"http://other.test/wip/v1/observe",
|
"http://other.test/wip/v1/observe",
|
||||||
|
|||||||
@@ -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,14 @@
|
|||||||
|
# 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"
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
[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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -939,7 +939,7 @@ mod tests {
|
|||||||
// A request identity has no public constructor; derive one through the runtime.
|
// A request identity has no public constructor; derive one through the runtime.
|
||||||
let mut client = wip_client::Client::new(
|
let mut client = wip_client::Client::new(
|
||||||
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
||||||
wip_http::Limits::new(1024, 1024, 8, 8).unwrap(),
|
wip_http::Limits::new(1024, 1024, 8).unwrap(),
|
||||||
);
|
);
|
||||||
let session = client
|
let session = client
|
||||||
.open_session(
|
.open_session(
|
||||||
|
|||||||
@@ -862,8 +862,7 @@ fn collect_entries_at(
|
|||||||
/// Standard bounded wire policy used by the executable and integration tests.
|
/// Standard bounded wire policy used by the executable and integration tests.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn default_wire_limits() -> Limits {
|
pub fn default_wire_limits() -> Limits {
|
||||||
Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
Limits::new(256 * 1024, 2 * 1024 * 1024, 64).expect("static runtime wire limits are nonzero")
|
||||||
.expect("static runtime wire limits are nonzero")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the interactive executable using process configuration.
|
/// Runs the interactive executable using process configuration.
|
||||||
|
|||||||
Reference in New Issue
Block a user