Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de82b66de4 | ||
|
|
db2a51c824 | ||
|
|
347b92b28a | ||
|
|
780150d7ae | ||
|
|
f5034c0e4b | ||
|
|
df51da3d03 | ||
|
|
fdfaa3a685 |
Generated
+821
-3
File diff suppressed because it is too large
Load Diff
@@ -6,11 +6,23 @@ The repository is a resolver-3 virtual Cargo workspace whose packages all live
|
|||||||
under `crates/*`. It provides a transport-independent protocol model, the
|
under `crates/*`. It provides a transport-independent protocol model, the
|
||||||
standard framework-independent WIP over HTTPS v1 binding, a stateful
|
standard framework-independent WIP over HTTPS v1 binding, a stateful
|
||||||
presentation-independent client runtime, a Rust interface-authoring facade, a
|
presentation-independent client runtime, a Rust interface-authoring facade, a
|
||||||
request-scoped host runtime, and a private public-API conformance consumer. The
|
request-scoped host runtime, a bounded Linux filesystem projection server, an
|
||||||
|
interactive terminal client, and a private public-API conformance consumer. The
|
||||||
repository root is not itself a package.
|
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)
|
||||||
|
├── wip-client Known Space, request identity, validators, and calls
|
||||||
|
├── wip-https framework-neutral HTTP request/response messages
|
||||||
|
└── wip-protocol descriptors and logical values
|
||||||
|
|
||||||
|
wip-fs-server (request-time filesystem projection and loopback listener)
|
||||||
|
├── wip-https standard routes/codecs/envelopes/batching
|
||||||
|
├── wip-host request-scoped publication and dispatch
|
||||||
|
└── wip-interface macro-generated filesystem capabilities
|
||||||
|
|
||||||
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
||||||
├── wip-protocol logical declarations, values, calls, and validation
|
├── wip-protocol logical declarations, values, calls, and validation
|
||||||
├── wip-https standard HTTPS v1 routes, JSON codecs, envelopes, and batching
|
├── wip-https standard HTTPS v1 routes, JSON codecs, envelopes, and batching
|
||||||
@@ -31,9 +43,11 @@ wip-public-api-example (workspace-only executable, integration tests, doctest)
|
|||||||
| `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-https` | Standard HTTPS v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, TLS termination, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
| `wip-https` | Standard HTTPS v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, TLS termination, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
||||||
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, lazy entry trees, 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, lazy entry trees, 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 HTTPS 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, and interface-qualified dispatch against one host-owned instance. | 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, bounded BFS trees and file operations, standard `wip-https` dispatch/batch handling, and a loopback HTTP binary for TLS-proxy or explicit development use. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, 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. |
|
||||||
|
|
||||||
The boundary is intentional: protocol types describe what can cross a
|
The boundary is intentional: protocol types describe what can cross a
|
||||||
@@ -242,6 +256,29 @@ rolled back. Without that proof, post-invocation failures remain
|
|||||||
comparison and backend commit atomic and return a validator describing the state
|
comparison and backend commit atomic and return a validator describing the state
|
||||||
that becomes committed.
|
that becomes committed.
|
||||||
|
|
||||||
|
## Interactive terminal client
|
||||||
|
|
||||||
|
[`crates/wip-tui`](crates/wip-tui) provides the `wip-tui` executable. It starts
|
||||||
|
from Worldspace `/`, lazily expands materialized tree nodes, displays current
|
||||||
|
object/interface/operation metadata, validates all canonical descriptor types in
|
||||||
|
a field editor, and requires a separate confirmation action before every call.
|
||||||
|
It uses the stateful `wip-client` runtime for request correlation, observed
|
||||||
|
validators, stale transitions, and unknown outcomes. HTTPS is the default;
|
||||||
|
loopback plain HTTP requires `--allow-http`. Full startup, TLS, key binding,
|
||||||
|
layout, validator, and filesystem-operation examples are in the
|
||||||
|
[package README](crates/wip-tui/README.md).
|
||||||
|
|
||||||
|
## Filesystem projection server
|
||||||
|
|
||||||
|
[`crates/wip-fs-server`](crates/wip-fs-server) contains the practical server
|
||||||
|
binary and its full security model, configuration, curl walkthrough, and
|
||||||
|
resource/failure semantics. It resolves every object from current filesystem
|
||||||
|
state, uses pinned directory-relative handles without following symlinks, omits
|
||||||
|
non-UTF-8 backend names, performs bounded breadth-first tree discovery, and
|
||||||
|
publishes validator-protected replacement only in explicit read-write mode.
|
||||||
|
The built-in cleartext listener is loopback-only: production HTTPS is explicitly
|
||||||
|
delegated to a reverse proxy, while local plain HTTP requires an opt-in flag.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
Enter the dev shell and run the acceptance commands exactly:
|
Enter the dev shell and run the acceptance commands exactly:
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-fs-server"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Request-time filesystem projection server for WIP over HTTPS"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
http = "1"
|
||||||
|
rustix = { version = "1.1", features = ["fs"] }
|
||||||
|
wip-host = { path = "../wip-host" }
|
||||||
|
wip-https = { path = "../wip-https" }
|
||||||
|
wip-interface = { path = "../wip-interface" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# wip-fs-server
|
||||||
|
|
||||||
|
`wip-fs-server` projects one configured Linux filesystem directory onto WIP
|
||||||
|
Worldspace `/` at request time. It does not register the filesystem contents or
|
||||||
|
keep one object instance per entry. It uses `wip-host` for publication and typed
|
||||||
|
operation dispatch and uses the standard `wip-https` routes, JSON codecs,
|
||||||
|
envelopes, batching, and HTTP status mapping.
|
||||||
|
|
||||||
|
## Security model
|
||||||
|
|
||||||
|
- The effective root is opened once as a directory capability. Root path
|
||||||
|
components must be real directories (symlink components are rejected), and the
|
||||||
|
displayed effective root is read back from that same pinned descriptor. Every
|
||||||
|
request is resolved segment-by-segment with directory-relative, `O_NOFOLLOW`
|
||||||
|
handles.
|
||||||
|
- Symlinks are projected as links and are never followed. Their stored target is
|
||||||
|
available only through the `SymlinkInspect.read_link` application operation.
|
||||||
|
- Regular files, directories, symlinks, and unsupported entry types have distinct
|
||||||
|
public descriptions and capability sets.
|
||||||
|
- WIP names are Unicode. Linux names that are not valid UTF-8 are deliberately
|
||||||
|
not published; valid UTF-8 names map byte-for-byte and therefore cannot collide.
|
||||||
|
Unicode paths containing backend-invalid NUL bytes are likewise treated as
|
||||||
|
unpublished rather than as backend failures.
|
||||||
|
- No object `ref` is issued. This avoids claiming representation identity for
|
||||||
|
hard links or path-specific names. Regular files and symlinks receive an opaque
|
||||||
|
validator containing filesystem identity plus protected metadata; replacing a
|
||||||
|
path therefore does not preserve its validator.
|
||||||
|
- Protocol metadata and errors never contain the backend absolute path. Startup
|
||||||
|
prints only the explicitly configured effective root and security-sensitive
|
||||||
|
modes.
|
||||||
|
- The built-in listener is cleartext and loopback-only. Production deployments
|
||||||
|
must pass `--behind-tls-proxy` and terminate HTTPS at a trusted reverse proxy.
|
||||||
|
Plain development HTTP requires the explicit `--development-http` flag.
|
||||||
|
|
||||||
|
The implementation currently targets Linux because it uses `O_PATH`,
|
||||||
|
directory-relative descriptor traversal, and `/proc/self/fd` to reopen the same
|
||||||
|
pinned backend object without resolving the untrusted Worldspace path twice.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
Read-only behind a TLS-terminating reverse proxy:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root /srv/public-files \
|
||||||
|
--listen 127.0.0.1:8443 \
|
||||||
|
--base-path /wip \
|
||||||
|
--behind-tls-proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
Local development with the write capability deliberately enabled:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root ./example-files \
|
||||||
|
--listen 127.0.0.1:8080 \
|
||||||
|
--base-path /wip \
|
||||||
|
--development-http \
|
||||||
|
--read-write
|
||||||
|
```
|
||||||
|
|
||||||
|
The server reports the effective root, `ReadOnly`/`ReadWrite` mode, transport
|
||||||
|
mode, endpoint, and actual listen address. It does not enumerate the root.
|
||||||
|
|
||||||
|
## Standard interactions
|
||||||
|
|
||||||
|
The following examples use development HTTP for readability. The JSON is the
|
||||||
|
standard `wip-https` profile; validators and operation `Bytes` are base64 body
|
||||||
|
fields, never `ETag` or `If-Match` headers.
|
||||||
|
|
||||||
|
Fetch root:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"path":"/"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Fetch a bounded tree (the root counts toward `limit`):
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_tree \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"path":"/","depth":2,"limit":100}'
|
||||||
|
```
|
||||||
|
|
||||||
|
A regular-file fetch returns the opaque read interface reference and an object
|
||||||
|
validator. Retrieve that descriptor with:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_interface \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{"interface":"<read-interface-from-fetch>"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Then call a bounded range read:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{
|
||||||
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
|
"interface":{"reference":"<read-interface>"},
|
||||||
|
"operation":"read",
|
||||||
|
"arguments":{"offset":0,"length":4096}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
In `--read-write` mode a second regular-file interface declares `replace`.
|
||||||
|
Writes require the current object validator and return the post-write validator:
|
||||||
|
|
||||||
|
```console
|
||||||
|
curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
||||||
|
-H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||||
|
--data '{
|
||||||
|
"target":{"path":"/notes.txt","validator":"<base64-validator>"},
|
||||||
|
"interface":{"reference":"<write-interface>"},
|
||||||
|
"operation":"replace",
|
||||||
|
"arguments":{"contents":"dXBkYXRlZA=="}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`fetch`, `fetch_tree`, and `fetch_interface` can also be combined through the
|
||||||
|
standard `POST /wip/v1/batch` route. `call_operation` is never batchable.
|
||||||
|
|
||||||
|
## Resource and failure behavior
|
||||||
|
|
||||||
|
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
||||||
|
nesting, batch items, file read/write bytes, tree depth/node count, pinned handles,
|
||||||
|
and active connections/requests. One absolute request deadline covers header and
|
||||||
|
body intake, dispatch, cooperative filesystem work, and response transmission;
|
||||||
|
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
||||||
|
accept connections directly, so the listener never moves more than the configured
|
||||||
|
concurrency into active userspace service. Advisory file-lock acquisition uses a
|
||||||
|
nonblocking loop and checks the same deadline/cancellation rather than allowing a
|
||||||
|
contended lock to stall a worker. Tree traversal is breadth-first and opens only
|
||||||
|
requested entries. Once a limit or depth boundary is reached it reads only far
|
||||||
|
enough to
|
||||||
|
prove whether an additional visible child exists, so `truncated` is true only
|
||||||
|
when something was actually omitted. I/O failure and cancellation remain errors,
|
||||||
|
not clean exhaustion.
|
||||||
|
|
||||||
|
Whole-file replacement compares the request validator against the identity and
|
||||||
|
state of the same pinned file handle used for the write. Failures before mutation
|
||||||
|
carry a `NotCommitted` guarantee and map to `Internal` or
|
||||||
|
`ResourceLimitExceeded`; a failure after truncation/write begins maps to
|
||||||
|
`OperationOutcomeUnknown`. The server and Clients do not automatically retry
|
||||||
|
side-effecting operations.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
//! Filesystem capability interfaces published by the projection.
|
||||||
|
|
||||||
|
use wip_interface as wip;
|
||||||
|
|
||||||
|
/// Bounded reads from a regular file.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait FileRead {
|
||||||
|
/// Reads bytes from the current regular file.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// At most the configured read limit, beginning at `offset`.
|
||||||
|
fn read(
|
||||||
|
&self,
|
||||||
|
/// Byte offset; omitted means zero.
|
||||||
|
offset: Option<u64>,
|
||||||
|
/// Requested byte count; omitted means the rest of the file.
|
||||||
|
length: Option<u64>,
|
||||||
|
) -> wip::OperationResult<wip::Bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inspection operations for a symbolic link itself.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait SymlinkInspect {
|
||||||
|
/// Reads the link payload without following it.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// The platform path bytes stored in the symbolic link.
|
||||||
|
fn read_link(&self) -> wip::OperationResult<wip::Bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicitly enabled mutation of a regular file.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait FileWrite {
|
||||||
|
/// Replaces the current regular file contents through its pinned handle.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// Unit after the new bytes have been written and synchronized.
|
||||||
|
fn replace(
|
||||||
|
&self,
|
||||||
|
/// Complete replacement contents.
|
||||||
|
contents: wip::Bytes,
|
||||||
|
) -> wip::OperationResult<()>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
//! Request-time filesystem projection served through the standard WIP HTTPS binding.
|
||||||
|
//!
|
||||||
|
//! This crate deliberately keeps the boundaries visible:
|
||||||
|
//!
|
||||||
|
//! - [`wip_protocol`] owns logical requests and responses;
|
||||||
|
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
||||||
|
//! - [`wip_https`] owns routes, JSON, envelopes, batching, and status mapping;
|
||||||
|
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
||||||
|
//!
|
||||||
|
//! TLS is terminated by an explicitly configured reverse proxy. The built-in
|
||||||
|
//! listener accepts cleartext only on loopback, either behind that proxy or when
|
||||||
|
//! [`TransportSecurity::DevelopmentHttp`] is deliberately selected.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
mod interfaces;
|
||||||
|
mod projection;
|
||||||
|
mod server;
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub use interfaces::{FileRead, FileWrite, SymlinkInspect};
|
||||||
|
pub use server::{BoundServer, ServerBuildError, WipFsServer};
|
||||||
|
|
||||||
|
/// Filesystem capabilities published by regular files.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AccessMode {
|
||||||
|
/// Publish bounded reads only.
|
||||||
|
ReadOnly,
|
||||||
|
/// Also publish validator-protected whole-file replacement.
|
||||||
|
ReadWrite,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How HTTPS is provided for the endpoint.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TransportSecurity {
|
||||||
|
/// A trusted reverse proxy terminates TLS and forwards to the loopback listener.
|
||||||
|
ReverseProxyTls,
|
||||||
|
/// Cleartext HTTP is deliberately enabled for local development only.
|
||||||
|
DevelopmentHttp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct ResourceLimits {
|
||||||
|
/// Standard JSON, body-size, nesting, and batch limits.
|
||||||
|
pub wire: wip_https::Limits,
|
||||||
|
/// Maximum bytes returned by one file read.
|
||||||
|
pub max_file_read_bytes: usize,
|
||||||
|
/// Maximum bytes accepted by one file replacement.
|
||||||
|
pub max_file_write_bytes: usize,
|
||||||
|
/// Maximum accepted `fetch_tree` depth.
|
||||||
|
pub max_tree_depth: u32,
|
||||||
|
/// Maximum accepted `fetch_tree` node count, including its root.
|
||||||
|
pub max_tree_nodes: u32,
|
||||||
|
/// Maximum simultaneously pinned projected filesystem handles.
|
||||||
|
pub max_open_handles: usize,
|
||||||
|
/// Maximum bytes accepted for one HTTP request head, including its terminator.
|
||||||
|
pub max_http_header_bytes: usize,
|
||||||
|
/// Maximum requests executing concurrently.
|
||||||
|
pub max_concurrent_requests: usize,
|
||||||
|
/// End-to-end deadline for HTTP intake, dispatch, and response transmission.
|
||||||
|
pub request_timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ResourceLimits {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
wire: wip_https::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
||||||
|
.expect("default wire limits are nonzero"),
|
||||||
|
max_file_read_bytes: 1024 * 1024,
|
||||||
|
max_file_write_bytes: 1024 * 1024,
|
||||||
|
max_tree_depth: 32,
|
||||||
|
max_tree_nodes: 1024,
|
||||||
|
max_open_handles: 2048,
|
||||||
|
max_http_header_bytes: 16 * 1024,
|
||||||
|
max_concurrent_requests: 32,
|
||||||
|
request_timeout: Duration::from_secs(30),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Complete listener and projection configuration.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
/// Filesystem directory projected as Worldspace `/`.
|
||||||
|
pub root: PathBuf,
|
||||||
|
/// Loopback socket used by the built-in cleartext listener.
|
||||||
|
pub listen: SocketAddr,
|
||||||
|
/// URL path prefix below which standard `v1/*` routes are mounted.
|
||||||
|
pub endpoint_base_path: String,
|
||||||
|
/// Read-only or explicit read-write publication mode.
|
||||||
|
pub access: AccessMode,
|
||||||
|
/// TLS termination or explicit development HTTP policy.
|
||||||
|
pub transport_security: TransportSecurity,
|
||||||
|
/// Request, operation, traversal, and concurrency bounds.
|
||||||
|
pub limits: ResourceLimits,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServerConfig {
|
||||||
|
/// Builds a secure-by-default configuration for `root`.
|
||||||
|
///
|
||||||
|
/// The listener defaults to an ephemeral loopback port, read-only access,
|
||||||
|
/// and TLS termination delegated to a reverse proxy.
|
||||||
|
#[must_use]
|
||||||
|
pub fn for_root(root: impl Into<PathBuf>) -> Self {
|
||||||
|
Self {
|
||||||
|
root: root.into(),
|
||||||
|
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
||||||
|
endpoint_base_path: "/wip".into(),
|
||||||
|
access: AccessMode::ReadOnly,
|
||||||
|
transport_security: TransportSecurity::ReverseProxyTls,
|
||||||
|
limits: ResourceLimits::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
if !self.listen.ip().is_loopback() {
|
||||||
|
return Err(ConfigError::NonLoopbackCleartext);
|
||||||
|
}
|
||||||
|
if !valid_base_path(&self.endpoint_base_path) {
|
||||||
|
return Err(ConfigError::InvalidBasePath);
|
||||||
|
}
|
||||||
|
if self.limits.max_file_read_bytes == 0
|
||||||
|
|| self.limits.max_file_write_bytes == 0
|
||||||
|
|| self.limits.max_tree_nodes == 0
|
||||||
|
|| self.limits.max_open_handles == 0
|
||||||
|
|| self.limits.max_http_header_bytes == 0
|
||||||
|
|| self.limits.max_concurrent_requests == 0
|
||||||
|
|| self.limits.request_timeout.is_zero()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::ZeroLimit);
|
||||||
|
}
|
||||||
|
if self.limits.max_open_handles < self.limits.max_tree_nodes as usize {
|
||||||
|
return Err(ConfigError::InsufficientHandles);
|
||||||
|
}
|
||||||
|
if self.limits.wire.max_response_bytes() < 512 {
|
||||||
|
return Err(ConfigError::ResponseLimitTooSmall);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn endpoint(&self) -> Result<wip_https::Endpoint, ConfigError> {
|
||||||
|
let endpoint = format!("https://localhost{}", self.endpoint_base_path);
|
||||||
|
wip_https::Endpoint::parse(&endpoint).map_err(|_| ConfigError::InvalidBasePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalid server configuration.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
/// The cleartext built-in listener was exposed beyond loopback.
|
||||||
|
NonLoopbackCleartext,
|
||||||
|
/// The endpoint prefix is not an absolute canonical URL path.
|
||||||
|
InvalidBasePath,
|
||||||
|
/// A resource limit is zero.
|
||||||
|
ZeroLimit,
|
||||||
|
/// Tree nodes could exhaust the configured handle ceiling by construction.
|
||||||
|
InsufficientHandles,
|
||||||
|
/// The response limit cannot reliably carry a bounded protocol error envelope.
|
||||||
|
ResponseLimitTooSmall,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ConfigError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
formatter.write_str(match self {
|
||||||
|
Self::NonLoopbackCleartext => "the built-in cleartext listener must bind to loopback",
|
||||||
|
Self::InvalidBasePath => {
|
||||||
|
"endpoint base path must be absolute, canonical, and query-free"
|
||||||
|
}
|
||||||
|
Self::ZeroLimit => "all resource limits and the request timeout must be nonzero",
|
||||||
|
Self::InsufficientHandles => "max_open_handles must cover max_tree_nodes",
|
||||||
|
Self::ResponseLimitTooSmall => "max_response_bytes must be at least 512",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ConfigError {}
|
||||||
|
|
||||||
|
fn valid_base_path(path: &str) -> bool {
|
||||||
|
path.starts_with('/')
|
||||||
|
&& !path.contains('?')
|
||||||
|
&& !path.contains('#')
|
||||||
|
&& !path.contains("//")
|
||||||
|
&& !path
|
||||||
|
.split('/')
|
||||||
|
.any(|segment| segment == "." || segment == "..")
|
||||||
|
&& (path == "/" || !path.ends_with('/'))
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let mut root: Option<PathBuf> = None;
|
||||||
|
let mut listen: SocketAddr = "127.0.0.1:8443".parse()?;
|
||||||
|
let mut base_path = "/wip".to_owned();
|
||||||
|
let mut access = AccessMode::ReadOnly;
|
||||||
|
let mut security = None;
|
||||||
|
let mut arguments = std::env::args().skip(1);
|
||||||
|
while let Some(argument) = arguments.next() {
|
||||||
|
match argument.as_str() {
|
||||||
|
"--root" => root = Some(PathBuf::from(required_value(&mut arguments, "--root")?)),
|
||||||
|
"--listen" => listen = required_value(&mut arguments, "--listen")?.parse()?,
|
||||||
|
"--base-path" => base_path = required_value(&mut arguments, "--base-path")?,
|
||||||
|
"--read-write" => access = AccessMode::ReadWrite,
|
||||||
|
"--development-http" => {
|
||||||
|
set_security(&mut security, TransportSecurity::DevelopmentHttp)?
|
||||||
|
}
|
||||||
|
"--behind-tls-proxy" => {
|
||||||
|
set_security(&mut security, TransportSecurity::ReverseProxyTls)?
|
||||||
|
}
|
||||||
|
"--help" | "-h" => {
|
||||||
|
print_help();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
unknown => return Err(format!("unknown argument `{unknown}`; use --help").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let root = root.ok_or("--root is required")?;
|
||||||
|
let transport_security =
|
||||||
|
security.ok_or("select exactly one of --behind-tls-proxy or --development-http")?;
|
||||||
|
let mut config = ServerConfig::for_root(root);
|
||||||
|
config.listen = listen;
|
||||||
|
config.endpoint_base_path = base_path;
|
||||||
|
config.access = access;
|
||||||
|
config.transport_security = transport_security;
|
||||||
|
|
||||||
|
let server = WipFsServer::new(config)?;
|
||||||
|
let effective_root = server.effective_root().to_owned();
|
||||||
|
let endpoint = server.endpoint().clone();
|
||||||
|
let bound = server.bind()?;
|
||||||
|
eprintln!(
|
||||||
|
"wip-fs-server root={} access={access:?} transport={transport_security:?} endpoint={} listen={}",
|
||||||
|
effective_root.display(),
|
||||||
|
endpoint,
|
||||||
|
bound.local_addr()
|
||||||
|
);
|
||||||
|
bound.serve()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_value(
|
||||||
|
arguments: &mut impl Iterator<Item = String>,
|
||||||
|
option: &str,
|
||||||
|
) -> Result<String, Box<dyn Error>> {
|
||||||
|
arguments
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| format!("{option} requires a value").into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_security(
|
||||||
|
security: &mut Option<TransportSecurity>,
|
||||||
|
value: TransportSecurity,
|
||||||
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
if security.replace(value).is_some() {
|
||||||
|
Err("select only one transport-security mode".into())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_help() {
|
||||||
|
println!(
|
||||||
|
"Usage: wip-fs-server --root PATH [--listen 127.0.0.1:8443] \\\n [--base-path /wip] [--read-write] \\\n (--behind-tls-proxy | --development-http)\n\n\
|
||||||
|
The built-in listener is cleartext and loopback-only. In production, \
|
||||||
|
select --behind-tls-proxy and terminate HTTPS at a trusted reverse proxy."
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,747 @@
|
|||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use http::{Request, Response, StatusCode};
|
||||||
|
use wip_host::{ExecutionContext, ObjectProvider};
|
||||||
|
use wip_https::{
|
||||||
|
BatchRequestKind, BatchResponse, BatchResponseItem, BatchSuccess, CodecError, EncodeHttpError,
|
||||||
|
Endpoint, RequestMetadataError, ResourceLimitKind, Route, decode_batch_request,
|
||||||
|
decode_call_operation_metadata, decode_fetch_interface_request, decode_fetch_request,
|
||||||
|
decode_fetch_tree_request, encode_batch_error_response,
|
||||||
|
encode_batch_resource_limit_error_response, encode_batch_response,
|
||||||
|
encode_call_operation_response, encode_fetch_interface_response, encode_fetch_response,
|
||||||
|
encode_fetch_tree_response, encode_protocol_error_response,
|
||||||
|
encode_resource_limit_error_response, validate_http_request,
|
||||||
|
};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
|
use crate::projection::Projection;
|
||||||
|
use crate::{ConfigError, ServerConfig};
|
||||||
|
|
||||||
|
/// Filesystem projection and framework-neutral standard WIP request adapter.
|
||||||
|
pub struct WipFsServer {
|
||||||
|
config: ServerConfig,
|
||||||
|
endpoint: Endpoint,
|
||||||
|
effective_root: std::path::PathBuf,
|
||||||
|
projection: Arc<Projection>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WipFsServer {
|
||||||
|
/// Validates configuration and opens the configured directory capability.
|
||||||
|
pub fn new(config: ServerConfig) -> Result<Self, ServerBuildError> {
|
||||||
|
config.validate()?;
|
||||||
|
let endpoint = config.endpoint()?;
|
||||||
|
let projection = Projection::open(&config.root, config.access, config.limits)?;
|
||||||
|
let effective_root = projection.effective_root()?;
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
endpoint,
|
||||||
|
effective_root,
|
||||||
|
projection: Arc::new(projection),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical effective filesystem root opened by the server.
|
||||||
|
#[must_use]
|
||||||
|
pub fn effective_root(&self) -> &std::path::Path {
|
||||||
|
&self.effective_root
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the configured transport endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub fn endpoint(&self) -> &Endpoint {
|
||||||
|
&self.endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles one already-buffered HTTP request with the standard `wip-https` codecs.
|
||||||
|
///
|
||||||
|
/// Listener integrations must enforce the same body limit while collecting bytes.
|
||||||
|
#[must_use]
|
||||||
|
pub fn handle_http(&self, request: Request<Vec<u8>>) -> Response<Vec<u8>> {
|
||||||
|
self.handle_http_with_deadline(request, Instant::now() + self.config.limits.request_timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_http_with_deadline(
|
||||||
|
&self,
|
||||||
|
request: Request<Vec<u8>>,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let Some(route) = self.route(request.uri().path()) else {
|
||||||
|
return empty_response(StatusCode::NOT_FOUND);
|
||||||
|
};
|
||||||
|
if let Err(error) = validate_http_request(&self.endpoint, route, &request) {
|
||||||
|
return self.metadata_error(route, error);
|
||||||
|
}
|
||||||
|
let context = ExecutionContext::new()
|
||||||
|
.with_deadline(deadline)
|
||||||
|
.with_resource_budget(u64::from(self.config.limits.max_tree_nodes));
|
||||||
|
match route {
|
||||||
|
Route::Fetch => self.fetch(request.body(), &context),
|
||||||
|
Route::FetchTree => self.fetch_tree(request.body(), &context),
|
||||||
|
Route::FetchInterface => self.fetch_interface(request.body()),
|
||||||
|
Route::CallOperation => self.call_operation(request.body(), &context),
|
||||||
|
Route::Batch => self.batch(request.body(), &context),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Binds the built-in bounded loopback HTTP listener.
|
||||||
|
///
|
||||||
|
/// The listener is cleartext by design. Configuration must explicitly state
|
||||||
|
/// whether TLS is terminated by a reverse proxy or development HTTP is in use.
|
||||||
|
pub fn bind(self) -> Result<BoundServer, ServerBuildError> {
|
||||||
|
let listener = TcpListener::bind(self.config.listen)
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
listener
|
||||||
|
.set_nonblocking(true)
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
let local_addr = listener
|
||||||
|
.local_addr()
|
||||||
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
|
Ok(BoundServer {
|
||||||
|
local_addr,
|
||||||
|
service: Arc::new(self),
|
||||||
|
listener: Arc::new(listener),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(&self, path: &str) -> Option<Route> {
|
||||||
|
[
|
||||||
|
Route::Fetch,
|
||||||
|
Route::FetchTree,
|
||||||
|
Route::FetchInterface,
|
||||||
|
Route::CallOperation,
|
||||||
|
Route::Batch,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|route| self.endpoint.route(*route).path() == path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
|
let request = match decode_fetch_request(body, self.config.limits.wire) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return self.codec_error(ProtocolInteraction::Fetch, error),
|
||||||
|
};
|
||||||
|
match self
|
||||||
|
.projection
|
||||||
|
.fetch_with_context(context, &request.path)
|
||||||
|
.map_err(|error| error.protocol_error())
|
||||||
|
{
|
||||||
|
Ok(object) => encode_fetch_response(&request, &object, self.config.limits.wire)
|
||||||
|
.unwrap_or_else(|error| self.read_encode_error(ProtocolInteraction::Fetch, error)),
|
||||||
|
Err(error) => self.protocol_error(ProtocolInteraction::Fetch, &error, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch_tree(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
|
let request = match decode_fetch_tree_request(body, self.config.limits.wire) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return self.codec_error(ProtocolInteraction::FetchTree, error),
|
||||||
|
};
|
||||||
|
match self.projection.fetch_tree(context, &request) {
|
||||||
|
Ok(tree) => encode_fetch_tree_response(&request, &tree, self.config.limits.wire)
|
||||||
|
.unwrap_or_else(|error| {
|
||||||
|
self.read_encode_error(ProtocolInteraction::FetchTree, error)
|
||||||
|
}),
|
||||||
|
Err(error) => self.protocol_error(ProtocolInteraction::FetchTree, &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::Fetch(request) => self
|
||||||
|
.projection
|
||||||
|
.fetch_with_context(context, &request.path)
|
||||||
|
.map(BatchSuccess::Fetch)
|
||||||
|
.map_err(|error| error.protocol_error()),
|
||||||
|
BatchRequestKind::FetchTree(request) => self
|
||||||
|
.projection
|
||||||
|
.fetch_tree(context, request)
|
||||||
|
.map(BatchSuccess::FetchTree),
|
||||||
|
BatchRequestKind::FetchInterface(request) => self
|
||||||
|
.projection
|
||||||
|
.fetch_interface(request)
|
||||||
|
.map(BatchSuccess::FetchInterface),
|
||||||
|
BatchRequestKind::Invalid { error, .. } => Err(error.clone()),
|
||||||
|
};
|
||||||
|
BatchResponseItem {
|
||||||
|
id: item.id.clone(),
|
||||||
|
outcome,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let response = BatchResponse { responses };
|
||||||
|
encode_batch_response(&request, &response, self.config.limits.wire).unwrap_or_else(
|
||||||
|
|error| match error {
|
||||||
|
EncodeHttpError::Codec(codec) => self.batch_codec_error(codec),
|
||||||
|
EncodeHttpError::Http(_) => self.batch_top_error(&internal_error(), None),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn metadata_error(&self, route: Route, error: RequestMetadataError) -> Response<Vec<u8>> {
|
||||||
|
match error {
|
||||||
|
RequestMetadataError::InvalidRequest(_) => self.protocol_error(
|
||||||
|
interaction(route),
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "invalid HTTP request metadata".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
RequestMetadataError::UnsupportedMediaType => {
|
||||||
|
empty_response(StatusCode::UNSUPPORTED_MEDIA_TYPE)
|
||||||
|
}
|
||||||
|
RequestMetadataError::NotAcceptable => empty_response(StatusCode::NOT_ACCEPTABLE),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codec_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: CodecError,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
if let Some(kind) = error.resource_limit_kind() {
|
||||||
|
self.protocol_error(interaction, &resource_error(), Some(kind))
|
||||||
|
} else {
|
||||||
|
self.protocol_error(
|
||||||
|
interaction,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "malformed WIP request".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch_codec_error(&self, error: CodecError) -> Response<Vec<u8>> {
|
||||||
|
if let Some(kind) = error.resource_limit_kind() {
|
||||||
|
self.batch_top_error(&resource_error(), Some(kind))
|
||||||
|
} else {
|
||||||
|
self.batch_top_error(
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "malformed WIP batch request".into(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_encode_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: EncodeHttpError,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
match error {
|
||||||
|
EncodeHttpError::Codec(codec) if codec.resource_limit_kind().is_some() => {
|
||||||
|
self.protocol_error(interaction, &resource_error(), codec.resource_limit_kind())
|
||||||
|
}
|
||||||
|
_ => self.protocol_error(interaction, &internal_error(), None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn protocol_error(
|
||||||
|
&self,
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
resource_kind: Option<ResourceLimitKind>,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let encoded = match resource_kind {
|
||||||
|
Some(kind) => encode_resource_limit_error_response(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
kind,
|
||||||
|
self.config.limits.wire,
|
||||||
|
),
|
||||||
|
None => encode_protocol_error_response(interaction, error, self.config.limits.wire),
|
||||||
|
};
|
||||||
|
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch_top_error(
|
||||||
|
&self,
|
||||||
|
error: &ProtocolError,
|
||||||
|
resource_kind: Option<ResourceLimitKind>,
|
||||||
|
) -> Response<Vec<u8>> {
|
||||||
|
let encoded = match resource_kind {
|
||||||
|
Some(kind) => {
|
||||||
|
encode_batch_resource_limit_error_response(error, kind, self.config.limits.wire)
|
||||||
|
}
|
||||||
|
None => encode_batch_error_response(error, self.config.limits.wire),
|
||||||
|
};
|
||||||
|
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bound real HTTP listener for a [`WipFsServer`].
|
||||||
|
pub struct BoundServer {
|
||||||
|
local_addr: SocketAddr,
|
||||||
|
service: Arc<WipFsServer>,
|
||||||
|
listener: Arc<TcpListener>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundServer {
|
||||||
|
/// Returns the actual bound loopback address, including an assigned port.
|
||||||
|
#[must_use]
|
||||||
|
pub fn local_addr(&self) -> SocketAddr {
|
||||||
|
self.local_addr
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves requests with a fixed worker count until `shutdown` becomes true.
|
||||||
|
///
|
||||||
|
/// Workers accept connections directly, so at most
|
||||||
|
/// `max_concurrent_requests` sockets are active in userspace. Each connection
|
||||||
|
/// is closed after one request and shares one absolute deadline across HTTP
|
||||||
|
/// intake, dispatch, and response transmission.
|
||||||
|
pub fn serve_until(&self, shutdown: Arc<AtomicBool>) -> Result<(), std::io::Error> {
|
||||||
|
let mut workers = Vec::with_capacity(self.service.config.limits.max_concurrent_requests);
|
||||||
|
for _ in 0..self.service.config.limits.max_concurrent_requests {
|
||||||
|
let listener = Arc::clone(&self.listener);
|
||||||
|
let service = Arc::clone(&self.service);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
workers.push(thread::spawn(move || {
|
||||||
|
while !shutdown.load(Ordering::Acquire) {
|
||||||
|
match listener.accept() {
|
||||||
|
Ok((stream, _)) => serve_connection(&service, stream),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||||
|
thread::sleep(Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
for worker in workers {
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.map_err(|_| std::io::Error::other("HTTP worker panicked"))??;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves until the process is terminated.
|
||||||
|
pub fn serve(&self) -> Result<(), std::io::Error> {
|
||||||
|
self.serve_until(Arc::new(AtomicBool::new(false)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct ParsedRequestHead {
|
||||||
|
method: http::Method,
|
||||||
|
target: String,
|
||||||
|
headers: Vec<(http::header::HeaderName, http::HeaderValue)>,
|
||||||
|
content_length: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum IntakeError {
|
||||||
|
Timeout,
|
||||||
|
HeaderTooLarge,
|
||||||
|
PayloadTooLarge { target: String },
|
||||||
|
BadRequest,
|
||||||
|
Socket,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve_connection(service: &WipFsServer, mut stream: TcpStream) {
|
||||||
|
let _ = stream.set_nonblocking(false);
|
||||||
|
let started = Instant::now();
|
||||||
|
let deadline = started
|
||||||
|
.checked_add(service.config.limits.request_timeout)
|
||||||
|
.unwrap_or(started);
|
||||||
|
let response = match read_http_request(
|
||||||
|
&mut stream,
|
||||||
|
service.config.limits.max_http_header_bytes,
|
||||||
|
service.config.limits.wire.max_request_bytes(),
|
||||||
|
deadline,
|
||||||
|
) {
|
||||||
|
Ok(request) => Some(service.handle_http_with_deadline(request, deadline)),
|
||||||
|
Err(IntakeError::HeaderTooLarge) => {
|
||||||
|
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
||||||
|
}
|
||||||
|
Err(IntakeError::PayloadTooLarge { target }) => {
|
||||||
|
Some(payload_too_large_response(service, &target))
|
||||||
|
}
|
||||||
|
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
||||||
|
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
||||||
|
};
|
||||||
|
if let Some(response) = response {
|
||||||
|
let _ = write_http_response(&mut stream, &response, deadline);
|
||||||
|
}
|
||||||
|
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_http_request(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
maximum_header: usize,
|
||||||
|
maximum_body: usize,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<Request<Vec<u8>>, IntakeError> {
|
||||||
|
let mut received = Vec::with_capacity(maximum_header.min(8 * 1024));
|
||||||
|
let header_end = loop {
|
||||||
|
if let Some(position) = received.windows(4).position(|window| window == b"\r\n\r\n") {
|
||||||
|
let end = position + 4;
|
||||||
|
if end > maximum_header {
|
||||||
|
return Err(IntakeError::HeaderTooLarge);
|
||||||
|
}
|
||||||
|
break end;
|
||||||
|
}
|
||||||
|
if received.len() >= maximum_header {
|
||||||
|
return Err(IntakeError::HeaderTooLarge);
|
||||||
|
}
|
||||||
|
let mut chunk = [0_u8; 4 * 1024];
|
||||||
|
let available = (maximum_header - received.len()).min(chunk.len());
|
||||||
|
let count = read_with_deadline(stream, &mut chunk[..available], deadline)?;
|
||||||
|
if count == 0 {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
received.extend_from_slice(&chunk[..count]);
|
||||||
|
};
|
||||||
|
|
||||||
|
let parsed = parse_request_head(&received[..header_end])?;
|
||||||
|
if parsed.content_length > maximum_body {
|
||||||
|
return Err(IntakeError::PayloadTooLarge {
|
||||||
|
target: parsed.target,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut body = Vec::with_capacity(parsed.content_length);
|
||||||
|
let buffered = &received[header_end..];
|
||||||
|
body.extend_from_slice(&buffered[..buffered.len().min(parsed.content_length)]);
|
||||||
|
while body.len() < parsed.content_length {
|
||||||
|
let mut chunk = [0_u8; 8 * 1024];
|
||||||
|
let wanted = (parsed.content_length - body.len()).min(chunk.len());
|
||||||
|
let count = read_with_deadline(stream, &mut chunk[..wanted], deadline)?;
|
||||||
|
if count == 0 {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk[..count]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut builder = Request::builder().method(parsed.method).uri(parsed.target);
|
||||||
|
for (name, value) in parsed.headers {
|
||||||
|
builder = builder.header(name, value);
|
||||||
|
}
|
||||||
|
builder.body(body).map_err(|_| IntakeError::BadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_request_head(bytes: &[u8]) -> Result<ParsedRequestHead, IntakeError> {
|
||||||
|
let text = std::str::from_utf8(bytes).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let mut lines = text
|
||||||
|
.strip_suffix("\r\n\r\n")
|
||||||
|
.ok_or(IntakeError::BadRequest)?
|
||||||
|
.split("\r\n");
|
||||||
|
let mut request_line = lines
|
||||||
|
.next()
|
||||||
|
.ok_or(IntakeError::BadRequest)?
|
||||||
|
.split_ascii_whitespace();
|
||||||
|
let method = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
let target = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
let version = request_line.next().ok_or(IntakeError::BadRequest)?;
|
||||||
|
if request_line.next().is_some()
|
||||||
|
|| !matches!(version, "HTTP/1.0" | "HTTP/1.1")
|
||||||
|
|| !target.starts_with('/')
|
||||||
|
{
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
let method =
|
||||||
|
http::Method::from_bytes(method.as_bytes()).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let _: http::Uri = target.parse().map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
let mut content_length = None;
|
||||||
|
for line in lines {
|
||||||
|
if line.is_empty() || line.starts_with([' ', '\t']) {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
let (name, value) = line.split_once(':').ok_or(IntakeError::BadRequest)?;
|
||||||
|
let name = http::header::HeaderName::from_bytes(name.as_bytes())
|
||||||
|
.map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
let value =
|
||||||
|
http::HeaderValue::from_str(value.trim()).map_err(|_| IntakeError::BadRequest)?;
|
||||||
|
if name == http::header::CONTENT_LENGTH {
|
||||||
|
if content_length.is_some() {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
content_length = Some(
|
||||||
|
value
|
||||||
|
.to_str()
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.parse::<usize>().ok())
|
||||||
|
.ok_or(IntakeError::BadRequest)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if name == http::header::TRANSFER_ENCODING {
|
||||||
|
return Err(IntakeError::BadRequest);
|
||||||
|
}
|
||||||
|
headers.push((name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ParsedRequestHead {
|
||||||
|
method,
|
||||||
|
target: target.to_owned(),
|
||||||
|
headers,
|
||||||
|
content_length: content_length.unwrap_or(0),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_with_deadline(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
buffer: &mut [u8],
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<usize, IntakeError> {
|
||||||
|
let remaining = deadline
|
||||||
|
.checked_duration_since(Instant::now())
|
||||||
|
.ok_or(IntakeError::Timeout)?;
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(remaining.max(Duration::from_millis(1))))
|
||||||
|
.map_err(|_| IntakeError::Socket)?;
|
||||||
|
stream.read(buffer).map_err(|error| match error.kind() {
|
||||||
|
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => IntakeError::Timeout,
|
||||||
|
_ => IntakeError::Socket,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload_too_large_response(service: &WipFsServer, target: &str) -> Response<Vec<u8>> {
|
||||||
|
let route = service.route(target.split('?').next().unwrap_or_default());
|
||||||
|
route.map_or_else(
|
||||||
|
|| empty_response(StatusCode::PAYLOAD_TOO_LARGE),
|
||||||
|
|route| {
|
||||||
|
if route == Route::Batch {
|
||||||
|
service.batch_top_error(
|
||||||
|
&resource_error(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
service.protocol_error(
|
||||||
|
interaction(route),
|
||||||
|
&resource_error(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_http_response(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
response: &Response<Vec<u8>>,
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<(), std::io::Error> {
|
||||||
|
let mut encoded = Vec::new();
|
||||||
|
write!(
|
||||||
|
encoded,
|
||||||
|
"HTTP/1.1 {} {}\r\n",
|
||||||
|
response.status().as_u16(),
|
||||||
|
response.status().canonical_reason().unwrap_or("")
|
||||||
|
)?;
|
||||||
|
for (name, value) in response.headers() {
|
||||||
|
if name == http::header::CONTENT_LENGTH
|
||||||
|
|| name == http::header::CONNECTION
|
||||||
|
|| name == http::header::TRANSFER_ENCODING
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
encoded.extend_from_slice(name.as_str().as_bytes());
|
||||||
|
encoded.extend_from_slice(b": ");
|
||||||
|
encoded.extend_from_slice(value.as_bytes());
|
||||||
|
encoded.extend_from_slice(b"\r\n");
|
||||||
|
}
|
||||||
|
write!(
|
||||||
|
encoded,
|
||||||
|
"Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||||
|
response.body().len()
|
||||||
|
)?;
|
||||||
|
encoded.extend_from_slice(response.body());
|
||||||
|
write_all_with_deadline(stream, &encoded, deadline)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_all_with_deadline(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
mut bytes: &[u8],
|
||||||
|
deadline: Instant,
|
||||||
|
) -> Result<(), std::io::Error> {
|
||||||
|
while !bytes.is_empty() {
|
||||||
|
let remaining = deadline
|
||||||
|
.checked_duration_since(Instant::now())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
std::io::Error::new(std::io::ErrorKind::TimedOut, "request timed out")
|
||||||
|
})?;
|
||||||
|
stream.set_write_timeout(Some(remaining.max(Duration::from_millis(1))))?;
|
||||||
|
match stream.write(bytes) {
|
||||||
|
Ok(0) => {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::WriteZero,
|
||||||
|
"socket closed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(count) => bytes = &bytes[count..],
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stream.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interaction(route: Route) -> ProtocolInteraction {
|
||||||
|
match route {
|
||||||
|
Route::Fetch => ProtocolInteraction::Fetch,
|
||||||
|
Route::FetchTree => ProtocolInteraction::FetchTree,
|
||||||
|
Route::FetchInterface => ProtocolInteraction::FetchInterface,
|
||||||
|
Route::CallOperation => ProtocolInteraction::CallOperation,
|
||||||
|
Route::Batch => ProtocolInteraction::Fetch,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resource_error() -> ProtocolError {
|
||||||
|
ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "configured resource limit exceeded".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal_error() -> ProtocolError {
|
||||||
|
ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "filesystem server failed".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_response(status: StatusCode) -> Response<Vec<u8>> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.body(Vec::new())
|
||||||
|
.expect("static status builds an HTTP response")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure while validating, opening, or binding the server.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ServerBuildError {
|
||||||
|
/// Configuration is unsafe or unbounded.
|
||||||
|
Config(ConfigError),
|
||||||
|
/// The root capability could not be opened.
|
||||||
|
Io(std::io::Error),
|
||||||
|
/// The listener could not be bound.
|
||||||
|
Listener(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ServerBuildError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Config(error) => write!(formatter, "invalid server configuration: {error}"),
|
||||||
|
Self::Io(error) => write!(formatter, "filesystem root could not be opened: {error}"),
|
||||||
|
Self::Listener(error) => write!(formatter, "HTTP listener could not be bound: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ServerBuildError {
|
||||||
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::Config(error) => Some(error),
|
||||||
|
Self::Io(error) => Some(error),
|
||||||
|
Self::Listener(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ConfigError> for ServerBuildError {
|
||||||
|
fn from(value: ConfigError) -> Self {
|
||||||
|
Self::Config(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for ServerBuildError {
|
||||||
|
fn from(value: std::io::Error) -> Self {
|
||||||
|
Self::Io(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpStream};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
||||||
|
use wip_https::{
|
||||||
|
BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse, BatchSuccess, DecodedResponse,
|
||||||
|
Endpoint, JSON_CONTENT_TYPE, Limits, Route, decode_batch_request, decode_batch_response,
|
||||||
|
decode_call_operation_response, decode_fetch_interface_response, decode_fetch_response,
|
||||||
|
decode_fetch_tree_response, encode_batch_request, encode_call_operation_request,
|
||||||
|
encode_fetch_interface_request, encode_fetch_request, encode_fetch_tree_request,
|
||||||
|
};
|
||||||
|
use wip_protocol::{
|
||||||
|
CallOperationRequest, FetchInterfaceRequest, FetchRequest, FetchTreeRequest, InterfaceTarget,
|
||||||
|
ProtocolErrorCode, Target, Value,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_listener_serves_four_core_interactions_batch_and_write() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
|
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
||||||
|
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.access = AccessMode::ReadWrite;
|
||||||
|
config.transport_security = TransportSecurity::DevelopmentHttp;
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
|
||||||
|
.expect("client endpoint");
|
||||||
|
|
||||||
|
let file_request = FetchRequest {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_request(&endpoint, &file_request, limits).expect("encode fetch"),
|
||||||
|
);
|
||||||
|
let file =
|
||||||
|
success(decode_fetch_response(&file_request, &response, limits).expect("decode fetch"));
|
||||||
|
assert_eq!(file.name, "hello.txt");
|
||||||
|
assert_eq!(file.interfaces.len(), 2);
|
||||||
|
assert!(file.validator.is_some());
|
||||||
|
|
||||||
|
let tree_request = FetchTreeRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 1,
|
||||||
|
limit: 10,
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_tree_request(&endpoint, &tree_request, limits).expect("encode tree"),
|
||||||
|
);
|
||||||
|
let tree =
|
||||||
|
success(decode_fetch_tree_response(&tree_request, &response, limits).expect("decode tree"));
|
||||||
|
assert!(!tree.truncated);
|
||||||
|
assert_eq!(tree.root.children.len(), 2);
|
||||||
|
|
||||||
|
let read_interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[0].clone(),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_interface_request(&endpoint, &read_interface_request, limits)
|
||||||
|
.expect("encode interface fetch"),
|
||||||
|
);
|
||||||
|
let read_interface = success(
|
||||||
|
decode_fetch_interface_response(&read_interface_request, &response, limits)
|
||||||
|
.expect("decode interface"),
|
||||||
|
);
|
||||||
|
assert_eq!(read_interface.descriptor.operations[0].name, "read");
|
||||||
|
|
||||||
|
let read_request = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
validator: file.validator.clone(),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[0].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "read".into(),
|
||||||
|
arguments: BTreeMap::from([
|
||||||
|
("offset".into(), Value::Integer(6)),
|
||||||
|
("length".into(), Value::Integer(5)),
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_call_operation_request(&endpoint, &read_request, &read_interface.descriptor, limits)
|
||||||
|
.expect("encode read call"),
|
||||||
|
);
|
||||||
|
let read = success(
|
||||||
|
decode_call_operation_response(
|
||||||
|
&read_request,
|
||||||
|
&read_interface.descriptor,
|
||||||
|
&response,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("decode read call"),
|
||||||
|
);
|
||||||
|
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
||||||
|
|
||||||
|
let batch_request = BatchRequest {
|
||||||
|
requests: vec![
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "root".into(),
|
||||||
|
request: BatchRequestKind::Fetch(FetchRequest { path: "/".into() }),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "tree".into(),
|
||||||
|
request: BatchRequestKind::FetchTree(FetchTreeRequest {
|
||||||
|
path: "/nested".into(),
|
||||||
|
depth: 1,
|
||||||
|
limit: 4,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(read_interface_request.clone()),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_batch_request(&endpoint, &batch_request, limits).expect("encode batch"),
|
||||||
|
);
|
||||||
|
let batch =
|
||||||
|
success(decode_batch_response(&batch_request, &response, limits).expect("decode batch"));
|
||||||
|
assert_batch_successes(&batch);
|
||||||
|
|
||||||
|
let write_interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[1].clone(),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_interface_request(&endpoint, &write_interface_request, limits)
|
||||||
|
.expect("encode write interface fetch"),
|
||||||
|
);
|
||||||
|
let write_interface = success(
|
||||||
|
decode_fetch_interface_response(&write_interface_request, &response, limits)
|
||||||
|
.expect("decode write interface"),
|
||||||
|
);
|
||||||
|
let write_request = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/hello.txt".into(),
|
||||||
|
validator: file.validator,
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[1].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "replace".into(),
|
||||||
|
arguments: BTreeMap::from([("contents".into(), Value::Bytes(b"updated".to_vec()))]),
|
||||||
|
};
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_call_operation_request(
|
||||||
|
&endpoint,
|
||||||
|
&write_request,
|
||||||
|
&write_interface.descriptor,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("encode write call"),
|
||||||
|
);
|
||||||
|
let write = success(
|
||||||
|
decode_call_operation_response(
|
||||||
|
&write_request,
|
||||||
|
&write_interface.descriptor,
|
||||||
|
&response,
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
.expect("decode write call"),
|
||||||
|
);
|
||||||
|
assert!(write.validator.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("read updated file"),
|
||||||
|
b"updated"
|
||||||
|
);
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.transport_security = TransportSecurity::DevelopmentHttp;
|
||||||
|
config.limits.max_concurrent_requests = 1;
|
||||||
|
config.limits.request_timeout = Duration::from_millis(200);
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut stalled = TcpStream::connect(address).expect("connect stalled client");
|
||||||
|
stalled
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.expect("set stalled read timeout");
|
||||||
|
write!(
|
||||||
|
stalled,
|
||||||
|
"POST /wip/v1/fetch HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nAccept: application/json\r\nContent-Length: 100\r\n\r\n{{"
|
||||||
|
)
|
||||||
|
.expect("write partial request");
|
||||||
|
stalled.flush().expect("flush partial request");
|
||||||
|
thread::sleep(Duration::from_millis(25));
|
||||||
|
|
||||||
|
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
|
||||||
|
.expect("client endpoint");
|
||||||
|
let fetch = FetchRequest { path: "/".into() };
|
||||||
|
let started = Instant::now();
|
||||||
|
let response = exchange(
|
||||||
|
address,
|
||||||
|
encode_fetch_request(&endpoint, &fetch, limits).expect("encode fetch"),
|
||||||
|
);
|
||||||
|
let _root = success(decode_fetch_response(&fetch, &response, limits).expect("decode fetch"));
|
||||||
|
assert!(
|
||||||
|
started.elapsed() < Duration::from_secs(1),
|
||||||
|
"the valid request remained starved after the intake deadline"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut byte = [0_u8; 1];
|
||||||
|
match stalled.read(&mut byte) {
|
||||||
|
Ok(0) => {}
|
||||||
|
Err(error)
|
||||||
|
if matches!(
|
||||||
|
error.kind(),
|
||||||
|
std::io::ErrorKind::ConnectionReset
|
||||||
|
| std::io::ErrorKind::ConnectionAborted
|
||||||
|
| std::io::ErrorKind::BrokenPipe
|
||||||
|
) => {}
|
||||||
|
outcome => panic!("stalled connection was not closed after its deadline: {outcome:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_keeps_known_malformed_arguments_item_local() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
||||||
|
let body = br#"{"requests":[{"id":"ok","method":"fetch","arguments":{"path":"/"}},{"id":"bad","method":"fetch_tree","arguments":{"path":"/","depth":"bad","limit":1}}]}"#;
|
||||||
|
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::Fetch(_))
|
||||||
|
));
|
||||||
|
assert!(batch.responses[1].outcome.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn call_argument_decoding_does_not_mask_missing_target() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
||||||
|
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
||||||
|
let request = http::Request::builder()
|
||||||
|
.method(http::Method::POST)
|
||||||
|
.uri(endpoint.route(Route::CallOperation).as_str())
|
||||||
|
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(http::header::ACCEPT, "application/json")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.expect("build request");
|
||||||
|
let response = server.handle_http(request);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(response.body())
|
||||||
|
.expect("UTF-8 error")
|
||||||
|
.contains("\"not_found\"")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn backend_invalid_unicode_path_is_not_found_not_internal() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
||||||
|
let request = FetchRequest {
|
||||||
|
path: "/bad\0name".into(),
|
||||||
|
};
|
||||||
|
let response = server
|
||||||
|
.handle_http(encode_fetch_request(&endpoint, &request, limits).expect("encode fetch"));
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
match decode_fetch_response(&request, &response, limits).expect("decode missing response") {
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => {
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::NotFound);
|
||||||
|
}
|
||||||
|
DecodedResponse::Success(_) => panic!("backend-invalid path must not resolve"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn read_response_size_failure_preserves_non_commit_guarantee() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(4_096, 1_024, 64, 64).expect("wire limits");
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
||||||
|
|
||||||
|
let fetch_request = FetchRequest {
|
||||||
|
path: "/large".into(),
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_fetch_request(&endpoint, &fetch_request, limits).expect("encode fetch"),
|
||||||
|
);
|
||||||
|
let file =
|
||||||
|
success(decode_fetch_response(&fetch_request, &response, limits).expect("decode fetch"));
|
||||||
|
let interface_request = FetchInterfaceRequest {
|
||||||
|
interface: file.interfaces[0].clone(),
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_fetch_interface_request(&endpoint, &interface_request, limits)
|
||||||
|
.expect("encode interface fetch"),
|
||||||
|
);
|
||||||
|
let interface = success(
|
||||||
|
decode_fetch_interface_response(&interface_request, &response, limits)
|
||||||
|
.expect("decode interface"),
|
||||||
|
);
|
||||||
|
let call = CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/large".into(),
|
||||||
|
validator: file.validator,
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: file.interfaces[0].clone(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
operation: "read".into(),
|
||||||
|
arguments: BTreeMap::from([("length".into(), Value::Integer(1_500))]),
|
||||||
|
};
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
||||||
|
.expect("encode read call"),
|
||||||
|
);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
match decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
||||||
|
.expect("decode resource failure")
|
||||||
|
{
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => {
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::ResourceLimitExceeded);
|
||||||
|
}
|
||||||
|
DecodedResponse::Success(_) => panic!("oversized read response must fail"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_batch_successes(batch: &BatchResponse) {
|
||||||
|
assert_eq!(batch.responses.len(), 3);
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[0].outcome,
|
||||||
|
Ok(BatchSuccess::Fetch(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[1].outcome,
|
||||||
|
Ok(BatchSuccess::FetchTree(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
batch.responses[2].outcome,
|
||||||
|
Ok(BatchSuccess::FetchInterface(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn success<T>(response: DecodedResponse<T>) -> T {
|
||||||
|
match response {
|
||||||
|
DecodedResponse::Success(value) => value,
|
||||||
|
DecodedResponse::ProtocolFailure { error, .. } => panic!("protocol failure: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
||||||
|
let mut stream = TcpStream::connect(address).expect("connect listener");
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.expect("set read timeout");
|
||||||
|
let path = request
|
||||||
|
.uri()
|
||||||
|
.path_and_query()
|
||||||
|
.map_or("/", |value| value.as_str());
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"{} {} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n",
|
||||||
|
request.method(),
|
||||||
|
path
|
||||||
|
)
|
||||||
|
.expect("write request line");
|
||||||
|
for (name, value) in request.headers() {
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"{}: {}\r\n",
|
||||||
|
name,
|
||||||
|
value.to_str().expect("ASCII request header")
|
||||||
|
)
|
||||||
|
.expect("write header");
|
||||||
|
}
|
||||||
|
write!(stream, "Content-Length: {}\r\n\r\n", request.body().len())
|
||||||
|
.expect("write content length");
|
||||||
|
stream.write_all(request.body()).expect("write body");
|
||||||
|
stream.flush().expect("flush request");
|
||||||
|
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
stream.read_to_end(&mut raw).expect("read response");
|
||||||
|
let split = raw
|
||||||
|
.windows(4)
|
||||||
|
.position(|window| window == b"\r\n\r\n")
|
||||||
|
.expect("HTTP response header");
|
||||||
|
let head = std::str::from_utf8(&raw[..split]).expect("UTF-8 response head");
|
||||||
|
let mut lines = head.split("\r\n");
|
||||||
|
let status = lines
|
||||||
|
.next()
|
||||||
|
.and_then(|line| line.split_whitespace().nth(1))
|
||||||
|
.and_then(|status| status.parse::<u16>().ok())
|
||||||
|
.expect("response status");
|
||||||
|
let mut builder = http::Response::builder().status(status);
|
||||||
|
for line in lines {
|
||||||
|
let (name, value) = line.split_once(':').expect("response header");
|
||||||
|
builder = builder.header(name, value.trim());
|
||||||
|
}
|
||||||
|
builder
|
||||||
|
.body(raw[split + 4..].to_vec())
|
||||||
|
.expect("build response")
|
||||||
|
}
|
||||||
+115
-28
@@ -535,11 +535,36 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
context: &ExecutionContext,
|
context: &ExecutionContext,
|
||||||
request: CallRequest,
|
request: CallRequest,
|
||||||
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
|
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
|
||||||
|
) -> OperationAttempt {
|
||||||
|
let CallRequest {
|
||||||
|
target,
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
arguments,
|
||||||
|
} = request;
|
||||||
|
self.dispatch_resolved_with_decoder(
|
||||||
|
context,
|
||||||
|
target,
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
|_| Ok::<_, std::convert::Infallible>(arguments),
|
||||||
|
authorize,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_resolved_with_decoder<E>(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
target: Target,
|
||||||
|
interface: InterfaceTarget,
|
||||||
|
operation: String,
|
||||||
|
decode_arguments: impl FnOnce(&InterfaceDescriptor) -> Result<BTreeMap<String, Value>, E>,
|
||||||
|
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
|
||||||
) -> OperationAttempt {
|
) -> OperationAttempt {
|
||||||
let pre_dispatch_failure =
|
let pre_dispatch_failure =
|
||||||
|kind, message: &str| OperationAttempt::NotStarted(CallError::new(kind, message));
|
|kind, message: &str| OperationAttempt::NotStarted(CallError::new(kind, message));
|
||||||
let current_object_validator = self.implementation.validator();
|
let current_object_validator = self.implementation.validator();
|
||||||
if let Some(supplied) = request.target.validator.as_deref()
|
if let Some(supplied) = target.validator.as_deref()
|
||||||
&& current_object_validator.map(Validator::as_bytes) != Some(supplied)
|
&& current_object_validator.map(Validator::as_bytes) != Some(supplied)
|
||||||
{
|
{
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
@@ -548,9 +573,11 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(bound) = self.interfaces.iter().find(|bound| {
|
let Some(bound) = self
|
||||||
bound.artifact.reference.as_str() == request.interface.reference.as_str()
|
.interfaces
|
||||||
}) else {
|
.iter()
|
||||||
|
.find(|bound| bound.artifact.reference.as_str() == interface.reference.as_str())
|
||||||
|
else {
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::InterfaceMismatch,
|
CallErrorKind::InterfaceMismatch,
|
||||||
"interface is not a member of the current object publication",
|
"interface is not a member of the current object publication",
|
||||||
@@ -559,7 +586,7 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
|
|
||||||
match (
|
match (
|
||||||
bound.artifact.validator.as_ref(),
|
bound.artifact.validator.as_ref(),
|
||||||
request.interface.validator.as_deref(),
|
interface.validator.as_deref(),
|
||||||
) {
|
) {
|
||||||
(Some(_), None) => {
|
(Some(_), None) => {
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
@@ -581,18 +608,18 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
.descriptor
|
.descriptor
|
||||||
.operations
|
.operations
|
||||||
.iter()
|
.iter()
|
||||||
.any(|operation| operation.name == request.operation)
|
.any(|declared| declared.name == operation)
|
||||||
{
|
{
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::OperationNotFound,
|
CallErrorKind::OperationNotFound,
|
||||||
&format!("operation `{}` is not declared", request.operation),
|
&format!("operation `{operation}` is not declared"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if request.target.validator.is_none()
|
if target.validator.is_none()
|
||||||
&& self
|
&& self
|
||||||
.implementation
|
.implementation
|
||||||
.requires_validator(&bound.artifact.reference, &request.operation)
|
.requires_validator(&bound.artifact.reference, &operation)
|
||||||
{
|
{
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::ValidatorRequired,
|
CallErrorKind::ValidatorRequired,
|
||||||
@@ -600,19 +627,24 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let arguments = match decode_arguments(&bound.artifact.descriptor) {
|
||||||
|
Ok(arguments) => arguments,
|
||||||
|
Err(_) => {
|
||||||
|
return pre_dispatch_failure(
|
||||||
|
CallErrorKind::InvalidArguments,
|
||||||
|
"operation arguments could not be decoded",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
if let Err(error) = bound
|
if let Err(error) = bound
|
||||||
.artifact
|
.artifact
|
||||||
.descriptor
|
.descriptor
|
||||||
.validate_arguments(&request.operation, &request.arguments)
|
.validate_arguments(&operation, &arguments)
|
||||||
{
|
{
|
||||||
return pre_dispatch_failure(CallErrorKind::InvalidArguments, &error.to_string());
|
return pre_dispatch_failure(CallErrorKind::InvalidArguments, &error.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
if !authorize(
|
if !authorize(&self.implementation, &bound.artifact.reference, &operation) {
|
||||||
&self.implementation,
|
|
||||||
&bound.artifact.reference,
|
|
||||||
&request.operation,
|
|
||||||
) {
|
|
||||||
return pre_dispatch_failure(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::PermissionDenied,
|
CallErrorKind::PermissionDenied,
|
||||||
"operation is not permitted for this caller",
|
"operation is not permitted for this caller",
|
||||||
@@ -623,23 +655,22 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
return OperationAttempt::NotStarted(error);
|
return OperationAttempt::NotStarted(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
let value =
|
let value = match (bound.dispatch)(&self.implementation, &operation, arguments) {
|
||||||
match (bound.dispatch)(&self.implementation, &request.operation, request.arguments) {
|
Ok(value) => value,
|
||||||
Ok(value) => value,
|
Err(
|
||||||
Err(
|
error @ (DispatchError::UnknownOperation(_)
|
||||||
error @ (DispatchError::UnknownOperation(_)
|
| DispatchError::InvalidArguments(_)
|
||||||
| DispatchError::InvalidArguments(_)
|
| DispatchError::Decode(_)),
|
||||||
| DispatchError::Decode(_)),
|
) => return OperationAttempt::NotStarted(CallError::from_pre_dispatch(error)),
|
||||||
) => return OperationAttempt::NotStarted(CallError::from_pre_dispatch(error)),
|
Err(error) => {
|
||||||
Err(error) => {
|
return OperationAttempt::Started(Err(OperationFailure::from_dispatch(error)));
|
||||||
return OperationAttempt::Started(Err(OperationFailure::from_dispatch(error)));
|
}
|
||||||
}
|
};
|
||||||
};
|
|
||||||
|
|
||||||
if bound
|
if bound
|
||||||
.artifact
|
.artifact
|
||||||
.descriptor
|
.descriptor
|
||||||
.validate_result(&request.operation, &value)
|
.validate_result(&operation, &value)
|
||||||
.is_err()
|
.is_err()
|
||||||
{
|
{
|
||||||
return OperationAttempt::Started(Err(OperationFailure::internal(
|
return OperationAttempt::Started(Err(OperationFailure::internal(
|
||||||
@@ -922,6 +953,62 @@ pub trait ObjectProvider {
|
|||||||
ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
|
ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolves one operation target and decodes its arguments only after all
|
||||||
|
/// descriptor-independent canonical preconditions have succeeded.
|
||||||
|
///
|
||||||
|
/// Transport bindings whose value representation depends on the selected
|
||||||
|
/// interface descriptor should use this method instead of resolving a
|
||||||
|
/// descriptor before [`ObjectProvider::call_operation_with_context`]. The
|
||||||
|
/// callback executes inside the same exact-once provider boundary after
|
||||||
|
/// object/interface validators, membership, operation lookup, and required
|
||||||
|
/// object-validator checks. A callback error becomes `InvalidArguments` and
|
||||||
|
/// typed implementation code is not invoked.
|
||||||
|
fn call_operation_with_context_and_decoder<E>(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
target: Target,
|
||||||
|
interface: InterfaceTarget,
|
||||||
|
operation: String,
|
||||||
|
decode_arguments: impl FnOnce(&InterfaceDescriptor) -> Result<BTreeMap<String, Value>, E>,
|
||||||
|
) -> Result<CallResult, CallError> {
|
||||||
|
wip_protocol::validate_path(&target.path)
|
||||||
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
|
let path = target.path.clone();
|
||||||
|
let execution = catch_unwind(AssertUnwindSafe(|| {
|
||||||
|
self.execute_operation(context, &path, |publication| {
|
||||||
|
publication.dispatch_resolved_with_decoder(
|
||||||
|
context,
|
||||||
|
target,
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
decode_arguments,
|
||||||
|
|object, interface, operation| {
|
||||||
|
self.authorize(&path, object, interface, operation)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
|
||||||
|
let execution = execution.map_err(|_| {
|
||||||
|
CallError::from_operation_failure(OperationFailure::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"provider execution panicked",
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
match execution {
|
||||||
|
ProviderResult::Found(OperationAttempt::NotStarted(error)) => Err(error),
|
||||||
|
ProviderResult::Found(OperationAttempt::Started(Ok(result))) => Ok(result),
|
||||||
|
ProviderResult::Found(OperationAttempt::Started(Err(error))) => {
|
||||||
|
Err(CallError::from_operation_failure(error))
|
||||||
|
}
|
||||||
|
ProviderResult::NotFound => Err(CallError::new(
|
||||||
|
CallErrorKind::NotFound,
|
||||||
|
"target path is not published",
|
||||||
|
)),
|
||||||
|
ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Failure to construct an explicit object publication.
|
/// Failure to construct an explicit object publication.
|
||||||
|
|||||||
@@ -741,6 +741,89 @@ fn call_failures_follow_canonical_precedence_without_execution() {
|
|||||||
assert_eq!(provider.calls.get(), 0);
|
assert_eq!(provider.calls.get(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn descriptor_guided_decoder_runs_inside_canonical_resolution_boundary() {
|
||||||
|
let (_, provider, hidden) = registry_and_provider();
|
||||||
|
let decodes = Cell::new(0_u32);
|
||||||
|
let decode_failure = || {
|
||||||
|
decodes.set(decodes.get() + 1);
|
||||||
|
Err::<BTreeMap<String, Value>, _>(())
|
||||||
|
};
|
||||||
|
|
||||||
|
let missing = provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
Target {
|
||||||
|
path: "/missing".into(),
|
||||||
|
validator: Some(b"stale".to_vec()),
|
||||||
|
},
|
||||||
|
InterfaceTarget {
|
||||||
|
reference: hidden.reference().as_str().into(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
"missing".into(),
|
||||||
|
|_| decode_failure(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(missing.kind(), CallErrorKind::NotFound);
|
||||||
|
assert_eq!(decodes.get(), 0);
|
||||||
|
|
||||||
|
let stale = provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
Target {
|
||||||
|
path: "/document".into(),
|
||||||
|
validator: Some(b"stale".to_vec()),
|
||||||
|
},
|
||||||
|
InterfaceTarget {
|
||||||
|
reference: hidden.reference().as_str().into(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
"hidden".into(),
|
||||||
|
|_| decode_failure(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(stale.kind(), CallErrorKind::ValidatorMismatch);
|
||||||
|
assert_eq!(decodes.get(), 0);
|
||||||
|
|
||||||
|
let mismatch = provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
Target {
|
||||||
|
path: "/document".into(),
|
||||||
|
validator: Some(b"object-v1".to_vec()),
|
||||||
|
},
|
||||||
|
InterfaceTarget {
|
||||||
|
reference: hidden.reference().as_str().into(),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
"hidden".into(),
|
||||||
|
|_| decode_failure(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(mismatch.kind(), CallErrorKind::InterfaceMismatch);
|
||||||
|
assert_eq!(decodes.get(), 0);
|
||||||
|
|
||||||
|
let invalid_arguments = provider
|
||||||
|
.call_operation_with_context_and_decoder(
|
||||||
|
&ExecutionContext::new(),
|
||||||
|
Target {
|
||||||
|
path: "/document".into(),
|
||||||
|
validator: Some(b"object-v1".to_vec()),
|
||||||
|
},
|
||||||
|
InterfaceTarget {
|
||||||
|
reference: provider.reader.reference().as_str().into(),
|
||||||
|
validator: Some(b"schema-v1".to_vec()),
|
||||||
|
},
|
||||||
|
"add".into(),
|
||||||
|
|_| decode_failure(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(invalid_arguments.kind(), CallErrorKind::InvalidArguments);
|
||||||
|
assert_eq!(decodes.get(), 1);
|
||||||
|
assert_eq!(provider.calls.get(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn immutable_interface_rejects_a_supplied_validator() {
|
fn immutable_interface_rejects_a_supplied_validator() {
|
||||||
let (_, provider, _) = registry_and_provider();
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-tui"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
|
crossterm = "0.28.1"
|
||||||
|
ratatui = "0.29.0"
|
||||||
|
serde_json = "1"
|
||||||
|
ureq = "3.1.2"
|
||||||
|
wip-client = { path = "../wip-client" }
|
||||||
|
wip-https = { path = "../wip-https" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
|
wip-fs-server = { path = "../wip-fs-server" }
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# wip-tui
|
||||||
|
|
||||||
|
`wip-tui` is an interactive terminal client for exploring and operating a WIP
|
||||||
|
Worldspace. It is a presentation and terminal-interaction layer over
|
||||||
|
`wip-client`: Known Space, request identity, validators, immutable operation call
|
||||||
|
contexts, stale transitions, response classification, and bounded histories remain
|
||||||
|
owned by the client runtime.
|
||||||
|
|
||||||
|
## Start
|
||||||
|
|
||||||
|
HTTPS is the normal mode:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-tui -- --endpoint https://wip.example.test/api/wip
|
||||||
|
```
|
||||||
|
|
||||||
|
The endpoint may instead be supplied as `WIP_ENDPOINT`. A non-secret cache
|
||||||
|
partition identity may be supplied with `--security-context NAME` or
|
||||||
|
`WIP_SECURITY_CONTEXT`. The default request timeout is 30 seconds and can be
|
||||||
|
changed with `--timeout SECONDS`.
|
||||||
|
|
||||||
|
An Authorization header can be read from an environment variable without placing
|
||||||
|
its value in arguments, application state, errors, snapshots, or debug output:
|
||||||
|
|
||||||
|
```console
|
||||||
|
export WIP_AUTHORIZATION='Bearer …'
|
||||||
|
cargo run -p wip-tui -- https://wip.example.test/wip
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `--authorization-env OTHER_VARIABLE` to select another variable. The value is
|
||||||
|
redacted from `Debug` and is never rendered. Shell and process environment security
|
||||||
|
remain the operator's responsibility.
|
||||||
|
|
||||||
|
Plain HTTP is rejected by default. It is available only as an explicit loopback
|
||||||
|
development mode:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-tui -- http://127.0.0.1:8080/wip --allow-http
|
||||||
|
```
|
||||||
|
|
||||||
|
Non-loopback HTTP remains rejected even with `--allow-http`. For production, use a
|
||||||
|
real HTTPS endpoint and a trusted TLS deployment.
|
||||||
|
|
||||||
|
### Filesystem server example
|
||||||
|
|
||||||
|
In one terminal:
|
||||||
|
|
||||||
|
```console
|
||||||
|
mkdir -p /tmp/wip-example
|
||||||
|
printf 'hello world' >/tmp/wip-example/notes.txt
|
||||||
|
cargo run -p wip-fs-server -- \
|
||||||
|
--root /tmp/wip-example \
|
||||||
|
--listen 127.0.0.1:8080 \
|
||||||
|
--base-path /wip \
|
||||||
|
--development-http \
|
||||||
|
--read-write
|
||||||
|
```
|
||||||
|
|
||||||
|
In another:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run -p wip-tui -- http://127.0.0.1:8080/wip --allow-http
|
||||||
|
```
|
||||||
|
|
||||||
|
Expand `/`, select `notes.txt`, focus the Interface/Operation pane, load the read
|
||||||
|
interface, and choose `read`. The editor labels `offset` and `length` as optional;
|
||||||
|
leave both blank to read the bounded file. `Bytes` results are shown as a bounded
|
||||||
|
hex preview. For `replace`, enter `contents` as RFC 4648 base64—for example,
|
||||||
|
`dXBkYXRlZA==` for `updated`—then review the target Entry, interface reference,
|
||||||
|
operation, and value on the confirmation screen before pressing Enter again.
|
||||||
|
|
||||||
|
## Keyboard bindings
|
||||||
|
|
||||||
|
All required actions are keyboard-accessible.
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| `↑`/`k`, `↓`/`j` | Move within the focused tree, operation list, history, or editor |
|
||||||
|
| `→`/`l`, `Enter` | Expand a tree node lazily; load/select an interface or operation |
|
||||||
|
| `←`/`h` | Collapse a node or move to its parent |
|
||||||
|
| `Tab` | Cycle Tree → Selected Entry → Operations → History |
|
||||||
|
| `r` | Reobserve the selected Entry and its direct subtree |
|
||||||
|
| `+` | Double the selected node limit and retry an incomplete/truncated tree |
|
||||||
|
| `c` | Cancel the newest retrieval; a dispatched operation is never presented as canceled |
|
||||||
|
| `R` | Reconnect after connection failure |
|
||||||
|
| `?` | Open help |
|
||||||
|
| `Esc` | Close a modal or return to the tree |
|
||||||
|
| `q`, `Ctrl-C` | Exit and restore the terminal |
|
||||||
|
|
||||||
|
Inside an argument editor, printable keys are field input, arrows move fields,
|
||||||
|
Backspace edits, Enter validates, and Esc cancels. The confirmation screen requires
|
||||||
|
a second explicit Enter (or `e`) to execute once. There is no operation auto-retry.
|
||||||
|
|
||||||
|
## Screen model
|
||||||
|
|
||||||
|
- **Worldspace tree** starts at `/` and materializes direct children only when a
|
||||||
|
node is expanded. Text labels distinguish unloaded, loading, empty, stale,
|
||||||
|
failed, and truncated state; color is supplemental. A truncated node is never
|
||||||
|
presented as a complete tree.
|
||||||
|
- **Selected Entry** shows only public WIP path, object name, description, ordered
|
||||||
|
interfaces, and freshness. Validators, credentials, Host internals, and backend
|
||||||
|
paths are deliberately hidden. If current metadata disappears, old text is not
|
||||||
|
presented as current.
|
||||||
|
- **Interfaces / Operations** identifies every operation by `(interface reference,
|
||||||
|
operation name)`. It shows descriptor documentation, ordered parameters,
|
||||||
|
required/optional status, and result types.
|
||||||
|
- **Argument editor** supports Unit, Boolean, Integer, Number, String, base64 Bytes,
|
||||||
|
Record, List, Entry, Enum, Union, Json, and descriptor-local named types. Record,
|
||||||
|
List, Union, and Json values use JSON syntax. Union input is
|
||||||
|
`{"$case":"name","value":…}` when the selected case has a payload. Diagnostics
|
||||||
|
remain attached to the failing field.
|
||||||
|
- **Recent results / diagnostics** explicitly distinguishes success, Host failure,
|
||||||
|
invalid protocol response, transport failure, client-local failure, and unknown
|
||||||
|
operation outcome. Large values, bytes, nesting, and control characters are
|
||||||
|
bounded before rendering. Only descriptor-declared `Entry` results become
|
||||||
|
navigation targets; path-looking String or Json values do not.
|
||||||
|
|
||||||
|
Terminals below 48×14 show a minimum-size screen instead of attempting the full
|
||||||
|
layout.
|
||||||
|
|
||||||
|
## Validator and failure behavior
|
||||||
|
|
||||||
|
Object and interface validators are observed and attached automatically by
|
||||||
|
`wip-client`; users neither copy nor edit them. A successful operation conservatively
|
||||||
|
marks related object observations stale because metadata may have changed.
|
||||||
|
Validator mismatch, interface mismatch, `OperationOutcomeUnknown`, undecodable
|
||||||
|
post-dispatch responses, and post-dispatch timeout/disconnect are displayed using
|
||||||
|
the runtime's authoritative transition.
|
||||||
|
|
||||||
|
For an unknown outcome, the UI states that execution or side effects may have
|
||||||
|
occurred, marks the related Entry stale, and tells the user to refresh. Refreshing
|
||||||
|
does not recreate the call: the user must select the operation, review fresh input,
|
||||||
|
and explicitly execute again. The same no-auto-retry rule applies after validator
|
||||||
|
or interface mismatch.
|
||||||
|
|
||||||
|
Retrieval work runs on I/O workers while the input/render loop continues. Responses
|
||||||
|
return with the original `RequestId`, so an old completion cannot populate another
|
||||||
|
Entry's details. Canceling a retrieval records a local cancellation and drops its
|
||||||
|
late response. Once an operation crosses dispatch, cancellation is never described
|
||||||
|
as undoing execution.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The library form keeps reducers and rendering independent of a real terminal.
|
||||||
|
`ratatui::TestBackend` snapshots cover tree/detail/result states and the minimum-size
|
||||||
|
fallback. Unit tests cover reducer focus, selection, modal confirmation, key
|
||||||
|
translation, descriptor inputs, bounded values, and descriptor-directed Entry
|
||||||
|
results. The real HTTP integration test launches `wip-fs-server` on a temporary
|
||||||
|
root and covers tree selection, reads, validator-protected replacement, external
|
||||||
|
stale-validator rejection without retry, explicit refresh/re-execution, and
|
||||||
|
symlink confinement.
|
||||||
@@ -0,0 +1,921 @@
|
|||||||
|
//! Pure application state, selection, modal, focus, and key reducer.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
|
||||||
|
use wip_protocol::{InterfaceDescriptor, Object, Value};
|
||||||
|
|
||||||
|
use crate::editor::ArgumentEditor;
|
||||||
|
|
||||||
|
const MAX_PRESENTATION_ENTRIES: usize = 2048;
|
||||||
|
const MAX_PRESENTATION_INTERFACES: usize = 256;
|
||||||
|
|
||||||
|
/// A terminal-independent key understood by the reducer.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum InputKey {
|
||||||
|
/// Up arrow or `k`.
|
||||||
|
Up,
|
||||||
|
/// Down arrow or `j`.
|
||||||
|
Down,
|
||||||
|
/// Left arrow or `h`.
|
||||||
|
Left,
|
||||||
|
/// Right arrow or `l`.
|
||||||
|
Right,
|
||||||
|
/// Focus the next pane.
|
||||||
|
Tab,
|
||||||
|
/// Activate the selected item.
|
||||||
|
Enter,
|
||||||
|
/// Close the current modal or return to the tree.
|
||||||
|
Escape,
|
||||||
|
/// Delete one editor character.
|
||||||
|
Backspace,
|
||||||
|
/// Refresh the selected Entry.
|
||||||
|
Refresh,
|
||||||
|
/// Retry a truncated tree with a larger limit.
|
||||||
|
IncreaseLimit,
|
||||||
|
/// Cancel the newest cancel-safe retrieval.
|
||||||
|
CancelRead,
|
||||||
|
/// Show key help.
|
||||||
|
Help,
|
||||||
|
/// Quit the application.
|
||||||
|
Quit,
|
||||||
|
/// Reconnect after startup or transport failure.
|
||||||
|
Reconnect,
|
||||||
|
/// A printable editor character.
|
||||||
|
Character(char),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pane receiving navigation keys.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Focus {
|
||||||
|
/// Worldspace tree.
|
||||||
|
Tree,
|
||||||
|
/// Selected Entry metadata.
|
||||||
|
Entry,
|
||||||
|
/// Interfaces and operations.
|
||||||
|
Operations,
|
||||||
|
/// Recent result and diagnostic history.
|
||||||
|
History,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Focus {
|
||||||
|
fn next(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Self::Tree => Self::Entry,
|
||||||
|
Self::Entry => Self::Operations,
|
||||||
|
Self::Operations => Self::History,
|
||||||
|
Self::History => Self::Tree,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connection lifecycle shown without relying on color.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ConnectionState {
|
||||||
|
/// No request has been attempted.
|
||||||
|
Disconnected,
|
||||||
|
/// Initial root request or reconnect is in progress.
|
||||||
|
Connecting,
|
||||||
|
/// The root was observed successfully.
|
||||||
|
Connected,
|
||||||
|
/// Connection failed; reconnect and exit remain available.
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Presentation-safe observation state.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ViewState {
|
||||||
|
/// No observation has been requested.
|
||||||
|
Unloaded,
|
||||||
|
/// One request is in flight.
|
||||||
|
Loading(u64),
|
||||||
|
/// The observation is current.
|
||||||
|
Fresh,
|
||||||
|
/// The retained value needs reobservation.
|
||||||
|
Stale,
|
||||||
|
/// The latest attempt failed.
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&ObservationState> for ViewState {
|
||||||
|
fn from(value: &ObservationState) -> Self {
|
||||||
|
match value {
|
||||||
|
ObservationState::Loading(id) => Self::Loading(id.get()),
|
||||||
|
ObservationState::Fresh => Self::Fresh,
|
||||||
|
ObservationState::Stale => Self::Stale,
|
||||||
|
ObservationState::Error(error) => Self::Error(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One materialized tree Entry.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct EntryView {
|
||||||
|
/// Canonical WIP path.
|
||||||
|
pub path: String,
|
||||||
|
/// Latest object when retained by the client runtime.
|
||||||
|
pub object: Option<Object>,
|
||||||
|
/// Object observation state.
|
||||||
|
pub state: ViewState,
|
||||||
|
/// Direct child paths in Host order.
|
||||||
|
pub children: Vec<String>,
|
||||||
|
/// Expansion observation state.
|
||||||
|
pub tree_state: ViewState,
|
||||||
|
/// Whether the user expanded this row.
|
||||||
|
pub expanded: bool,
|
||||||
|
/// Whether the observed child list is incomplete.
|
||||||
|
pub truncated: bool,
|
||||||
|
/// Current bounded expansion limit.
|
||||||
|
pub limit: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EntryView {
|
||||||
|
fn placeholder(path: impl Into<String>, default_limit: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
path: path.into(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: Vec::new(),
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
truncated: false,
|
||||||
|
limit: default_limit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cached interface descriptor state used by presentation.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct InterfaceView {
|
||||||
|
/// Opaque interface reference.
|
||||||
|
pub reference: String,
|
||||||
|
/// Descriptor when accepted by the client runtime.
|
||||||
|
pub descriptor: Option<InterfaceDescriptor>,
|
||||||
|
/// Descriptor observation state.
|
||||||
|
pub state: ViewState,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable result/diagnostic category.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum HistoryKind {
|
||||||
|
/// A descriptor-validated operation result.
|
||||||
|
Success,
|
||||||
|
/// A valid Host-declared failure.
|
||||||
|
DomainFailure,
|
||||||
|
/// An invalid protocol response.
|
||||||
|
ProtocolError,
|
||||||
|
/// Network or TLS failure.
|
||||||
|
TransportFailure,
|
||||||
|
/// Client-local validation or capacity failure.
|
||||||
|
ClientFailure,
|
||||||
|
/// Dispatch occurred but execution or commit is uncertain.
|
||||||
|
OutcomeUnknown,
|
||||||
|
/// Informational request state.
|
||||||
|
Information,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One bounded recent result or diagnostic.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct HistoryItem {
|
||||||
|
/// Explicit outcome category.
|
||||||
|
pub kind: HistoryKind,
|
||||||
|
/// Short bounded heading.
|
||||||
|
pub title: String,
|
||||||
|
/// Bounded, terminal-safe detail.
|
||||||
|
pub detail: String,
|
||||||
|
/// Navigation target only when declared as descriptor `Entry`.
|
||||||
|
pub entry_target: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kind of request currently in flight.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum InFlightKind {
|
||||||
|
/// Object refresh.
|
||||||
|
Object(String),
|
||||||
|
/// Tree expansion or refresh.
|
||||||
|
Tree(String),
|
||||||
|
/// Descriptor fetch.
|
||||||
|
Interface(String),
|
||||||
|
/// Explicit operation call.
|
||||||
|
Operation {
|
||||||
|
/// Target path.
|
||||||
|
path: String,
|
||||||
|
/// Interface reference.
|
||||||
|
interface: String,
|
||||||
|
/// Operation name.
|
||||||
|
operation: String,
|
||||||
|
/// Whether the transport dispatch boundary was crossed.
|
||||||
|
dispatched: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InFlightKind {
|
||||||
|
/// Whether dropping the response is a safe cancellation operation.
|
||||||
|
#[must_use]
|
||||||
|
pub fn cancel_safe(&self) -> bool {
|
||||||
|
!matches!(self, Self::Operation { .. })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Active overlay.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Modal {
|
||||||
|
/// No overlay.
|
||||||
|
None,
|
||||||
|
/// Keyboard help.
|
||||||
|
Help,
|
||||||
|
/// Descriptor-driven field editor.
|
||||||
|
Editor(ArgumentEditor),
|
||||||
|
/// Explicit pre-execution confirmation.
|
||||||
|
Confirm {
|
||||||
|
/// Editor retained when confirmation is cancelled.
|
||||||
|
editor: ArgumentEditor,
|
||||||
|
/// Validated arguments that will be sent.
|
||||||
|
arguments: BTreeMap<String, Value>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Side effect requested by the pure reducer.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Action {
|
||||||
|
/// Expand one node lazily.
|
||||||
|
Expand {
|
||||||
|
/// Tree root path.
|
||||||
|
path: String,
|
||||||
|
/// Maximum returned nodes.
|
||||||
|
limit: u32,
|
||||||
|
},
|
||||||
|
/// Reobserve an Entry and its direct children.
|
||||||
|
Refresh {
|
||||||
|
/// Selected path.
|
||||||
|
path: String,
|
||||||
|
/// Current tree limit.
|
||||||
|
limit: u32,
|
||||||
|
},
|
||||||
|
/// Retrieve one interface descriptor.
|
||||||
|
FetchInterface(String),
|
||||||
|
/// Execute only after explicit confirmation.
|
||||||
|
Execute {
|
||||||
|
/// Entry target.
|
||||||
|
path: String,
|
||||||
|
/// Interface reference.
|
||||||
|
interface: String,
|
||||||
|
/// Operation name.
|
||||||
|
operation: String,
|
||||||
|
/// Descriptor-validated arguments.
|
||||||
|
arguments: BTreeMap<String, Value>,
|
||||||
|
},
|
||||||
|
/// Cancel the newest safe retrieval.
|
||||||
|
CancelRead,
|
||||||
|
/// Reconnect and fetch the root.
|
||||||
|
Reconnect,
|
||||||
|
/// Navigate to a descriptor-declared Entry result.
|
||||||
|
NavigateEntry(String),
|
||||||
|
/// Exit normally.
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Complete presentation model.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct App {
|
||||||
|
/// Effective endpoint label (never credential material).
|
||||||
|
pub endpoint: String,
|
||||||
|
/// Connection lifecycle.
|
||||||
|
pub connection: ConnectionState,
|
||||||
|
/// Materialized tree nodes by path.
|
||||||
|
pub entries: BTreeMap<String, EntryView>,
|
||||||
|
/// Selected Entry path.
|
||||||
|
pub selected_path: String,
|
||||||
|
/// Focused pane.
|
||||||
|
pub focus: Focus,
|
||||||
|
/// Interface descriptor views by opaque reference.
|
||||||
|
pub interfaces: BTreeMap<String, InterfaceView>,
|
||||||
|
/// Selected row in the flattened interface/operation view.
|
||||||
|
pub operation_cursor: usize,
|
||||||
|
/// Selected recent-history row.
|
||||||
|
pub history_cursor: usize,
|
||||||
|
/// Active overlay.
|
||||||
|
pub modal: Modal,
|
||||||
|
/// In-flight requests keyed by client request identity.
|
||||||
|
pub in_flight: BTreeMap<u64, InFlightKind>,
|
||||||
|
/// Recent result and diagnostic history, newest first.
|
||||||
|
pub history: Vec<HistoryItem>,
|
||||||
|
/// Maximum retained presentation history.
|
||||||
|
pub history_limit: usize,
|
||||||
|
/// Default node limit for lazy expansion.
|
||||||
|
pub default_tree_limit: u32,
|
||||||
|
/// One-line status for local action feedback.
|
||||||
|
pub status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
/// Creates a disconnected model with `/` selected.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(endpoint: impl Into<String>) -> Self {
|
||||||
|
let default_tree_limit = 64;
|
||||||
|
let mut entries = BTreeMap::new();
|
||||||
|
entries.insert("/".into(), EntryView::placeholder("/", default_tree_limit));
|
||||||
|
Self {
|
||||||
|
endpoint: endpoint.into(),
|
||||||
|
connection: ConnectionState::Disconnected,
|
||||||
|
entries,
|
||||||
|
selected_path: "/".into(),
|
||||||
|
focus: Focus::Tree,
|
||||||
|
interfaces: BTreeMap::new(),
|
||||||
|
operation_cursor: 0,
|
||||||
|
history_cursor: 0,
|
||||||
|
modal: Modal::None,
|
||||||
|
in_flight: BTreeMap::new(),
|
||||||
|
history: Vec::new(),
|
||||||
|
history_limit: 64,
|
||||||
|
default_tree_limit,
|
||||||
|
status: "press ? for help".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies one key and returns requested effects without performing I/O.
|
||||||
|
pub fn reduce(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
match std::mem::replace(&mut self.modal, Modal::None) {
|
||||||
|
Modal::Help => {
|
||||||
|
if !matches!(key, InputKey::Escape | InputKey::Help) {
|
||||||
|
self.modal = Modal::Help;
|
||||||
|
}
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
Modal::Editor(mut editor) => {
|
||||||
|
match key {
|
||||||
|
InputKey::Escape => {}
|
||||||
|
InputKey::Up => {
|
||||||
|
editor.previous_field();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Down | InputKey::Tab => {
|
||||||
|
editor.next_field();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Backspace => {
|
||||||
|
editor.backspace();
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Character(character) => {
|
||||||
|
editor.insert(character);
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
}
|
||||||
|
InputKey::Enter => match editor.validate() {
|
||||||
|
Ok(arguments) => self.modal = Modal::Confirm { editor, arguments },
|
||||||
|
Err(_) => self.modal = Modal::Editor(editor),
|
||||||
|
},
|
||||||
|
_ => self.modal = Modal::Editor(editor),
|
||||||
|
}
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
Modal::Confirm { editor, arguments } => match key {
|
||||||
|
InputKey::Escape => {
|
||||||
|
self.modal = Modal::Editor(editor);
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
InputKey::Enter | InputKey::Character('e') => {
|
||||||
|
let action = Action::Execute {
|
||||||
|
path: self.selected_path.clone(),
|
||||||
|
interface: editor.interface.clone(),
|
||||||
|
operation: editor.operation.name.clone(),
|
||||||
|
arguments,
|
||||||
|
};
|
||||||
|
self.status =
|
||||||
|
"operation confirmed; preparing request (not yet dispatched)".into();
|
||||||
|
return vec![action];
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.modal = Modal::Confirm { editor, arguments };
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Modal::None => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if key == InputKey::Help {
|
||||||
|
self.modal = Modal::Help;
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
if key == InputKey::Quit {
|
||||||
|
return vec![Action::Quit];
|
||||||
|
}
|
||||||
|
if key == InputKey::Reconnect {
|
||||||
|
return vec![Action::Reconnect];
|
||||||
|
}
|
||||||
|
if key == InputKey::CancelRead {
|
||||||
|
return vec![Action::CancelRead];
|
||||||
|
}
|
||||||
|
if key == InputKey::Tab {
|
||||||
|
self.focus = self.focus.next();
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.focus {
|
||||||
|
Focus::Tree => self.reduce_tree(key),
|
||||||
|
Focus::Operations => self.reduce_operations(key),
|
||||||
|
Focus::History => self.reduce_history(key),
|
||||||
|
Focus::Entry => {
|
||||||
|
if key == InputKey::Escape {
|
||||||
|
self.focus = Focus::Tree;
|
||||||
|
} else if key == InputKey::Refresh {
|
||||||
|
return vec![self.refresh_action()];
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_tree(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
let visible = self.visible_paths();
|
||||||
|
let position = visible
|
||||||
|
.iter()
|
||||||
|
.position(|path| path == &self.selected_path)
|
||||||
|
.unwrap_or(0);
|
||||||
|
match key {
|
||||||
|
InputKey::Up if position > 0 => self.selected_path = visible[position - 1].clone(),
|
||||||
|
InputKey::Down if position + 1 < visible.len() => {
|
||||||
|
self.selected_path = visible[position + 1].clone();
|
||||||
|
}
|
||||||
|
InputKey::Right | InputKey::Enter => {
|
||||||
|
let node = self
|
||||||
|
.entries
|
||||||
|
.entry(self.selected_path.clone())
|
||||||
|
.or_insert_with(|| {
|
||||||
|
EntryView::placeholder(&self.selected_path, self.default_tree_limit)
|
||||||
|
});
|
||||||
|
node.expanded = true;
|
||||||
|
if !matches!(node.tree_state, ViewState::Fresh) || node.truncated {
|
||||||
|
return vec![Action::Expand {
|
||||||
|
path: node.path.clone(),
|
||||||
|
limit: node.limit,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Left => {
|
||||||
|
let node = self
|
||||||
|
.entries
|
||||||
|
.get_mut(&self.selected_path)
|
||||||
|
.expect("selected Entry exists");
|
||||||
|
if node.expanded {
|
||||||
|
node.expanded = false;
|
||||||
|
} else if self.selected_path != "/" {
|
||||||
|
self.selected_path = parent_path(&self.selected_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Refresh => return vec![self.refresh_action()],
|
||||||
|
InputKey::IncreaseLimit => {
|
||||||
|
let node = self
|
||||||
|
.entries
|
||||||
|
.get_mut(&self.selected_path)
|
||||||
|
.expect("selected exists");
|
||||||
|
node.limit = node.limit.saturating_mul(2).max(1);
|
||||||
|
node.expanded = true;
|
||||||
|
return vec![Action::Expand {
|
||||||
|
path: node.path.clone(),
|
||||||
|
limit: node.limit,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
self.operation_cursor = 0;
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_operations(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
let rows = self.operation_rows();
|
||||||
|
match key {
|
||||||
|
InputKey::Up => self.operation_cursor = self.operation_cursor.saturating_sub(1),
|
||||||
|
InputKey::Down if self.operation_cursor + 1 < rows.len() => self.operation_cursor += 1,
|
||||||
|
InputKey::Refresh => return vec![self.refresh_action()],
|
||||||
|
InputKey::Escape => self.focus = Focus::Tree,
|
||||||
|
InputKey::Enter => {
|
||||||
|
if let Some(row) = rows.get(self.operation_cursor) {
|
||||||
|
if let Some(operation_name) = &row.operation {
|
||||||
|
if let Some(interface) = self.interfaces.get(&row.interface)
|
||||||
|
&& let Some(descriptor) = &interface.descriptor
|
||||||
|
&& let Some(operation) = descriptor
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.name == *operation_name)
|
||||||
|
{
|
||||||
|
self.modal = Modal::Editor(ArgumentEditor::new(
|
||||||
|
row.interface.clone(),
|
||||||
|
descriptor.clone(),
|
||||||
|
operation.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return vec![Action::FetchInterface(row.interface.clone())];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reduce_history(&mut self, key: InputKey) -> Vec<Action> {
|
||||||
|
match key {
|
||||||
|
InputKey::Up => self.history_cursor = self.history_cursor.saturating_sub(1),
|
||||||
|
InputKey::Down if self.history_cursor + 1 < self.history.len() => {
|
||||||
|
self.history_cursor += 1;
|
||||||
|
}
|
||||||
|
InputKey::Enter => {
|
||||||
|
if let Some(path) = self
|
||||||
|
.history
|
||||||
|
.get(self.history_cursor)
|
||||||
|
.and_then(|item| item.entry_target.clone())
|
||||||
|
{
|
||||||
|
return vec![Action::NavigateEntry(path)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputKey::Escape => self.focus = Focus::Tree,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_action(&self) -> Action {
|
||||||
|
let limit = self
|
||||||
|
.entries
|
||||||
|
.get(&self.selected_path)
|
||||||
|
.map_or(self.default_tree_limit, |entry| entry.limit);
|
||||||
|
Action::Refresh {
|
||||||
|
path: self.selected_path.clone(),
|
||||||
|
limit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records a pending request separately by interaction type.
|
||||||
|
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
|
||||||
|
match &kind {
|
||||||
|
InFlightKind::Object(path) => {
|
||||||
|
self.ensure_entry(path).state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Tree(path) => {
|
||||||
|
let entry = self.ensure_entry(path);
|
||||||
|
entry.state = ViewState::Loading(id);
|
||||||
|
entry.tree_state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Interface(reference) => {
|
||||||
|
self.ensure_interface(reference).state = ViewState::Loading(id);
|
||||||
|
}
|
||||||
|
InFlightKind::Operation { .. } => {}
|
||||||
|
}
|
||||||
|
self.in_flight.insert(id, kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks an operation as handed to the transport.
|
||||||
|
pub fn request_dispatched(&mut self, id: u64) {
|
||||||
|
if let Some(InFlightKind::Operation { dispatched, .. }) = self.in_flight.get_mut(&id) {
|
||||||
|
*dispatched = true;
|
||||||
|
self.status = "operation dispatched once; automatic retry is disabled".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a completed request identity.
|
||||||
|
pub fn request_finished(&mut self, id: u64) -> Option<InFlightKind> {
|
||||||
|
self.in_flight.remove(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies an object observation from `wip-client`.
|
||||||
|
pub fn apply_object(&mut self, observation: ObjectObservation) {
|
||||||
|
let entry = self.ensure_entry(&observation.path);
|
||||||
|
entry.object = observation.object;
|
||||||
|
entry.state = ViewState::from(&observation.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a lazy tree observation and ensures child placeholders exist.
|
||||||
|
pub fn apply_tree(&mut self, observation: TreeObservation) {
|
||||||
|
let children = observation.children.clone();
|
||||||
|
let entry = self.ensure_entry(&observation.path);
|
||||||
|
entry.children = children.clone();
|
||||||
|
entry.truncated = observation.truncated;
|
||||||
|
entry.tree_state = ViewState::from(&observation.state);
|
||||||
|
entry.expanded = true;
|
||||||
|
for path in children {
|
||||||
|
self.ensure_entry(&path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies one interface observation from `wip-client`.
|
||||||
|
pub fn apply_interface(&mut self, observation: InterfaceObservation) {
|
||||||
|
let view = self.ensure_interface(&observation.reference);
|
||||||
|
*view = InterfaceView {
|
||||||
|
reference: observation.reference,
|
||||||
|
descriptor: observation.descriptor,
|
||||||
|
state: ViewState::from(&observation.state),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces current Entry details from the client's current snapshot.
|
||||||
|
pub fn sync_object(&mut self, path: &str, observation: Option<ObjectObservation>) {
|
||||||
|
match observation {
|
||||||
|
Some(observation) => self.apply_object(observation),
|
||||||
|
None => {
|
||||||
|
let entry = self.ensure_entry(path);
|
||||||
|
entry.object = None;
|
||||||
|
entry.state = ViewState::Stale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Selects a known or newly discovered descriptor-declared Entry path.
|
||||||
|
pub fn navigate_entry(&mut self, path: impl Into<String>) {
|
||||||
|
let path = path.into();
|
||||||
|
self.ensure_entry(&path);
|
||||||
|
self.selected_path = path;
|
||||||
|
self.focus = Focus::Tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds one bounded recent item.
|
||||||
|
pub fn push_history(&mut self, item: HistoryItem) {
|
||||||
|
self.history.insert(0, item);
|
||||||
|
self.history.truncate(self.history_limit);
|
||||||
|
self.history_cursor = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns visible tree paths in display order.
|
||||||
|
#[must_use]
|
||||||
|
pub fn visible_paths(&self) -> Vec<String> {
|
||||||
|
let mut visible = Vec::new();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
self.collect_visible("/", &mut seen, &mut visible);
|
||||||
|
if !seen.contains(&self.selected_path) && self.entries.contains_key(&self.selected_path) {
|
||||||
|
visible.push(self.selected_path.clone());
|
||||||
|
}
|
||||||
|
visible
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_visible(&self, path: &str, seen: &mut BTreeSet<String>, visible: &mut Vec<String>) {
|
||||||
|
if !seen.insert(path.to_owned()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
visible.push(path.to_owned());
|
||||||
|
let Some(entry) = self.entries.get(path) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if entry.expanded {
|
||||||
|
for child in &entry.children {
|
||||||
|
self.collect_visible(child, seen, visible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns flattened interface headers and operations for the selected Entry.
|
||||||
|
#[must_use]
|
||||||
|
pub fn operation_rows(&self) -> Vec<OperationRow> {
|
||||||
|
let Some(object) = self
|
||||||
|
.entries
|
||||||
|
.get(&self.selected_path)
|
||||||
|
.filter(|entry| entry.state == ViewState::Fresh)
|
||||||
|
.and_then(|entry| entry.object.as_ref())
|
||||||
|
else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for reference in &object.interfaces {
|
||||||
|
rows.push(OperationRow {
|
||||||
|
interface: reference.clone(),
|
||||||
|
operation: None,
|
||||||
|
});
|
||||||
|
if let Some(descriptor) = self
|
||||||
|
.interfaces
|
||||||
|
.get(reference)
|
||||||
|
.filter(|view| view.state == ViewState::Fresh)
|
||||||
|
.and_then(|view| view.descriptor.as_ref())
|
||||||
|
{
|
||||||
|
rows.extend(descriptor.operations.iter().map(|operation| OperationRow {
|
||||||
|
interface: reference.clone(),
|
||||||
|
operation: Some(operation.name.clone()),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
|
||||||
|
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
|
||||||
|
let candidate = self
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.find(|(candidate, entry)| {
|
||||||
|
candidate.as_str() != "/"
|
||||||
|
&& candidate.as_str() != self.selected_path
|
||||||
|
&& matches!(
|
||||||
|
entry.state,
|
||||||
|
ViewState::Unloaded | ViewState::Stale | ViewState::Error(_)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.entries.iter().find(|(candidate, entry)| {
|
||||||
|
candidate.as_str() != "/"
|
||||||
|
&& candidate.as_str() != self.selected_path
|
||||||
|
&& !matches!(entry.state, ViewState::Loading(_))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(|(candidate, _)| candidate.clone());
|
||||||
|
if let Some(candidate) = candidate {
|
||||||
|
self.entries.remove(&candidate);
|
||||||
|
for entry in self.entries.values_mut() {
|
||||||
|
entry.children.retain(|child| child != &candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.entries
|
||||||
|
.entry(path.to_owned())
|
||||||
|
.or_insert_with(|| EntryView::placeholder(path, self.default_tree_limit))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_interface(&mut self, reference: &str) -> &mut InterfaceView {
|
||||||
|
if !self.interfaces.contains_key(reference)
|
||||||
|
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
|
||||||
|
{
|
||||||
|
let protected = self
|
||||||
|
.entries
|
||||||
|
.get(&self.selected_path)
|
||||||
|
.and_then(|entry| entry.object.as_ref())
|
||||||
|
.map(|object| object.interfaces.iter().cloned().collect::<BTreeSet<_>>())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let candidate = self
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.find(|(candidate, interface)| {
|
||||||
|
!protected.contains(*candidate)
|
||||||
|
&& !matches!(interface.state, ViewState::Loading(_))
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
self.interfaces
|
||||||
|
.iter()
|
||||||
|
.find(|(_, interface)| !matches!(interface.state, ViewState::Loading(_)))
|
||||||
|
})
|
||||||
|
.map(|(candidate, _)| candidate.clone());
|
||||||
|
if let Some(candidate) = candidate {
|
||||||
|
self.interfaces.remove(&candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.interfaces
|
||||||
|
.entry(reference.to_owned())
|
||||||
|
.or_insert_with(|| InterfaceView {
|
||||||
|
reference: reference.to_owned(),
|
||||||
|
descriptor: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row in the combined Interface and Operation pane.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct OperationRow {
|
||||||
|
/// Interface reference, which participates in operation identity.
|
||||||
|
pub interface: String,
|
||||||
|
/// Operation name, or `None` for the interface heading.
|
||||||
|
pub operation: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical parent of a non-root path.
|
||||||
|
#[must_use]
|
||||||
|
pub fn parent_path(path: &str) -> String {
|
||||||
|
match path.rsplit_once('/') {
|
||||||
|
Some(("", _)) | None => "/".into(),
|
||||||
|
Some((parent, _)) => parent.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
|
||||||
|
|
||||||
|
fn object(name: &str, interfaces: &[&str]) -> Object {
|
||||||
|
Object {
|
||||||
|
name: name.into(),
|
||||||
|
description: Some(format!("{name} description")),
|
||||||
|
interfaces: interfaces.iter().map(|value| (*value).into()).collect(),
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tree_navigation_expansion_parent_and_limit_are_pure() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.apply_tree(TreeObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
children: vec!["/a".into(), "/b".into()],
|
||||||
|
truncated: true,
|
||||||
|
revision: request_id(),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
assert_eq!(app.visible_paths(), ["/", "/a", "/b"]);
|
||||||
|
app.reduce(InputKey::Down);
|
||||||
|
assert_eq!(app.selected_path, "/a");
|
||||||
|
app.reduce(InputKey::Left);
|
||||||
|
assert_eq!(app.selected_path, "/");
|
||||||
|
assert!(matches!(
|
||||||
|
app.reduce(InputKey::IncreaseLimit).as_slice(),
|
||||||
|
[Action::Expand { path, limit: 128 }] if path == "/"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn focus_modal_and_explicit_confirmation_gate_execution() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(object("", &["iface"])),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let descriptor = InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "ping".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "iface".into(),
|
||||||
|
descriptor: Some(descriptor),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.focus = Focus::Operations;
|
||||||
|
app.operation_cursor = 1;
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
assert!(matches!(app.modal, Modal::Editor(_)));
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
assert!(matches!(app.modal, Modal::Confirm { .. }));
|
||||||
|
assert!(matches!(
|
||||||
|
app.reduce(InputKey::Enter).as_slice(),
|
||||||
|
[Action::Execute { operation, .. }] if operation == "ping"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presentation_maps_enforce_client_sized_hard_bounds() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
for index in 0..(MAX_PRESENTATION_ENTRIES + 100) {
|
||||||
|
app.navigate_entry(format!("/discovered-{index}"));
|
||||||
|
app.selected_path = "/".into();
|
||||||
|
}
|
||||||
|
assert!(app.entries.len() <= MAX_PRESENTATION_ENTRIES);
|
||||||
|
assert!(app.entries.contains_key("/"));
|
||||||
|
|
||||||
|
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: format!("interface-{index}"),
|
||||||
|
descriptor: None,
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert!(app.interfaces.len() <= MAX_PRESENTATION_INTERFACES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn result_navigation_only_uses_explicit_entry_target() {
|
||||||
|
let mut app = App::new("https://example.test/wip");
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Success,
|
||||||
|
title: "string".into(),
|
||||||
|
detail: "/looks/like/a/path".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
app.focus = Focus::History;
|
||||||
|
assert!(app.reduce(InputKey::Enter).is_empty());
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Success,
|
||||||
|
title: "Entry".into(),
|
||||||
|
detail: "/actual".into(),
|
||||||
|
entry_target: Some("/actual".into()),
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
app.reduce(InputKey::Enter),
|
||||||
|
vec![Action::NavigateEntry("/actual".into())]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_id() -> wip_client::RequestId {
|
||||||
|
// A request identity has no public constructor; derive one through the runtime.
|
||||||
|
let mut client = wip_client::Client::new(
|
||||||
|
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
||||||
|
wip_https::Limits::new(1024, 1024, 8, 8).unwrap(),
|
||||||
|
);
|
||||||
|
let session = client
|
||||||
|
.open_session(
|
||||||
|
"https://example.test/wip",
|
||||||
|
wip_client::SecurityContext::new("test"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.prepare_fetch(&session, "/").unwrap().id
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
//! Secure-by-default command-line and environment configuration.
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Debug, Display, Formatter};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use wip_https::url::Url;
|
||||||
|
|
||||||
|
/// Credential wrapper whose debug output is always redacted.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Secret(String);
|
||||||
|
|
||||||
|
impl Secret {
|
||||||
|
pub(crate) fn expose(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for Secret {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter.write_str("Secret([REDACTED])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validated runtime configuration.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Canonical logical HTTPS endpoint used by `wip-client`.
|
||||||
|
logical_endpoint: String,
|
||||||
|
/// Actual request origin; differs only for explicit loopback development HTTP.
|
||||||
|
transport_endpoint: String,
|
||||||
|
/// Non-secret cache partition identity.
|
||||||
|
security_context: String,
|
||||||
|
/// Bounded network timeout.
|
||||||
|
timeout: Duration,
|
||||||
|
/// Optional complete Authorization header value, never rendered or logged.
|
||||||
|
authorization: Option<Secret>,
|
||||||
|
/// Whether loopback request URIs are deliberately downgraded to HTTP.
|
||||||
|
development_http: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Debug for Config {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter
|
||||||
|
.debug_struct("Config")
|
||||||
|
.field("logical_endpoint", &self.logical_endpoint)
|
||||||
|
.field("transport_endpoint", &self.transport_endpoint)
|
||||||
|
.field("security_context", &self.security_context)
|
||||||
|
.field("timeout", &self.timeout)
|
||||||
|
.field("authorization", &self.authorization)
|
||||||
|
.field("development_http", &self.development_http)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// Returns the canonical HTTPS endpoint used for protocol request construction.
|
||||||
|
#[must_use]
|
||||||
|
pub fn logical_endpoint(&self) -> &str {
|
||||||
|
&self.logical_endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the validated effective transport endpoint shown in the UI.
|
||||||
|
#[must_use]
|
||||||
|
pub fn transport_endpoint(&self) -> &str {
|
||||||
|
&self.transport_endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the non-secret session cache partition identity.
|
||||||
|
#[must_use]
|
||||||
|
pub fn security_context(&self) -> &str {
|
||||||
|
&self.security_context
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the end-to-end request timeout.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn timeout(&self) -> Duration {
|
||||||
|
self.timeout
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether explicit loopback development HTTP is enabled.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn development_http(&self) -> bool {
|
||||||
|
self.development_http
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn authorization(&self) -> Option<&Secret> {
|
||||||
|
self.authorization.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses process arguments and supported environment variables.
|
||||||
|
///
|
||||||
|
/// Endpoint precedence is `--endpoint`, a positional endpoint, then
|
||||||
|
/// `WIP_ENDPOINT`. Authorization is read only from the variable named by
|
||||||
|
/// `--authorization-env` (default `WIP_AUTHORIZATION`).
|
||||||
|
pub fn from_env() -> Result<Self, ConfigError> {
|
||||||
|
let arguments = std::env::args().skip(1).collect::<Vec<_>>();
|
||||||
|
let endpoint_env = std::env::var("WIP_ENDPOINT").ok();
|
||||||
|
let security_context = std::env::var("WIP_SECURITY_CONTEXT").ok();
|
||||||
|
Self::parse(arguments, endpoint_env, security_context, |name| {
|
||||||
|
std::env::var(name).ok()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses supplied values; exposed to make startup policy independently testable.
|
||||||
|
pub fn parse<I, S, F>(
|
||||||
|
arguments: I,
|
||||||
|
endpoint_env: Option<String>,
|
||||||
|
security_context_env: Option<String>,
|
||||||
|
mut read_secret: F,
|
||||||
|
) -> Result<Self, ConfigError>
|
||||||
|
where
|
||||||
|
I: IntoIterator<Item = S>,
|
||||||
|
S: Into<String>,
|
||||||
|
F: FnMut(&str) -> Option<String>,
|
||||||
|
{
|
||||||
|
let mut endpoint = None;
|
||||||
|
let mut allow_http = false;
|
||||||
|
let mut timeout = Duration::from_secs(30);
|
||||||
|
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
|
||||||
|
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
|
||||||
|
let mut iter = arguments.into_iter().map(Into::into);
|
||||||
|
while let Some(argument) = iter.next() {
|
||||||
|
match argument.as_str() {
|
||||||
|
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
|
||||||
|
"--allow-http" => allow_http = true,
|
||||||
|
"--security-context" => {
|
||||||
|
security_context = next_value(&mut iter, "--security-context")?;
|
||||||
|
}
|
||||||
|
"--authorization-env" => {
|
||||||
|
authorization_env = next_value(&mut iter, "--authorization-env")?;
|
||||||
|
}
|
||||||
|
"--timeout" => {
|
||||||
|
let raw = next_value(&mut iter, "--timeout")?;
|
||||||
|
let seconds = raw
|
||||||
|
.parse::<u64>()
|
||||||
|
.ok()
|
||||||
|
.filter(|seconds| *seconds > 0)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
ConfigError::Invalid("--timeout must be a positive integer".into())
|
||||||
|
})?;
|
||||||
|
timeout = Duration::from_secs(seconds);
|
||||||
|
}
|
||||||
|
"--help" | "-h" => return Err(ConfigError::Help),
|
||||||
|
value if value.starts_with('-') => {
|
||||||
|
return Err(ConfigError::Invalid(format!("unknown option {value}")));
|
||||||
|
}
|
||||||
|
value if endpoint.is_none() => endpoint = Some(value.to_owned()),
|
||||||
|
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let endpoint = endpoint
|
||||||
|
.or(endpoint_env)
|
||||||
|
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
|
||||||
|
let mut actual = Url::parse(&endpoint)
|
||||||
|
.map_err(|_| ConfigError::Invalid("endpoint is not a valid absolute URL".into()))?;
|
||||||
|
if actual.query().is_some()
|
||||||
|
|| actual.fragment().is_some()
|
||||||
|
|| actual.host_str().is_none()
|
||||||
|
|| !actual.username().is_empty()
|
||||||
|
|| actual.password().is_some()
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"endpoint must be an absolute URL without userinfo, query, or fragment".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !actual.path().ends_with('/') {
|
||||||
|
let path = format!("{}/", actual.path());
|
||||||
|
actual.set_path(&path);
|
||||||
|
}
|
||||||
|
let development_http = actual.scheme() == "http";
|
||||||
|
match actual.scheme() {
|
||||||
|
"https" => {}
|
||||||
|
"http" if allow_http && loopback_host(&actual) => {}
|
||||||
|
"http" if !allow_http => {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"plain HTTP requires the explicit --allow-http development option".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
"http" => {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"development HTTP is restricted to loopback endpoints".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
_ => return Err(ConfigError::Invalid("endpoint must use HTTPS".into())),
|
||||||
|
}
|
||||||
|
let transport_endpoint = actual.to_string();
|
||||||
|
let mut logical = actual;
|
||||||
|
if development_http {
|
||||||
|
logical
|
||||||
|
.set_scheme("https")
|
||||||
|
.expect("http and https are interchangeable hierarchical schemes");
|
||||||
|
}
|
||||||
|
// Let the binding enforce all remaining canonical endpoint rules.
|
||||||
|
let logical_endpoint = wip_https::Endpoint::parse(logical.as_str())
|
||||||
|
.map_err(|error| ConfigError::Invalid(error.to_string()))?
|
||||||
|
.to_string();
|
||||||
|
if security_context.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"security context must not be empty".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let authorization = read_secret(&authorization_env)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(Secret);
|
||||||
|
Ok(Self {
|
||||||
|
logical_endpoint,
|
||||||
|
transport_endpoint,
|
||||||
|
security_context,
|
||||||
|
timeout,
|
||||||
|
authorization,
|
||||||
|
development_http,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns concise command usage without mentioning credential values.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn usage() -> &'static str {
|
||||||
|
"usage: wip-tui [--endpoint] URL [--allow-http] [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
|
||||||
|
URL may also be supplied as WIP_ENDPOINT; HTTPS is required unless loopback HTTP is explicitly enabled."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_value(
|
||||||
|
iter: &mut impl Iterator<Item = String>,
|
||||||
|
option: &str,
|
||||||
|
) -> Result<String, ConfigError> {
|
||||||
|
iter.next()
|
||||||
|
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loopback_host(url: &Url) -> bool {
|
||||||
|
match url.host() {
|
||||||
|
Some(wip_https::url::Host::Ipv4(address)) => address.is_loopback(),
|
||||||
|
Some(wip_https::url::Host::Ipv6(address)) => address.is_loopback(),
|
||||||
|
Some(wip_https::url::Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"),
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Startup configuration failure.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
/// Help was requested.
|
||||||
|
Help,
|
||||||
|
/// A safe, non-secret configuration diagnostic.
|
||||||
|
Invalid(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ConfigError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Help => formatter.write_str(Config::usage()),
|
||||||
|
Self::Invalid(detail) => write!(formatter, "{detail}\n{}", Config::usage()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ConfigError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn https_is_default_and_secrets_are_redacted() {
|
||||||
|
let config = Config::parse(
|
||||||
|
["https://example.test/wip", "--authorization-env", "TOKEN"],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(config.logical_endpoint(), "https://example.test/wip/");
|
||||||
|
let debug = format!("{config:?}");
|
||||||
|
assert!(debug.contains("[REDACTED]"));
|
||||||
|
assert!(!debug.contains("secret-value"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
|
||||||
|
for arguments in [
|
||||||
|
vec!["https://user:password@example.test/wip"],
|
||||||
|
vec!["http://user:password@localhost:3000/wip", "--allow-http"],
|
||||||
|
] {
|
||||||
|
let error = Config::parse(arguments, None, None, |_| None).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("without userinfo"));
|
||||||
|
assert!(!error.to_string().contains("password"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn http_requires_explicit_loopback_development_mode() {
|
||||||
|
assert!(Config::parse(["http://localhost:3000/wip"], None, None, |_| None).is_err());
|
||||||
|
let config = Config::parse(
|
||||||
|
["http://127.0.0.1:3000/wip", "--allow-http"],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(config.logical_endpoint(), "https://127.0.0.1:3000/wip/");
|
||||||
|
assert_eq!(config.transport_endpoint(), "http://127.0.0.1:3000/wip/");
|
||||||
|
assert!(config.development_http());
|
||||||
|
assert!(
|
||||||
|
Config::parse(
|
||||||
|
["http://example.test/wip", "--allow-http"],
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,628 @@
|
|||||||
|
//! Descriptor-driven operation argument editing and validation.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::STANDARD;
|
||||||
|
use wip_protocol::{InterfaceDescriptor, OperationDeclaration, TypeExpr, Value};
|
||||||
|
|
||||||
|
const MAX_FIELD_INPUT_BYTES: usize = 256 * 1024;
|
||||||
|
|
||||||
|
/// One editable top-level operation parameter.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArgumentField {
|
||||||
|
/// Parameter name.
|
||||||
|
pub name: String,
|
||||||
|
/// Whether the parameter must be supplied.
|
||||||
|
pub required: bool,
|
||||||
|
/// Canonical descriptor type.
|
||||||
|
pub r#type: TypeExpr,
|
||||||
|
/// User-entered text.
|
||||||
|
pub input: String,
|
||||||
|
/// Field-local validation diagnostic.
|
||||||
|
pub diagnostic: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marker returned when one or more field diagnostics prevent submission.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct InvalidArguments;
|
||||||
|
|
||||||
|
/// Pure, terminal-independent editor built from an operation descriptor.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ArgumentEditor {
|
||||||
|
/// Opaque interface reference selected for the call.
|
||||||
|
pub interface: String,
|
||||||
|
/// Selected operation declaration.
|
||||||
|
pub operation: OperationDeclaration,
|
||||||
|
/// Complete descriptor used to resolve named types.
|
||||||
|
pub descriptor: InterfaceDescriptor,
|
||||||
|
/// Top-level parameter fields in declaration order.
|
||||||
|
pub fields: Vec<ArgumentField>,
|
||||||
|
/// Index of the active field.
|
||||||
|
pub cursor: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ArgumentEditor {
|
||||||
|
/// Builds an editor whose fields preserve descriptor order.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(
|
||||||
|
interface: impl Into<String>,
|
||||||
|
descriptor: InterfaceDescriptor,
|
||||||
|
operation: OperationDeclaration,
|
||||||
|
) -> Self {
|
||||||
|
let fields = operation
|
||||||
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| ArgumentField {
|
||||||
|
name: parameter.name.clone(),
|
||||||
|
required: parameter.required,
|
||||||
|
r#type: parameter.r#type.clone(),
|
||||||
|
input: if parameter.required && parameter.r#type == TypeExpr::Unit {
|
||||||
|
"null".into()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
|
diagnostic: None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
interface: interface.into(),
|
||||||
|
operation,
|
||||||
|
descriptor,
|
||||||
|
fields,
|
||||||
|
cursor: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves to the preceding field without wrapping.
|
||||||
|
pub fn previous_field(&mut self) {
|
||||||
|
self.cursor = self.cursor.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves to the following field without wrapping.
|
||||||
|
pub fn next_field(&mut self) {
|
||||||
|
if self.cursor + 1 < self.fields.len() {
|
||||||
|
self.cursor += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends one printable character to the active field.
|
||||||
|
pub fn insert(&mut self, character: char) {
|
||||||
|
if !character.is_control()
|
||||||
|
&& let Some(field) = self.fields.get_mut(self.cursor)
|
||||||
|
{
|
||||||
|
if field.input.len().saturating_add(character.len_utf8()) <= MAX_FIELD_INPUT_BYTES {
|
||||||
|
field.input.push(character);
|
||||||
|
field.diagnostic = None;
|
||||||
|
} else {
|
||||||
|
field.diagnostic = Some("field input reached the 256 KiB limit".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes one scalar value from the active field.
|
||||||
|
pub fn backspace(&mut self) {
|
||||||
|
if let Some(field) = self.fields.get_mut(self.cursor) {
|
||||||
|
field.input.pop();
|
||||||
|
field.diagnostic = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates all fields and returns protocol values when every field is valid.
|
||||||
|
///
|
||||||
|
/// Invalid or missing values are retained as field-local diagnostics. Optional
|
||||||
|
/// blank fields are omitted from the resulting argument map.
|
||||||
|
pub fn validate(&mut self) -> Result<BTreeMap<String, Value>, InvalidArguments> {
|
||||||
|
let mut arguments = BTreeMap::new();
|
||||||
|
let mut invalid = false;
|
||||||
|
for field in &mut self.fields {
|
||||||
|
field.diagnostic = None;
|
||||||
|
if field.input.len() > MAX_FIELD_INPUT_BYTES {
|
||||||
|
field.diagnostic = Some("field input exceeds the 256 KiB limit".into());
|
||||||
|
invalid = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if field.input.trim().is_empty() {
|
||||||
|
if field.required {
|
||||||
|
field.diagnostic = Some("required value is missing".into());
|
||||||
|
invalid = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match parse_value(
|
||||||
|
&self.descriptor,
|
||||||
|
&field.r#type,
|
||||||
|
field.input.trim(),
|
||||||
|
&field.name,
|
||||||
|
) {
|
||||||
|
Ok(value) => {
|
||||||
|
arguments.insert(field.name.clone(), value);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
field.diagnostic = Some(error);
|
||||||
|
invalid = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if invalid {
|
||||||
|
return Err(InvalidArguments);
|
||||||
|
}
|
||||||
|
if let Err(error) = self
|
||||||
|
.descriptor
|
||||||
|
.validate_arguments(&self.operation.name, &arguments)
|
||||||
|
{
|
||||||
|
if let Some(field) = self.fields.get_mut(self.cursor) {
|
||||||
|
field.diagnostic = Some(error.to_string());
|
||||||
|
}
|
||||||
|
return Err(InvalidArguments);
|
||||||
|
}
|
||||||
|
Ok(arguments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a compact canonical spelling for a type expression.
|
||||||
|
#[must_use]
|
||||||
|
pub fn type_name(r#type: &TypeExpr) -> String {
|
||||||
|
match r#type {
|
||||||
|
TypeExpr::Unit => "Unit".into(),
|
||||||
|
TypeExpr::Boolean => "Boolean".into(),
|
||||||
|
TypeExpr::Integer => "Integer".into(),
|
||||||
|
TypeExpr::Number => "Number".into(),
|
||||||
|
TypeExpr::String => "String".into(),
|
||||||
|
TypeExpr::Bytes => "Bytes(base64)".into(),
|
||||||
|
TypeExpr::Json => "Json".into(),
|
||||||
|
TypeExpr::Entry => "Entry".into(),
|
||||||
|
TypeExpr::Named { name } => name.clone(),
|
||||||
|
TypeExpr::Record { fields } => format!(
|
||||||
|
"Record{{{}}}",
|
||||||
|
fields
|
||||||
|
.iter()
|
||||||
|
.map(|field| format!(
|
||||||
|
"{}{}: {}",
|
||||||
|
field.name,
|
||||||
|
if field.required { "" } else { "?" },
|
||||||
|
type_name(&field.r#type)
|
||||||
|
))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
),
|
||||||
|
TypeExpr::List { items } => format!("List<{}>", type_name(items)),
|
||||||
|
TypeExpr::Enum { cases } => format!(
|
||||||
|
"Enum<{}>",
|
||||||
|
cases
|
||||||
|
.iter()
|
||||||
|
.map(|case| case.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" | ")
|
||||||
|
),
|
||||||
|
TypeExpr::Union { cases } => format!(
|
||||||
|
"Union<{}>",
|
||||||
|
cases
|
||||||
|
.iter()
|
||||||
|
.map(|case| case.name.as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" | ")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_value(
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
r#type: &TypeExpr,
|
||||||
|
input: &str,
|
||||||
|
field: &str,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
if let TypeExpr::Named { name } = r#type {
|
||||||
|
let declaration = descriptor
|
||||||
|
.types
|
||||||
|
.iter()
|
||||||
|
.find(|declaration| declaration.name == *name)
|
||||||
|
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
|
||||||
|
return parse_value(descriptor, &declaration.definition, input, field);
|
||||||
|
}
|
||||||
|
let value = match r#type {
|
||||||
|
TypeExpr::Unit => {
|
||||||
|
if matches!(input, "null" | "()") {
|
||||||
|
Value::Unit
|
||||||
|
} else {
|
||||||
|
return Err(format!("{field}: expected null"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TypeExpr::Boolean => input
|
||||||
|
.parse::<bool>()
|
||||||
|
.map(Value::Boolean)
|
||||||
|
.map_err(|_| format!("{field}: expected true or false"))?,
|
||||||
|
TypeExpr::Integer => input
|
||||||
|
.parse::<i64>()
|
||||||
|
.map(Value::Integer)
|
||||||
|
.map_err(|_| format!("{field}: expected a signed integer"))?,
|
||||||
|
TypeExpr::Number => {
|
||||||
|
let number = input
|
||||||
|
.parse::<f64>()
|
||||||
|
.map_err(|_| format!("{field}: expected a finite number"))?;
|
||||||
|
if !number.is_finite() {
|
||||||
|
return Err(format!("{field}: expected a finite number"));
|
||||||
|
}
|
||||||
|
Value::Number(number)
|
||||||
|
}
|
||||||
|
TypeExpr::String => Value::String(parse_string(input)),
|
||||||
|
TypeExpr::Bytes => Value::Bytes(
|
||||||
|
STANDARD
|
||||||
|
.decode(input)
|
||||||
|
.map_err(|_| format!("{field}: expected RFC 4648 base64"))?,
|
||||||
|
),
|
||||||
|
TypeExpr::Entry => {
|
||||||
|
let path = parse_string(input);
|
||||||
|
wip_protocol::validate_path(&path)
|
||||||
|
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
|
||||||
|
Value::String(path)
|
||||||
|
}
|
||||||
|
TypeExpr::Enum { cases } => {
|
||||||
|
let case = parse_string(input);
|
||||||
|
if !cases.iter().any(|candidate| candidate.name == case) {
|
||||||
|
return Err(format!("{field}: unknown enum case {case}"));
|
||||||
|
}
|
||||||
|
Value::String(case)
|
||||||
|
}
|
||||||
|
TypeExpr::Json => {
|
||||||
|
let json = serde_json::from_str(input)
|
||||||
|
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
|
||||||
|
json_to_untyped(&json, field)?
|
||||||
|
}
|
||||||
|
TypeExpr::Record { .. } | TypeExpr::List { .. } | TypeExpr::Union { .. } => {
|
||||||
|
let json = serde_json::from_str(input)
|
||||||
|
.map_err(|error| format!("{field}: invalid JSON: {error}"))?;
|
||||||
|
json_to_typed(descriptor, r#type, &json, field)?
|
||||||
|
}
|
||||||
|
TypeExpr::Named { .. } => unreachable!("named types handled above"),
|
||||||
|
};
|
||||||
|
descriptor
|
||||||
|
.validate_value(r#type, &value)
|
||||||
|
.map_err(|error| format!("{field}: {error}"))?;
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_string(input: &str) -> String {
|
||||||
|
serde_json::from_str::<String>(input).unwrap_or_else(|_| input.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_to_typed(
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
r#type: &TypeExpr,
|
||||||
|
json: &serde_json::Value,
|
||||||
|
field: &str,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
if let TypeExpr::Named { name } = r#type {
|
||||||
|
let declaration = descriptor
|
||||||
|
.types
|
||||||
|
.iter()
|
||||||
|
.find(|declaration| declaration.name == *name)
|
||||||
|
.ok_or_else(|| format!("{field}: unknown named type {name}"))?;
|
||||||
|
return json_to_typed(descriptor, &declaration.definition, json, field);
|
||||||
|
}
|
||||||
|
match r#type {
|
||||||
|
TypeExpr::Unit if json.is_null() => Ok(Value::Unit),
|
||||||
|
TypeExpr::Boolean => json
|
||||||
|
.as_bool()
|
||||||
|
.map(Value::Boolean)
|
||||||
|
.ok_or_else(|| format!("{field}: expected boolean")),
|
||||||
|
TypeExpr::Integer => json
|
||||||
|
.as_i64()
|
||||||
|
.map(Value::Integer)
|
||||||
|
.ok_or_else(|| format!("{field}: expected integer")),
|
||||||
|
TypeExpr::Number => json
|
||||||
|
.as_f64()
|
||||||
|
.filter(|value| value.is_finite())
|
||||||
|
.map(Value::Number)
|
||||||
|
.ok_or_else(|| format!("{field}: expected finite number")),
|
||||||
|
TypeExpr::String => json
|
||||||
|
.as_str()
|
||||||
|
.map(|value| Value::String(value.into()))
|
||||||
|
.ok_or_else(|| format!("{field}: expected string")),
|
||||||
|
TypeExpr::Bytes => json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected base64 string"))
|
||||||
|
.and_then(|value| {
|
||||||
|
STANDARD
|
||||||
|
.decode(value)
|
||||||
|
.map(Value::Bytes)
|
||||||
|
.map_err(|_| format!("{field}: expected RFC 4648 base64"))
|
||||||
|
}),
|
||||||
|
TypeExpr::Entry => {
|
||||||
|
let path = json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected Entry string"))?;
|
||||||
|
wip_protocol::validate_path(path)
|
||||||
|
.map_err(|error| format!("{field}: invalid Entry path: {error}"))?;
|
||||||
|
Ok(Value::String(path.into()))
|
||||||
|
}
|
||||||
|
TypeExpr::Enum { cases } => {
|
||||||
|
let case = json
|
||||||
|
.as_str()
|
||||||
|
.ok_or_else(|| format!("{field}: expected enum string"))?;
|
||||||
|
if !cases.iter().any(|candidate| candidate.name == case) {
|
||||||
|
return Err(format!("{field}: unknown enum case {case}"));
|
||||||
|
}
|
||||||
|
Ok(Value::String(case.into()))
|
||||||
|
}
|
||||||
|
TypeExpr::Json => json_to_untyped(json, field),
|
||||||
|
TypeExpr::List { items } => json
|
||||||
|
.as_array()
|
||||||
|
.ok_or_else(|| format!("{field}: expected array"))?
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, item)| {
|
||||||
|
json_to_typed(descriptor, items, item, &format!("{field}[{index}]"))
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map(Value::List),
|
||||||
|
TypeExpr::Record { fields } => {
|
||||||
|
let object = json
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| format!("{field}: expected object"))?;
|
||||||
|
for name in object.keys() {
|
||||||
|
if !fields.iter().any(|candidate| candidate.name == *name) {
|
||||||
|
return Err(format!("{field}.{name}: unknown field"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut values = BTreeMap::new();
|
||||||
|
for declaration in fields {
|
||||||
|
match object.get(&declaration.name) {
|
||||||
|
Some(value) => {
|
||||||
|
values.insert(
|
||||||
|
declaration.name.clone(),
|
||||||
|
json_to_typed(
|
||||||
|
descriptor,
|
||||||
|
&declaration.r#type,
|
||||||
|
value,
|
||||||
|
&format!("{field}.{}", declaration.name),
|
||||||
|
)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
None if declaration.required => {
|
||||||
|
return Err(format!(
|
||||||
|
"{field}.{}: required field is missing",
|
||||||
|
declaration.name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Value::Record(values))
|
||||||
|
}
|
||||||
|
TypeExpr::Union { cases } => {
|
||||||
|
let object = json
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| format!("{field}: expected union object"))?;
|
||||||
|
if object.keys().any(|name| name != "$case" && name != "value") {
|
||||||
|
return Err(format!("{field}: union accepts only $case and value"));
|
||||||
|
}
|
||||||
|
let case_name = object
|
||||||
|
.get("$case")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.ok_or_else(|| format!("{field}.$case: required string is missing"))?;
|
||||||
|
let case = cases
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.name == case_name)
|
||||||
|
.ok_or_else(|| format!("{field}.$case: unknown union case {case_name}"))?;
|
||||||
|
let mut values = BTreeMap::from([("$case".into(), Value::String(case_name.into()))]);
|
||||||
|
match (&case.payload, object.get("value")) {
|
||||||
|
(Some(payload), Some(value)) => {
|
||||||
|
values.insert(
|
||||||
|
"value".into(),
|
||||||
|
json_to_typed(descriptor, payload, value, &format!("{field}.value"))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
(Some(_), None) => {
|
||||||
|
return Err(format!("{field}.value: required payload is missing"));
|
||||||
|
}
|
||||||
|
(None, Some(_)) => {
|
||||||
|
return Err(format!("{field}.value: payload-free case has a value"));
|
||||||
|
}
|
||||||
|
(None, None) => {}
|
||||||
|
}
|
||||||
|
Ok(Value::Record(values))
|
||||||
|
}
|
||||||
|
TypeExpr::Named { .. } => unreachable!("named types handled above"),
|
||||||
|
_ => Err(format!(
|
||||||
|
"{field}: value does not match {}",
|
||||||
|
type_name(r#type)
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_to_untyped(json: &serde_json::Value, field: &str) -> Result<Value, String> {
|
||||||
|
match json {
|
||||||
|
serde_json::Value::Null => Ok(Value::Unit),
|
||||||
|
serde_json::Value::Bool(value) => Ok(Value::Boolean(*value)),
|
||||||
|
serde_json::Value::Number(value) => {
|
||||||
|
if let Some(integer) = value.as_i64() {
|
||||||
|
Ok(Value::Integer(integer))
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
.as_f64()
|
||||||
|
.filter(|number| number.is_finite())
|
||||||
|
.map(Value::Number)
|
||||||
|
.ok_or_else(|| format!("{field}: number is not finite"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::String(value) => Ok(Value::String(value.clone())),
|
||||||
|
serde_json::Value::Array(values) => values
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, value)| json_to_untyped(value, &format!("{field}[{index}]")))
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map(Value::List),
|
||||||
|
serde_json::Value::Object(values) => values
|
||||||
|
.iter()
|
||||||
|
.map(|(name, value)| {
|
||||||
|
json_to_untyped(value, &format!("{field}.{name}"))
|
||||||
|
.map(|value| (name.clone(), value))
|
||||||
|
})
|
||||||
|
.collect::<Result<BTreeMap<_, _>, _>>()
|
||||||
|
.map(Value::Record),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use wip_protocol::{
|
||||||
|
EnumCase, FieldDeclaration, INTERFACE_FORMAT_V1, ParameterDeclaration, ReturnDeclaration,
|
||||||
|
TypeDeclaration, UnionCase,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn descriptor(
|
||||||
|
parameters: Vec<ParameterDeclaration>,
|
||||||
|
types: Vec<TypeDeclaration>,
|
||||||
|
) -> InterfaceDescriptor {
|
||||||
|
InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types,
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "run".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters,
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_every_canonical_shape_and_reports_fields() {
|
||||||
|
let parameters = vec![
|
||||||
|
parameter("unit", true, TypeExpr::Unit),
|
||||||
|
parameter("flag", true, TypeExpr::Boolean),
|
||||||
|
parameter("count", true, TypeExpr::Integer),
|
||||||
|
parameter("number", true, TypeExpr::Number),
|
||||||
|
parameter("text", true, TypeExpr::String),
|
||||||
|
parameter("bytes", true, TypeExpr::Bytes),
|
||||||
|
parameter("entry", true, TypeExpr::Entry),
|
||||||
|
parameter("json", true, TypeExpr::Json),
|
||||||
|
parameter(
|
||||||
|
"list",
|
||||||
|
true,
|
||||||
|
TypeExpr::List {
|
||||||
|
items: Box::new(TypeExpr::Integer),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"record",
|
||||||
|
true,
|
||||||
|
TypeExpr::Record {
|
||||||
|
fields: vec![FieldDeclaration {
|
||||||
|
name: "name".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"choice",
|
||||||
|
true,
|
||||||
|
TypeExpr::Enum {
|
||||||
|
cases: vec![EnumCase {
|
||||||
|
name: "yes".into(),
|
||||||
|
documentation: None,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"union",
|
||||||
|
true,
|
||||||
|
TypeExpr::Union {
|
||||||
|
cases: vec![UnionCase {
|
||||||
|
name: "some".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: Some(TypeExpr::Integer),
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"named",
|
||||||
|
true,
|
||||||
|
TypeExpr::Named {
|
||||||
|
name: "Alias".into(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let descriptor = descriptor(
|
||||||
|
parameters,
|
||||||
|
vec![TypeDeclaration {
|
||||||
|
name: "Alias".into(),
|
||||||
|
documentation: None,
|
||||||
|
definition: TypeExpr::String,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let operation = descriptor.operations[0].clone();
|
||||||
|
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
||||||
|
let inputs = [
|
||||||
|
"null",
|
||||||
|
"true",
|
||||||
|
"7",
|
||||||
|
"2.5",
|
||||||
|
"hello",
|
||||||
|
"aGk=",
|
||||||
|
"/item",
|
||||||
|
"{\"safe\":true}",
|
||||||
|
"[1,2]",
|
||||||
|
"{\"name\":\"n\"}",
|
||||||
|
"yes",
|
||||||
|
"{\"$case\":\"some\",\"value\":4}",
|
||||||
|
"value",
|
||||||
|
];
|
||||||
|
for (field, input) in editor.fields.iter_mut().zip(inputs) {
|
||||||
|
field.input = input.into();
|
||||||
|
}
|
||||||
|
let values = editor.validate().expect("valid values");
|
||||||
|
assert_eq!(values["bytes"], Value::Bytes(b"hi".to_vec()));
|
||||||
|
assert_eq!(values["entry"], Value::String("/item".into()));
|
||||||
|
assert!(editor.fields.iter().all(|field| field.diagnostic.is_none()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_invalid_and_optional_fields_are_field_local() {
|
||||||
|
let descriptor = descriptor(
|
||||||
|
vec![
|
||||||
|
parameter("required", true, TypeExpr::Integer),
|
||||||
|
parameter("optional", false, TypeExpr::Boolean),
|
||||||
|
],
|
||||||
|
vec![],
|
||||||
|
);
|
||||||
|
let operation = descriptor.operations[0].clone();
|
||||||
|
let mut editor = ArgumentEditor::new("test", descriptor, operation);
|
||||||
|
editor.fields[1].input = "not-a-bool".into();
|
||||||
|
assert_eq!(editor.validate(), Err(InvalidArguments));
|
||||||
|
assert!(
|
||||||
|
editor.fields[0]
|
||||||
|
.diagnostic
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("required")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
editor.fields[1]
|
||||||
|
.diagnostic
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("true or false")
|
||||||
|
);
|
||||||
|
editor.fields[0].input = "1".into();
|
||||||
|
editor.fields[1].input.clear();
|
||||||
|
assert_eq!(editor.validate().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter(name: &str, required: bool, r#type: TypeExpr) -> ParameterDeclaration {
|
||||||
|
ParameterDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
required,
|
||||||
|
documentation: None,
|
||||||
|
r#type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//! Presentation and terminal interaction for stateful WIP client sessions.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
pub mod app;
|
||||||
|
pub mod config;
|
||||||
|
pub mod editor;
|
||||||
|
pub mod render;
|
||||||
|
pub mod runtime;
|
||||||
|
pub mod terminal;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
fn main() {
|
||||||
|
if let Err(error) = wip_tui::runtime::run_from_env() {
|
||||||
|
eprintln!("wip-tui: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,840 @@
|
|||||||
|
//! Deterministic bounded rendering for real and test terminal backends.
|
||||||
|
|
||||||
|
use ratatui::Frame;
|
||||||
|
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
|
||||||
|
use ratatui::style::{Color, Modifier, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap};
|
||||||
|
|
||||||
|
use crate::app::{App, ConnectionState, Focus, HistoryKind, Modal, OperationRow, ViewState};
|
||||||
|
use crate::editor::type_name;
|
||||||
|
|
||||||
|
const MAX_RENDER_TEXT: usize = 512;
|
||||||
|
|
||||||
|
/// Draws the complete application without mutating it.
|
||||||
|
pub fn draw(frame: &mut Frame<'_>, app: &App) {
|
||||||
|
let area = frame.area();
|
||||||
|
if area.width < 48 || area.height < 14 {
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new("wip-tui\nTerminal is too small. Resize to at least 48 x 14.\nq: quit")
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Minimum size "),
|
||||||
|
)
|
||||||
|
.alignment(Alignment::Center)
|
||||||
|
.wrap(Wrap { trim: true }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let vertical = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(2),
|
||||||
|
Constraint::Min(8),
|
||||||
|
Constraint::Length(2),
|
||||||
|
])
|
||||||
|
.split(area);
|
||||||
|
render_header(frame, vertical[0], app);
|
||||||
|
let columns = Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([Constraint::Percentage(38), Constraint::Percentage(62)])
|
||||||
|
.split(vertical[1]);
|
||||||
|
render_tree(frame, columns[0], app);
|
||||||
|
let right = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage(31),
|
||||||
|
Constraint::Percentage(39),
|
||||||
|
Constraint::Percentage(30),
|
||||||
|
])
|
||||||
|
.split(columns[1]);
|
||||||
|
render_selected(frame, right[0], app);
|
||||||
|
render_operations(frame, right[1], app);
|
||||||
|
render_history(frame, right[2], app);
|
||||||
|
render_footer(frame, vertical[2], app);
|
||||||
|
render_modal(frame, app);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_header(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let connection = match &app.connection {
|
||||||
|
ConnectionState::Disconnected => "DISCONNECTED",
|
||||||
|
ConnectionState::Connecting => "CONNECTING",
|
||||||
|
ConnectionState::Connected => "CONNECTED",
|
||||||
|
ConnectionState::Failed(_) => "FAILED (R reconnect / q quit)",
|
||||||
|
};
|
||||||
|
let text = format!(
|
||||||
|
" wip-tui {} [{}] in-flight: {}",
|
||||||
|
sanitize(&app.endpoint),
|
||||||
|
connection,
|
||||||
|
app.in_flight.len()
|
||||||
|
);
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(text).style(Style::default().add_modifier(Modifier::BOLD)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_tree(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let mut paths = app.visible_paths();
|
||||||
|
let selected_index = paths
|
||||||
|
.iter()
|
||||||
|
.position(|path| path == &app.selected_path)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let (start, end) = list_window(paths.len(), selected_index, area.height.saturating_sub(2));
|
||||||
|
let rows = paths.drain(start..end).map(|path| {
|
||||||
|
let node = app.entries.get(&path);
|
||||||
|
let selected = path == app.selected_path;
|
||||||
|
let depth = if path == "/" {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
path.trim_start_matches('/').split('/').count()
|
||||||
|
};
|
||||||
|
let marker = node.map_or('·', |node| if node.expanded { '▼' } else { '▶' });
|
||||||
|
let label = node.and_then(|node| node.object.as_ref()).map_or_else(
|
||||||
|
|| path.clone(),
|
||||||
|
|object| {
|
||||||
|
if path == "/" {
|
||||||
|
"/".into()
|
||||||
|
} else {
|
||||||
|
object.name.clone()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let mut suffix = node.map_or_else(
|
||||||
|
|| " [unloaded]".into(),
|
||||||
|
|node| {
|
||||||
|
let tree = match &node.tree_state {
|
||||||
|
ViewState::Loading(_) => " [loading children]",
|
||||||
|
ViewState::Stale => " [stale children]",
|
||||||
|
ViewState::Error(_) => " [failed children]",
|
||||||
|
ViewState::Fresh if node.children.is_empty() => " [empty]",
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
let incomplete = if node.truncated {
|
||||||
|
" [truncated: + to increase limit]"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
let object = state_suffix(&node.state);
|
||||||
|
format!("{object}{tree}{incomplete}")
|
||||||
|
},
|
||||||
|
);
|
||||||
|
suffix = sanitize(&suffix);
|
||||||
|
let style = if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
};
|
||||||
|
ListItem::new(Line::from(vec![
|
||||||
|
Span::raw(" ".repeat(depth)),
|
||||||
|
Span::raw(format!("{marker} {}", sanitize(&label))),
|
||||||
|
Span::styled(suffix, state_style(node.map(|value| &value.state))),
|
||||||
|
]))
|
||||||
|
.style(style)
|
||||||
|
});
|
||||||
|
frame.render_widget(
|
||||||
|
List::new(rows).block(focused_block(" Worldspace tree ", app.focus == Focus::Tree)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_selected(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let mut lines = vec![Line::from(format!(
|
||||||
|
"Path: {}",
|
||||||
|
sanitize(&app.selected_path)
|
||||||
|
))];
|
||||||
|
if let Some(entry) = app.entries.get(&app.selected_path) {
|
||||||
|
lines.push(Line::from(format!("State: {}", state_label(&entry.state))));
|
||||||
|
if entry.state == ViewState::Fresh {
|
||||||
|
if let Some(object) = &entry.object {
|
||||||
|
lines.push(Line::from(format!("Name: {}", sanitize(&object.name))));
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"Description: {}",
|
||||||
|
object
|
||||||
|
.description
|
||||||
|
.as_deref()
|
||||||
|
.map(sanitize)
|
||||||
|
.unwrap_or_else(|| "(none)".into())
|
||||||
|
)));
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"Interfaces (ordered): {}",
|
||||||
|
if object.interfaces.is_empty() {
|
||||||
|
"(none)".into()
|
||||||
|
} else {
|
||||||
|
object
|
||||||
|
.interfaces
|
||||||
|
.iter()
|
||||||
|
.map(|value| sanitize(value))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
}
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(Line::from(
|
||||||
|
"No current object metadata; refresh required (old metadata hidden).",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if entry.truncated {
|
||||||
|
lines.push(Line::styled(
|
||||||
|
"TRUNCATED: this is not a complete subtree.",
|
||||||
|
Style::default()
|
||||||
|
.fg(Color::Yellow)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(focused_block(" Selected Entry ", app.focus == Focus::Entry))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_operations(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let rows = app.operation_rows();
|
||||||
|
let selected_index = app.operation_cursor.min(rows.len().saturating_sub(1));
|
||||||
|
let (start, end) = list_window(rows.len(), selected_index, area.height.saturating_sub(2));
|
||||||
|
let items = rows[start..end].iter().enumerate().map(|(offset, row)| {
|
||||||
|
let index = start + offset;
|
||||||
|
let (text, style) = operation_line(app, row);
|
||||||
|
let selected = app.focus == Focus::Operations && index == app.operation_cursor;
|
||||||
|
ListItem::new(text).style(if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
style
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let title = " Interfaces / Operations (Enter: load or edit) ";
|
||||||
|
if rows.is_empty() {
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new("No declared interfaces or no current object.")
|
||||||
|
.block(focused_block(title, app.focus == Focus::Operations)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
frame.render_widget(
|
||||||
|
List::new(items).block(focused_block(title, app.focus == Focus::Operations)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
|
||||||
|
if let Some(name) = &row.operation {
|
||||||
|
let descriptor = app
|
||||||
|
.interfaces
|
||||||
|
.get(&row.interface)
|
||||||
|
.and_then(|view| view.descriptor.as_ref());
|
||||||
|
let declaration = descriptor.and_then(|descriptor| {
|
||||||
|
descriptor
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.name == *name)
|
||||||
|
});
|
||||||
|
let signature = declaration.map_or_else(
|
||||||
|
|| format!(" ({}, {})", row.interface, name),
|
||||||
|
|operation| {
|
||||||
|
let parameters = operation
|
||||||
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| {
|
||||||
|
format!(
|
||||||
|
"{}{}: {}",
|
||||||
|
parameter.name,
|
||||||
|
if parameter.required { "" } else { "?" },
|
||||||
|
type_name(¶meter.r#type)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
let documentation = operation
|
||||||
|
.documentation
|
||||||
|
.as_ref()
|
||||||
|
.map(|documentation| format!(" — {}", documentation.summary))
|
||||||
|
.unwrap_or_default();
|
||||||
|
format!(
|
||||||
|
" ({}, {}) ({parameters}) -> {}{}",
|
||||||
|
row.interface,
|
||||||
|
name,
|
||||||
|
type_name(&operation.returns.r#type),
|
||||||
|
documentation
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
|
(Line::from(sanitize(&signature)), Style::default())
|
||||||
|
} else {
|
||||||
|
let interface = app.interfaces.get(&row.interface);
|
||||||
|
let state = interface.map_or("unloaded".into(), |view| state_label(&view.state));
|
||||||
|
let documentation = interface
|
||||||
|
.filter(|view| view.state == ViewState::Fresh)
|
||||||
|
.and_then(|view| view.descriptor.as_ref())
|
||||||
|
.and_then(|descriptor| descriptor.documentation.as_ref())
|
||||||
|
.map(|documentation| format!(" — {}", sanitize(&documentation.summary)))
|
||||||
|
.unwrap_or_default();
|
||||||
|
(
|
||||||
|
Line::from(format!(
|
||||||
|
"Interface {} [{}]{}",
|
||||||
|
sanitize(&row.interface),
|
||||||
|
state,
|
||||||
|
documentation
|
||||||
|
)),
|
||||||
|
Style::default().add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_history(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let selected_index = app.history_cursor.min(app.history.len().saturating_sub(1));
|
||||||
|
let (start, end) = list_window(
|
||||||
|
app.history.len(),
|
||||||
|
selected_index,
|
||||||
|
area.height.saturating_sub(2),
|
||||||
|
);
|
||||||
|
let items = app.history[start..end]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(offset, item)| {
|
||||||
|
let index = start + offset;
|
||||||
|
let label = match item.kind {
|
||||||
|
HistoryKind::Success => "SUCCESS",
|
||||||
|
HistoryKind::DomainFailure => "HOST FAILURE",
|
||||||
|
HistoryKind::ProtocolError => "PROTOCOL ERROR",
|
||||||
|
HistoryKind::TransportFailure => "TRANSPORT FAILURE",
|
||||||
|
HistoryKind::ClientFailure => "CLIENT FAILURE",
|
||||||
|
HistoryKind::OutcomeUnknown => "OUTCOME UNKNOWN",
|
||||||
|
HistoryKind::Information => "INFO",
|
||||||
|
};
|
||||||
|
let link = item
|
||||||
|
.entry_target
|
||||||
|
.as_ref()
|
||||||
|
.map_or("", |_| " [Enter: go to Entry]");
|
||||||
|
let text = format!(
|
||||||
|
"[{label}] {}: {}{link}",
|
||||||
|
sanitize(&item.title),
|
||||||
|
sanitize(&item.detail)
|
||||||
|
);
|
||||||
|
let selected = app.focus == Focus::History && index == app.history_cursor;
|
||||||
|
ListItem::new(text).style(if selected {
|
||||||
|
Style::default().fg(Color::Black).bg(Color::Cyan)
|
||||||
|
} else if item.kind == HistoryKind::OutcomeUnknown {
|
||||||
|
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let block = focused_block(
|
||||||
|
" Recent results / diagnostics ",
|
||||||
|
app.focus == Focus::History,
|
||||||
|
);
|
||||||
|
if app.history.is_empty() {
|
||||||
|
frame.render_widget(Paragraph::new("No results yet.").block(block), area);
|
||||||
|
} else {
|
||||||
|
frame.render_widget(List::new(items).block(block), area);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_footer(frame: &mut Frame<'_>, area: Rect, app: &App) {
|
||||||
|
let help = " ↑↓/jk move ←→/hl parent/expand Tab focus Enter select r refresh + larger tree c cancel read ? help q quit ";
|
||||||
|
let text = format!("{}\n{}", help, sanitize(&app.status));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(text).style(Style::default().fg(Color::DarkGray)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_modal(frame: &mut Frame<'_>, app: &App) {
|
||||||
|
match &app.modal {
|
||||||
|
Modal::None => {}
|
||||||
|
Modal::Help => {
|
||||||
|
let area = centered(frame.area(), 76, 70);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(
|
||||||
|
"Keyboard help\n\n↑/↓ or j/k move selection / editor field\n←/→ or h/l collapse/expand or parent\nTab next pane\nEnter load interface, edit operation, confirm execute\nr refresh selected Entry and subtree\n+ increase truncated tree limit and retry\nc cancel newest retrieval (never cancels a sent operation)\nR reconnect after failure\nEsc close modal\nq quit\n\nOperations are never sent until the confirmation screen is accepted.",
|
||||||
|
)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title(" Help "))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Modal::Editor(editor) => {
|
||||||
|
let area = centered(frame.area(), 86, 78);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
let mut lines = vec![Line::from(format!(
|
||||||
|
"Target: {} Operation: ({}, {})",
|
||||||
|
sanitize(&app.selected_path),
|
||||||
|
sanitize(&editor.interface),
|
||||||
|
sanitize(&editor.operation.name)
|
||||||
|
))];
|
||||||
|
if editor.fields.is_empty() {
|
||||||
|
lines.push(Line::from("(no parameters)"));
|
||||||
|
}
|
||||||
|
for (index, field) in editor.fields.iter().enumerate() {
|
||||||
|
let cursor = if index == editor.cursor { ">" } else { " " };
|
||||||
|
let requirement = if field.required {
|
||||||
|
"required"
|
||||||
|
} else {
|
||||||
|
"optional"
|
||||||
|
};
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
"{cursor} {} [{requirement}, {}] = {}",
|
||||||
|
sanitize(&field.name),
|
||||||
|
sanitize(&type_name(&field.r#type)),
|
||||||
|
sanitize(&field.input)
|
||||||
|
)));
|
||||||
|
if let Some(diagnostic) = &field.diagnostic {
|
||||||
|
lines.push(Line::styled(
|
||||||
|
format!(" ERROR: {}", sanitize(diagnostic)),
|
||||||
|
Style::default().fg(Color::Red),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(Line::from("Enter: validate and review Esc: cancel"));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Argument editor "),
|
||||||
|
)
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Modal::Confirm { editor, arguments } => {
|
||||||
|
let area = centered(frame.area(), 82, 58);
|
||||||
|
frame.render_widget(Clear, area);
|
||||||
|
let mut lines = vec![
|
||||||
|
Line::styled(
|
||||||
|
"EXPLICIT EXECUTION CONFIRMATION",
|
||||||
|
Style::default()
|
||||||
|
.fg(Color::Yellow)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Line::from(format!("Entry: {}", sanitize(&app.selected_path))),
|
||||||
|
Line::from(format!("Interface: {}", sanitize(&editor.interface))),
|
||||||
|
Line::from(format!("Operation: {}", sanitize(&editor.operation.name))),
|
||||||
|
Line::from("Input values:"),
|
||||||
|
];
|
||||||
|
for (name, value) in arguments {
|
||||||
|
lines.push(Line::from(format!(
|
||||||
|
" {} = {}",
|
||||||
|
sanitize(name),
|
||||||
|
sanitize(&bounded_value(value))
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
lines.push(Line::from(""));
|
||||||
|
lines.push(Line::styled(
|
||||||
|
"Enter/e: EXECUTE ONCE Esc: back to editor",
|
||||||
|
Style::default().add_modifier(Modifier::BOLD),
|
||||||
|
));
|
||||||
|
frame.render_widget(
|
||||||
|
Paragraph::new(lines)
|
||||||
|
.block(Block::default().borders(Borders::ALL).title(" Confirm "))
|
||||||
|
.wrap(Wrap { trim: false }),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_window(total: usize, selected: usize, area_height: u16) -> (usize, usize) {
|
||||||
|
let capacity = usize::from(area_height);
|
||||||
|
if total == 0 || capacity == 0 {
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
let selected = selected.min(total - 1);
|
||||||
|
let start = selected
|
||||||
|
.saturating_add(1)
|
||||||
|
.saturating_sub(capacity)
|
||||||
|
.min(total.saturating_sub(capacity));
|
||||||
|
(start, start.saturating_add(capacity).min(total))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn focused_block(title: &'static str, focused: bool) -> Block<'static> {
|
||||||
|
let style = if focused {
|
||||||
|
Style::default().fg(Color::Cyan)
|
||||||
|
} else {
|
||||||
|
Style::default()
|
||||||
|
};
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(title)
|
||||||
|
.border_style(style)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn centered(area: Rect, percent_x: u16, percent_y: u16) -> Rect {
|
||||||
|
let vertical = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
|
Constraint::Percentage(percent_y),
|
||||||
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
|
])
|
||||||
|
.split(area);
|
||||||
|
Layout::default()
|
||||||
|
.direction(Direction::Horizontal)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
|
Constraint::Percentage(percent_x),
|
||||||
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
|
])
|
||||||
|
.split(vertical[1])[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_suffix(state: &ViewState) -> &'static str {
|
||||||
|
match state {
|
||||||
|
ViewState::Unloaded => " [unloaded]",
|
||||||
|
ViewState::Loading(_) => " [loading]",
|
||||||
|
ViewState::Fresh => "",
|
||||||
|
ViewState::Stale => " [stale: refresh required]",
|
||||||
|
ViewState::Error(_) => " [error]",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_label(state: &ViewState) -> String {
|
||||||
|
match state {
|
||||||
|
ViewState::Unloaded => "unloaded".into(),
|
||||||
|
ViewState::Loading(id) => format!("loading request #{id}"),
|
||||||
|
ViewState::Fresh => "fresh".into(),
|
||||||
|
ViewState::Stale => "stale — refresh required".into(),
|
||||||
|
ViewState::Error(error) => format!("error — {}", sanitize(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_style(state: Option<&ViewState>) -> Style {
|
||||||
|
match state {
|
||||||
|
Some(ViewState::Stale) => Style::default().fg(Color::Yellow),
|
||||||
|
Some(ViewState::Error(_)) => Style::default().fg(Color::Red),
|
||||||
|
Some(ViewState::Loading(_)) => Style::default().fg(Color::Blue),
|
||||||
|
_ => Style::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces terminal control characters and bounds user/remote text by Unicode scalars.
|
||||||
|
#[must_use]
|
||||||
|
pub fn sanitize(input: &str) -> String {
|
||||||
|
let mut output = String::new();
|
||||||
|
for (count, character) in input.chars().enumerate() {
|
||||||
|
if count >= MAX_RENDER_TEXT {
|
||||||
|
output.push('…');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if character.is_control() && !matches!(character, '\n' | '\t') {
|
||||||
|
output.push('�');
|
||||||
|
} else {
|
||||||
|
output.push(character);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formats a protocol value with strict byte and collection bounds.
|
||||||
|
#[must_use]
|
||||||
|
pub fn bounded_value(value: &wip_protocol::Value) -> String {
|
||||||
|
bounded_value_at(value, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bounded_value_at(value: &wip_protocol::Value, depth: usize) -> String {
|
||||||
|
if depth >= 8 {
|
||||||
|
return "…".into();
|
||||||
|
}
|
||||||
|
match value {
|
||||||
|
wip_protocol::Value::Unit => "null".into(),
|
||||||
|
wip_protocol::Value::Boolean(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::Integer(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::Number(value) => value.to_string(),
|
||||||
|
wip_protocol::Value::String(value) => format!("{:?}", sanitize(value)),
|
||||||
|
wip_protocol::Value::Bytes(bytes) => {
|
||||||
|
let shown = bytes
|
||||||
|
.iter()
|
||||||
|
.take(32)
|
||||||
|
.map(|byte| format!("{byte:02x}"))
|
||||||
|
.collect::<String>();
|
||||||
|
if bytes.len() > 32 {
|
||||||
|
format!("bytes[{}]: {shown}…", bytes.len())
|
||||||
|
} else {
|
||||||
|
format!("bytes[{}]: {shown}", bytes.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wip_protocol::Value::Record(values) => {
|
||||||
|
let mut fields = values
|
||||||
|
.iter()
|
||||||
|
.take(16)
|
||||||
|
.map(|(name, value)| {
|
||||||
|
format!("{}: {}", sanitize(name), bounded_value_at(value, depth + 1))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if values.len() > 16 {
|
||||||
|
fields.push("…".into());
|
||||||
|
}
|
||||||
|
format!("{{{}}}", fields.join(", "))
|
||||||
|
}
|
||||||
|
wip_protocol::Value::List(values) => {
|
||||||
|
let mut items = values
|
||||||
|
.iter()
|
||||||
|
.take(16)
|
||||||
|
.map(|value| bounded_value_at(value, depth + 1))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if values.len() > 16 {
|
||||||
|
items.push("…".into());
|
||||||
|
}
|
||||||
|
format!("[{}]", items.join(", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::app::{EntryView, HistoryItem};
|
||||||
|
use crate::editor::ArgumentEditor;
|
||||||
|
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState};
|
||||||
|
use wip_protocol::{
|
||||||
|
INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, OperationDeclaration,
|
||||||
|
ParameterDeclaration, ReturnDeclaration, TypeExpr,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn rendered(app: &App, width: u16, height: u16) -> String {
|
||||||
|
let backend = TestBackend::new(width, height);
|
||||||
|
let mut terminal = Terminal::new(backend).unwrap();
|
||||||
|
terminal.draw(|frame| draw(frame, app)).unwrap();
|
||||||
|
terminal
|
||||||
|
.backend()
|
||||||
|
.buffer()
|
||||||
|
.content
|
||||||
|
.iter()
|
||||||
|
.map(|cell| cell.symbol())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.chunks(width as usize)
|
||||||
|
.map(|line| line.concat())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshot_contains_non_color_state_markers_and_hides_validators() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
app.entries.get_mut("/").unwrap().truncated = true;
|
||||||
|
app.entries.get_mut("/").unwrap().state = ViewState::Stale;
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::OutcomeUnknown,
|
||||||
|
title: "replace".into(),
|
||||||
|
detail: "execution and side effects are unknown; refresh before deciding again".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
let snapshot = rendered(&app, 110, 30);
|
||||||
|
assert!(snapshot.contains("truncated"));
|
||||||
|
assert!(snapshot.contains("stale"));
|
||||||
|
assert!(snapshot.contains("OUTCOME UNKNOWN"));
|
||||||
|
assert!(!snapshot.contains("validator"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshots_cover_selected_operation_editor_and_failure_categories() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(Object {
|
||||||
|
name: String::new(),
|
||||||
|
description: Some("public root description".into()),
|
||||||
|
interfaces: vec!["demo-interface".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
}),
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let descriptor = InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "run".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![ParameterDeclaration {
|
||||||
|
name: "count".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Integer,
|
||||||
|
}],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "demo-interface".into(),
|
||||||
|
descriptor: Some(descriptor.clone()),
|
||||||
|
validator: Some(b"must-not-render".to_vec()),
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
for (kind, title) in [
|
||||||
|
(HistoryKind::Success, "result"),
|
||||||
|
(HistoryKind::ProtocolError, "invalid response"),
|
||||||
|
(HistoryKind::TransportFailure, "network"),
|
||||||
|
(HistoryKind::ClientFailure, "local"),
|
||||||
|
] {
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind,
|
||||||
|
title: title.into(),
|
||||||
|
detail: "bounded detail".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let snapshot = rendered(&app, 140, 40);
|
||||||
|
assert!(snapshot.contains("public root description"));
|
||||||
|
assert!(snapshot.contains("(demo-interface, run)"));
|
||||||
|
assert!(snapshot.contains("SUCCESS"));
|
||||||
|
assert!(snapshot.contains("PROTOCOL ERROR"));
|
||||||
|
assert!(snapshot.contains("TRANSPORT FAILURE"));
|
||||||
|
assert!(snapshot.contains("CLIENT FAILURE"));
|
||||||
|
assert!(!snapshot.contains("must-not-render"));
|
||||||
|
|
||||||
|
let mut editor = ArgumentEditor::new(
|
||||||
|
"demo-interface",
|
||||||
|
descriptor.clone(),
|
||||||
|
descriptor.operations[0].clone(),
|
||||||
|
);
|
||||||
|
editor.fields[0].diagnostic = Some("expected integer".into());
|
||||||
|
app.modal = Modal::Editor(editor);
|
||||||
|
let snapshot = rendered(&app, 140, 40);
|
||||||
|
assert!(snapshot.contains("Argument editor"));
|
||||||
|
assert!(snapshot.contains("count [required, Integer]"));
|
||||||
|
assert!(snapshot.contains("ERROR: expected integer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn list_panes_keep_the_active_row_inside_the_bounded_viewport() {
|
||||||
|
let mut app = App::new("https://example.test/wip/");
|
||||||
|
app.connection = ConnectionState::Connected;
|
||||||
|
|
||||||
|
let children = (0..40)
|
||||||
|
.map(|index| format!("/tree-row-{index:02}"))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
{
|
||||||
|
let root = app.entries.get_mut("/").unwrap();
|
||||||
|
root.children = children.clone();
|
||||||
|
root.tree_state = ViewState::Fresh;
|
||||||
|
root.expanded = true;
|
||||||
|
}
|
||||||
|
for child in &children {
|
||||||
|
app.entries.insert(
|
||||||
|
child.clone(),
|
||||||
|
EntryView {
|
||||||
|
path: child.clone(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: vec![],
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
truncated: false,
|
||||||
|
limit: 1,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
app.selected_path = children.last().unwrap().clone();
|
||||||
|
app.focus = Focus::Tree;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
let tree_pane = snapshot
|
||||||
|
.lines()
|
||||||
|
.map(|line| line.chars().take(38).collect::<String>())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
assert!(tree_pane.contains("tree-row-39"));
|
||||||
|
|
||||||
|
app.selected_path = "/".into();
|
||||||
|
app.apply_object(ObjectObservation {
|
||||||
|
path: "/".into(),
|
||||||
|
object: Some(Object {
|
||||||
|
name: String::new(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec!["many".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
}),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
let operations = (0..20)
|
||||||
|
.map(|index| OperationDeclaration {
|
||||||
|
name: format!("operation-{index:02}"),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Unit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
app.apply_interface(InterfaceObservation {
|
||||||
|
reference: "many".into(),
|
||||||
|
descriptor: Some(InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations,
|
||||||
|
}),
|
||||||
|
validator: None,
|
||||||
|
state: ObservationState::Fresh,
|
||||||
|
});
|
||||||
|
app.focus = Focus::Operations;
|
||||||
|
app.operation_cursor = app.operation_rows().len() - 1;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
assert!(snapshot.contains("(many, operation-19)"));
|
||||||
|
|
||||||
|
for index in 0..20 {
|
||||||
|
app.push_history(HistoryItem {
|
||||||
|
kind: HistoryKind::Information,
|
||||||
|
title: format!("history-{index:02}"),
|
||||||
|
detail: "diagnostic".into(),
|
||||||
|
entry_target: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
app.focus = Focus::History;
|
||||||
|
app.history_cursor = app.history.len() - 1;
|
||||||
|
let snapshot = rendered(&app, 100, 30);
|
||||||
|
assert!(snapshot.contains("[INFO] history-00"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tiny_terminal_has_a_safe_fallback() {
|
||||||
|
let snapshot = rendered(&App::new("https://example.test/"), 30, 8);
|
||||||
|
assert!(snapshot.contains("too small"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn control_characters_and_large_bytes_are_bounded() {
|
||||||
|
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
|
||||||
|
let display = bounded_value(&wip_protocol::Value::Bytes(vec![7; 1000]));
|
||||||
|
assert!(display.starts_with("bytes[1000]"));
|
||||||
|
assert!(display.ends_with('…'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entry_view_type_remains_constructible_for_external_snapshots() {
|
||||||
|
let entry = EntryView {
|
||||||
|
path: "/".into(),
|
||||||
|
object: None,
|
||||||
|
state: ViewState::Unloaded,
|
||||||
|
children: vec![],
|
||||||
|
tree_state: ViewState::Unloaded,
|
||||||
|
expanded: false,
|
||||||
|
truncated: false,
|
||||||
|
limit: 1,
|
||||||
|
};
|
||||||
|
assert_eq!(entry.path, "/");
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,132 @@
|
|||||||
|
//! Terminal lifecycle guard and crossterm input translation.
|
||||||
|
|
||||||
|
use std::io::{self, Stdout};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crossterm::cursor::{Hide, Show};
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
|
use crossterm::execute;
|
||||||
|
use crossterm::terminal::{
|
||||||
|
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
|
||||||
|
};
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::CrosstermBackend;
|
||||||
|
|
||||||
|
use crate::app::InputKey;
|
||||||
|
|
||||||
|
type PanicHook = dyn for<'a> Fn(&std::panic::PanicHookInfo<'a>) + Send + Sync + 'static;
|
||||||
|
|
||||||
|
/// RAII owner of raw mode, alternate screen, cursor visibility, and panic recovery.
|
||||||
|
pub struct TerminalGuard {
|
||||||
|
terminal: Terminal<CrosstermBackend<Stdout>>,
|
||||||
|
previous_hook: Arc<PanicHook>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerminalGuard {
|
||||||
|
/// Enters terminal UI mode, restoring partial setup on failure.
|
||||||
|
pub fn enter() -> io::Result<Self> {
|
||||||
|
enable_raw_mode()?;
|
||||||
|
let mut stdout = io::stdout();
|
||||||
|
if let Err(error) = execute!(stdout, EnterAlternateScreen, Hide) {
|
||||||
|
let _ = disable_raw_mode();
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
let terminal = match Terminal::new(CrosstermBackend::new(stdout)) {
|
||||||
|
Ok(terminal) => terminal,
|
||||||
|
Err(error) => {
|
||||||
|
restore_terminal();
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let previous_hook: Arc<PanicHook> = std::panic::take_hook().into();
|
||||||
|
let panic_hook = Arc::clone(&previous_hook);
|
||||||
|
let terminal_owner = std::thread::current().id();
|
||||||
|
std::panic::set_hook(Box::new(move |information| {
|
||||||
|
if std::thread::current().id() == terminal_owner {
|
||||||
|
restore_terminal();
|
||||||
|
}
|
||||||
|
panic_hook(information);
|
||||||
|
}));
|
||||||
|
Ok(Self {
|
||||||
|
terminal,
|
||||||
|
previous_hook,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the ratatui terminal for drawing.
|
||||||
|
pub fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
|
||||||
|
&mut self.terminal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TerminalGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let previous = Arc::clone(&self.previous_hook);
|
||||||
|
std::panic::set_hook(Box::new(move |information| previous(information)));
|
||||||
|
restore_terminal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_terminal() {
|
||||||
|
let _ = disable_raw_mode();
|
||||||
|
let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts one crossterm key event into a terminal-independent reducer key.
|
||||||
|
///
|
||||||
|
/// When `editing` is true, printable command letters remain text input and only
|
||||||
|
/// Ctrl-C/Escape retain global meaning.
|
||||||
|
#[must_use]
|
||||||
|
pub fn translate_key(event: KeyEvent, editing: bool) -> Option<InputKey> {
|
||||||
|
if event.modifiers.contains(KeyModifiers::CONTROL) && event.code == KeyCode::Char('c') {
|
||||||
|
return Some(InputKey::Quit);
|
||||||
|
}
|
||||||
|
let key = match event.code {
|
||||||
|
KeyCode::Up => InputKey::Up,
|
||||||
|
KeyCode::Down => InputKey::Down,
|
||||||
|
KeyCode::Left => InputKey::Left,
|
||||||
|
KeyCode::Right => InputKey::Right,
|
||||||
|
KeyCode::Tab => InputKey::Tab,
|
||||||
|
KeyCode::Enter => InputKey::Enter,
|
||||||
|
KeyCode::Esc => InputKey::Escape,
|
||||||
|
KeyCode::Backspace => InputKey::Backspace,
|
||||||
|
KeyCode::Char(character) if editing => InputKey::Character(character),
|
||||||
|
KeyCode::Char('k') => InputKey::Up,
|
||||||
|
KeyCode::Char('j') => InputKey::Down,
|
||||||
|
KeyCode::Char('h') => InputKey::Left,
|
||||||
|
KeyCode::Char('l') => InputKey::Right,
|
||||||
|
KeyCode::Char('r') => InputKey::Refresh,
|
||||||
|
KeyCode::Char('R') => InputKey::Reconnect,
|
||||||
|
KeyCode::Char('+') | KeyCode::Char('=') => InputKey::IncreaseLimit,
|
||||||
|
KeyCode::Char('c') => InputKey::CancelRead,
|
||||||
|
KeyCode::Char('?') => InputKey::Help,
|
||||||
|
KeyCode::Char('q') => InputKey::Quit,
|
||||||
|
KeyCode::Char(character) => InputKey::Character(character),
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn editing_keeps_command_letters_as_text_but_ctrl_c_quits() {
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), true),
|
||||||
|
Some(InputKey::Character('q'))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), false),
|
||||||
|
Some(InputKey::Quit)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
translate_key(
|
||||||
|
KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
|
||||||
|
true
|
||||||
|
),
|
||||||
|
Some(InputKey::Quit)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
||||||
|
use wip_tui::app::{Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
|
use wip_tui::config::Config;
|
||||||
|
use wip_tui::runtime::{HttpTransport, Runtime, default_wire_limits};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_http_filesystem_workflow_is_lazy_validator_safe_and_symlink_confined() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let outside = tempdir().expect("outside root");
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
|
std::fs::create_dir(temporary.path().join("nested")).expect("create nested directory");
|
||||||
|
std::fs::write(outside.path().join("secret.txt"), b"outside-secret").expect("outside file");
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::symlink(outside.path(), temporary.path().join("outside-link"))
|
||||||
|
.expect("create symlink");
|
||||||
|
|
||||||
|
let mut server_config = ServerConfig::for_root(temporary.path());
|
||||||
|
server_config.access = AccessMode::ReadWrite;
|
||||||
|
server_config.transport_security = TransportSecurity::DevelopmentHttp;
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(server_config)
|
||||||
|
.expect("build filesystem server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind filesystem server"),
|
||||||
|
);
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
let endpoint = format!("http://127.0.0.1:{}/wip", bound.local_addr().port());
|
||||||
|
let config = Config::parse(
|
||||||
|
[endpoint, "--allow-http".into()],
|
||||||
|
None,
|
||||||
|
Some("filesystem-test".into()),
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.expect("development config");
|
||||||
|
let transport = HttpTransport::new(&config, default_wire_limits().max_response_bytes())
|
||||||
|
.expect("HTTP transport");
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().selected_path, "/");
|
||||||
|
assert!(runtime.app().entries.contains_key("/hello.txt"));
|
||||||
|
assert!(runtime.app().entries.contains_key("/nested"));
|
||||||
|
assert!(runtime.app().entries.contains_key("/outside-link"));
|
||||||
|
|
||||||
|
// Keyboard-select the file and load its read interface and descriptor.
|
||||||
|
runtime.app_mut().selected_path = "/hello.txt".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 0;
|
||||||
|
assert!(!runtime.handle_key(InputKey::Enter));
|
||||||
|
settle(&mut runtime);
|
||||||
|
let read_reference = runtime.app().entries["/hello.txt"]
|
||||||
|
.object
|
||||||
|
.as_ref()
|
||||||
|
.expect("file object")
|
||||||
|
.interfaces[0]
|
||||||
|
.clone();
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().interfaces[&read_reference]
|
||||||
|
.descriptor
|
||||||
|
.as_ref()
|
||||||
|
.expect("read descriptor")
|
||||||
|
.operations[0]
|
||||||
|
.name,
|
||||||
|
"read"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Descriptor-driven read editor, explicit confirmation, and execution.
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("68656c6c6f20776f726c64")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calls conservatively stale the object even for a read operation; refresh
|
||||||
|
// before constructing the separately confirmed write call.
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
|
||||||
|
// Load the separately-qualified write interface and replace with the
|
||||||
|
// automatically attached observed validator.
|
||||||
|
runtime.app_mut().operation_cursor = 2;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "dXBkYXRlZA=="); // "updated"
|
||||||
|
confirm_and_execute(&mut runtime);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("updated file"),
|
||||||
|
b"updated"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Stale);
|
||||||
|
|
||||||
|
// Reobserve, prepare a replacement from that observation, then mutate the
|
||||||
|
// file externally before explicit execution. The stale validator is rejected,
|
||||||
|
// the Entry becomes stale, and no automatic call is created.
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Fresh);
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "c3RhbGUtd3JpdGU=");
|
||||||
|
runtime.handle_key(InputKey::Enter); // confirmation fixes user input only
|
||||||
|
std::fs::write(temporary.path().join("hello.txt"), b"external").expect("external change");
|
||||||
|
let history_before = runtime.app().history.len();
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("externally changed file"),
|
||||||
|
b"external"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Stale);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history.len(), history_before + 1);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::DomainFailure);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("no automatic retry")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Refresh enables a new, separately confirmed execution.
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 3;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
set_only_field(&mut runtime, "ZmluYWw=");
|
||||||
|
confirm_and_execute(&mut runtime);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(temporary.path().join("hello.txt")).expect("final file"),
|
||||||
|
b"final"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Symlink inspection exposes the link payload only. It never traverses or
|
||||||
|
// materializes the target directory outside the configured root.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
runtime.app_mut().selected_path = "/outside-link".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 0;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
|
||||||
|
assert!(!runtime.app().history[0].detail.contains("outside-secret"));
|
||||||
|
assert!(
|
||||||
|
!runtime
|
||||||
|
.app()
|
||||||
|
.entries
|
||||||
|
.contains_key("/outside-link/secret.txt")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join filesystem listener")
|
||||||
|
.expect("filesystem listener exits");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(runtime: &mut Runtime<HttpTransport>) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !runtime.app().in_flight.is_empty() {
|
||||||
|
assert!(Instant::now() < deadline, "runtime requests did not settle");
|
||||||
|
runtime.wait_and_poll(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_only_field(runtime: &mut Runtime<HttpTransport>, input: &str) {
|
||||||
|
let Modal::Editor(editor) = &mut runtime.app_mut().modal else {
|
||||||
|
panic!("operation editor was not open")
|
||||||
|
};
|
||||||
|
assert_eq!(editor.fields.len(), 1);
|
||||||
|
editor.fields[0].input = input.into();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn confirm_and_execute(runtime: &mut Runtime<HttpTransport>) {
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
}
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::tempdir;
|
||||||
|
use wip_fs_server::{ServerConfig, WipFsServer};
|
||||||
|
use wip_https::encode_protocol_error_response;
|
||||||
|
use wip_https::http::{Request, Response};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
use wip_tui::app::{ConnectionState, Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
|
use wip_tui::config::Config;
|
||||||
|
use wip_tui::runtime::{
|
||||||
|
Runtime, Transport, TransportError, TransportErrorKind, default_wire_limits,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ScriptedTransport {
|
||||||
|
server: Arc<WipFsServer>,
|
||||||
|
sequence: Arc<AtomicUsize>,
|
||||||
|
delayed_after_startup: bool,
|
||||||
|
unknown_calls: bool,
|
||||||
|
fail_call_prepare: bool,
|
||||||
|
fail_tree_prepare: bool,
|
||||||
|
panic_calls: bool,
|
||||||
|
root_tree_protocol_failures: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScriptedTransport {
|
||||||
|
fn new(server: Arc<WipFsServer>) -> Self {
|
||||||
|
Self {
|
||||||
|
server,
|
||||||
|
sequence: Arc::new(AtomicUsize::new(0)),
|
||||||
|
delayed_after_startup: false,
|
||||||
|
unknown_calls: false,
|
||||||
|
fail_call_prepare: false,
|
||||||
|
fail_tree_prepare: false,
|
||||||
|
panic_calls: false,
|
||||||
|
root_tree_protocol_failures: Arc::new(AtomicUsize::new(0)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport for ScriptedTransport {
|
||||||
|
type Prepared = Request<Vec<u8>>;
|
||||||
|
|
||||||
|
fn prepare(&self, request: Request<Vec<u8>>) -> Result<Self::Prepared, TransportError> {
|
||||||
|
if self.fail_call_prepare && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
return Err(TransportError {
|
||||||
|
kind: TransportErrorKind::Disconnect,
|
||||||
|
detail: "scripted local conversion failure".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if self.fail_tree_prepare && request.uri().path().ends_with("/v1/fetch_tree") {
|
||||||
|
return Err(TransportError {
|
||||||
|
kind: TransportErrorKind::Disconnect,
|
||||||
|
detail: "scripted tree conversion failure".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&self, request: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError> {
|
||||||
|
let sequence = self.sequence.fetch_add(1, Ordering::AcqRel);
|
||||||
|
if request.uri().path().ends_with("/v1/fetch_tree")
|
||||||
|
&& self
|
||||||
|
.root_tree_protocol_failures
|
||||||
|
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| {
|
||||||
|
remaining.checked_sub(1)
|
||||||
|
})
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
return Ok(encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::FetchTree,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "scripted startup failure".into(),
|
||||||
|
},
|
||||||
|
default_wire_limits(),
|
||||||
|
)
|
||||||
|
.expect("encode tree failure"));
|
||||||
|
}
|
||||||
|
if self.delayed_after_startup && sequence > 0 {
|
||||||
|
// Each refresh starts object then tree. Make the first pair lose to
|
||||||
|
// the second pair to exercise exact RequestId ownership.
|
||||||
|
let delay = if matches!(sequence, 1 | 2) { 80 } else { 5 };
|
||||||
|
thread::sleep(Duration::from_millis(delay));
|
||||||
|
}
|
||||||
|
if self.panic_calls && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
panic!("scripted transport worker panic");
|
||||||
|
}
|
||||||
|
if self.unknown_calls && request.uri().path().ends_with("/v1/call_operation") {
|
||||||
|
return Ok(encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::CallOperation,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
message: "scripted commit uncertainty".into(),
|
||||||
|
},
|
||||||
|
default_wire_limits(),
|
||||||
|
)
|
||||||
|
.expect("encode unknown outcome"));
|
||||||
|
}
|
||||||
|
Ok(self.server.handle_http(request))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_refresh_and_cancel_keep_request_identity_safe() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.delayed_after_startup = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
runtime.app_mut().focus = Focus::Tree;
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().entries["/"].state, ViewState::Fresh);
|
||||||
|
assert!(runtime.app().history.iter().any(|item| {
|
||||||
|
item.kind == HistoryKind::Information && item.title.contains("stale response")
|
||||||
|
}));
|
||||||
|
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
runtime.handle_key(InputKey::CancelRead);
|
||||||
|
runtime.handle_key(InputKey::CancelRead);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert!(
|
||||||
|
runtime
|
||||||
|
.app()
|
||||||
|
.history
|
||||||
|
.iter()
|
||||||
|
.any(|item| item.title == "retrieval canceled")
|
||||||
|
);
|
||||||
|
|
||||||
|
// When a refreshed tree omits a formerly selected Entry, the client marks
|
||||||
|
// it stale and the presentation no longer exposes old metadata/operations
|
||||||
|
// as current.
|
||||||
|
std::fs::remove_file(temporary.path().join("file")).expect("remove file");
|
||||||
|
runtime.app_mut().selected_path = "/".into();
|
||||||
|
runtime.handle_key(InputKey::Refresh);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
|
||||||
|
runtime.app_mut().selected_path = "/file".into();
|
||||||
|
assert!(runtime.app().operation_rows().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn startup_transport_preparation_failure_enters_failed_state() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.fail_tree_prepare = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(matches!(
|
||||||
|
runtime.app().connection,
|
||||||
|
ConnectionState::Failed(ref detail) if detail.contains("scripted tree conversion failure")
|
||||||
|
));
|
||||||
|
assert!(runtime.app().status.contains("press R to reconnect"));
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn startup_protocol_failure_enters_failed_state_and_reconnects() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let transport = ScriptedTransport::new(server);
|
||||||
|
transport
|
||||||
|
.root_tree_protocol_failures
|
||||||
|
.store(1, Ordering::Release);
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(matches!(
|
||||||
|
runtime.app().connection,
|
||||||
|
ConnectionState::Failed(ref detail) if detail.contains("scripted startup failure")
|
||||||
|
));
|
||||||
|
assert!(runtime.app().status.contains("press R to reconnect"));
|
||||||
|
assert!(runtime.app().history.iter().any(|item| {
|
||||||
|
item.kind == HistoryKind::DomainFailure && item.detail.contains("scripted startup failure")
|
||||||
|
}));
|
||||||
|
|
||||||
|
runtime.handle_key(InputKey::Reconnect);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert_eq!(runtime.app().connection, ConnectionState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_transport_preparation_failure_is_definitely_not_dispatched() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.fail_call_prepare = true;
|
||||||
|
let execute_calls = Arc::clone(&transport.sequence);
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
let calls_before_operation = execute_calls.load(Ordering::Acquire);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert_eq!(
|
||||||
|
execute_calls.load(Ordering::Acquire),
|
||||||
|
calls_before_operation,
|
||||||
|
"preparation failure must not invoke transport I/O"
|
||||||
|
);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::TransportFailure);
|
||||||
|
assert!(runtime.app().history[0].detail.contains("not dispatched"));
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().status,
|
||||||
|
"operation not dispatched; not executed"
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Fresh);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn worker_panic_settles_as_unknown_instead_of_stranding_the_main_loop() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.panic_calls = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("transport worker failed")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn post_dispatch_unknown_is_prominent_stale_and_never_retried() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
|
||||||
|
let server = Arc::new(
|
||||||
|
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
|
||||||
|
);
|
||||||
|
let mut transport = ScriptedTransport::new(server);
|
||||||
|
transport.unknown_calls = true;
|
||||||
|
let config = config();
|
||||||
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
runtime.connect();
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
open_read_editor(&mut runtime);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(&mut runtime);
|
||||||
|
|
||||||
|
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
|
||||||
|
assert!(
|
||||||
|
runtime.app().history[0]
|
||||||
|
.detail
|
||||||
|
.contains("side effects are unknown")
|
||||||
|
);
|
||||||
|
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
|
||||||
|
assert!(runtime.app().in_flight.is_empty());
|
||||||
|
let history = runtime.app().history.len();
|
||||||
|
thread::sleep(Duration::from_millis(20));
|
||||||
|
runtime.poll();
|
||||||
|
assert_eq!(
|
||||||
|
runtime.app().history.len(),
|
||||||
|
history,
|
||||||
|
"no retry was manufactured"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config() -> Config {
|
||||||
|
Config::parse(
|
||||||
|
["https://example.test/wip"],
|
||||||
|
None,
|
||||||
|
Some("scripted-test".into()),
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.expect("config")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_read_editor(runtime: &mut Runtime<ScriptedTransport>) {
|
||||||
|
runtime.app_mut().selected_path = "/file".into();
|
||||||
|
runtime.app_mut().focus = Focus::Operations;
|
||||||
|
runtime.app_mut().operation_cursor = 0;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
settle(runtime);
|
||||||
|
runtime.app_mut().operation_cursor = 1;
|
||||||
|
runtime.handle_key(InputKey::Enter);
|
||||||
|
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(runtime: &mut Runtime<ScriptedTransport>) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !runtime.app().in_flight.is_empty() {
|
||||||
|
assert!(Instant::now() < deadline, "scripted runtime did not settle");
|
||||||
|
runtime.wait_and_poll(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user