Compare commits

...
46 changed files with 10335 additions and 994 deletions
Generated
+736 -12
View File
@@ -2,12 +2,30 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -20,12 +38,119 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cassowary"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "castaway"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
dependencies = [
"rustversion",
]
[[package]]
name = "cc"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "compact_str"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"static_assertions",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossterm"
version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
dependencies = [
"bitflags",
"crossterm_winapi",
"mio",
"parking_lot",
"rustix 0.38.44",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
"winapi",
]
[[package]]
name = "darling"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 3.0.6",
]
[[package]]
name = "darling_macro"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core",
"quote",
"syn 3.0.6",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -37,6 +162,12 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "either"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -50,7 +181,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -59,6 +190,29 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -68,6 +222,17 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -85,12 +250,29 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "http"
version = "1.5.0"
@@ -101,6 +283,12 @@ dependencies = [
"itoa",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "icu_collections"
version = "2.3.0"
@@ -184,6 +372,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
version = "1.1.0"
@@ -212,7 +406,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"hashbrown 0.17.1",
]
[[package]]
name = "indoc"
version = "2.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
dependencies = [
"rustversion",
]
[[package]]
name = "instability"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20"
dependencies = [
"darling",
"indoc",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
@@ -227,6 +452,12 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -239,18 +470,93 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lru"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
dependencies = [
"hashbrown 0.15.5",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "mio"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -290,6 +596,63 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "ratatui"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"
dependencies = [
"bitflags",
"cassowary",
"compact_str",
"crossterm",
"indoc",
"instability",
"itertools",
"lru",
"paste",
"strum",
"unicode-segmentation",
"unicode-truncate",
"unicode-width 0.2.0",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys 0.4.15",
"windows-sys 0.59.0",
]
[[package]]
name = "rustix"
version = "1.1.5"
@@ -299,10 +662,63 @@ dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
@@ -354,6 +770,49 @@ dependencies = [
"serde_core",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "smallvec"
version = "1.16.2"
@@ -366,6 +825,46 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck",
"proc-macro2",
"quote",
"rustversion",
"syn 2.0.119",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
@@ -412,10 +911,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys",
"rustix 1.1.5",
"windows-sys 0.61.2",
]
[[package]]
@@ -497,6 +996,70 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-truncate"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
dependencies = [
"itertools",
"unicode-segmentation",
"unicode-width 0.1.14",
]
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
dependencies = [
"base64 0.23.1",
"flate2",
"log",
"percent-encoding",
"rustls",
"rustls-pki-types",
"ureq-proto",
"utf8-zero",
"webpki-roots",
]
[[package]]
name = "ureq-proto"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
dependencies = [
"base64 0.23.1",
"http",
"httparse",
"log",
]
[[package]]
name = "url"
version = "2.5.8"
@@ -509,27 +1072,88 @@ dependencies = [
"serde",
]
[[package]]
name = "utf8-zero"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "webpki-roots"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -539,21 +1163,93 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
[[package]]
name = "wip-client"
version = "0.1.0"
dependencies = [
"wip-http",
"wip-protocol",
]
[[package]]
name = "wip-fs-server"
version = "0.1.0"
dependencies = [
"http",
"rustix",
"rustix 1.1.5",
"tempfile",
"wip-host",
"wip-https",
"wip-http",
"wip-interface",
"wip-protocol",
]
@@ -568,10 +1264,10 @@ dependencies = [
]
[[package]]
name = "wip-https"
name = "wip-http"
version = "0.1.0"
dependencies = [
"base64",
"base64 0.22.1",
"http",
"serde",
"serde_json",
@@ -610,6 +1306,22 @@ dependencies = [
"wip-protocol",
]
[[package]]
name = "wip-tui"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"crossterm",
"ratatui",
"serde_json",
"tempfile",
"ureq",
"wip-client",
"wip-fs-server",
"wip-http",
"wip-protocol",
]
[[package]]
name = "writeable"
version = "0.6.4"
@@ -660,6 +1372,12 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
[[package]]
name = "zerotrie"
version = "0.2.5"
@@ -693,6 +1411,12 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
+39 -12
View File
@@ -4,22 +4,31 @@ Rust building blocks for the Web Interface Protocol (WIP).
The repository is a resolver-3 virtual Cargo workspace whose packages all live
under `crates/*`. It provides a transport-independent protocol model, the
standard framework-independent WIP over HTTPS v1 binding, a Rust
interface-authoring facade, a request-scoped host runtime, a bounded Linux
filesystem projection server, and a private public-API conformance consumer. The
standard framework-independent WIP over HTTP v1 binding, a stateful
presentation-independent client runtime, a Rust interface-authoring facade, a
request-scoped host runtime, a bounded Linux filesystem projection server, an
interactive terminal client, and a private public-API conformance consumer. The
repository root is not itself a package.
## Crate graph and responsibilities
```text
wip-tui (interactive Worldspace explorer and operation editor)
├── wip-client Known Space, request identity, validators, and calls
├── wip-http framework-neutral HTTP request/response messages
└── wip-protocol descriptors and logical values
wip-fs-server (request-time filesystem projection and loopback listener)
├── wip-https standard routes/codecs/envelopes/batching
├── wip-http standard routes/codecs/envelopes/batching
├── wip-host request-scoped publication and dispatch
└── wip-interface macro-generated filesystem capabilities
wip-public-api-example (workspace-only executable, integration tests, doctest)
├── wip-protocol logical declarations, values, calls, and validation
├── wip-https standard HTTPS v1 routes, JSON codecs, envelopes, and batching
├── wip-http standard HTTP v1 routes, JSON codecs, envelopes, and batching
│ └── wip-protocol
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
│ ├── wip-http
│ └── wip-protocol
├── wip-interface application DTO codecs and interface authoring facade
│ ├── wip-protocol
@@ -32,16 +41,18 @@ wip-public-api-example (workspace-only executable, integration tests, doctest)
| Crate | Responsibility | Does not own |
| --- | --- | --- |
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
| `wip-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-http` | Standard WIP over HTTP v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, URL scheme or TLS policy, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTP I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
| `wip-fs-server` | Linux directory-handle-confined request-time projection, 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-fs-server` | Linux directory-handle-confined request-time projection, complete depth-bounded observations and bounded file operations, standard `wip-http` dispatch/batch handling, and a loopback HTTP binary. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, TLS termination, or filesystem-wide preregistration. |
| `wip-public-api-example` | An independently compiled consumer of the protocol, authoring, and host public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
The boundary is intentional: protocol types describe what can cross a
transport; application DTOs opt into that model with `WipType`; a host-private
implementation owns credentials, handles, and backend state; and `wip-https`
implementation owns credentials, handles, and backend state; and `wip-http`
maps standard routes/envelopes to `CallOperationRequest` and
`CallOperationResponse` without placing transport-specific types in descriptors
or application traits.
@@ -245,16 +256,32 @@ rolled back. Without that proof, post-invocation failures remain
comparison and backend commit atomic and return a validator describing the state
that becomes committed.
## Interactive terminal client
[`crates/wip-tui`](crates/wip-tui) provides the `wip-tui` executable. It starts
from Worldspace `/`, lazily expands materialized tree nodes, displays current
object/interface/operation metadata, validates all canonical descriptor types in
a field editor, and requires a separate confirmation action before every call.
It uses the stateful `wip-client` runtime for request correlation, observed
validators, stale transitions, and unknown outcomes. One canonical `http` or
`https` endpoint is used unchanged for request construction, transport, and
cache partitioning. Scheme, TLS, certificates, authentication, and proxy policy
belong to the HTTP implementation and deployment. Full startup, key binding,
layout, validator, and filesystem-operation examples are in the
[package README](crates/wip-tui/README.md).
## Filesystem projection server
[`crates/wip-fs-server`](crates/wip-fs-server) contains the practical server
binary and its full security model, configuration, curl walkthrough, and
resource/failure semantics. It resolves every object from current filesystem
state, uses pinned directory-relative handles without following symlinks, omits
non-UTF-8 backend names, 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.
non-UTF-8 backend names, returns complete recursive observations through the
requested depth or a resource-limit failure, and publishes validator-protected
replacement only in explicit read-write mode.
The built-in HTTP listener is loopback-only. Externally visible URL schemes,
TLS termination, certificates, authentication, and proxy routing are deployment
concerns rather than separate WIP profiles.
## Validation
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "wip-client"
version = "0.1.0"
edition = "2024"
description = "Presentation-independent stateful WIP client runtime"
license = "MIT OR Apache-2.0"
[dependencies]
wip-http = { path = "../wip-http" }
wip-protocol = { path = "../wip-protocol" }
File diff suppressed because it is too large Load Diff
+252
View File
@@ -0,0 +1,252 @@
use std::collections::BTreeMap;
use wip_client::{
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
ObservationState, OutcomeUnknownReason, SecurityContext,
};
use wip_http::http::{Response, StatusCode};
use wip_http::{
Limits, encode_fetch_interface_response, encode_observe_response,
encode_protocol_error_response,
};
use wip_protocol::{
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
Object, ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration,
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ReturnDeclaration, TypeExpr, Value,
};
fn limits() -> Limits {
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
}
fn setup() -> (Client, wip_client::SessionId) {
let mut client = Client::new(ClientLimits::new(2, 16, 16, 16, 16).unwrap(), limits());
let session = client
.open_session("https://example.test/wip", SecurityContext::new("subject"))
.unwrap();
(client, session)
}
fn response(status: StatusCode, body: &[u8]) -> Response<Vec<u8>> {
Response::builder()
.status(status)
.header("content-type", "application/json; charset=utf-8")
.body(body.to_vec())
.unwrap()
}
fn object() -> Object {
Object {
name: "item".into(),
description: None,
interfaces: vec!["math".into()],
r#ref: None,
validator: Some(b"object-v1".to_vec()),
}
}
fn descriptor(format: &str) -> InterfaceDescriptor {
InterfaceDescriptor {
format: format.into(),
documentation: None,
types: vec![],
operations: vec![OperationDeclaration {
name: "calculate".into(),
documentation: None,
parameters: vec![ParameterDeclaration {
name: "value".into(),
required: true,
documentation: None,
r#type: TypeExpr::Integer,
}],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::Integer,
},
}],
}
}
#[test]
fn malformed_json_unknown_fields_duplicates_and_invalid_success_are_invalid_response() {
let cases: &[&[u8]] = &[
b"{not json",
br#"{"name":"item","interfaces":[],"unknown":true}"#,
br#"{"name":"item","interfaces":["math","math"]}"#,
br#"{"name":"wrong","interfaces":[]}"#,
];
for body in cases {
let (mut client, session) = setup();
let request = client.refresh_observed(&session, "/item", 0).unwrap();
let error = client
.complete(request.id, response(StatusCode::OK, body))
.unwrap_err();
assert_eq!(error.kind, ClientErrorKind::InvalidResponse);
assert!(matches!(
client.object(&session, "/item").unwrap().state,
ObservationState::Error(_)
));
}
}
#[test]
fn disallowed_code_and_status_success_contradictions_are_invalid_response() {
let cases = [
(
StatusCode::NOT_FOUND,
br#"{"error":{"code":"interface_not_found","message":"wrong"}}"#.as_slice(),
),
(
StatusCode::OK,
br#"{"error":{"code":"not_found","message":"wrong status"}}"#.as_slice(),
),
(
StatusCode::CREATED,
br#"{"name":"item","interfaces":[]}"#.as_slice(),
),
];
for (status, body) in cases {
let (mut client, session) = setup();
let request = client.refresh_observed(&session, "/item", 0).unwrap();
assert_eq!(
client
.complete(request.id, response(status, body))
.unwrap_err()
.kind,
ClientErrorKind::InvalidResponse
);
}
}
#[test]
fn valid_error_envelope_is_authoritative_and_status_mismatch_is_diagnostic() {
let (mut client, session) = setup();
let request = client.refresh_observed(&session, "/item", 0).unwrap();
let error = ProtocolError {
code: ProtocolErrorCode::NotFound,
message: "missing".into(),
};
let mut encoded =
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
assert_eq!(
client.complete(request.id, encoded).unwrap(),
Completion::ProtocolFailure(error)
);
assert_eq!(
client.object(&session, "/item").unwrap().state,
ObservationState::Stale
);
assert_eq!(
client.diagnostics(&session).unwrap().back().unwrap().kind,
DiagnosticKind::HttpStatusMismatch
);
}
#[test]
fn non_success_without_valid_envelope_remains_transport_failure() {
let (mut client, session) = setup();
let request = client.refresh_observed(&session, "/item", 0).unwrap();
let error = client
.complete(
request.id,
response(StatusCode::BAD_GATEWAY, b"gateway html"),
)
.unwrap_err();
assert_eq!(error.kind, ClientErrorKind::Transport);
}
#[test]
fn unsupported_descriptor_format_is_distinct_from_invalid_response() {
let (mut client, session) = setup();
let request = client.prepare_interface(&session, "math").unwrap();
let logical = FetchInterfaceRequest {
interface: "math".into(),
};
let value = FetchInterfaceResponse {
interface: "math".into(),
descriptor: descriptor("future-format/2"),
validator: Some(b"v2".to_vec()),
};
let encoded = encode_fetch_interface_response(&logical, &value, limits()).unwrap();
let error = client.complete(request.id, encoded).unwrap_err();
assert_eq!(error.kind, ClientErrorKind::UnsupportedDescriptorFormat);
}
#[test]
fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object() {
let (mut client, session) = setup();
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
client
.complete(
observation.id,
encode_observe_response(
&ObserveRequest {
path: "/item".into(),
depth: 0,
},
&ObjectObservation {
object: object(),
children: None,
},
limits(),
)
.unwrap(),
)
.unwrap();
let interface = client.prepare_interface(&session, "math").unwrap();
client
.complete(
interface.id,
encode_fetch_interface_response(
&FetchInterfaceRequest {
interface: "math".into(),
},
&FetchInterfaceResponse {
interface: "math".into(),
descriptor: descriptor(INTERFACE_FORMAT_V1),
validator: None,
},
limits(),
)
.unwrap(),
)
.unwrap();
let call = client
.prepare_call(
&session,
"/item",
"math",
"calculate",
BTreeMap::from([("value".into(), Value::Integer(2))]),
)
.unwrap();
client.mark_dispatched(call.id).unwrap();
let completion = client
.complete(
call.id,
response(
StatusCode::OK,
br#"{"result":"not an integer","unknown":true}"#,
),
)
.unwrap();
assert!(matches!(
completion,
Completion::Call(record)
if matches!(
&record.outcome,
CallOutcome::Unknown {
reason: OutcomeUnknownReason::ResponseDecode,
failure: Some(failure),
} if failure.kind == ClientErrorKind::InvalidResponse
)
));
assert_eq!(
client.object(&session, "/item").unwrap().state,
ObservationState::Stale
);
assert_eq!(client.in_flight_len(), 0);
}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -2,7 +2,7 @@
name = "wip-fs-server"
version = "0.1.0"
edition = "2024"
description = "Request-time filesystem projection server for WIP over HTTPS"
description = "Request-time filesystem projection server for WIP over HTTP"
license = "MIT OR Apache-2.0"
readme = "README.md"
publish = false
@@ -11,7 +11,7 @@ publish = false
http = "1"
rustix = { version = "1.1", features = ["fs"] }
wip-host = { path = "../wip-host" }
wip-https = { path = "../wip-https" }
wip-http = { path = "../wip-http" }
wip-interface = { path = "../wip-interface" }
wip-protocol = { path = "../wip-protocol" }
+27 -30
View File
@@ -3,7 +3,7 @@
`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,
operation dispatch and uses the standard `wip-http` routes, JSON codecs,
envelopes, batching, and HTTP status mapping.
## Security model
@@ -28,9 +28,9 @@ envelopes, batching, and HTTP status mapping.
- 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 built-in HTTP listener is loopback-only. TLS termination, certificates,
authentication, an externally visible URL scheme, and proxy routing are
deployment concerns rather than separate WIP transport profiles.
The implementation currently targets Linux because it uses `O_PATH`,
directory-relative descriptor traversal, and `/proc/self/fd` to reopen the same
@@ -38,59 +38,57 @@ pinned backend object without resolving the untrusted Worldspace path twice.
## Run
Read-only behind a TLS-terminating reverse proxy:
Run the loopback listener in read-only mode:
```console
cargo run -p wip-fs-server -- \
--root /srv/public-files \
--listen 127.0.0.1:8443 \
--base-path /wip \
--behind-tls-proxy
--listen 127.0.0.1:8080 \
--base-path /wip
```
Local development with the write capability deliberately enabled:
Run with the write capability deliberately enabled:
```console
cargo run -p wip-fs-server -- \
--root ./example-files \
--listen 127.0.0.1:8080 \
--base-path /wip \
--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.
The server reports the effective root, `ReadOnly`/`ReadWrite` mode, endpoint,
and actual listen address. It does not enumerate the root.
## Standard interactions
The following examples use development HTTP for readability. The JSON is the
standard `wip-https` profile; validators and operation `Bytes` are base64 body
The following examples use the built-in HTTP listener. The JSON follows the
standard WIP over HTTP binding; validators and operation `Bytes` are base64 body
fields, never `ETag` or `If-Match` headers.
Fetch root:
Observe only the root Object:
```console
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch \
curl -sS -X POST http://127.0.0.1:8080/wip/v1/observe \
-H 'Content-Type: application/json' -H 'Accept: application/json' \
--data '{"path":"/"}'
--data '{"path":"/","depth":0}'
```
Fetch a bounded tree (the root counts toward `limit`):
Observe the root and two levels of indexable children:
```console
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_tree \
curl -sS -X POST http://127.0.0.1:8080/wip/v1/observe \
-H 'Content-Type: application/json' -H 'Accept: application/json' \
--data '{"path":"/","depth":2,"limit":100}'
--data '{"path":"/","depth":2}'
```
A regular-file fetch returns the opaque read interface reference and an object
A regular-file observation returns the opaque read interface reference and an object
validator. Retrieve that descriptor with:
```console
curl -sS -X POST http://127.0.0.1:8080/wip/v1/fetch_interface \
-H 'Content-Type: application/json' -H 'Accept: application/json' \
--data '{"interface":"<read-interface-from-fetch>"}'
--data '{"interface":"<read-interface-from-observation>"}'
```
Then call a bounded range read:
@@ -120,8 +118,8 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
}'
```
`fetch`, `fetch_tree`, and `fetch_interface` can also be combined through the
standard `POST /wip/v1/batch` route. `call_operation` is never batchable.
`observe` and `fetch_interface` can also be combined through the standard
`POST /wip/v1/batch` route. `call_operation` is never batchable.
## Resource and failure behavior
@@ -133,12 +131,11 @@ 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.
contended lock to stall a worker. Object observation recursively opens only the
requested depth. A successful response is complete through that depth; if the
configured projected-node budget would be exceeded, the interaction fails with
`ResourceLimitExceeded` instead of returning a partial observation. I/O failure
and cancellation remain errors.
Whole-file replacement compares the request validator against the identity and
state of the same pinned file handle used for the write. Failures before mutation
+20 -33
View File
@@ -1,15 +1,15 @@
//! Request-time filesystem projection served through the standard WIP HTTPS binding.
//! Request-time filesystem projection served through the standard WIP over HTTP binding.
//!
//! This crate deliberately keeps the boundaries visible:
//!
//! - [`wip_protocol`] owns logical requests and responses;
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
//! - [`wip_https`] owns routes, JSON, envelopes, batching, and status mapping;
//! - [`wip_http`] 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.
//! The built-in HTTP listener is intentionally loopback-only. TLS termination,
//! certificates, authentication, and externally visible schemes are independent
//! deployment concerns rather than WIP transport profiles.
#![deny(missing_docs)]
@@ -33,28 +33,19 @@ pub enum AccessMode {
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,
pub wire: wip_http::Limits,
/// Maximum bytes returned by one file read.
pub max_file_read_bytes: usize,
/// Maximum bytes accepted by one file replacement.
pub max_file_write_bytes: usize,
/// Maximum accepted `fetch_tree` depth.
pub max_tree_depth: u32,
/// Maximum accepted `fetch_tree` node count, including its root.
pub max_tree_nodes: u32,
/// Maximum accepted `observe` depth.
pub max_observation_depth: u32,
/// Maximum accepted `observe` node count, including its root.
pub max_observation_nodes: u32,
/// Maximum simultaneously pinned projected filesystem handles.
pub max_open_handles: usize,
/// Maximum bytes accepted for one HTTP request head, including its terminator.
@@ -68,12 +59,12 @@ pub struct ResourceLimits {
impl Default for ResourceLimits {
fn default() -> Self {
Self {
wire: wip_https::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
wire: wip_http::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
.expect("default wire limits are nonzero"),
max_file_read_bytes: 1024 * 1024,
max_file_write_bytes: 1024 * 1024,
max_tree_depth: 32,
max_tree_nodes: 1024,
max_observation_depth: 32,
max_observation_nodes: 1024,
max_open_handles: 2048,
max_http_header_bytes: 16 * 1024,
max_concurrent_requests: 32,
@@ -93,8 +84,6 @@ pub struct ServerConfig {
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,
}
@@ -102,8 +91,7 @@ pub struct ServerConfig {
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.
/// The listener defaults to an ephemeral loopback port and read-only access.
#[must_use]
pub fn for_root(root: impl Into<PathBuf>) -> Self {
Self {
@@ -111,7 +99,6 @@ impl ServerConfig {
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
endpoint_base_path: "/wip".into(),
access: AccessMode::ReadOnly,
transport_security: TransportSecurity::ReverseProxyTls,
limits: ResourceLimits::default(),
}
}
@@ -125,7 +112,7 @@ impl ServerConfig {
}
if self.limits.max_file_read_bytes == 0
|| self.limits.max_file_write_bytes == 0
|| self.limits.max_tree_nodes == 0
|| self.limits.max_observation_nodes == 0
|| self.limits.max_open_handles == 0
|| self.limits.max_http_header_bytes == 0
|| self.limits.max_concurrent_requests == 0
@@ -133,7 +120,7 @@ impl ServerConfig {
{
return Err(ConfigError::ZeroLimit);
}
if self.limits.max_open_handles < self.limits.max_tree_nodes as usize {
if self.limits.max_open_handles < self.limits.max_observation_nodes as usize {
return Err(ConfigError::InsufficientHandles);
}
if self.limits.wire.max_response_bytes() < 512 {
@@ -142,9 +129,9 @@ impl ServerConfig {
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)
pub(crate) fn endpoint(&self) -> Result<wip_http::Endpoint, ConfigError> {
let endpoint = format!("http://localhost{}", self.endpoint_base_path);
wip_http::Endpoint::parse(&endpoint).map_err(|_| ConfigError::InvalidBasePath)
}
}
@@ -171,7 +158,7 @@ impl std::fmt::Display for ConfigError {
"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::InsufficientHandles => "max_open_handles must cover max_observation_nodes",
Self::ResponseLimitTooSmall => "max_response_bytes must be at least 512",
})
}
+6 -27
View File
@@ -2,14 +2,13 @@ use std::error::Error;
use std::net::SocketAddr;
use std::path::PathBuf;
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
fn main() -> Result<(), Box<dyn Error>> {
let mut root: Option<PathBuf> = None;
let mut listen: SocketAddr = "127.0.0.1:8443".parse()?;
let mut listen: SocketAddr = "127.0.0.1:8080".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() {
@@ -17,12 +16,6 @@ fn main() -> Result<(), Box<dyn Error>> {
"--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(());
@@ -32,20 +25,17 @@ fn main() -> Result<(), Box<dyn Error>> {
}
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={}",
"wip-fs-server root={} access={access:?} endpoint={} listen={}",
effective_root.display(),
endpoint,
bound.local_addr()
@@ -63,21 +53,10 @@ fn required_value(
.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."
"Usage: wip-fs-server --root PATH [--listen 127.0.0.1:8080] \\\n [--base-path /wip] [--read-write]\n\n\
The built-in HTTP listener is loopback-only. TLS termination, authentication, \
and external routing are deployment concerns."
);
}
+102 -110
View File
@@ -1,4 +1,3 @@
use std::collections::VecDeque;
use std::ffi::CStr;
use std::mem::MaybeUninit;
use std::os::fd::{AsRawFd, OwnedFd};
@@ -17,8 +16,8 @@ use wip_host::{
};
use wip_interface as wip;
use wip_protocol::{
FetchInterfaceRequest, FetchInterfaceResponse, FetchTreeRequest, FetchTreeResponse, Object,
ObjectTreeNode, ProtocolError, ProtocolErrorCode,
FetchInterfaceRequest, FetchInterfaceResponse, ObjectObservation, ObserveRequest,
ObserveResponse, ProtocolError, ProtocolErrorCode,
};
use crate::interfaces::{
@@ -223,37 +222,60 @@ impl Projection {
.protocol_response()
}
pub(crate) fn fetch_tree(
pub(crate) fn observe(
&self,
context: &ExecutionContext,
request: &FetchTreeRequest,
) -> Result<FetchTreeResponse, ProtocolError> {
request: &ObserveRequest,
) -> Result<ObserveResponse, ProtocolError> {
request.validate().map_err(|_| ProtocolError {
code: ProtocolErrorCode::InvalidRequest,
message: "invalid fetch_tree request".into(),
message: "invalid observe request".into(),
})?;
if request.depth > self.limits.max_tree_depth || request.limit > self.limits.max_tree_nodes
{
if request.depth > self.limits.max_observation_depth {
return Err(ProjectionError::Resource.protocol());
}
let root = self
.resolve(context, &request.path)
.map_err(ProjectionError::protocol)?;
let root_object = self
.publication(root.clone(), context.clone())
.protocol_object();
let mut objects = vec![root_object];
let mut children: Vec<Vec<usize>> = vec![Vec::new()];
let mut queue = VecDeque::from([(0_usize, root, 0_u32)]);
let mut truncated = false;
let mut node_count = 0_u32;
let response = self.observe_entry(context, root, 0, request.depth, &mut node_count)?;
request
.validate_response(&response)
.map_err(|_| ProtocolError {
code: ProtocolErrorCode::Internal,
message: "Host produced an invalid observation response".into(),
})?;
Ok(response)
}
while let Some((parent_index, parent, depth)) = queue.pop_front() {
check_context(context).map_err(ProjectionError::protocol)?;
if parent.kind != EntryKind::Directory {
continue;
}
let directory_fd = reopen(parent.fd(), OFlags::RDONLY | OFlags::DIRECTORY)
fn observe_entry(
&self,
context: &ExecutionContext,
entry: Entry,
depth: u32,
maximum_depth: u32,
node_count: &mut u32,
) -> Result<ObjectObservation, ProtocolError> {
check_context(context).map_err(ProjectionError::protocol)?;
*node_count = node_count.saturating_add(1);
if *node_count > self.limits.max_observation_nodes {
return Err(ProjectionError::Resource.protocol());
}
let object = self
.publication(entry.clone(), context.clone())
.protocol_object();
if depth == maximum_depth {
return Ok(ObjectObservation {
object,
children: None,
});
}
let mut children = Vec::new();
if entry.kind == EntryKind::Directory {
let directory_fd = reopen(entry.fd(), OFlags::RDONLY | OFlags::DIRECTORY)
.map_err(ProjectionError::protocol)?;
let mut buffer = [MaybeUninit::<u8>::uninit(); 8192];
let mut directory = RawDir::new(directory_fd, &mut buffer);
@@ -271,50 +293,25 @@ impl Projection {
if name.contains('/') || name.is_empty() || name == "." || name == ".." {
continue;
}
let child = match self.open_child(context, parent.fd(), name) {
let child = match self.open_child(context, entry.fd(), name) {
Ok(child) => child,
Err(ProjectionError::NotFound) => continue,
Err(error) => return Err(error.protocol()),
};
if depth == request.depth || objects.len() == request.limit as usize {
truncated = true;
break;
}
let child_index = objects.len();
objects.push(
self.publication(child.clone(), context.clone())
.protocol_object(),
);
children.push(Vec::new());
children[parent_index].push(child_index);
if child.kind == EntryKind::Directory {
queue.push_back((child_index, child, depth + 1));
}
}
if truncated && objects.len() == request.limit as usize {
break;
children.push(self.observe_entry(
context,
child,
depth + 1,
maximum_depth,
node_count,
)?);
}
}
fn build(index: usize, objects: &[Object], children: &[Vec<usize>]) -> ObjectTreeNode {
ObjectTreeNode {
object: objects[index].clone(),
children: children[index]
.iter()
.map(|child| build(*child, objects, children))
.collect(),
}
}
let response = FetchTreeResponse {
root: build(0, &objects, &children),
truncated,
};
response.validate_for(request).map_err(|_| ProtocolError {
code: ProtocolErrorCode::Internal,
message: "Host produced an invalid tree response".into(),
})?;
Ok(response)
Ok(ObjectObservation {
object,
children: Some(children),
})
}
fn publication(
@@ -809,7 +806,7 @@ mod tests {
use wip_host::{
CallErrorKind, CallRequest, ExecutionContext, InterfaceTarget, ObjectProvider, Target,
};
use wip_protocol::{FetchTreeRequest, ProtocolErrorCode, Value};
use wip_protocol::{ObserveRequest, ProtocolErrorCode, Value};
use super::{FailureInjection, FlockOperation, Projection};
use crate::{AccessMode, ResourceLimits};
@@ -850,23 +847,29 @@ mod tests {
.expect("create symlink");
let projection = projection(temporary.path(), AccessMode::ReadOnly);
let root = projection.fetch("/").expect("fetch root");
let root = projection.observe_object("/").expect("observe root");
assert_eq!(root.name, "");
assert_eq!(root.description.as_deref(), Some("Filesystem directory"));
assert!(root.interfaces.is_empty());
assert!(root.validator.is_none());
let file = projection.fetch("/file.txt").expect("fetch file");
let file = projection
.observe_object("/file.txt")
.expect("observe file");
assert_eq!(file.interfaces.len(), 1);
assert!(file.validator.is_some());
assert!(file.r#ref.is_none());
let directory = projection.fetch("/dir").expect("fetch directory");
let directory = projection
.observe_object("/dir")
.expect("observe directory");
assert!(directory.interfaces.is_empty());
#[cfg(unix)]
{
let link = projection.fetch("/link").expect("fetch link itself");
let link = projection
.observe_object("/link")
.expect("observe link itself");
assert_eq!(
link.description.as_deref(),
Some("Symbolic link (not followed)")
@@ -874,7 +877,7 @@ mod tests {
assert_eq!(link.interfaces.len(), 1);
assert_eq!(
projection
.fetch("/link/shadow")
.observe_object("/link/shadow")
.expect_err("must not follow")
.kind(),
CallErrorKind::NotFound
@@ -892,18 +895,21 @@ mod tests {
}
assert_eq!(
projection.fetch("/missing").expect_err("missing").kind(),
projection
.observe_object("/missing")
.expect_err("missing")
.kind(),
CallErrorKind::NotFound
);
}
#[test]
fn reads_are_bounded_and_tree_truncation_is_exact() {
fn reads_are_bounded_and_observation_is_complete() {
let temporary = tempdir().expect("temporary root");
fs::write(temporary.path().join("a"), b"abcdef").expect("write file");
fs::write(temporary.path().join("b"), b"b").expect("write file");
let projection = projection(temporary.path(), AccessMode::ReadOnly);
let file = projection.fetch("/a").expect("fetch file");
let file = projection.observe_object("/a").expect("observe file");
let result = call(
&projection,
"/a",
@@ -919,30 +925,17 @@ mod tests {
assert_eq!(result.result, Value::Bytes(b"cde".to_vec()));
let complete = projection
.fetch_tree(
.observe(
&ExecutionContext::new(),
&FetchTreeRequest {
&ObserveRequest {
path: "/".into(),
depth: 1,
limit: 3,
},
)
.expect("complete tree");
assert!(!complete.truncated);
assert_eq!(complete.root.children.len(), 2);
let limited = projection
.fetch_tree(
&ExecutionContext::new(),
&FetchTreeRequest {
path: "/".into(),
depth: 1,
limit: 2,
},
)
.expect("limited tree");
assert!(limited.truncated);
assert_eq!(limited.root.children.len(), 1);
.expect("complete observation");
let children = complete.children.as_ref().expect("root children observed");
assert_eq!(children.len(), 2);
assert!(children.iter().all(|child| child.children.is_none()));
}
#[test]
@@ -951,7 +944,7 @@ mod tests {
let path = temporary.path().join("file");
fs::write(&path, b"old").expect("write file");
let projection = projection(temporary.path(), AccessMode::ReadWrite);
let observed = projection.fetch("/file").expect("fetch file");
let observed = projection.observe_object("/file").expect("observe file");
assert_eq!(observed.interfaces.len(), 2);
let write_interface = observed.interfaces[1].clone();
@@ -981,7 +974,9 @@ mod tests {
assert_eq!(stale.kind(), CallErrorKind::ValidatorMismatch);
assert_eq!(fs::read(&path).expect("read replacement"), b"replacement");
let current = projection.fetch("/file").expect("fetch replacement");
let current = projection
.observe_object("/file")
.expect("observe replacement");
let result = call(
&projection,
"/file",
@@ -1001,7 +996,7 @@ mod tests {
let path = temporary.path().join("file");
fs::write(&path, b"old").expect("write file");
let projection = projection(temporary.path(), AccessMode::ReadWrite);
let observed = projection.fetch("/file").expect("fetch file");
let observed = projection.observe_object("/file").expect("observe file");
let request = || {
call(
&projection,
@@ -1029,25 +1024,23 @@ mod tests {
}
#[test]
fn large_directory_stops_after_proving_truncation() {
fn large_directory_fails_without_partial_observation() {
let temporary = tempdir().expect("temporary root");
for index in 0..2_000 {
fs::write(temporary.path().join(format!("entry-{index}")), b"x")
.expect("write directory entry");
}
let projection = projection(temporary.path(), AccessMode::ReadOnly);
let tree = projection
.fetch_tree(
let error = projection
.observe(
&ExecutionContext::new(),
&FetchTreeRequest {
&ObserveRequest {
path: "/".into(),
depth: 1,
limit: 2,
},
)
.expect("bounded tree");
assert!(tree.truncated);
assert_eq!(tree.root.children.len(), 1);
.expect_err("complete observation exceeds node budget");
assert_eq!(error.code, ProtocolErrorCode::ResourceLimitExceeded);
}
#[cfg(unix)]
@@ -1065,22 +1058,22 @@ mod tests {
let projection = projection(temporary.path(), AccessMode::ReadOnly);
let tree = projection
.fetch_tree(
.observe(
&ExecutionContext::new(),
&FetchTreeRequest {
&ObserveRequest {
path: "/".into(),
depth: 1,
limit: 10,
},
)
.expect("list root");
assert_eq!(tree.root.children.len(), 1);
assert_eq!(tree.root.children[0].object.name, "socket");
let children = tree.children.as_ref().expect("root children observed");
assert_eq!(children.len(), 1);
assert_eq!(children[0].object.name, "socket");
assert_eq!(
tree.root.children[0].object.description.as_deref(),
children[0].object.description.as_deref(),
Some("Unsupported filesystem entry")
);
assert!(tree.root.children[0].object.interfaces.is_empty());
assert!(children[0].object.interfaces.is_empty());
}
#[test]
@@ -1091,12 +1084,11 @@ mod tests {
let cancellation = wip_host::CancellationToken::new();
cancellation.cancel();
let error = projection
.fetch_tree(
.observe(
&ExecutionContext::new().with_cancellation(cancellation),
&FetchTreeRequest {
&ObserveRequest {
path: "/".into(),
depth: 1,
limit: 2,
},
)
.expect_err("cancelled traversal");
@@ -1108,7 +1100,7 @@ mod tests {
let temporary = tempdir().expect("temporary root");
let projection = projection(temporary.path(), AccessMode::ReadOnly);
let error = projection
.fetch("/bad\0name")
.observe_object("/bad\0name")
.expect_err("NUL cannot name a backend entry");
assert_eq!(error.kind(), CallErrorKind::NotFound);
}
@@ -1144,7 +1136,7 @@ mod tests {
};
let projection = Projection::open(temporary.path(), AccessMode::ReadOnly, limits)
.expect("open projection");
let observed = projection.fetch("/file").expect("fetch file");
let observed = projection.observe_object("/file").expect("observe file");
let started = std::time::Instant::now();
let error = call(
&projection,
+24 -49
View File
@@ -7,15 +7,13 @@ use std::time::{Duration, Instant};
use http::{Request, Response, StatusCode};
use wip_host::{ExecutionContext, ObjectProvider};
use wip_https::{
use wip_http::{
BatchRequestKind, BatchResponse, BatchResponseItem, BatchSuccess, CodecError, EncodeHttpError,
Endpoint, RequestMetadataError, ResourceLimitKind, Route, decode_batch_request,
decode_call_operation_metadata, decode_fetch_interface_request, decode_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,
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
encode_batch_error_response, encode_batch_resource_limit_error_response, encode_batch_response,
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
encode_protocol_error_response, encode_resource_limit_error_response, validate_http_request,
};
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
@@ -57,7 +55,7 @@ impl WipFsServer {
&self.endpoint
}
/// Handles one already-buffered HTTP request with the standard `wip-https` codecs.
/// Handles one already-buffered HTTP request with the standard `wip-http` codecs.
///
/// Listener integrations must enforce the same body limit while collecting bytes.
#[must_use]
@@ -78,10 +76,9 @@ impl WipFsServer {
}
let context = ExecutionContext::new()
.with_deadline(deadline)
.with_resource_budget(u64::from(self.config.limits.max_tree_nodes));
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
match route {
Route::Fetch => self.fetch(request.body(), &context),
Route::FetchTree => self.fetch_tree(request.body(), &context),
Route::Observe => self.observe(request.body(), &context),
Route::FetchInterface => self.fetch_interface(request.body()),
Route::CallOperation => self.call_operation(request.body(), &context),
Route::Batch => self.batch(request.body(), &context),
@@ -90,8 +87,9 @@ impl WipFsServer {
/// 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.
/// The built-in listener is cleartext and loopback-only. Externally visible
/// schemes, TLS termination, authentication, and proxy routing are deployment
/// concerns rather than WIP transport profiles.
pub fn bind(self) -> Result<BoundServer, ServerBuildError> {
let listener = TcpListener::bind(self.config.listen)
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
@@ -110,8 +108,7 @@ impl WipFsServer {
fn route(&self, path: &str) -> Option<Route> {
[
Route::Fetch,
Route::FetchTree,
Route::Observe,
Route::FetchInterface,
Route::CallOperation,
Route::Batch,
@@ -120,33 +117,17 @@ impl WipFsServer {
.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) {
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
let request = match decode_observe_request(body, self.config.limits.wire) {
Ok(request) => request,
Err(error) => return self.codec_error(ProtocolInteraction::Fetch, error),
Err(error) => return self.codec_error(ProtocolInteraction::Observe, 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)
match self.projection.observe(context, &request) {
Ok(tree) => encode_observe_response(&request, &tree, self.config.limits.wire)
.unwrap_or_else(|error| {
self.read_encode_error(ProtocolInteraction::FetchTree, error)
self.read_encode_error(ProtocolInteraction::Observe, error)
}),
Err(error) => self.protocol_error(ProtocolInteraction::FetchTree, &error, None),
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error, None),
}
}
@@ -236,15 +217,10 @@ impl WipFsServer {
.iter()
.map(|item| {
let outcome = match &item.request {
BatchRequestKind::Fetch(request) => self
BatchRequestKind::Observe(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),
.observe(context, request)
.map(BatchSuccess::Observe),
BatchRequestKind::FetchInterface(request) => self
.projection
.fetch_interface(request)
@@ -674,11 +650,10 @@ fn write_all_with_deadline(
fn interaction(route: Route) -> ProtocolInteraction {
match route {
Route::Fetch => ProtocolInteraction::Fetch,
Route::FetchTree => ProtocolInteraction::FetchTree,
Route::Observe => ProtocolInteraction::Observe,
Route::FetchInterface => ProtocolInteraction::FetchInterface,
Route::CallOperation => ProtocolInteraction::CallOperation,
Route::Batch => ProtocolInteraction::Fetch,
Route::Batch => ProtocolInteraction::Observe,
}
}
+60 -44
View File
@@ -7,28 +7,27 @@ use std::thread;
use std::time::{Duration, Instant};
use tempfile::tempdir;
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
use wip_https::{
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
use wip_http::{
BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse, BatchSuccess, DecodedResponse,
Endpoint, JSON_CONTENT_TYPE, Limits, Route, decode_batch_request, decode_batch_response,
decode_call_operation_response, decode_fetch_interface_response, decode_fetch_response,
decode_fetch_tree_response, encode_batch_request, encode_call_operation_request,
encode_fetch_interface_request, encode_fetch_request, encode_fetch_tree_request,
decode_call_operation_response, decode_fetch_interface_response, decode_observe_response,
encode_batch_request, encode_call_operation_request, encode_fetch_interface_request,
encode_observe_request,
};
use wip_protocol::{
CallOperationRequest, FetchInterfaceRequest, FetchRequest, FetchTreeRequest, InterfaceTarget,
CallOperationRequest, FetchInterfaceRequest, InterfaceTarget, ObserveRequest,
ProtocolErrorCode, Target, Value,
};
#[test]
fn real_listener_serves_four_core_interactions_batch_and_write() {
fn real_listener_serves_three_core_interactions_batch_and_write() {
let temporary = tempdir().expect("temporary root");
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
let mut config = ServerConfig::for_root(temporary.path());
config.access = AccessMode::ReadWrite;
config.transport_security = TransportSecurity::DevelopmentHttp;
let limits = config.limits.wire;
let bound = Arc::new(
WipFsServer::new(config)
@@ -43,35 +42,42 @@ fn real_listener_serves_four_core_interactions_batch_and_write() {
let shutdown = Arc::clone(&shutdown);
thread::spawn(move || bound.serve_until(shutdown))
};
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
.expect("client endpoint");
let file_request = FetchRequest {
let file_request = ObserveRequest {
path: "/hello.txt".into(),
depth: 0,
};
let response = exchange(
address,
encode_fetch_request(&endpoint, &file_request, limits).expect("encode fetch"),
encode_observe_request(&endpoint, &file_request, limits).expect("encode observation"),
);
let file =
success(decode_fetch_response(&file_request, &response, limits).expect("decode fetch"));
let file = success(
decode_observe_response(&file_request, &response, limits).expect("decode observation"),
)
.object;
assert_eq!(file.name, "hello.txt");
assert_eq!(file.interfaces.len(), 2);
assert!(file.validator.is_some());
let tree_request = FetchTreeRequest {
let tree_request = ObserveRequest {
path: "/".into(),
depth: 1,
limit: 10,
};
let response = exchange(
address,
encode_fetch_tree_request(&endpoint, &tree_request, limits).expect("encode tree"),
encode_observe_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);
success(decode_observe_response(&tree_request, &response, limits).expect("decode tree"));
assert_eq!(
tree.children
.as_ref()
.expect("root children observed")
.len(),
2
);
let read_interface_request = FetchInterfaceRequest {
interface: file.interfaces[0].clone(),
@@ -122,14 +128,16 @@ fn real_listener_serves_four_core_interactions_batch_and_write() {
requests: vec![
BatchRequestItem {
id: "root".into(),
request: BatchRequestKind::Fetch(FetchRequest { path: "/".into() }),
request: BatchRequestKind::Observe(ObserveRequest {
path: "/".into(),
depth: 0,
}),
},
BatchRequestItem {
id: "tree".into(),
request: BatchRequestKind::FetchTree(FetchTreeRequest {
request: BatchRequestKind::Observe(ObserveRequest {
path: "/nested".into(),
depth: 1,
limit: 4,
}),
},
BatchRequestItem {
@@ -206,7 +214,6 @@ fn real_listener_serves_four_core_interactions_batch_and_write() {
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;
@@ -230,21 +237,25 @@ fn stalled_request_body_times_out_and_releases_the_only_worker() {
.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{{"
"POST /wip/v1/observe HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nAccept: application/json\r\nContent-Length: 100\r\n\r\n{{"
)
.expect("write partial request");
stalled.flush().expect("flush partial request");
thread::sleep(Duration::from_millis(25));
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
.expect("client endpoint");
let fetch = FetchRequest { path: "/".into() };
let observe = ObserveRequest {
path: "/".into(),
depth: 0,
};
let started = Instant::now();
let response = exchange(
address,
encode_fetch_request(&endpoint, &fetch, limits).expect("encode fetch"),
encode_observe_request(&endpoint, &observe, limits).expect("encode observation"),
);
let _root = success(decode_fetch_response(&fetch, &response, limits).expect("decode fetch"));
let _root =
success(decode_observe_response(&observe, &response, limits).expect("decode observation"));
assert!(
started.elapsed() < Duration::from_secs(1),
"the valid request remained starved after the intake deadline"
@@ -276,8 +287,8 @@ fn batch_keeps_known_malformed_arguments_item_local() {
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 endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
let body = br#"{"requests":[{"id":"ok","method":"observe","arguments":{"path":"/","depth":0}},{"id":"bad","method":"observe","arguments":{"path":"/","depth":"bad"}}]}"#;
let logical = decode_batch_request(body, limits).expect("decode item-local invalid request");
assert!(matches!(
logical.requests[1].request,
@@ -296,7 +307,7 @@ fn batch_keeps_known_malformed_arguments_item_local() {
);
assert!(matches!(
batch.responses[0].outcome,
Ok(BatchSuccess::Fetch(_))
Ok(BatchSuccess::Observe(_))
));
assert!(batch.responses[1].outcome.is_err());
}
@@ -306,7 +317,7 @@ 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 endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
let request = http::Request::builder()
.method(http::Method::POST)
@@ -330,14 +341,16 @@ fn backend_invalid_unicode_path_is_not_found_not_internal() {
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 {
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
let request = ObserveRequest {
path: "/bad\0name".into(),
depth: 0,
};
let response = server
.handle_http(encode_fetch_request(&endpoint, &request, limits).expect("encode fetch"));
let response = server.handle_http(
encode_observe_request(&endpoint, &request, limits).expect("encode observation"),
);
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
match decode_fetch_response(&request, &response, limits).expect("decode missing response") {
match decode_observe_response(&request, &response, limits).expect("decode missing response") {
DecodedResponse::ProtocolFailure { error, .. } => {
assert_eq!(error.code, ProtocolErrorCode::NotFound);
}
@@ -353,16 +366,19 @@ fn read_response_size_failure_preserves_non_commit_guarantee() {
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 endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
let fetch_request = FetchRequest {
let observe_request = ObserveRequest {
path: "/large".into(),
depth: 0,
};
let response = server.handle_http(
encode_fetch_request(&endpoint, &fetch_request, limits).expect("encode fetch"),
encode_observe_request(&endpoint, &observe_request, limits).expect("encode observation"),
);
let file =
success(decode_fetch_response(&fetch_request, &response, limits).expect("decode fetch"));
let file = success(
decode_observe_response(&observe_request, &response, limits).expect("decode observation"),
)
.object;
let interface_request = FetchInterfaceRequest {
interface: file.interfaces[0].clone(),
};
@@ -405,11 +421,11 @@ fn assert_batch_successes(batch: &BatchResponse) {
assert_eq!(batch.responses.len(), 3);
assert!(matches!(
batch.responses[0].outcome,
Ok(BatchSuccess::Fetch(_))
Ok(BatchSuccess::Observe(_))
));
assert!(matches!(
batch.responses[1].outcome,
Ok(BatchSuccess::FetchTree(_))
Ok(BatchSuccess::Observe(_))
));
assert!(matches!(
batch.responses[2].outcome,
+7 -7
View File
@@ -352,7 +352,7 @@ impl InterfaceRegistry {
/// Observes a registered interface by its host-side reference.
#[must_use]
pub fn observe(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
pub fn observe_object(&self, reference: &InterfaceRef) -> Option<InterfaceObservation> {
self.artifacts.get(reference).map(Self::observation)
}
@@ -863,13 +863,13 @@ pub trait ObjectProvider {
true
}
/// Fetches the canonical object projection currently published at `path`.
fn fetch(&self, path: &str) -> Result<Object, CallError> {
self.fetch_with_context(&ExecutionContext::default(), path)
/// Observes the canonical object projection currently published at `path`.
fn observe_object(&self, path: &str) -> Result<Object, CallError> {
self.observe_object_with_context(&ExecutionContext::default(), path)
}
/// Fetches an object while propagating runtime execution controls.
fn fetch_with_context(
/// Observes an object while propagating runtime execution controls.
fn observe_object_with_context(
&self,
context: &ExecutionContext,
path: &str,
@@ -882,7 +882,7 @@ pub trait ObjectProvider {
.map_err(|_| {
CallError::new(
CallErrorKind::Internal,
"provider panicked while fetching an object",
"provider panicked while observing an object",
)
})?;
let object = match resolved {
+8 -8
View File
@@ -467,7 +467,7 @@ fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor()
#[test]
fn canonical_object_projection_supports_optional_metadata_and_ordered_sets() {
let (_, provider, _) = registry_and_provider();
let object = provider.fetch("/document").unwrap();
let object = provider.observe_object("/document").unwrap();
assert_eq!(object.name, "document");
assert_eq!(object.description.as_deref(), Some("public document"));
@@ -483,7 +483,7 @@ fn canonical_object_projection_supports_optional_metadata_and_ordered_sets() {
assert!(!format!("{object:?}").contains("secret-handle"));
assert!(!format!("{object:?}").contains("/document"));
let empty = provider.fetch("/empty").unwrap();
let empty = provider.observe_object("/empty").unwrap();
assert!(empty.interfaces.is_empty());
assert_eq!(empty.r#ref, None);
assert_eq!(empty.validator, None);
@@ -518,13 +518,13 @@ fn duplicate_exposure_is_rejected_and_private_state_is_not_projected() {
fn paths_are_resolution_context_not_object_identity() {
let (_, provider, _) = registry_and_provider();
let left = provider.fetch("/left/document").unwrap();
let right = provider.fetch("/right/document").unwrap();
let left = provider.observe_object("/left/document").unwrap();
let right = provider.observe_object("/right/document").unwrap();
assert_eq!(left, right);
assert_eq!(left.r#ref.as_deref(), Some("shared-ref"));
let first = provider.fetch("/switch").unwrap();
let second = provider.fetch("/switch").unwrap();
let first = provider.observe_object("/switch").unwrap();
let second = provider.observe_object("/switch").unwrap();
assert_ne!(first.r#ref, second.r#ref);
assert_ne!(first.validator, second.validator);
}
@@ -603,7 +603,7 @@ fn call_failures_follow_canonical_precedence_without_execution() {
}
assert_eq!(provider.resolutions.get(), resolutions);
assert_failure(
provider.fetch("/invalid/").unwrap_err(),
provider.observe_object("/invalid/").unwrap_err(),
CallErrorKind::InvalidRequest,
ProtocolErrorCode::InvalidRequest,
);
@@ -849,7 +849,7 @@ fn invalid_host_responses_and_uncertain_operation_failures_use_canonical_codes()
let (_, provider, _) = registry_and_provider();
assert_failure(
provider.fetch("/invalid-object").unwrap_err(),
provider.observe_object("/invalid-object").unwrap_err(),
CallErrorKind::Internal,
ProtocolErrorCode::Internal,
);
@@ -1,8 +1,8 @@
[package]
name = "wip-https"
name = "wip-http"
version = "0.1.0"
edition = "2024"
description = "Framework-independent standard WIP over HTTPS v1 binding"
description = "Framework-independent standard WIP over HTTP v1 binding"
license = "MIT OR Apache-2.0"
[dependencies]
@@ -4,8 +4,8 @@ use http::header::{ACCEPT, CONTENT_TYPE};
use http::{Method, Request, Response, StatusCode};
use serde_json::{Map, Value as Json};
use wip_protocol::{
FetchInterfaceRequest, FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest,
FetchTreeResponse, INTERFACE_FORMAT_V1, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, ObserveRequest,
ObserveResponse, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
};
use crate::response::{self, DecodedResponse};
@@ -17,10 +17,8 @@ use crate::{
/// A retrieval method accepted by the standard v1 batch endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatchMethod {
/// Fetch one object.
Fetch,
/// Fetch one bounded tree.
FetchTree,
/// Observe one object and its indexable descendants.
Observe,
/// Fetch one interface descriptor.
FetchInterface,
}
@@ -28,16 +26,14 @@ pub enum BatchMethod {
impl BatchMethod {
fn name(self) -> &'static str {
match self {
Self::Fetch => "fetch",
Self::FetchTree => "fetch_tree",
Self::Observe => "observe",
Self::FetchInterface => "fetch_interface",
}
}
fn interaction(self) -> ProtocolInteraction {
match self {
Self::Fetch => ProtocolInteraction::Fetch,
Self::FetchTree => ProtocolInteraction::FetchTree,
Self::Observe => ProtocolInteraction::Observe,
Self::FetchInterface => ProtocolInteraction::FetchInterface,
}
}
@@ -46,10 +42,8 @@ impl BatchMethod {
/// One retrieval interaction accepted by the standard v1 batch endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BatchRequestKind {
/// Fetch one object.
Fetch(FetchRequest),
/// Fetch one bounded tree.
FetchTree(FetchTreeRequest),
/// Observe one object and its indexable descendants.
Observe(ObserveRequest),
/// Fetch one interface descriptor.
FetchInterface(FetchInterfaceRequest),
/// A known method whose `arguments` are not a valid logical request.
@@ -64,8 +58,7 @@ pub enum BatchRequestKind {
impl BatchRequestKind {
fn interaction(&self) -> ProtocolInteraction {
match self {
Self::Fetch(_) => ProtocolInteraction::Fetch,
Self::FetchTree(_) => ProtocolInteraction::FetchTree,
Self::Observe(_) => ProtocolInteraction::Observe,
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
Self::Invalid { method, .. } => method.interaction(),
}
@@ -91,10 +84,8 @@ pub struct BatchRequest {
/// Successful result of one batch item.
#[derive(Debug, Clone, PartialEq)]
pub enum BatchSuccess {
/// Successful `fetch` result.
Fetch(FetchResponse),
/// Successful `fetch_tree` result.
FetchTree(FetchTreeResponse),
/// Successful `observe` result.
Observe(ObserveResponse),
/// Successful `fetch_interface` result.
FetchInterface(FetchInterfaceResponse),
}
@@ -135,10 +126,7 @@ fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Resul
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
let (method, arguments) = match &item.request {
BatchRequestKind::Fetch(value) => ("fetch", json::fetch_request_to_json(value)),
BatchRequestKind::FetchTree(value) => {
("fetch_tree", json::fetch_tree_request_to_json(value))
}
BatchRequestKind::Observe(value) => ("observe", json::observe_request_to_json(value)),
BatchRequestKind::FetchInterface(value) => (
"fetch_interface",
json::fetch_interface_request_to_json(value),
@@ -160,8 +148,7 @@ fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, Codec
)?;
for item in &request.requests {
match &item.request {
BatchRequestKind::Fetch(value) => value.validate()?,
BatchRequestKind::FetchTree(value) => value.validate()?,
BatchRequestKind::Observe(value) => value.validate()?,
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
}
}
@@ -190,22 +177,18 @@ fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, Codec
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
let arguments = required(fields, "arguments")?;
let method = match method_name.as_str() {
"fetch" => BatchMethod::Fetch,
"fetch_tree" => BatchMethod::FetchTree,
"observe" => BatchMethod::Observe,
"fetch_interface" => BatchMethod::FetchInterface,
_ => {
return Err(CodecError::InvalidField {
field: format!("{field}.method"),
reason: "batch supports only fetch, fetch_tree, and fetch_interface".into(),
reason: "batch supports only observe and fetch_interface".into(),
});
}
};
let decoded = match method {
BatchMethod::Fetch => {
json::fetch_request_from_json(arguments).map(BatchRequestKind::Fetch)
}
BatchMethod::FetchTree => {
json::fetch_tree_request_from_json(arguments).map(BatchRequestKind::FetchTree)
BatchMethod::Observe => {
json::observe_request_from_json(arguments).map(BatchRequestKind::Observe)
}
BatchMethod::FetchInterface => json::fetch_interface_request_from_json(arguments)
.map(BatchRequestKind::FetchInterface),
@@ -249,8 +232,7 @@ pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest,
fn success_to_json(success: &BatchSuccess) -> Json {
match success {
BatchSuccess::Fetch(value) => json::object_to_json(value),
BatchSuccess::FetchTree(value) => json::fetch_tree_response_to_json(value),
BatchSuccess::Observe(value) => json::observe_response_to_json(value),
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
}
}
@@ -299,12 +281,9 @@ fn correlate(
});
};
match (&item.outcome, *kind) {
(Ok(BatchSuccess::Fetch(value)), BatchRequestKind::Fetch(request)) => {
(Ok(BatchSuccess::Observe(value)), BatchRequestKind::Observe(request)) => {
request.validate_response(value)?;
}
(Ok(BatchSuccess::FetchTree(value)), BatchRequestKind::FetchTree(request)) => {
value.validate_for(request)?;
}
(
Ok(BatchSuccess::FetchInterface(value)),
BatchRequestKind::FetchInterface(request),
@@ -459,15 +438,10 @@ fn response_from_json(
Err(error)
}
(Some(result), None) => Ok(match kind {
BatchRequestKind::Fetch(request) => {
let value = json::object_from_json(result, "result")?;
BatchRequestKind::Observe(request) => {
let value = json::observe_response_from_json(result)?;
request.validate_response(&value)?;
BatchSuccess::Fetch(value)
}
BatchRequestKind::FetchTree(request) => {
let value = json::fetch_tree_response_from_json(result)?;
value.validate_for(request)?;
BatchSuccess::FetchTree(value)
BatchSuccess::Observe(value)
}
BatchRequestKind::FetchInterface(request) => {
let value = json::fetch_interface_response_from_json(result)?;
@@ -509,7 +483,7 @@ pub fn decode_batch_response<B: AsRef<[u8]>>(
let decoded = response::decode(
value.status(),
value.body().as_ref(),
ProtocolInteraction::Fetch,
ProtocolInteraction::Observe,
limits,
|json| response_from_json(json, request, limits),
)
@@ -5,8 +5,8 @@ use http::header::{ACCEPT, CONTENT_TYPE};
use http::{HeaderMap, Method, Request, Response, StatusCode};
use wip_protocol::{
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
FetchRequest, FetchResponse, FetchTreeRequest, FetchTreeResponse, INTERFACE_FORMAT_V1,
InterfaceDescriptor, InterfaceTarget, ProtocolError, ProtocolInteraction, Target,
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, ObserveRequest, ObserveResponse,
ProtocolError, ProtocolInteraction, Target,
};
use crate::response::{self, DecodedResponse};
@@ -264,49 +264,25 @@ pub fn validate_http_request<B>(
Ok(())
}
/// Encodes a `fetch` HTTP request.
pub fn encode_fetch_request(
/// Encodes an `observe` HTTP request.
pub fn encode_observe_request(
endpoint: &Endpoint,
value: &FetchRequest,
value: &ObserveRequest,
limits: Limits,
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
value.validate().map_err(CodecError::from)?;
let body = json::serialize(
&json::fetch_request_to_json(value),
&json::observe_request_to_json(value),
BodyKind::Request,
limits,
)?;
Ok(request(endpoint, Route::Fetch, body)?)
Ok(request(endpoint, Route::Observe, body)?)
}
/// Decodes a `fetch` request body.
pub fn decode_fetch_request(body: &[u8], limits: Limits) -> Result<FetchRequest, CodecError> {
/// Decodes an `observe` request body.
pub fn decode_observe_request(body: &[u8], limits: Limits) -> Result<ObserveRequest, CodecError> {
let value = json::parse(body, BodyKind::Request, limits)?;
json::fetch_request_from_json(&value)
}
/// Encodes a `fetch_tree` HTTP request.
pub fn encode_fetch_tree_request(
endpoint: &Endpoint,
value: &FetchTreeRequest,
limits: Limits,
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
value.validate().map_err(CodecError::from)?;
let body = json::serialize(
&json::fetch_tree_request_to_json(value),
BodyKind::Request,
limits,
)?;
Ok(request(endpoint, Route::FetchTree, body)?)
}
/// Decodes a `fetch_tree` request body.
pub fn decode_fetch_tree_request(
body: &[u8],
limits: Limits,
) -> Result<FetchTreeRequest, CodecError> {
let value = json::parse(body, BodyKind::Request, limits)?;
json::fetch_tree_request_from_json(&value)
json::observe_request_from_json(&value)
}
/// Encodes a `fetch_interface` HTTP request.
@@ -407,72 +383,39 @@ pub fn decode_call_operation_request(
json::call_request_from_json(&value, descriptor)
}
/// Encodes a successful `fetch` response as a direct body with HTTP 200.
pub fn encode_fetch_response(
request_value: &FetchRequest,
value: &FetchResponse,
/// Encodes a successful `observe` response as a direct body with HTTP 200.
pub fn encode_observe_response(
request_value: &ObserveRequest,
value: &ObserveResponse,
limits: Limits,
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
request_value
.validate_response(value)
.map_err(CodecError::from)?;
let body = json::serialize(&json::object_to_json(value), BodyKind::Response, limits)?;
Ok(response(StatusCode::OK, body)?)
}
/// Decodes and classifies a `fetch` client response.
pub fn decode_fetch_response<B: AsRef<[u8]>>(
request_value: &FetchRequest,
value: &Response<B>,
limits: Limits,
) -> Result<DecodedResponse<FetchResponse>, ClientResponseError> {
require_response_content_type(value)?;
response::decode(
value.status(),
value.body().as_ref(),
ProtocolInteraction::Fetch,
limits,
|json| {
let object = json::object_from_json(json, "response")?;
request_value.validate_response(&object)?;
Ok(object)
},
)
}
/// Encodes a successful `fetch_tree` response as a direct body with HTTP 200.
pub fn encode_fetch_tree_response(
request_value: &FetchTreeRequest,
value: &FetchTreeResponse,
limits: Limits,
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
value
.validate_for(request_value)
.map_err(CodecError::from)?;
let body = json::serialize(
&json::fetch_tree_response_to_json(value),
&json::observe_response_to_json(value),
BodyKind::Response,
limits,
)?;
Ok(response(StatusCode::OK, body)?)
}
/// Decodes and classifies a `fetch_tree` client response.
pub fn decode_fetch_tree_response<B: AsRef<[u8]>>(
request_value: &FetchTreeRequest,
/// Decodes and classifies an `observe` client response.
pub fn decode_observe_response<B: AsRef<[u8]>>(
request_value: &ObserveRequest,
value: &Response<B>,
limits: Limits,
) -> Result<DecodedResponse<FetchTreeResponse>, ClientResponseError> {
) -> Result<DecodedResponse<ObserveResponse>, ClientResponseError> {
require_response_content_type(value)?;
response::decode(
value.status(),
value.body().as_ref(),
ProtocolInteraction::FetchTree,
ProtocolInteraction::Observe,
limits,
|json| {
let tree = json::fetch_tree_response_from_json(json)?;
tree.validate_for(request_value)?;
Ok(tree)
let observation = json::observe_response_from_json(json)?;
request_value.validate_response(&observation)?;
Ok(observation)
},
)
}
@@ -6,13 +6,11 @@ use url::Url;
/// The media type emitted for every WIP request and every response with a body.
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
/// A fixed standard WIP over HTTPS v1 route.
/// A fixed standard WIP over HTTP v1 route.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Route {
/// Fetch one object.
Fetch,
/// Fetch a bounded object tree.
FetchTree,
/// Observe one object and its indexable descendants.
Observe,
/// Fetch an interface descriptor.
FetchInterface,
/// Call one operation.
@@ -26,8 +24,7 @@ impl Route {
#[must_use]
pub const fn relative_reference(self) -> &'static str {
match self {
Self::Fetch => "v1/fetch",
Self::FetchTree => "v1/fetch_tree",
Self::Observe => "v1/observe",
Self::FetchInterface => "v1/fetch_interface",
Self::CallOperation => "v1/call_operation",
Self::Batch => "v1/batch",
@@ -35,22 +32,20 @@ impl Route {
}
}
/// A canonical absolute HTTPS base URL whose path always ends in `/`.
/// A canonical absolute hierarchical base URL whose path always ends in `/`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoint(Url);
impl Endpoint {
/// Parses and canonicalizes an endpoint.
///
/// The input must be an absolute HTTPS URL without a query or fragment. Its
/// path is an endpoint prefix, not a Worldspace path. A trailing slash is
/// appended when absent so RFC 3986 relative-reference resolution preserves
/// the final prefix segment.
/// The input must be an absolute hierarchical URL with a host and without a
/// query or fragment. Its path is an endpoint prefix, not a Worldspace path.
/// A trailing slash is appended when absent so RFC 3986 relative-reference
/// resolution preserves the final prefix segment. The supplied scheme is
/// preserved; scheme and transport security are deployment concerns.
pub fn parse(input: &str) -> Result<Self, EndpointError> {
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
if url.scheme() != "https" {
return Err(EndpointError::NotHttps);
}
if url.cannot_be_a_base() || url.host_str().is_none() {
return Err(EndpointError::NotAbsoluteBase);
}
@@ -87,9 +82,8 @@ impl Endpoint {
/// are not route components and therefore never match.
#[must_use]
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
const ROUTES: [Route; 5] = [
Route::Fetch,
Route::FetchTree,
const ROUTES: [Route; 4] = [
Route::Observe,
Route::FetchInterface,
Route::CallOperation,
Route::Batch,
@@ -117,13 +111,11 @@ impl TryFrom<&str> for Endpoint {
}
}
/// Why an endpoint is not a valid standard WIP HTTPS base.
/// Why an endpoint is not a valid standard WIP over HTTP base.
#[derive(Debug)]
pub enum EndpointError {
/// URL parsing failed.
InvalidUrl(url::ParseError),
/// The URL scheme is not `https`.
NotHttps,
/// The URL is not a hierarchical absolute URL with an authority.
NotAbsoluteBase,
/// A query component was supplied.
@@ -136,7 +128,6 @@ impl Display for EndpointError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
Self::NotHttps => formatter.write_str("WIP endpoint must use HTTPS"),
Self::NotAbsoluteBase => {
formatter.write_str("WIP endpoint must be an absolute base URL")
}
@@ -7,9 +7,9 @@ use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde_json::{Map, Number, Value as Json};
use wip_protocol::{
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER,
Object, ObjectTreeNode, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
InterfaceTarget, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
ObserveResponse, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
TypeDeclaration, TypeExpr, UnionCase, Value,
};
@@ -271,29 +271,15 @@ fn insert_optional_bytes(map: &mut Map<String, Json>, name: &str, value: &Option
}
}
pub(crate) fn fetch_request_to_json(request: &FetchRequest) -> Json {
serde_json::json!({"path": request.path})
pub(crate) fn observe_request_to_json(request: &ObserveRequest) -> Json {
serde_json::json!({"path": request.path, "depth": request.depth})
}
pub(crate) fn fetch_request_from_json(value: &Json) -> Result<FetchRequest, CodecError> {
let fields = exact_object(value, "request", &["path"])?;
let request = FetchRequest {
path: string(required(fields, "path")?, "path")?,
};
request.validate()?;
Ok(request)
}
pub(crate) fn fetch_tree_request_to_json(request: &FetchTreeRequest) -> Json {
serde_json::json!({"path": request.path, "depth": request.depth, "limit": request.limit})
}
pub(crate) fn fetch_tree_request_from_json(value: &Json) -> Result<FetchTreeRequest, CodecError> {
let fields = exact_object(value, "request", &["path", "depth", "limit"])?;
let request = FetchTreeRequest {
pub(crate) fn observe_request_from_json(value: &Json) -> Result<ObserveRequest, CodecError> {
let fields = exact_object(value, "request", &["path", "depth"])?;
let request = ObserveRequest {
path: string(required(fields, "path")?, "path")?,
depth: u32_number(required(fields, "depth")?, "depth")?,
limit: u32_number(required(fields, "limit")?, "limit")?,
};
request.validate()?;
Ok(request)
@@ -360,35 +346,43 @@ pub(crate) fn object_from_json(value: &Json, field: &str) -> Result<Object, Code
Ok(object)
}
fn tree_node_to_json(node: &ObjectTreeNode) -> Json {
serde_json::json!({
"object": object_to_json(&node.object),
"children": node.children.iter().map(tree_node_to_json).collect::<Vec<_>>()
})
fn observation_to_json(node: &ObjectObservation) -> Json {
let mut fields = Map::new();
fields.insert("object".into(), object_to_json(&node.object));
if let Some(children) = &node.children {
fields.insert(
"children".into(),
Json::Array(children.iter().map(observation_to_json).collect()),
);
}
Json::Object(fields)
}
fn tree_node_from_json(value: &Json, field: &str) -> Result<ObjectTreeNode, CodecError> {
fn observation_from_json(value: &Json, field: &str) -> Result<ObjectObservation, CodecError> {
let fields = exact_object(value, field, &["object", "children"])?;
Ok(ObjectTreeNode {
let children = optional(fields, "children")?
.map(|value| {
array(value, &qualified(field, "children"))?
.iter()
.enumerate()
.map(|(index, child)| {
observation_from_json(child, &format!("{field}.children[{index}]"))
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
Ok(ObjectObservation {
object: object_from_json(required(fields, "object")?, &qualified(field, "object"))?,
children: array(required(fields, "children")?, &qualified(field, "children"))?
.iter()
.enumerate()
.map(|(index, child)| tree_node_from_json(child, &format!("{field}.children[{index}]")))
.collect::<Result<Vec<_>, _>>()?,
children,
})
}
pub(crate) fn fetch_tree_response_to_json(response: &FetchTreeResponse) -> Json {
serde_json::json!({"root": tree_node_to_json(&response.root), "truncated": response.truncated})
pub(crate) fn observe_response_to_json(response: &ObserveResponse) -> Json {
observation_to_json(response)
}
pub(crate) fn fetch_tree_response_from_json(value: &Json) -> Result<FetchTreeResponse, CodecError> {
let fields = exact_object(value, "response", &["root", "truncated"])?;
Ok(FetchTreeResponse {
root: tree_node_from_json(required(fields, "root")?, "root")?,
truncated: boolean(required(fields, "truncated")?, "truncated")?,
})
pub(crate) fn observe_response_from_json(value: &Json) -> Result<ObserveResponse, CodecError> {
observation_from_json(value, "response")
}
fn documentation_to_json(documentation: &Documentation) -> Json {
@@ -1,27 +1,29 @@
//! Framework-independent standard WIP over HTTPS v1 binding.
//! Framework-independent standard WIP over HTTP v1 binding.
//!
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
//! success and error response handling, HTTP status mapping, descriptor-guided
//! operation-value conversion, and retrieval batching. It deliberately performs
//! no I/O and depends on no server framework, TLS implementation, filesystem
//! projection, client cache, or presentation layer.
//! projection, client cache, or presentation layer. URL schemes, TLS,
//! certificates, authentication mechanisms, proxies, and caches are selected by
//! the HTTP implementation and deployment rather than by WIP conformance.
//!
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
//!
//! ```
//! use wip_https::{Endpoint, Limits, encode_fetch_request};
//! use wip_protocol::FetchRequest;
//! use wip_http::{Endpoint, Limits, encode_observe_request};
//! use wip_protocol::ObserveRequest;
//!
//! let endpoint = Endpoint::parse("https://example.test/api/wip")?;
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
//! let request = encode_fetch_request(
//! let request = encode_observe_request(
//! &endpoint,
//! &FetchRequest { path: "/items/123".into() },
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
//! limits,
//! )?;
//! assert_eq!(request.uri(), "https://example.test/api/wip/v1/fetch");
//! assert_eq!(request.uri(), "http://example.test/api/wip/v1/observe");
//! assert_eq!(request.method(), http::Method::POST);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
@@ -44,12 +46,11 @@ pub use batch::{
pub use codec::{
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
decode_fetch_interface_response, decode_fetch_request, decode_fetch_response,
decode_fetch_tree_request, decode_fetch_tree_response, encode_call_operation_request,
encode_call_operation_response, encode_fetch_interface_request,
encode_fetch_interface_response, encode_fetch_request, encode_fetch_response,
encode_fetch_tree_request, encode_fetch_tree_response, encode_protocol_error_response,
encode_resource_limit_error_response, is_json_content_type, validate_http_request,
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
encode_protocol_error_response, encode_resource_limit_error_response, is_json_content_type,
validate_http_request,
};
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
@@ -1,9 +1,9 @@
use wip_https::http::StatusCode;
use wip_https::wip_protocol::{
FetchInterfaceRequest, FetchInterfaceResponse, FetchRequest, INTERFACE_FORMAT_V1,
InterfaceDescriptor, Object, ProtocolError, ProtocolErrorCode,
use wip_http::http::StatusCode;
use wip_http::wip_protocol::{
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
Object, ObjectObservation, ObserveRequest, ProtocolError, ProtocolErrorCode,
};
use wip_https::{
use wip_http::{
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
BatchResponseItem, BatchSuccess, ClientResponseError, DecodedResponse, Endpoint,
InvalidResponseKind, Limits, ResourceLimitKind, decode_batch_request, decode_batch_response,
@@ -15,13 +15,27 @@ fn limits() -> Limits {
Limits::new(100_000, 100_000, 64, 4).unwrap()
}
fn observed_item(validator: Option<Vec<u8>>) -> ObjectObservation {
ObjectObservation {
object: Object {
name: "item".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator,
},
children: None,
}
}
fn request() -> BatchRequest {
BatchRequest {
requests: vec![
BatchRequestItem {
id: "object".into(),
request: BatchRequestKind::Fetch(FetchRequest {
request: BatchRequestKind::Observe(ObserveRequest {
path: "/item".into(),
depth: 0,
}),
},
BatchRequestItem {
@@ -57,13 +71,9 @@ fn batch_round_trips_by_unique_id_with_item_failures_and_validators() {
},
BatchResponseItem {
id: "object".into(),
outcome: Ok(BatchSuccess::Fetch(Object {
name: "item".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator: Some(vec![0, 1, 2, 255]),
})),
outcome: Ok(BatchSuccess::Observe(observed_item(Some(vec![
0, 1, 2, 255,
])))),
},
],
};
@@ -121,18 +131,18 @@ fn batch_interface_validator_round_trips_in_item_body() {
fn malformed_known_method_arguments_are_item_local() {
let body = br#"{
"requests": [
{"id":"valid","method":"fetch","arguments":{"path":"/item"}},
{"id":"invalid","method":"fetch_tree","arguments":{"path":"/","depth":"deep","limit":1}}
{"id":"valid","method":"observe","arguments":{"path":"/item","depth":0}},
{"id":"invalid","method":"observe","arguments":{"path":"/","depth":"deep"}}
]
}"#;
let decoded = decode_batch_request(body, limits()).unwrap();
assert!(matches!(
decoded.requests[0].request,
BatchRequestKind::Fetch(_)
BatchRequestKind::Observe(_)
));
let invalid = match &decoded.requests[1].request {
BatchRequestKind::Invalid { method, error } => {
assert_eq!(*method, BatchMethod::FetchTree);
assert_eq!(*method, BatchMethod::Observe);
assert_eq!(error.code, ProtocolErrorCode::InvalidRequest);
error.clone()
}
@@ -143,13 +153,7 @@ fn malformed_known_method_arguments_are_item_local() {
responses: vec![
BatchResponseItem {
id: "valid".into(),
outcome: Ok(BatchSuccess::Fetch(Object {
name: "item".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator: None,
})),
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
},
BatchResponseItem {
id: "invalid".into(),
@@ -171,15 +175,15 @@ fn invalid_batch_envelopes_are_rejected_at_top_level() {
let malformed_item = br#"{
"requests": [
{"id":"item","method":"fetch","arguments":{"path":"/"},"extra":true}
{"id":"item","method":"observe","arguments":{"path":"/","depth":0},"extra":true}
]
}"#;
assert!(decode_batch_request(malformed_item, limits()).is_err());
let duplicate = br#"{
"requests": [
{"id":"same","method":"fetch","arguments":{"path":"/a"}},
{"id":"same","method":"fetch","arguments":{"path":"/b"}}
{"id":"same","method":"observe","arguments":{"path":"/a","depth":0}},
{"id":"same","method":"observe","arguments":{"path":"/b","depth":0}}
]
}"#;
assert!(decode_batch_request(duplicate, limits()).is_err());
@@ -228,13 +232,7 @@ fn batch_success_body_requires_exactly_http_200() {
responses: vec![
BatchResponseItem {
id: "object".into(),
outcome: Ok(BatchSuccess::Fetch(Object {
name: "item".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator: None,
})),
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
},
BatchResponseItem {
id: "interface".into(),
@@ -271,7 +269,7 @@ fn top_level_batch_errors_use_the_batch_allowed_code_set() {
}
);
let not_found = wip_https::http::Response::builder()
let not_found = wip_http::http::Response::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "application/json; charset=utf-8")
.body(br#"{"error":{"code":"not_found","message":"not a batch failure"}}"#.to_vec())
@@ -287,7 +285,7 @@ fn top_level_batch_errors_use_the_batch_allowed_code_set() {
#[test]
fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
let duplicate = wip_https::http::Response::builder()
let duplicate = wip_http::http::Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json; charset=utf-8")
.body(
@@ -303,7 +301,7 @@ fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
}
));
let missing = wip_https::http::Response::builder()
let missing = wip_http::http::Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json; charset=utf-8")
.body(
@@ -340,13 +338,7 @@ fn batch_response_must_have_exactly_the_requested_ids() {
let missing = BatchResponse {
responses: vec![BatchResponseItem {
id: "object".into(),
outcome: Ok(BatchSuccess::Fetch(Object {
name: "item".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator: None,
})),
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
}],
};
assert!(encode_batch_response(&request, &missing, limits()).is_err());
@@ -1,22 +1,20 @@
use std::collections::BTreeMap;
use wip_https::http::StatusCode;
use wip_https::wip_protocol::{
use wip_http::http::StatusCode;
use wip_http::wip_protocol::{
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, Object,
ObjectTreeNode, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
TypeDeclaration, TypeExpr, UnionCase, Value,
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target, TypeDeclaration,
TypeExpr, UnionCase, Value,
};
use wip_https::{
use wip_http::{
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
ResourceLimitKind, decode_call_operation_metadata, decode_call_operation_request,
decode_call_operation_response, decode_fetch_interface_request,
decode_fetch_interface_response, decode_fetch_request, decode_fetch_response,
decode_fetch_tree_request, decode_fetch_tree_response, encode_call_operation_request,
encode_call_operation_response, encode_fetch_interface_request,
encode_fetch_interface_response, encode_fetch_request, encode_fetch_response,
encode_fetch_tree_request, encode_fetch_tree_response,
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
};
fn limits() -> Limits {
@@ -196,14 +194,11 @@ fn call_request() -> CallOperationRequest {
#[test]
fn every_single_interaction_request_accepts_json() {
let fetch =
encode_fetch_request(&endpoint(), &FetchRequest { path: "/".into() }, limits()).unwrap();
let fetch_tree = encode_fetch_tree_request(
let observe = encode_observe_request(
&endpoint(),
&FetchTreeRequest {
&ObserveRequest {
path: "/".into(),
depth: 1,
limit: 1,
depth: 0,
},
limits(),
)
@@ -219,59 +214,75 @@ fn every_single_interaction_request_accepts_json() {
let call = encode_call_operation_request(&endpoint(), &call_request(), &descriptor(), limits())
.unwrap();
for request in [fetch, fetch_tree, fetch_interface, call] {
for request in [observe, fetch_interface, call] {
assert_eq!(request.headers()["accept"], "application/json");
}
}
#[test]
fn fetch_round_trips_direct_body_and_body_validator() {
let request = FetchRequest {
fn depth_zero_observe_round_trips_direct_body_and_validator() {
let request = ObserveRequest {
path: "/items/123".into(),
depth: 0,
};
let encoded_request = encode_fetch_request(&endpoint(), &request, limits()).unwrap();
assert_eq!(encoded_request.uri().path(), "/wip/v1/fetch");
let encoded_request = encode_observe_request(&endpoint(), &request, limits()).unwrap();
assert_eq!(encoded_request.uri().path(), "/wip/v1/observe");
assert_eq!(
decode_fetch_request(encoded_request.body(), limits()).unwrap(),
decode_observe_request(encoded_request.body(), limits()).unwrap(),
request
);
let expected = object("123", &[0, 1, 2, 255]);
let encoded = encode_fetch_response(&request, &expected, limits()).unwrap();
let expected = ObjectObservation {
object: object("123", &[0, 1, 2, 255]),
children: None,
};
let encoded = encode_observe_response(&request, &expected, limits()).unwrap();
assert_eq!(encoded.status(), StatusCode::OK);
assert!(
!std::str::from_utf8(encoded.body())
.unwrap()
.contains("children")
);
assert_eq!(
decode_fetch_response(&request, &encoded, limits()).unwrap(),
decode_observe_response(&request, &encoded, limits()).unwrap(),
DecodedResponse::Success(expected)
);
assert!(encoded.headers().get("etag").is_none());
}
#[test]
fn tree_and_interface_round_trip_nested_logical_models() {
let tree_request = FetchTreeRequest {
fn observe_and_interface_round_trip_nested_logical_models() {
let observe_request = ObserveRequest {
path: "/items".into(),
depth: 1,
limit: 2,
};
let encoded_request = encode_fetch_tree_request(&endpoint(), &tree_request, limits()).unwrap();
let encoded_request = encode_observe_request(&endpoint(), &observe_request, limits()).unwrap();
assert_eq!(
decode_fetch_tree_request(encoded_request.body(), limits()).unwrap(),
tree_request
decode_observe_request(encoded_request.body(), limits()).unwrap(),
observe_request
);
let tree = FetchTreeResponse {
root: ObjectTreeNode {
object: object("items", b"root-validator"),
children: vec![ObjectTreeNode {
object: object("123", b"child-validator"),
children: vec![],
}],
},
truncated: false,
let observation = ObjectObservation {
object: object("items", b"root-validator"),
children: Some(vec![ObjectObservation {
object: object("123", b"child-validator"),
children: None,
}]),
};
let encoded = encode_fetch_tree_response(&tree_request, &tree, limits()).unwrap();
let encoded = encode_observe_response(&observe_request, &observation, limits()).unwrap();
assert_eq!(
decode_fetch_tree_response(&tree_request, &encoded, limits()).unwrap(),
DecodedResponse::Success(tree)
decode_observe_response(&observe_request, &encoded, limits()).unwrap(),
DecodedResponse::Success(observation)
);
let empty = ObjectObservation {
object: object("items", b"root-validator"),
children: Some(vec![]),
};
let encoded_empty = encode_observe_response(&observe_request, &empty, limits()).unwrap();
assert!(
std::str::from_utf8(encoded_empty.body())
.unwrap()
.contains("\"children\":[]")
);
let interface_request = FetchInterfaceRequest {
@@ -363,8 +374,10 @@ fn descriptor_guided_values_and_validators_round_trip_both_directions() {
#[test]
fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
let limits = limits();
assert!(decode_fetch_request(br#"{"path":"/","extra":true}"#, limits).is_err());
assert!(decode_fetch_request(br#"{"path":"relative","path":"/"}"#, limits).is_err());
assert!(decode_observe_request(br#"{"path":"/","depth":0,"extra":true}"#, limits).is_err());
assert!(
decode_observe_request(br#"{"path":"relative","path":"/","depth":0}"#, limits).is_err()
);
let request = call_request();
let descriptor = descriptor();
@@ -393,16 +406,16 @@ fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
#[test]
fn caller_limits_bound_bytes_and_nesting() {
let tiny = Limits::new(8, 8, 2, 1).unwrap();
let too_large = decode_fetch_request(br#"{"path":"/long"}"#, tiny).unwrap_err();
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
assert_eq!(
too_large.resource_limit_kind(),
Some(ResourceLimitKind::RepresentationBytes)
);
let nested = br#"{"path":[[["/"]]]}"#;
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
let nesting_limited = Limits::new(1024, 1024, 2, 1).unwrap();
let too_deep = decode_fetch_request(nested, nesting_limited).unwrap_err();
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
assert_eq!(
too_deep.resource_limit_kind(),
@@ -420,11 +433,15 @@ fn caller_limits_bound_bytes_and_nesting() {
.is_err()
);
assert!(
encode_fetch_response(
&FetchRequest {
encode_observe_response(
&ObserveRequest {
path: "/item".into(),
depth: 0,
},
&ObjectObservation {
object: object("item", b"validator"),
children: None,
},
&object("item", b"validator"),
outbound_limited,
)
.is_err()
@@ -449,7 +466,7 @@ fn unsupported_descriptor_format_is_client_local() {
ClientResponseError::UnsupportedDescriptorFormat { .. }
));
let future_shape = wip_https::http::Response::builder()
let future_shape = wip_http::http::Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json; charset=utf-8")
.body(
@@ -468,7 +485,7 @@ fn unsupported_descriptor_format_is_client_local() {
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
.as_slice(),
] {
let response = wip_https::http::Response::builder()
let response = wip_http::http::Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json; charset=utf-8")
.body(malformed.to_vec())
@@ -485,14 +502,15 @@ fn unsupported_descriptor_format_is_client_local() {
#[test]
fn invalid_success_is_classified_as_invalid_response() {
let response = wip_https::http::Response::builder()
let response = wip_http::http::Response::builder()
.status(StatusCode::OK)
.header("content-type", "application/json; charset=utf-8")
.body(br#"{"name":"wrong","interfaces":[]}"#.to_vec())
.body(br#"{"object":{"name":"wrong","interfaces":[]}}"#.to_vec())
.unwrap();
let error = decode_fetch_response(
&FetchRequest {
let error = decode_observe_response(
&ObserveRequest {
path: "/expected".into(),
depth: 0,
},
&response,
limits(),
@@ -1,10 +1,10 @@
use wip_https::http::{Response, StatusCode};
use wip_https::wip_protocol::{
FetchRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
use wip_http::http::{Response, StatusCode};
use wip_http::wip_protocol::{
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
};
use wip_https::{
use wip_http::{
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, ResourceLimitKind,
TransportFailureKind, decode_fetch_response, encode_protocol_error_response,
TransportFailureKind, decode_observe_response, encode_protocol_error_response,
encode_resource_limit_error_response, error_code_name, is_json_content_type, status_for_error,
status_for_resource_limit,
};
@@ -13,8 +13,11 @@ fn limits() -> Limits {
Limits::new(64 * 1024, 64 * 1024, 32, 16).unwrap()
}
fn request() -> FetchRequest {
FetchRequest { path: "/".into() }
fn request() -> ObserveRequest {
ObserveRequest {
path: "/".into(),
depth: 0,
}
}
fn response(status: StatusCode, body: impl Into<Vec<u8>>) -> Response<Vec<u8>> {
@@ -132,7 +135,7 @@ fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
for (kind, status) in cases {
assert_eq!(status_for_resource_limit(kind), status);
let encoded = encode_resource_limit_error_response(
ProtocolInteraction::Fetch,
ProtocolInteraction::Observe,
&error,
kind,
limits(),
@@ -140,7 +143,7 @@ fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
.unwrap();
assert_eq!(encoded.status(), status);
assert_eq!(
decode_fetch_response(&request(), &encoded, limits()).unwrap(),
decode_observe_response(&request(), &encoded, limits()).unwrap(),
DecodedResponse::ProtocolFailure {
error: error.clone(),
status_mismatch: None,
@@ -149,7 +152,7 @@ fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
}
let default =
encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).unwrap();
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
assert_eq!(default.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_ne!(default.status(), StatusCode::TOO_MANY_REQUESTS);
}
@@ -161,7 +164,7 @@ fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
.body(b"rate limited".to_vec())
.unwrap();
assert!(matches!(
decode_fetch_response(&request(), &response, limits()).unwrap_err(),
decode_observe_response(&request(), &response, limits()).unwrap_err(),
ClientResponseError::TransportBinding(failure)
if failure.status == StatusCode::TOO_MANY_REQUESTS
&& failure.kind == TransportFailureKind::HttpStatus
@@ -170,10 +173,10 @@ fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
#[test]
fn valid_success_body_requires_exactly_http_200() {
let success_body = br#"{"name":"","interfaces":[]}"#;
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
assert!(matches!(
decode_fetch_response(&request(), &response(status, success_body), limits())
decode_observe_response(&request(), &response(status, success_body), limits())
.unwrap_err(),
ClientResponseError::InvalidResponse {
kind: InvalidResponseKind::NonCanonicalSuccessStatus,
@@ -187,9 +190,11 @@ fn valid_success_body_requires_exactly_http_200() {
fn server_encoder_rejects_codes_disallowed_for_the_interaction() {
let error = ProtocolError {
code: ProtocolErrorCode::InterfaceNotFound,
message: "not valid for fetch".into(),
message: "not valid for observe".into(),
};
assert!(encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).is_err());
assert!(
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).is_err()
);
}
#[test]
@@ -199,14 +204,14 @@ fn valid_envelope_code_is_authoritative_when_status_mismatches() {
message: "missing".into(),
};
let mut encoded =
encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).unwrap();
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
assert_eq!(
decode_fetch_response(&request(), &encoded, limits()).unwrap(),
decode_observe_response(&request(), &encoded, limits()).unwrap(),
DecodedResponse::ProtocolFailure {
error,
status_mismatch: Some(wip_https::StatusMismatch {
status_mismatch: Some(wip_http::StatusMismatch {
actual: StatusCode::IM_A_TEAPOT,
expected: StatusCode::NOT_FOUND,
}),
@@ -218,7 +223,7 @@ fn valid_envelope_code_is_authoritative_when_status_mismatches() {
fn envelope_and_status_contradictions_are_invalid_responses() {
let error_body = br#"{"error":{"code":"not_found","message":"missing"}}"#;
let on_success =
decode_fetch_response(&request(), &response(StatusCode::OK, error_body), limits())
decode_observe_response(&request(), &response(StatusCode::OK, error_body), limits())
.unwrap_err();
assert!(matches!(
on_success,
@@ -228,8 +233,8 @@ fn envelope_and_status_contradictions_are_invalid_responses() {
}
));
let success_body = br#"{"name":"","interfaces":[]}"#;
let on_error = decode_fetch_response(
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
let on_error = decode_observe_response(
&request(),
&response(StatusCode::BAD_GATEWAY, success_body),
limits(),
@@ -247,8 +252,9 @@ fn envelope_and_status_contradictions_are_invalid_responses() {
#[test]
fn disallowed_protocol_code_is_invalid_instead_of_reclassified() {
let body = br#"{"error":{"code":"interface_not_found","message":"wrong interaction"}}"#;
let error = decode_fetch_response(&request(), &response(StatusCode::NOT_FOUND, body), limits())
.unwrap_err();
let error =
decode_observe_response(&request(), &response(StatusCode::NOT_FOUND, body), limits())
.unwrap_err();
assert!(matches!(
error,
ClientResponseError::InvalidResponse {
@@ -282,7 +288,7 @@ fn proxy_authentication_and_endpoint_failures_stay_transport_failures() {
.status(status)
.body(body.to_vec())
.unwrap();
let error = decode_fetch_response(&request(), &response, limits()).unwrap_err();
let error = decode_observe_response(&request(), &response, limits()).unwrap_err();
assert!(matches!(
error,
ClientResponseError::TransportBinding(failure)
@@ -298,7 +304,7 @@ fn malformed_non_success_envelope_is_transport_binding_failure() {
br#"{"error":{"code":"not_found","message":null}}"#,
);
assert!(matches!(
decode_fetch_response(&request(), &malformed, limits()).unwrap_err(),
decode_observe_response(&request(), &malformed, limits()).unwrap_err(),
ClientResponseError::TransportBinding(_)
));
}
+142
View File
@@ -0,0 +1,142 @@
use wip_http::http::{Method, Request, StatusCode};
use wip_http::{Endpoint, RequestMetadataError, Route, validate_http_request};
#[test]
fn endpoint_preserves_http_and_https_when_resolving_canonical_routes() {
for scheme in ["http", "https"] {
let endpoint = Endpoint::parse(&format!("{scheme}://example.test/root/prefix")).unwrap();
assert_eq!(
endpoint.to_string(),
format!("{scheme}://example.test/root/prefix/")
);
let expected = [
(Route::Observe, "v1/observe"),
(Route::FetchInterface, "v1/fetch_interface"),
(Route::CallOperation, "v1/call_operation"),
(Route::Batch, "v1/batch"),
];
for (route, suffix) in expected {
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
assert_eq!(endpoint.route(route).as_str(), url);
assert_eq!(
endpoint.recognize(&wip_http::url::Url::parse(&url).unwrap()),
Some(route)
);
}
assert_eq!(
endpoint.recognize(
&wip_http::url::Url::parse(&format!(
"{scheme}://example.test/root/prefix/v1/observe?path=/items"
))
.unwrap()
),
None
);
}
}
#[test]
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
let route = endpoint.route(Route::Observe);
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/observe");
assert!(!route.as_str().contains("items"));
}
#[test]
fn inbound_http_metadata_enforces_post_route_and_json() {
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
let valid = Request::builder()
.method(Method::POST)
.uri("/wip/v1/observe")
.header("content-type", "application/json; charset=utf-8")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Observe, &valid).is_ok());
let wrong_method = Request::builder()
.method(Method::GET)
.uri("/wip/v1/observe")
.header("content-type", "application/json")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_method).is_err());
let wrong_route = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch_interface")
.header("content-type", "application/json")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_route).is_err());
for accept in [
"text/plain, */*;q=1, application/json;q=0",
"application/json; charset=utf-16",
"application/json; profile=future",
] {
let incompatible_accept = Request::builder()
.method(Method::POST)
.uri("/wip/v1/observe")
.header("content-type", "application/json")
.header("accept", accept)
.body(Vec::<u8>::new())
.unwrap();
let error =
validate_http_request(&endpoint, Route::Observe, &incompatible_accept).unwrap_err();
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
}
for accept in [
"application/json; charset=UTF-8",
"application/json; q=1; profile=accept-extension",
] {
let compatible_accept = Request::builder()
.method(Method::POST)
.uri("/wip/v1/observe")
.header("content-type", "application/json")
.header("accept", accept)
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Observe, &compatible_accept).is_ok());
}
let unsupported_media_type = Request::builder()
.method(Method::POST)
.uri("/wip/v1/observe")
.header("content-type", "text/plain")
.header("accept", "application/json")
.body(Vec::<u8>::new())
.unwrap();
let error =
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
#[test]
fn invalid_endpoint_components_and_non_routes_are_rejected() {
assert!(Endpoint::parse("/relative").is_err());
assert!(Endpoint::parse("file:///wip").is_err());
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
let deployment_endpoint = Endpoint::parse("http://user:secret@example.test/wip").unwrap();
assert_eq!(deployment_endpoint.as_url().scheme(), "http");
assert_eq!(deployment_endpoint.as_url().username(), "user");
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
for outside in [
"http://example.test/wip/v1/unknown",
"http://example.test/wip/v1/observe/extra",
"https://example.test/wip/v1/observe",
"http://other.test/wip/v1/observe",
] {
assert_eq!(
endpoint.recognize(&wip_http::url::Url::parse(outside).unwrap()),
None
);
}
}
-127
View File
@@ -1,127 +0,0 @@
use wip_https::http::{Method, Request, StatusCode};
use wip_https::{Endpoint, RequestMetadataError, Route, validate_http_request};
#[test]
fn endpoint_is_https_absolute_queryless_and_canonical() {
let endpoint = Endpoint::parse("https://example.test/root/prefix").unwrap();
assert_eq!(endpoint.to_string(), "https://example.test/root/prefix/");
let expected = [
(Route::Fetch, "https://example.test/root/prefix/v1/fetch"),
(
Route::FetchTree,
"https://example.test/root/prefix/v1/fetch_tree",
),
(
Route::FetchInterface,
"https://example.test/root/prefix/v1/fetch_interface",
),
(
Route::CallOperation,
"https://example.test/root/prefix/v1/call_operation",
),
(Route::Batch, "https://example.test/root/prefix/v1/batch"),
];
for (route, url) in expected {
assert_eq!(endpoint.route(route).as_str(), url);
assert_eq!(
endpoint.recognize(&wip_https::url::Url::parse(url).unwrap()),
Some(route)
);
}
assert_eq!(
endpoint.recognize(
&wip_https::url::Url::parse("https://example.test/root/prefix/v1/fetch?path=/items")
.unwrap()
),
None
);
}
#[test]
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
let route = endpoint.route(Route::Fetch);
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/fetch");
assert!(!route.as_str().contains("items"));
}
#[test]
fn inbound_http_metadata_enforces_post_route_and_json() {
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
let valid = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch")
.header("content-type", "application/json; charset=utf-8")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Fetch, &valid).is_ok());
let wrong_method = Request::builder()
.method(Method::GET)
.uri("/wip/v1/fetch")
.header("content-type", "application/json")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Fetch, &wrong_method).is_err());
let wrong_route = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch_tree")
.header("content-type", "application/json")
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Fetch, &wrong_route).is_err());
for accept in [
"text/plain, */*;q=1, application/json;q=0",
"application/json; charset=utf-16",
"application/json; profile=future",
] {
let incompatible_accept = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch")
.header("content-type", "application/json")
.header("accept", accept)
.body(Vec::<u8>::new())
.unwrap();
let error =
validate_http_request(&endpoint, Route::Fetch, &incompatible_accept).unwrap_err();
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
}
for accept in [
"application/json; charset=UTF-8",
"application/json; q=1; profile=accept-extension",
] {
let compatible_accept = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch")
.header("content-type", "application/json")
.header("accept", accept)
.body(Vec::<u8>::new())
.unwrap();
assert!(validate_http_request(&endpoint, Route::Fetch, &compatible_accept).is_ok());
}
let unsupported_media_type = Request::builder()
.method(Method::POST)
.uri("/wip/v1/fetch")
.header("content-type", "text/plain")
.header("accept", "application/json")
.body(Vec::<u8>::new())
.unwrap();
let error =
validate_http_request(&endpoint, Route::Fetch, &unsupported_media_type).unwrap_err();
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
#[test]
fn invalid_endpoint_components_are_rejected() {
assert!(Endpoint::parse("http://example.test/wip").is_err());
assert!(Endpoint::parse("/relative").is_err());
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
}
+13 -17
View File
@@ -62,7 +62,7 @@ pub enum PathSegment {
Return,
/// Object at a Worldspace path.
Object(String),
/// Child object in a tree response.
/// Child object in an observation response.
Child(String),
}
@@ -163,17 +163,15 @@ pub enum ValidationErrorKind {
/// Shared opaque object reference.
reference: String,
},
/// A `fetch_tree` request used a zero limit.
ZeroTreeLimit,
/// A tree response exceeds the requested maximum depth.
TreeDepthExceeded {
/// Requested maximum depth.
maximum: u32,
/// An observation omitted children before reaching the requested depth.
ChildrenMissingBeforeDepth {
/// Node depth where children were required.
depth: u32,
},
/// A tree response exceeds the requested maximum node count.
TreeLimitExceeded {
/// Requested maximum node count.
limit: u32,
/// An observation included children at the requested depth boundary.
ChildrenAtDepthBoundary {
/// Boundary depth where children must be unobserved.
depth: u32,
},
/// A response refers to a different interface than its request.
InterfaceResponseMismatch {
@@ -226,10 +224,8 @@ impl Error for ValidationError {}
/// One core interaction whose failure codes form a closed set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolInteraction {
/// Fetch one object by its Worldspace path.
Fetch,
/// Fetch a bounded tree of objects.
FetchTree,
/// Observe one object and its indexable descendants to a requested depth.
Observe,
/// Fetch one interface descriptor by its opaque reference.
FetchInterface,
/// Invoke one operation on a path-targeted object.
@@ -315,11 +311,11 @@ impl ProtocolErrorCode {
OperationNotFound, OperationOutcomeUnknown, PermissionDenied, ResourceLimitExceeded,
ValidatorMismatch, ValidatorRequired,
};
use ProtocolInteraction::{CallOperation, Fetch, FetchInterface, FetchTree};
use ProtocolInteraction::{CallOperation, FetchInterface, Observe};
match (interaction, self) {
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
(Fetch | FetchTree, NotFound) => true,
(Observe, NotFound) => true,
(FetchInterface, InterfaceNotFound) => true,
(
CallOperation,
+4 -6
View File
@@ -11,8 +11,7 @@
//! | Interface Descriptor | [`InterfaceDescriptor`] |
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
//! | Schema-neutral primitive/composite value | [`Value`] |
//! | `fetch` | [`FetchRequest`] / [`FetchResponse`] |
//! | `fetch_tree` | [`FetchTreeRequest`] / [`FetchTreeResponse`] |
//! | `observe` | [`ObserveRequest`] / [`ObserveResponse`] |
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
@@ -53,10 +52,9 @@ pub use error::{
};
pub use model::{
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest, FetchTreeResponse,
FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object, ObjectTreeNode,
OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
TypeDeclaration, TypeExpr, UnionCase, Value,
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceTarget, Object,
ObjectObservation, ObserveRequest, ObserveResponse, OperationDeclaration, ParameterDeclaration,
ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr, UnionCase, Value,
};
/// Validates a canonical absolute Worldspace path.
+15 -50
View File
@@ -218,44 +218,26 @@ impl Value {
}
}
/// Request for the object currently published at one path.
/// Request for the object currently published at one path and its indexable descendants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchRequest {
/// Canonical absolute Worldspace path.
pub struct ObserveRequest {
/// Canonical absolute path of the observation root.
pub path: String,
}
/// Successful `fetch` response.
pub type FetchResponse = Object;
/// Request for a bounded breadth-first object-tree observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTreeRequest {
/// Canonical absolute path of the tree root.
pub path: String,
/// Maximum depth, where the requested object has depth zero.
/// Maximum observed depth, where the requested object has depth zero.
pub depth: u32,
/// Maximum total node count, including the root. Must be nonzero.
pub limit: u32,
}
/// One node in a tree observation.
/// One node in an object observation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectTreeNode {
/// Object observed at this tree position.
pub struct ObjectObservation {
/// Object observed at this Worldspace position.
pub object: Object,
/// Direct children in host-defined traversal order.
pub children: Vec<ObjectTreeNode>,
/// Complete direct children when observed, or `None` at the requested depth boundary.
pub children: Option<Vec<ObjectObservation>>,
}
/// Successful `fetch_tree` response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchTreeResponse {
/// Observed tree rooted at the requested path.
pub root: ObjectTreeNode,
/// Whether public indexable children were omitted by depth or limit.
pub truncated: bool,
}
/// Successful `observe` response.
pub type ObserveResponse = ObjectObservation;
/// Request for the current descriptor of one opaque interface reference.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -372,35 +354,18 @@ impl InterfaceDescriptor {
}
}
impl FetchRequest {
impl ObserveRequest {
/// Validates the request path.
pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_path(&self.path)
}
/// Validates an object returned for this request.
/// Validates observation shape, names, and requested depth.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`].
pub fn validate_response(&self, response: &FetchResponse) -> Result<(), ValidationError> {
response.validate_at_path(&self.path)
}
}
impl FetchTreeRequest {
/// Validates the request path and nonzero node limit.
pub fn validate(&self) -> Result<(), ValidationError> {
crate::validation::validate_fetch_tree_request(self)
}
}
impl FetchTreeResponse {
/// Validates tree shape, names, depth, and node limit for `request`.
///
/// Failure means the Client received an invalid success response; it is not a
/// Host-returned [`crate::ProtocolErrorCode`].
pub fn validate_for(&self, request: &FetchTreeRequest) -> Result<(), ValidationError> {
crate::validation::validate_fetch_tree_response(self, request)
pub fn validate_response(&self, response: &ObserveResponse) -> Result<(), ValidationError> {
crate::validation::validate_observe_response(response, self)
}
}
+26 -55
View File
@@ -1,10 +1,10 @@
use std::collections::{BTreeMap, HashMap, HashSet};
use crate::{
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, FetchTreeRequest,
FetchTreeResponse, InterfaceDescriptor, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace,
Object, ObjectTreeNode, PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD,
UNION_VALUE_FIELD, ValidationError, ValidationErrorKind, Value, ValueKind,
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace, Object, ObjectObservation, ObserveRequest,
PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD, UNION_VALUE_FIELD, ValidationError,
ValidationErrorKind, Value, ValueKind,
};
pub(crate) fn validate_object(object: &Object) -> Result<(), ValidationError> {
@@ -604,60 +604,38 @@ fn find_operation<'a>(
})
}
pub(crate) fn validate_fetch_tree_request(
request: &FetchTreeRequest,
) -> Result<(), ValidationError> {
validate_path(&request.path)?;
if request.limit == 0 {
Err(ValidationError::new(ValidationErrorKind::ZeroTreeLimit))
} else {
Ok(())
}
}
pub(crate) fn validate_fetch_tree_response(
response: &FetchTreeResponse,
request: &FetchTreeRequest,
pub(crate) fn validate_observe_response(
response: &ObjectObservation,
request: &ObserveRequest,
) -> Result<(), ValidationError> {
request.validate()?;
let mut node_count = 0_u32;
validate_tree_node(
&response.root,
&request.path,
0,
request.depth,
request.limit,
&mut node_count,
)
validate_observation_node(response, &request.path, 0, request.depth)
}
fn validate_tree_node(
node: &ObjectTreeNode,
fn validate_observation_node(
node: &ObjectObservation,
path: &str,
depth: u32,
maximum_depth: u32,
limit: u32,
node_count: &mut u32,
) -> Result<(), ValidationError> {
if depth > maximum_depth {
return Err(
ValidationError::new(ValidationErrorKind::TreeDepthExceeded {
maximum: maximum_depth,
})
.prepend(PathSegment::Object(path.to_owned())),
);
}
*node_count = node_count.saturating_add(1);
if *node_count > limit {
return Err(
ValidationError::new(ValidationErrorKind::TreeLimitExceeded { limit })
.prepend(PathSegment::Object(path.to_owned())),
);
node.object.validate_at_path(path)?;
if depth == maximum_depth {
if node.children.is_some() {
return Err(
ValidationError::new(ValidationErrorKind::ChildrenAtDepthBoundary { depth })
.prepend(PathSegment::Object(path.to_owned())),
);
}
return Ok(());
}
node.object.validate_at_path(path)?;
let children = node.children.as_ref().ok_or_else(|| {
ValidationError::new(ValidationErrorKind::ChildrenMissingBeforeDepth { depth })
.prepend(PathSegment::Object(path.to_owned()))
})?;
let mut names = HashSet::new();
for child in &node.children {
for child in children {
validate_object_name(&child.object.name, false)
.map_err(|error| error.prepend(PathSegment::Child(child.object.name.clone())))?;
if !names.insert(child.object.name.as_str()) {
@@ -673,14 +651,7 @@ fn validate_tree_node(
} else {
format!("{path}/{}", child.object.name)
};
validate_tree_node(
child,
&child_path,
depth.saturating_add(1),
maximum_depth,
limit,
node_count,
)?;
validate_observation_node(child, &child_path, depth + 1, maximum_depth)?;
}
Ok(())
}
+65 -67
View File
@@ -2,11 +2,11 @@ use std::collections::BTreeMap;
use wip_protocol::{
CallOperationRequest, CallOperationResponse, EnumCase, FetchInterfaceRequest,
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace,
Object, ObjectTreeNode, OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError,
ProtocolErrorCode, ProtocolInteraction, ProtocolResult, ReturnDeclaration, Target,
TypeDeclaration, TypeExpr, UnionCase, ValidationErrorKind, Value, ValueKind,
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace, Object, ObjectObservation, ObserveRequest,
OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError, ProtocolErrorCode,
ProtocolInteraction, ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr,
UnionCase, ValidationErrorKind, Value, ValueKind,
};
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
@@ -617,13 +617,26 @@ fn calls_validate_canonical_paths_named_arguments_and_unit_results() {
}
#[test]
fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
let fetch = FetchRequest {
fn observe_and_fetch_interface_dtos_validate_request_response_correspondence() {
let observe = ObserveRequest {
path: "/articles/one".into(),
depth: 0,
};
fetch.validate().unwrap();
fetch.validate_response(&object("one")).unwrap();
assert!(fetch.validate_response(&object("two")).is_err());
observe.validate().unwrap();
observe
.validate_response(&ObjectObservation {
object: object("one"),
children: None,
})
.unwrap();
assert!(
observe
.validate_response(&ObjectObservation {
object: object("two"),
children: None,
})
.is_err()
);
for invalid in [
"",
@@ -634,8 +647,9 @@ fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
"/a/../b",
] {
assert!(matches!(
FetchRequest {
path: invalid.into()
ObserveRequest {
path: invalid.into(),
depth: 0,
}
.validate()
.unwrap_err()
@@ -666,61 +680,51 @@ fn fetch_and_fetch_interface_dtos_validate_request_response_correspondence() {
}
#[test]
fn fetch_tree_dtos_validate_names_depth_limit_and_siblings() {
let request = FetchTreeRequest {
fn observe_response_validates_complete_children_and_depth_boundary() {
let request = ObserveRequest {
path: "/articles".into(),
depth: 1,
limit: 3,
};
let leaf = |name: &str| ObjectTreeNode {
let leaf = |name: &str| ObjectObservation {
object: object(name),
children: vec![],
children: None,
};
let response = FetchTreeResponse {
root: ObjectTreeNode {
object: object("articles"),
children: vec![leaf("one"), leaf("two")],
},
truncated: false,
let response = ObjectObservation {
object: object("articles"),
children: Some(vec![leaf("one"), leaf("two")]),
};
response.validate_for(&request).unwrap();
request.validate_response(&response).unwrap();
let zero = FetchTreeRequest {
limit: 0,
..request.clone()
let empty = ObjectObservation {
object: object("articles"),
children: Some(vec![]),
};
assert_eq!(
zero.validate().unwrap_err().kind,
ValidationErrorKind::ZeroTreeLimit
);
request.validate_response(&empty).unwrap();
let shallow = FetchTreeRequest {
let missing = ObjectObservation {
object: object("articles"),
children: None,
};
assert!(matches!(
request.validate_response(&missing).unwrap_err().kind,
ValidationErrorKind::ChildrenMissingBeforeDepth { depth: 0 }
));
let boundary = ObserveRequest {
depth: 0,
..request.clone()
};
assert!(matches!(
response.validate_for(&shallow).unwrap_err().kind,
ValidationErrorKind::TreeDepthExceeded { .. }
boundary.validate_response(&response).unwrap_err().kind,
ValidationErrorKind::ChildrenAtDepthBoundary { depth: 0 }
));
let small = FetchTreeRequest {
limit: 2,
..request.clone()
let duplicate = ObjectObservation {
object: object("articles"),
children: Some(vec![leaf("one"), leaf("one")]),
};
assert!(matches!(
response.validate_for(&small).unwrap_err().kind,
ValidationErrorKind::TreeLimitExceeded { .. }
));
let duplicate = FetchTreeResponse {
root: ObjectTreeNode {
object: object("articles"),
children: vec![leaf("one"), leaf("one")],
},
truncated: false,
};
assert!(matches!(
duplicate.validate_for(&request).unwrap_err().kind,
request.validate_response(&duplicate).unwrap_err().kind,
ValidationErrorKind::DuplicateName {
namespace: NameNamespace::ChildObject,
..
@@ -778,22 +782,9 @@ fn assert_allowed_codes(interaction: ProtocolInteraction, expected: &[ProtocolEr
}
#[test]
fn fetch_error_codes_are_exhaustive() {
fn observe_error_codes_are_exhaustive() {
assert_allowed_codes(
ProtocolInteraction::Fetch,
&[
ProtocolErrorCode::InvalidRequest,
ProtocolErrorCode::NotFound,
ProtocolErrorCode::ResourceLimitExceeded,
ProtocolErrorCode::Internal,
],
);
}
#[test]
fn fetch_tree_error_codes_are_exhaustive() {
assert_allowed_codes(
ProtocolInteraction::FetchTree,
ProtocolInteraction::Observe,
&[
ProtocolErrorCode::InvalidRequest,
ProtocolErrorCode::NotFound,
@@ -840,11 +831,18 @@ fn call_operation_error_codes_are_exhaustive() {
#[test]
fn invalid_success_payloads_remain_client_local_validation_failures() {
let fetch = FetchRequest {
let observe = ObserveRequest {
path: "/articles/one".into(),
depth: 0,
};
assert!(matches!(
fetch.validate_response(&object("other")).unwrap_err().kind,
observe
.validate_response(&ObjectObservation {
object: object("other"),
children: None,
})
.unwrap_err()
.kind,
ValidationErrorKind::ObjectNameMismatch { .. }
));
+1 -1
View File
@@ -190,7 +190,7 @@ pub fn run() -> Result<DemoReport, Box<dyn Error>> {
audit: audit.clone(),
};
let object = provider.fetch(OBJECT_PATH)?;
let object = provider.observe_object(OBJECT_PATH)?;
let catalog_response = registry
.fetch_interface(
object
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "wip-tui"
version = "0.1.0"
edition = "2024"
description = "Interactive terminal client for exploring and operating WIP Worldspaces"
license = "MIT OR Apache-2.0"
readme = "README.md"
publish = false
[dependencies]
base64 = "0.22"
crossterm = "0.28.1"
ratatui = "0.29.0"
serde_json = "1"
ureq = "3.1.2"
wip-client = { path = "../wip-client" }
wip-http = { path = "../wip-http" }
wip-protocol = { path = "../wip-protocol" }
[dev-dependencies]
tempfile = "3"
wip-fs-server = { path = "../wip-fs-server" }
+148
View File
@@ -0,0 +1,148 @@
# wip-tui
`wip-tui` is an interactive terminal client for exploring and operating a WIP
Worldspace. It is a presentation and terminal-interaction layer over
`wip-client`: Known Space, request identity, validators, immutable operation call
contexts, stale transitions, response classification, and bounded histories remain
owned by the client runtime.
## Start
Supply one `http` or `https` endpoint:
```console
cargo run -p wip-tui -- --endpoint https://wip.example.test/api/wip
```
The same canonical endpoint is used unchanged to construct requests, perform
HTTP I/O, and partition the client cache. WIP over HTTP does not define separate
HTTPS and development-HTTP profiles; URL scheme, TLS, certificate, authentication,
and proxy policy belong to the HTTP implementation and deployment.
The endpoint may instead be supplied as `WIP_ENDPOINT`. A non-secret cache
partition identity may be supplied with `--security-context NAME` or
`WIP_SECURITY_CONTEXT`. The default request timeout is 30 seconds and can be
changed with `--timeout SECONDS`.
An Authorization header can be read from an environment variable without placing
its value in arguments, application state, errors, snapshots, or debug output:
```console
export WIP_AUTHORIZATION='Bearer …'
cargo run -p wip-tui -- https://wip.example.test/wip
```
Use `--authorization-env OTHER_VARIABLE` to select another variable. The value is
redacted from `Debug` and is never rendered. Shell and process environment security
remain the operator's responsibility.
### Filesystem server example
In one terminal:
```console
mkdir -p /tmp/wip-example
printf 'hello world' >/tmp/wip-example/notes.txt
cargo run -p wip-fs-server -- \
--root /tmp/wip-example \
--listen 127.0.0.1:8080 \
--base-path /wip \
--read-write
```
In another:
```console
cargo run -p wip-tui -- http://127.0.0.1:8080/wip
```
Expand `/`, select `notes.txt`, focus the Interface/Operation pane, and choose
`read`; descriptors advertised by visible Objects are normally prefetched already.
The editor labels `offset` and `length` as optional; leave both blank to read the
bounded file. `Bytes` results are shown as a bounded hex preview. For `replace`,
enter `contents` as RFC 4648 base64—for example, `dXBkYXRlZA==` for
`updated`—then review the target Entry, interface reference, operation, and value
on the confirmation screen before pressing Enter again.
## Keyboard bindings
All required actions are keyboard-accessible.
| Key | Action |
| --- | --- |
| `↑`/`k`, `↓`/`j` | Move within the focused tree, operation list, history, or editor |
| `→`/`l`, `Enter` | Expand a tree node lazily; load/select an interface or operation |
| `←`/`h` | Collapse a node or move to its parent |
| `Tab` | Cycle Tree → Selected Entry → Operations → History |
| `r` | Reobserve the selected Entry and its direct subtree |
| `c` | Cancel the newest retrieval; a dispatched operation is never presented as canceled |
| `R` | Reconnect after connection failure |
| `?` | Open help |
| `Esc` | Close a modal or return to the tree |
| `q`, `Ctrl-C` | Exit and restore the terminal |
Inside an argument editor, printable keys are field input, arrows move fields,
Backspace edits, Enter validates, and Esc cancels. The confirmation screen requires
a second explicit Enter (or `e`) to execute once. There is no operation auto-retry.
## Screen model
- **Worldspace tree** starts at `/`, lazily materializes expanded nodes, and
prefetches children for each visible Object so emptiness and the next expansion
frontier are known without selecting that Object first. Text labels distinguish
unloaded, loading, empty, stale, and failed state; color is supplemental. Every
successful expansion is complete for its requested depth.
- **Selected Entry** shows only public WIP path, object name, description, ordered
interfaces, and freshness. Validators, credentials, Host internals, and backend
paths are deliberately hidden. If current metadata disappears, old text is not
presented as current.
- **Interfaces / Operations** identifies every operation by `(interface reference,
operation name)`. Descriptor lookahead follows fresh visible Objects, shares the
client's in-flight/cache bounds, and never retries retained failures implicitly.
The pane shows descriptor documentation, ordered parameters, required/optional
status, and result types.
- **Argument editor** supports Unit, Boolean, Integer, Number, String, base64 Bytes,
Record, List, Entry, Enum, Union, Json, and descriptor-local named types. Record,
List, Union, and Json values use JSON syntax. Union input is
`{"$case":"name","value":…}` when the selected case has a payload. Diagnostics
remain attached to the failing field.
- **Recent results / diagnostics** explicitly distinguishes success, Host failure,
invalid protocol response, transport failure, client-local failure, and unknown
operation outcome. Large values, bytes, nesting, and control characters are
bounded before rendering. Only descriptor-declared `Entry` results become
navigation targets; path-looking String or Json values do not.
Terminals below 48×14 show a minimum-size screen instead of attempting the full
layout.
## Validator and failure behavior
Object and interface validators are observed and attached automatically by
`wip-client`; users neither copy nor edit them. A successful operation may update the
cached Object validator but does not by itself make the Object observation stale.
Validator mismatch, interface mismatch, `OperationOutcomeUnknown`, undecodable
post-dispatch responses, and post-dispatch timeout/disconnect are displayed using
the runtime's authoritative transition.
For an unknown outcome, the UI states that execution or side effects may have
occurred, marks the related Entry stale, and tells the user to refresh. Refreshing
does not recreate the call: the user must select the operation, review fresh input,
and explicitly execute again. The same no-auto-retry rule applies after validator
or interface mismatch.
Retrieval work runs on I/O workers while the input/render loop continues. Responses
return with the original `RequestId`, so an old completion cannot populate another
Entry's details. Canceling a retrieval records a local cancellation and drops its
late response. Once an operation crosses dispatch, cancellation is never described
as undoing execution.
## Tests
The library form keeps reducers and rendering independent of a real terminal.
`ratatui::TestBackend` snapshots cover tree/detail/result states and the minimum-size
fallback. Unit tests cover reducer focus, selection, modal confirmation, key
translation, descriptor inputs, bounded values, and descriptor-directed Entry
results. The real HTTP integration test launches `wip-fs-server` on a temporary
root and covers tree selection, reads, validator-protected replacement, external
stale-validator rejection without retry, explicit refresh/re-execution, and
symlink confinement.
+952
View File
@@ -0,0 +1,952 @@
//! Pure application state, selection, modal, focus, and key reducer.
use std::collections::{BTreeMap, BTreeSet};
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState, TreeObservation};
use wip_protocol::{InterfaceDescriptor, Object, Value};
use crate::editor::ArgumentEditor;
const MAX_PRESENTATION_ENTRIES: usize = 2048;
const MAX_PRESENTATION_INTERFACES: usize = 256;
/// A terminal-independent key understood by the reducer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKey {
/// Up arrow or `k`.
Up,
/// Down arrow or `j`.
Down,
/// Left arrow or `h`.
Left,
/// Right arrow or `l`.
Right,
/// Focus the next pane.
Tab,
/// Activate the selected item.
Enter,
/// Close the current modal or return to the tree.
Escape,
/// Delete one editor character.
Backspace,
/// Refresh the selected Entry.
Refresh,
/// Cancel the newest cancel-safe retrieval.
CancelRead,
/// Show key help.
Help,
/// Quit the application.
Quit,
/// Reconnect after startup or transport failure.
Reconnect,
/// A printable editor character.
Character(char),
}
/// Pane receiving navigation keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
/// Worldspace tree.
Tree,
/// Selected Entry metadata.
Entry,
/// Interfaces and operations.
Operations,
/// Recent result and diagnostic history.
History,
}
impl Focus {
fn next(self) -> Self {
match self {
Self::Tree => Self::Entry,
Self::Entry => Self::Operations,
Self::Operations => Self::History,
Self::History => Self::Tree,
}
}
}
/// Connection lifecycle shown without relying on color.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionState {
/// No request has been attempted.
Disconnected,
/// Initial root request or reconnect is in progress.
Connecting,
/// The root was observed successfully.
Connected,
/// Connection failed; reconnect and exit remain available.
Failed(String),
}
/// Presentation-safe observation state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewState {
/// No observation has been requested.
Unloaded,
/// One request is in flight.
Loading(u64),
/// The observation is current.
Fresh,
/// The retained value needs reobservation.
Stale,
/// The latest attempt failed.
Error(String),
}
impl From<&ObservationState> for ViewState {
fn from(value: &ObservationState) -> Self {
match value {
ObservationState::Loading(id) => Self::Loading(id.get()),
ObservationState::Fresh => Self::Fresh,
ObservationState::Stale => Self::Stale,
ObservationState::Error(error) => Self::Error(error.to_string()),
}
}
}
/// One materialized tree Entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryView {
/// Canonical WIP path.
pub path: String,
/// Latest object when retained by the client runtime.
pub object: Option<Object>,
/// Object observation state.
pub state: ViewState,
/// Direct child paths in Host order.
pub children: Vec<String>,
/// Expansion observation state.
pub tree_state: ViewState,
/// Whether the user expanded this row.
pub expanded: bool,
}
impl EntryView {
fn placeholder(path: impl Into<String>) -> Self {
Self {
path: path.into(),
object: None,
state: ViewState::Unloaded,
children: Vec::new(),
tree_state: ViewState::Unloaded,
expanded: false,
}
}
}
/// Cached interface descriptor state used by presentation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceView {
/// Opaque interface reference.
pub reference: String,
/// Descriptor when accepted by the client runtime.
pub descriptor: Option<InterfaceDescriptor>,
/// Descriptor observation state.
pub state: ViewState,
}
/// Stable result/diagnostic category.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HistoryKind {
/// A descriptor-validated operation result.
Success,
/// A valid Host-declared failure.
DomainFailure,
/// An invalid protocol response.
ProtocolError,
/// Network or TLS failure.
TransportFailure,
/// Client-local validation or capacity failure.
ClientFailure,
/// Dispatch occurred but execution or commit is uncertain.
OutcomeUnknown,
/// Informational request state.
Information,
}
/// One bounded recent result or diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryItem {
/// Explicit outcome category.
pub kind: HistoryKind,
/// Short bounded heading.
pub title: String,
/// Bounded, terminal-safe detail.
pub detail: String,
/// Navigation target only when declared as descriptor `Entry`.
pub entry_target: Option<String>,
}
/// Kind of request currently in flight.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InFlightKind {
/// Object refresh.
Object(String),
/// Tree expansion or refresh.
Tree(String),
/// Descriptor fetch.
Interface(String),
/// Explicit operation call.
Operation {
/// Target path.
path: String,
/// Interface reference.
interface: String,
/// Operation name.
operation: String,
/// Whether the transport dispatch boundary was crossed.
dispatched: bool,
},
}
impl InFlightKind {
/// Whether dropping the response is a safe cancellation operation.
#[must_use]
pub fn cancel_safe(&self) -> bool {
!matches!(self, Self::Operation { .. })
}
}
/// Active overlay.
#[derive(Debug, Clone, PartialEq)]
pub enum Modal {
/// No overlay.
None,
/// Keyboard help.
Help,
/// Descriptor-driven field editor.
Editor(ArgumentEditor),
/// Explicit pre-execution confirmation.
Confirm {
/// Editor retained when confirmation is cancelled.
editor: ArgumentEditor,
/// Validated arguments that will be sent.
arguments: BTreeMap<String, Value>,
},
}
/// Side effect requested by the pure reducer.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
/// Expand one node lazily.
Expand {
/// Tree root path.
path: String,
},
/// Reobserve an Entry and its direct children.
Refresh {
/// Selected path.
path: String,
},
/// Retrieve one interface descriptor.
FetchInterface(String),
/// Execute only after explicit confirmation.
Execute {
/// Entry target.
path: String,
/// Interface reference.
interface: String,
/// Operation name.
operation: String,
/// Descriptor-validated arguments.
arguments: BTreeMap<String, Value>,
},
/// Cancel the newest safe retrieval.
CancelRead,
/// Reconnect and observe the root.
Reconnect,
/// Navigate to a descriptor-declared Entry result.
NavigateEntry(String),
/// Exit normally.
Quit,
}
/// Complete presentation model.
#[derive(Debug, Clone, PartialEq)]
pub struct App {
/// Effective endpoint label (never credential material).
pub endpoint: String,
/// Connection lifecycle.
pub connection: ConnectionState,
/// Materialized tree nodes by path.
pub entries: BTreeMap<String, EntryView>,
/// Selected Entry path.
pub selected_path: String,
/// Focused pane.
pub focus: Focus,
/// Interface descriptor views by opaque reference.
pub interfaces: BTreeMap<String, InterfaceView>,
/// Selected row in the flattened interface/operation view.
pub operation_cursor: usize,
/// Selected recent-history row.
pub history_cursor: usize,
/// Active overlay.
pub modal: Modal,
/// In-flight requests keyed by client request identity.
pub in_flight: BTreeMap<u64, InFlightKind>,
/// Recent result and diagnostic history, newest first.
pub history: Vec<HistoryItem>,
/// Maximum retained presentation history.
pub history_limit: usize,
/// One-line status for local action feedback.
pub status: String,
}
impl App {
/// Creates a disconnected model with `/` selected.
#[must_use]
pub fn new(endpoint: impl Into<String>) -> Self {
let mut entries = BTreeMap::new();
let mut root = EntryView::placeholder("/");
root.expanded = true;
entries.insert("/".into(), root);
Self {
endpoint: endpoint.into(),
connection: ConnectionState::Disconnected,
entries,
selected_path: "/".into(),
focus: Focus::Tree,
interfaces: BTreeMap::new(),
operation_cursor: 0,
history_cursor: 0,
modal: Modal::None,
in_flight: BTreeMap::new(),
history: Vec::new(),
history_limit: 64,
status: "press ? for help".into(),
}
}
/// Applies one key and returns requested effects without performing I/O.
pub fn reduce(&mut self, key: InputKey) -> Vec<Action> {
match std::mem::replace(&mut self.modal, Modal::None) {
Modal::Help => {
if !matches!(key, InputKey::Escape | InputKey::Help) {
self.modal = Modal::Help;
}
return Vec::new();
}
Modal::Editor(mut editor) => {
match key {
InputKey::Escape => {}
InputKey::Up => {
editor.previous_field();
self.modal = Modal::Editor(editor);
}
InputKey::Down | InputKey::Tab => {
editor.next_field();
self.modal = Modal::Editor(editor);
}
InputKey::Backspace => {
editor.backspace();
self.modal = Modal::Editor(editor);
}
InputKey::Character(character) => {
editor.insert(character);
self.modal = Modal::Editor(editor);
}
InputKey::Enter => match editor.validate() {
Ok(arguments) => self.modal = Modal::Confirm { editor, arguments },
Err(_) => self.modal = Modal::Editor(editor),
},
_ => self.modal = Modal::Editor(editor),
}
return Vec::new();
}
Modal::Confirm { editor, arguments } => match key {
InputKey::Escape => {
self.modal = Modal::Editor(editor);
return Vec::new();
}
InputKey::Enter | InputKey::Character('e') => {
let action = Action::Execute {
path: self.selected_path.clone(),
interface: editor.interface.clone(),
operation: editor.operation.name.clone(),
arguments,
};
self.status =
"operation confirmed; preparing request (not yet dispatched)".into();
return vec![action];
}
_ => {
self.modal = Modal::Confirm { editor, arguments };
return Vec::new();
}
},
Modal::None => {}
}
if key == InputKey::Help {
self.modal = Modal::Help;
return Vec::new();
}
if key == InputKey::Quit {
return vec![Action::Quit];
}
if key == InputKey::Reconnect {
return vec![Action::Reconnect];
}
if key == InputKey::CancelRead {
return vec![Action::CancelRead];
}
if key == InputKey::Tab {
self.focus = self.focus.next();
return Vec::new();
}
match self.focus {
Focus::Tree => self.reduce_tree(key),
Focus::Operations => self.reduce_operations(key),
Focus::History => self.reduce_history(key),
Focus::Entry => {
if key == InputKey::Escape {
self.focus = Focus::Tree;
} else if key == InputKey::Refresh {
return vec![self.refresh_action()];
}
Vec::new()
}
}
}
fn reduce_tree(&mut self, key: InputKey) -> Vec<Action> {
let visible = self.visible_paths();
let position = visible
.iter()
.position(|path| path == &self.selected_path)
.unwrap_or(0);
match key {
InputKey::Up if position > 0 => self.selected_path = visible[position - 1].clone(),
InputKey::Down if position + 1 < visible.len() => {
self.selected_path = visible[position + 1].clone();
}
InputKey::Right | InputKey::Enter => {
let node = self
.entries
.entry(self.selected_path.clone())
.or_insert_with(|| EntryView::placeholder(&self.selected_path));
node.expanded = true;
if !matches!(node.tree_state, ViewState::Fresh) {
return vec![Action::Expand {
path: node.path.clone(),
}];
}
}
InputKey::Left => {
let node = self
.entries
.get_mut(&self.selected_path)
.expect("selected Entry exists");
if node.expanded {
node.expanded = false;
} else if self.selected_path != "/" {
self.selected_path = parent_path(&self.selected_path);
}
}
InputKey::Refresh => return vec![self.refresh_action()],
_ => {}
}
self.operation_cursor = 0;
Vec::new()
}
fn reduce_operations(&mut self, key: InputKey) -> Vec<Action> {
let rows = self.operation_rows();
match key {
InputKey::Up => self.operation_cursor = self.operation_cursor.saturating_sub(1),
InputKey::Down if self.operation_cursor + 1 < rows.len() => self.operation_cursor += 1,
InputKey::Refresh => return vec![self.refresh_action()],
InputKey::Escape => self.focus = Focus::Tree,
InputKey::Enter => {
if let Some(row) = rows.get(self.operation_cursor) {
if let Some(operation_name) = &row.operation {
if let Some(interface) = self.interfaces.get(&row.interface)
&& let Some(descriptor) = &interface.descriptor
&& let Some(operation) = descriptor
.operations
.iter()
.find(|operation| operation.name == *operation_name)
{
self.modal = Modal::Editor(ArgumentEditor::new(
row.interface.clone(),
descriptor.clone(),
operation.clone(),
));
}
} else {
return vec![Action::FetchInterface(row.interface.clone())];
}
}
}
_ => {}
}
Vec::new()
}
fn reduce_history(&mut self, key: InputKey) -> Vec<Action> {
match key {
InputKey::Up => self.history_cursor = self.history_cursor.saturating_sub(1),
InputKey::Down if self.history_cursor + 1 < self.history.len() => {
self.history_cursor += 1;
}
InputKey::Enter => {
if let Some(path) = self
.history
.get(self.history_cursor)
.and_then(|item| item.entry_target.clone())
{
return vec![Action::NavigateEntry(path)];
}
}
InputKey::Escape => self.focus = Focus::Tree,
_ => {}
}
Vec::new()
}
fn refresh_action(&self) -> Action {
Action::Refresh {
path: self.selected_path.clone(),
}
}
/// Records a pending request separately by interaction type.
pub fn request_started(&mut self, id: u64, kind: InFlightKind) {
match &kind {
InFlightKind::Object(path) => {
self.ensure_entry(path).state = ViewState::Loading(id);
}
InFlightKind::Tree(path) => {
let entry = self.ensure_entry(path);
entry.state = ViewState::Loading(id);
entry.tree_state = ViewState::Loading(id);
}
InFlightKind::Interface(reference) => {
self.ensure_interface(reference).state = ViewState::Loading(id);
}
InFlightKind::Operation { .. } => {}
}
self.in_flight.insert(id, kind);
}
/// Marks an operation as handed to the transport.
pub fn request_dispatched(&mut self, id: u64) {
if let Some(InFlightKind::Operation { dispatched, .. }) = self.in_flight.get_mut(&id) {
*dispatched = true;
self.status = "operation dispatched once; automatic retry is disabled".into();
}
}
/// Removes a completed request identity.
pub fn request_finished(&mut self, id: u64) -> Option<InFlightKind> {
self.in_flight.remove(&id)
}
/// Applies an object observation from `wip-client`.
pub fn apply_object(&mut self, observation: ObjectObservation) {
let entry = self.ensure_entry(&observation.path);
entry.object = observation.object;
entry.state = ViewState::from(&observation.state);
}
/// Applies a lazy tree observation and ensures child placeholders exist.
pub fn apply_tree(&mut self, observation: TreeObservation) {
let children = observation.children.clone();
let entry = self.ensure_entry(&observation.path);
entry.children = children.clone();
entry.tree_state = ViewState::from(&observation.state);
for path in children {
self.ensure_entry(&path);
}
}
/// Applies one interface observation from `wip-client`.
pub fn apply_interface(&mut self, observation: InterfaceObservation) {
let view = self.ensure_interface(&observation.reference);
*view = InterfaceView {
reference: observation.reference,
descriptor: observation.descriptor,
state: ViewState::from(&observation.state),
};
}
/// Replaces current Entry details from the client's current snapshot.
pub fn sync_object(&mut self, path: &str, observation: Option<ObjectObservation>) {
match observation {
Some(observation) => self.apply_object(observation),
None => {
let entry = self.ensure_entry(path);
entry.object = None;
entry.state = ViewState::Stale;
}
}
}
/// Selects a known or newly discovered descriptor-declared Entry path.
pub fn navigate_entry(&mut self, path: impl Into<String>) {
let path = path.into();
self.ensure_entry(&path);
self.selected_path = path;
self.focus = Focus::Tree;
}
/// Adds one bounded recent item.
pub fn push_history(&mut self, item: HistoryItem) {
self.history.insert(0, item);
self.history.truncate(self.history_limit);
self.history_cursor = 0;
}
/// Returns visible tree paths in display order.
#[must_use]
pub fn visible_paths(&self) -> Vec<String> {
let mut visible = Vec::new();
let mut seen = BTreeSet::new();
self.collect_visible("/", &mut seen, &mut visible);
if !seen.contains(&self.selected_path) && self.entries.contains_key(&self.selected_path) {
visible.push(self.selected_path.clone());
}
visible
}
/// Returns interface references advertised by fresh visible Objects in display
/// and per-Object declaration order, with duplicates removed.
#[must_use]
pub fn visible_interface_references(&self) -> Vec<String> {
let mut references = Vec::new();
let mut seen = BTreeSet::new();
for path in self.visible_paths() {
let Some(object) = self
.entries
.get(&path)
.filter(|entry| entry.state == ViewState::Fresh)
.and_then(|entry| entry.object.as_ref())
else {
continue;
};
for reference in &object.interfaces {
if seen.insert(reference.clone()) {
references.push(reference.clone());
}
}
}
references
}
fn collect_visible(&self, path: &str, seen: &mut BTreeSet<String>, visible: &mut Vec<String>) {
if !seen.insert(path.to_owned()) {
return;
}
visible.push(path.to_owned());
let Some(entry) = self.entries.get(path) else {
return;
};
if entry.expanded {
for child in &entry.children {
self.collect_visible(child, seen, visible);
}
}
}
/// Returns flattened interface headers and operations for the selected Entry.
#[must_use]
pub fn operation_rows(&self) -> Vec<OperationRow> {
let Some(object) = self
.entries
.get(&self.selected_path)
.filter(|entry| entry.state == ViewState::Fresh)
.and_then(|entry| entry.object.as_ref())
else {
return Vec::new();
};
let mut rows = Vec::new();
for reference in &object.interfaces {
rows.push(OperationRow {
interface: reference.clone(),
operation: None,
});
if let Some(descriptor) = self
.interfaces
.get(reference)
.filter(|view| view.state == ViewState::Fresh)
.and_then(|view| view.descriptor.as_ref())
{
rows.extend(descriptor.operations.iter().map(|operation| OperationRow {
interface: reference.clone(),
operation: Some(operation.name.clone()),
}));
}
}
rows
}
fn ensure_entry(&mut self, path: &str) -> &mut EntryView {
if !self.entries.contains_key(path) && self.entries.len() >= MAX_PRESENTATION_ENTRIES {
let candidate = self
.entries
.iter()
.find(|(candidate, entry)| {
candidate.as_str() != "/"
&& candidate.as_str() != self.selected_path
&& matches!(
entry.state,
ViewState::Unloaded | ViewState::Stale | ViewState::Error(_)
)
})
.or_else(|| {
self.entries.iter().find(|(candidate, entry)| {
candidate.as_str() != "/"
&& candidate.as_str() != self.selected_path
&& !matches!(entry.state, ViewState::Loading(_))
})
})
.map(|(candidate, _)| candidate.clone());
if let Some(candidate) = candidate {
self.entries.remove(&candidate);
for entry in self.entries.values_mut() {
entry.children.retain(|child| child != &candidate);
}
}
}
self.entries
.entry(path.to_owned())
.or_insert_with(|| EntryView::placeholder(path))
}
fn ensure_interface(&mut self, reference: &str) -> &mut InterfaceView {
if !self.interfaces.contains_key(reference)
&& self.interfaces.len() >= MAX_PRESENTATION_INTERFACES
{
let protected = self
.entries
.get(&self.selected_path)
.and_then(|entry| entry.object.as_ref())
.map(|object| object.interfaces.iter().cloned().collect::<BTreeSet<_>>())
.unwrap_or_default();
let candidate = self
.interfaces
.iter()
.find(|(candidate, interface)| {
!protected.contains(*candidate)
&& !matches!(interface.state, ViewState::Loading(_))
})
.or_else(|| {
self.interfaces
.iter()
.find(|(_, interface)| !matches!(interface.state, ViewState::Loading(_)))
})
.map(|(candidate, _)| candidate.clone());
if let Some(candidate) = candidate {
self.interfaces.remove(&candidate);
}
}
self.interfaces
.entry(reference.to_owned())
.or_insert_with(|| InterfaceView {
reference: reference.to_owned(),
descriptor: None,
state: ViewState::Unloaded,
})
}
}
/// One row in the combined Interface and Operation pane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationRow {
/// Interface reference, which participates in operation identity.
pub interface: String,
/// Operation name, or `None` for the interface heading.
pub operation: Option<String>,
}
/// Returns the canonical parent of a non-root path.
#[must_use]
pub fn parent_path(path: &str) -> String {
match path.rsplit_once('/') {
Some(("", _)) | None => "/".into(),
Some((parent, _)) => parent.into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use wip_protocol::{INTERFACE_FORMAT_V1, OperationDeclaration, ReturnDeclaration, TypeExpr};
fn object(name: &str, interfaces: &[&str]) -> Object {
Object {
name: name.into(),
description: Some(format!("{name} description")),
interfaces: interfaces.iter().map(|value| (*value).into()).collect(),
r#ref: None,
validator: None,
}
}
#[test]
fn tree_navigation_and_lazy_expansion_are_pure() {
let mut app = App::new("https://example.test/wip");
app.apply_tree(TreeObservation {
path: "/".into(),
children: vec!["/a".into(), "/b".into()],
revision: request_id(),
state: ObservationState::Fresh,
});
assert_eq!(app.visible_paths(), ["/", "/a", "/b"]);
app.reduce(InputKey::Down);
assert_eq!(app.selected_path, "/a");
assert!(matches!(
app.reduce(InputKey::Right).as_slice(),
[Action::Expand { path }] if path == "/a"
));
}
#[test]
fn visible_interface_references_are_ordered_deduplicated_and_fresh() {
let mut app = App::new("https://example.test/wip");
app.apply_tree(TreeObservation {
path: "/".into(),
children: vec!["/a".into(), "/stale".into()],
revision: request_id(),
state: ObservationState::Fresh,
});
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(object("", &["root", "shared"])),
validator: None,
state: ObservationState::Fresh,
});
app.apply_object(ObjectObservation {
path: "/a".into(),
object: Some(object("a", &["shared", "child"])),
validator: None,
state: ObservationState::Fresh,
});
app.apply_object(ObjectObservation {
path: "/stale".into(),
object: Some(object("stale", &["ignored"])),
validator: None,
state: ObservationState::Stale,
});
app.apply_tree(TreeObservation {
path: "/a".into(),
children: vec!["/a/hidden".into()],
revision: request_id(),
state: ObservationState::Fresh,
});
app.apply_object(ObjectObservation {
path: "/a/hidden".into(),
object: Some(object("hidden", &["hidden"])),
validator: None,
state: ObservationState::Fresh,
});
assert_eq!(
app.visible_interface_references(),
["root", "shared", "child"]
);
}
#[test]
fn focus_modal_and_explicit_confirmation_gate_execution() {
let mut app = App::new("https://example.test/wip");
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(object("", &["iface"])),
validator: None,
state: ObservationState::Fresh,
});
let descriptor = InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types: vec![],
operations: vec![OperationDeclaration {
name: "ping".into(),
documentation: None,
parameters: vec![],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::Unit,
},
}],
};
app.apply_interface(InterfaceObservation {
reference: "iface".into(),
descriptor: Some(descriptor),
validator: None,
state: ObservationState::Fresh,
});
app.focus = Focus::Operations;
app.operation_cursor = 1;
assert!(app.reduce(InputKey::Enter).is_empty());
assert!(matches!(app.modal, Modal::Editor(_)));
assert!(app.reduce(InputKey::Enter).is_empty());
assert!(matches!(app.modal, Modal::Confirm { .. }));
assert!(matches!(
app.reduce(InputKey::Enter).as_slice(),
[Action::Execute { operation, .. }] if operation == "ping"
));
}
#[test]
fn presentation_maps_enforce_client_sized_hard_bounds() {
let mut app = App::new("https://example.test/wip");
for index in 0..(MAX_PRESENTATION_ENTRIES + 100) {
app.navigate_entry(format!("/discovered-{index}"));
app.selected_path = "/".into();
}
assert!(app.entries.len() <= MAX_PRESENTATION_ENTRIES);
assert!(app.entries.contains_key("/"));
for index in 0..(MAX_PRESENTATION_INTERFACES + 50) {
app.apply_interface(InterfaceObservation {
reference: format!("interface-{index}"),
descriptor: None,
validator: None,
state: ObservationState::Fresh,
});
}
assert!(app.interfaces.len() <= MAX_PRESENTATION_INTERFACES);
}
#[test]
fn result_navigation_only_uses_explicit_entry_target() {
let mut app = App::new("https://example.test/wip");
app.push_history(HistoryItem {
kind: HistoryKind::Success,
title: "string".into(),
detail: "/looks/like/a/path".into(),
entry_target: None,
});
app.focus = Focus::History;
assert!(app.reduce(InputKey::Enter).is_empty());
app.push_history(HistoryItem {
kind: HistoryKind::Success,
title: "Entry".into(),
detail: "/actual".into(),
entry_target: Some("/actual".into()),
});
assert_eq!(
app.reduce(InputKey::Enter),
vec![Action::NavigateEntry("/actual".into())]
);
}
fn request_id() -> wip_client::RequestId {
// A request identity has no public constructor; derive one through the runtime.
let mut client = wip_client::Client::new(
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
wip_http::Limits::new(1024, 1024, 8, 8).unwrap(),
);
let session = client
.open_session(
"https://example.test/wip",
wip_client::SecurityContext::new("test"),
)
.unwrap();
client.refresh_object(&session, "/").unwrap().id
}
}
+239
View File
@@ -0,0 +1,239 @@
//! Command-line and environment configuration for the HTTP client.
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::time::Duration;
use wip_http::Endpoint;
/// Credential wrapper whose debug output is always redacted.
#[derive(Clone)]
pub struct Secret(String);
impl Secret {
pub(crate) fn expose(&self) -> &str {
&self.0
}
}
impl Debug for Secret {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("Secret([REDACTED])")
}
}
/// Validated runtime configuration.
#[derive(Clone)]
pub struct Config {
/// Canonical endpoint used for request construction, transport, and cache partitioning.
endpoint: String,
/// Non-secret cache partition identity.
security_context: String,
/// Bounded network timeout.
timeout: Duration,
/// Optional complete Authorization header value, never rendered or logged.
authorization: Option<Secret>,
}
impl Debug for Config {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Config")
.field("endpoint", &self.endpoint)
.field("security_context", &self.security_context)
.field("timeout", &self.timeout)
.field("authorization", &self.authorization)
.finish()
}
}
impl Config {
/// Returns the canonical endpoint used by the client and HTTP transport.
#[must_use]
pub fn endpoint(&self) -> &str {
&self.endpoint
}
/// Returns the non-secret session cache partition identity.
#[must_use]
pub fn security_context(&self) -> &str {
&self.security_context
}
/// Returns the end-to-end request timeout.
#[must_use]
pub const fn timeout(&self) -> Duration {
self.timeout
}
pub(crate) fn authorization(&self) -> Option<&Secret> {
self.authorization.as_ref()
}
/// Parses process arguments and supported environment variables.
///
/// Endpoint precedence is `--endpoint`, a positional endpoint, then
/// `WIP_ENDPOINT`. Authorization is read only from the variable named by
/// `--authorization-env` (default `WIP_AUTHORIZATION`).
pub fn from_env() -> Result<Self, ConfigError> {
let arguments = std::env::args().skip(1).collect::<Vec<_>>();
let endpoint_env = std::env::var("WIP_ENDPOINT").ok();
let security_context = std::env::var("WIP_SECURITY_CONTEXT").ok();
Self::parse(arguments, endpoint_env, security_context, |name| {
std::env::var(name).ok()
})
}
/// Parses supplied values; exposed to make startup policy independently testable.
pub fn parse<I, S, F>(
arguments: I,
endpoint_env: Option<String>,
security_context_env: Option<String>,
mut read_secret: F,
) -> Result<Self, ConfigError>
where
I: IntoIterator<Item = S>,
S: Into<String>,
F: FnMut(&str) -> Option<String>,
{
let mut endpoint = None;
let mut timeout = Duration::from_secs(30);
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
let mut iter = arguments.into_iter().map(Into::into);
while let Some(argument) = iter.next() {
match argument.as_str() {
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
"--security-context" => {
security_context = next_value(&mut iter, "--security-context")?;
}
"--authorization-env" => {
authorization_env = next_value(&mut iter, "--authorization-env")?;
}
"--timeout" => {
let raw = next_value(&mut iter, "--timeout")?;
let seconds = raw
.parse::<u64>()
.ok()
.filter(|seconds| *seconds > 0)
.ok_or_else(|| {
ConfigError::Invalid("--timeout must be a positive integer".into())
})?;
timeout = Duration::from_secs(seconds);
}
"--help" | "-h" => return Err(ConfigError::Help),
value if value.starts_with('-') => {
return Err(ConfigError::Invalid(format!("unknown option {value}")));
}
value if endpoint.is_none() => endpoint = Some(value.to_owned()),
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
}
}
let supplied = endpoint
.or(endpoint_env)
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
let endpoint =
Endpoint::parse(&supplied).map_err(|error| ConfigError::Invalid(error.to_string()))?;
if !endpoint.as_url().username().is_empty() || endpoint.as_url().password().is_some() {
return Err(ConfigError::Invalid(
"endpoint userinfo is not accepted; supply credentials through the configured environment variable"
.into(),
));
}
if !matches!(endpoint.as_url().scheme(), "http" | "https") {
return Err(ConfigError::Invalid(
"this HTTP client supports http and https endpoint schemes".into(),
));
}
if security_context.is_empty() {
return Err(ConfigError::Invalid(
"security context must not be empty".into(),
));
}
let authorization = read_secret(&authorization_env)
.filter(|value| !value.is_empty())
.map(Secret);
Ok(Self {
endpoint: endpoint.to_string(),
security_context,
timeout,
authorization,
})
}
/// Returns concise command usage without mentioning credential values.
#[must_use]
pub const fn usage() -> &'static str {
"usage: wip-tui [--endpoint] URL [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
URL may also be supplied as WIP_ENDPOINT; the HTTP adapter supports http and https."
}
}
fn next_value(
iter: &mut impl Iterator<Item = String>,
option: &str,
) -> Result<String, ConfigError> {
iter.next()
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
}
/// Startup configuration failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
/// Help was requested.
Help,
/// A safe, non-secret configuration diagnostic.
Invalid(String),
}
impl Display for ConfigError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Help => formatter.write_str(Config::usage()),
Self::Invalid(detail) => write!(formatter, "{detail}\n{}", Config::usage()),
}
}
}
impl Error for ConfigError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn endpoint_is_canonical_and_secrets_are_redacted() {
let config = Config::parse(
["https://example.test/wip", "--authorization-env", "TOKEN"],
None,
None,
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
)
.unwrap();
assert_eq!(config.endpoint(), "https://example.test/wip/");
let debug = format!("{config:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("secret-value"));
}
#[test]
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
for endpoint in [
"https://user:password@example.test/wip",
"http://user:password@localhost:3000/wip",
] {
let error = Config::parse([endpoint], None, None, |_| None).unwrap_err();
assert!(error.to_string().contains("userinfo"));
assert!(!error.to_string().contains("password"));
}
}
#[test]
fn http_and_https_are_preserved_as_the_single_endpoint() {
for expected in ["http://example.test:3000/wip/", "https://example.test/wip/"] {
let supplied = expected.trim_end_matches('/');
let config = Config::parse([supplied], None, None, |_| None).unwrap();
assert_eq!(config.endpoint(), expected);
}
}
}
+628
View File
@@ -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,
}
}
}
+10
View File
@@ -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;
+6
View File
@@ -0,0 +1,6 @@
fn main() {
if let Err(error) = wip_tui::runtime::run_from_env() {
eprintln!("wip-tui: {error}");
std::process::exit(1);
}
}
+851
View File
@@ -0,0 +1,851 @@
//! Deterministic bounded rendering for real and test terminal backends.
use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap};
use crate::app::{App, ConnectionState, Focus, HistoryKind, Modal, OperationRow, ViewState};
use crate::editor::type_name;
const MAX_RENDER_TEXT: usize = 512;
/// Draws the complete application without mutating it.
pub fn draw(frame: &mut Frame<'_>, app: &App) {
let area = frame.area();
if area.width < 48 || area.height < 14 {
frame.render_widget(
Paragraph::new("wip-tui\nTerminal is too small. Resize to at least 48 x 14.\nq: quit")
.block(
Block::default()
.borders(Borders::ALL)
.title(" Minimum size "),
)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
area,
);
return;
}
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(2),
Constraint::Min(8),
Constraint::Length(2),
])
.split(area);
render_header(frame, vertical[0], app);
let columns = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(38), Constraint::Percentage(62)])
.split(vertical[1]);
render_tree(frame, columns[0], app);
let right = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(31),
Constraint::Percentage(39),
Constraint::Percentage(30),
])
.split(columns[1]);
render_selected(frame, right[0], app);
render_operations(frame, right[1], app);
render_history(frame, right[2], app);
render_footer(frame, vertical[2], app);
render_modal(frame, app);
}
fn render_header(frame: &mut Frame<'_>, area: Rect, app: &App) {
let connection = match &app.connection {
ConnectionState::Disconnected => "DISCONNECTED",
ConnectionState::Connecting => "CONNECTING",
ConnectionState::Connected => "CONNECTED",
ConnectionState::Failed(_) => "FAILED (R reconnect / q quit)",
};
let text = format!(
" wip-tui {} [{}] in-flight: {}",
sanitize(&app.endpoint),
connection,
app.in_flight.len()
);
frame.render_widget(
Paragraph::new(text).style(Style::default().add_modifier(Modifier::BOLD)),
area,
);
}
fn render_tree(frame: &mut Frame<'_>, area: Rect, app: &App) {
let mut paths = app.visible_paths();
let selected_index = paths
.iter()
.position(|path| path == &app.selected_path)
.unwrap_or(0);
let (start, end) = list_window(paths.len(), selected_index, area.height.saturating_sub(2));
let rows = paths.drain(start..end).map(|path| {
let node = app.entries.get(&path);
let selected = path == app.selected_path;
let depth = if path == "/" {
0
} else {
path.trim_start_matches('/').split('/').count()
};
let marker = node.map_or('·', |node| if node.expanded { '▼' } else { '▶' });
let label = node.and_then(|node| node.object.as_ref()).map_or_else(
|| path.clone(),
|object| {
if path == "/" {
"/".into()
} else {
object.name.clone()
}
},
);
let mut suffix = node.map_or_else(
|| " [unloaded]".into(),
|node| {
let tree = match &node.tree_state {
ViewState::Loading(_) => " [loading children]",
ViewState::Stale => " [stale children]",
ViewState::Error(_) => " [failed children]",
ViewState::Fresh if node.children.is_empty() => " [empty]",
_ => "",
};
let object = state_suffix(&node.state);
format!("{object}{tree}")
},
);
suffix = sanitize(&suffix);
let style = if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else {
Style::default()
};
ListItem::new(Line::from(vec![
Span::raw(" ".repeat(depth)),
Span::raw(format!("{marker} {}", sanitize(&label))),
Span::styled(suffix, state_style(node.map(|value| &value.state))),
]))
.style(style)
});
frame.render_widget(
List::new(rows).block(focused_block(" Worldspace tree ", app.focus == Focus::Tree)),
area,
);
}
fn render_selected(frame: &mut Frame<'_>, area: Rect, app: &App) {
let mut lines = vec![Line::from(format!(
"Path: {}",
sanitize(&app.selected_path)
))];
if let Some(entry) = app.entries.get(&app.selected_path) {
lines.push(Line::from(format!("State: {}", state_label(&entry.state))));
if entry.state == ViewState::Fresh {
if let Some(object) = &entry.object {
lines.push(Line::from(format!("Name: {}", sanitize(&object.name))));
lines.push(Line::from(format!(
"Description: {}",
object
.description
.as_deref()
.map(sanitize)
.unwrap_or_else(|| "(none)".into())
)));
lines.push(Line::from(format!(
"Interfaces (ordered): {}",
if object.interfaces.is_empty() {
"(none)".into()
} else {
object
.interfaces
.iter()
.map(|value| sanitize(value))
.collect::<Vec<_>>()
.join(", ")
}
)));
}
} else {
lines.push(Line::from(
"No current object metadata; refresh required (old metadata hidden).",
));
}
}
frame.render_widget(
Paragraph::new(lines)
.block(focused_block(" Selected Entry ", app.focus == Focus::Entry))
.wrap(Wrap { trim: false }),
area,
);
}
fn render_operations(frame: &mut Frame<'_>, area: Rect, app: &App) {
let rows = app.operation_rows();
let selected_index = app.operation_cursor.min(rows.len().saturating_sub(1));
let (start, end) = list_window(rows.len(), selected_index, area.height.saturating_sub(2));
let items = rows[start..end].iter().enumerate().map(|(offset, row)| {
let index = start + offset;
let (text, style) = operation_line(app, row);
let selected = app.focus == Focus::Operations && index == app.operation_cursor;
ListItem::new(text).style(if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else {
style
})
});
let title = " Interfaces / Operations (Enter: load or edit) ";
if rows.is_empty() {
frame.render_widget(
Paragraph::new("No declared interfaces or no current object.")
.block(focused_block(title, app.focus == Focus::Operations)),
area,
);
} else {
frame.render_widget(
List::new(items).block(focused_block(title, app.focus == Focus::Operations)),
area,
);
}
}
fn operation_line(app: &App, row: &OperationRow) -> (Line<'static>, Style) {
if let Some(name) = &row.operation {
let descriptor = app
.interfaces
.get(&row.interface)
.and_then(|view| view.descriptor.as_ref());
let declaration = descriptor.and_then(|descriptor| {
descriptor
.operations
.iter()
.find(|operation| operation.name == *name)
});
let signature = declaration.map_or_else(
|| format!(" ({}, {})", row.interface, name),
|operation| {
let parameters = operation
.parameters
.iter()
.map(|parameter| {
format!(
"{}{}: {}",
parameter.name,
if parameter.required { "" } else { "?" },
type_name(&parameter.r#type)
)
})
.collect::<Vec<_>>()
.join(", ");
let documentation = operation
.documentation
.as_ref()
.map(|documentation| format!(" — {}", documentation.summary))
.unwrap_or_default();
format!(
" ({}, {}) ({parameters}) -> {}{}",
row.interface,
name,
type_name(&operation.returns.r#type),
documentation
)
},
);
(Line::from(sanitize(&signature)), Style::default())
} else {
let interface = app.interfaces.get(&row.interface);
let state = interface.map_or("unloaded".into(), |view| state_label(&view.state));
let documentation = interface
.filter(|view| view.state == ViewState::Fresh)
.and_then(|view| view.descriptor.as_ref())
.and_then(|descriptor| descriptor.documentation.as_ref())
.map(|documentation| format!(" — {}", sanitize(&documentation.summary)))
.unwrap_or_default();
(
Line::from(format!(
"Interface {} [{}]{}",
sanitize(&row.interface),
state,
documentation
)),
Style::default().add_modifier(Modifier::BOLD),
)
}
}
fn render_history(frame: &mut Frame<'_>, area: Rect, app: &App) {
let selected_index = app.history_cursor.min(app.history.len().saturating_sub(1));
let (start, end) = list_window(
app.history.len(),
selected_index,
area.height.saturating_sub(2),
);
let items = app.history[start..end]
.iter()
.enumerate()
.map(|(offset, item)| {
let index = start + offset;
let label = match item.kind {
HistoryKind::Success => "SUCCESS",
HistoryKind::DomainFailure => "HOST FAILURE",
HistoryKind::ProtocolError => "PROTOCOL ERROR",
HistoryKind::TransportFailure => "TRANSPORT FAILURE",
HistoryKind::ClientFailure => "CLIENT FAILURE",
HistoryKind::OutcomeUnknown => "OUTCOME UNKNOWN",
HistoryKind::Information => "INFO",
};
let link = item
.entry_target
.as_ref()
.map_or("", |_| " [Enter: go to Entry]");
let text = format!(
"[{label}] {}: {}{link}",
sanitize(&item.title),
sanitize(&item.detail)
);
let selected = app.focus == Focus::History && index == app.history_cursor;
ListItem::new(text).style(if selected {
Style::default().fg(Color::Black).bg(Color::Cyan)
} else if item.kind == HistoryKind::OutcomeUnknown {
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
} else {
Style::default()
})
});
let block = focused_block(
" Recent results / diagnostics ",
app.focus == Focus::History,
);
if app.history.is_empty() {
frame.render_widget(Paragraph::new("No results yet.").block(block), area);
} else {
frame.render_widget(List::new(items).block(block), area);
}
}
fn render_footer(frame: &mut Frame<'_>, area: Rect, app: &App) {
let help = " ↑↓/jk move ←→/hl parent/expand Tab focus Enter select r refresh + larger tree c cancel read ? help q quit ";
let text = format!("{}\n{}", help, sanitize(&app.status));
frame.render_widget(
Paragraph::new(text).style(Style::default().fg(Color::DarkGray)),
area,
);
}
fn render_modal(frame: &mut Frame<'_>, app: &App) {
match &app.modal {
Modal::None => {}
Modal::Help => {
let area = centered(frame.area(), 76, 70);
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(
"Keyboard help\n\n↑/↓ or j/k move selection / editor field\n←/→ or h/l collapse/expand or parent\nTab next pane\nEnter load interface, edit operation, confirm execute\nr refresh selected Entry and subtree\nc cancel newest retrieval (never cancels a sent operation)\nR reconnect after failure\nEsc close modal\nq quit\n\nOperations are never sent until the confirmation screen is accepted.",
)
.block(Block::default().borders(Borders::ALL).title(" Help "))
.wrap(Wrap { trim: false }),
area,
);
}
Modal::Editor(editor) => {
let area = centered(frame.area(), 86, 78);
frame.render_widget(Clear, area);
let mut lines = vec![Line::from(format!(
"Target: {} Operation: ({}, {})",
sanitize(&app.selected_path),
sanitize(&editor.interface),
sanitize(&editor.operation.name)
))];
if editor.fields.is_empty() {
lines.push(Line::from("(no parameters)"));
}
for (index, field) in editor.fields.iter().enumerate() {
let cursor = if index == editor.cursor { ">" } else { " " };
let requirement = if field.required {
"required"
} else {
"optional"
};
lines.push(Line::from(format!(
"{cursor} {} [{requirement}, {}] = {}",
sanitize(&field.name),
sanitize(&type_name(&field.r#type)),
sanitize(&field.input)
)));
if let Some(diagnostic) = &field.diagnostic {
lines.push(Line::styled(
format!(" ERROR: {}", sanitize(diagnostic)),
Style::default().fg(Color::Red),
));
}
}
lines.push(Line::from(""));
lines.push(Line::from("Enter: validate and review Esc: cancel"));
frame.render_widget(
Paragraph::new(lines)
.block(
Block::default()
.borders(Borders::ALL)
.title(" Argument editor "),
)
.wrap(Wrap { trim: false }),
area,
);
}
Modal::Confirm { editor, arguments } => {
let area = centered(frame.area(), 82, 58);
frame.render_widget(Clear, area);
let mut lines = vec![
Line::styled(
"EXPLICIT EXECUTION CONFIRMATION",
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD),
),
Line::from(format!("Entry: {}", sanitize(&app.selected_path))),
Line::from(format!("Interface: {}", sanitize(&editor.interface))),
Line::from(format!("Operation: {}", sanitize(&editor.operation.name))),
Line::from("Input values:"),
];
for (name, value) in arguments {
lines.push(Line::from(format!(
" {} = {}",
sanitize(name),
sanitize(&bounded_value(value))
)));
}
lines.push(Line::from(""));
lines.push(Line::styled(
"Enter/e: EXECUTE ONCE Esc: back to editor",
Style::default().add_modifier(Modifier::BOLD),
));
frame.render_widget(
Paragraph::new(lines)
.block(Block::default().borders(Borders::ALL).title(" Confirm "))
.wrap(Wrap { trim: false }),
area,
);
}
}
}
fn list_window(total: usize, selected: usize, area_height: u16) -> (usize, usize) {
let capacity = usize::from(area_height);
if total == 0 || capacity == 0 {
return (0, 0);
}
let selected = selected.min(total - 1);
let start = selected
.saturating_add(1)
.saturating_sub(capacity)
.min(total.saturating_sub(capacity));
(start, start.saturating_add(capacity).min(total))
}
fn focused_block(title: &'static str, focused: bool) -> Block<'static> {
let style = if focused {
Style::default().fg(Color::Cyan)
} else {
Style::default()
};
Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(style)
}
fn centered(area: Rect, percent_x: u16, percent_y: u16) -> Rect {
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(area);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(vertical[1])[1]
}
fn state_suffix(state: &ViewState) -> &'static str {
match state {
ViewState::Unloaded => " [unloaded]",
ViewState::Loading(_) => " [loading]",
ViewState::Fresh => "",
ViewState::Stale => " [stale: refresh required]",
ViewState::Error(_) => " [error]",
}
}
fn state_label(state: &ViewState) -> String {
match state {
ViewState::Unloaded => "unloaded".into(),
ViewState::Loading(id) => format!("loading request #{id}"),
ViewState::Fresh => "fresh".into(),
ViewState::Stale => "stale — refresh required".into(),
ViewState::Error(error) => format!("error — {}", sanitize(error)),
}
}
fn state_style(state: Option<&ViewState>) -> Style {
match state {
Some(ViewState::Stale) => Style::default().fg(Color::Yellow),
Some(ViewState::Error(_)) => Style::default().fg(Color::Red),
Some(ViewState::Loading(_)) => Style::default().fg(Color::Blue),
_ => Style::default(),
}
}
/// Replaces terminal control characters and bounds user/remote text by Unicode scalars.
#[must_use]
pub fn sanitize(input: &str) -> String {
let mut output = String::new();
for (count, character) in input.chars().enumerate() {
if count >= MAX_RENDER_TEXT {
output.push('…');
break;
}
if character.is_control() && !matches!(character, '\n' | '\t') {
output.push('�');
} else {
output.push(character);
}
}
output
}
/// Formats a protocol value with strict byte and collection bounds.
#[must_use]
pub fn bounded_value(value: &wip_protocol::Value) -> String {
bounded_value_at(value, 0)
}
fn bounded_value_at(value: &wip_protocol::Value, depth: usize) -> String {
if depth >= 8 {
return "…".into();
}
match value {
wip_protocol::Value::Unit => "null".into(),
wip_protocol::Value::Boolean(value) => value.to_string(),
wip_protocol::Value::Integer(value) => value.to_string(),
wip_protocol::Value::Number(value) => value.to_string(),
wip_protocol::Value::String(value) => format!("{:?}", sanitize(value)),
wip_protocol::Value::Bytes(bytes) => {
let shown = bytes
.iter()
.take(32)
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
if bytes.len() > 32 {
format!("bytes[{}]: {shown}…", bytes.len())
} else {
format!("bytes[{}]: {shown}", bytes.len())
}
}
wip_protocol::Value::Record(values) => {
let mut fields = values
.iter()
.take(16)
.map(|(name, value)| {
format!("{}: {}", sanitize(name), bounded_value_at(value, depth + 1))
})
.collect::<Vec<_>>();
if values.len() > 16 {
fields.push("…".into());
}
format!("{{{}}}", fields.join(", "))
}
wip_protocol::Value::List(values) => {
let mut items = values
.iter()
.take(16)
.map(|value| bounded_value_at(value, depth + 1))
.collect::<Vec<_>>();
if values.len() > 16 {
items.push("…".into());
}
format!("[{}]", items.join(", "))
}
}
}
#[cfg(test)]
mod tests {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use super::*;
use crate::app::{EntryView, HistoryItem};
use crate::editor::ArgumentEditor;
use wip_client::{InterfaceObservation, ObjectObservation, ObservationState};
use wip_protocol::{
INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, OperationDeclaration,
ParameterDeclaration, ReturnDeclaration, TypeExpr,
};
fn rendered(app: &App, width: u16, height: u16) -> String {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).unwrap();
terminal.draw(|frame| draw(frame, app)).unwrap();
terminal
.backend()
.buffer()
.content
.iter()
.map(|cell| cell.symbol())
.collect::<Vec<_>>()
.chunks(width as usize)
.map(|line| line.concat())
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn observed_empty_visible_entry_is_labeled_without_expansion() {
let mut app = App::new("https://example.test/wip/");
{
let root = app.entries.get_mut("/").unwrap();
root.children = vec!["/empty".into()];
root.tree_state = ViewState::Fresh;
}
app.entries.insert(
"/empty".into(),
EntryView {
path: "/empty".into(),
object: Some(Object {
name: "empty".into(),
description: None,
interfaces: vec![],
r#ref: None,
validator: None,
}),
state: ViewState::Fresh,
children: vec![],
tree_state: ViewState::Fresh,
expanded: false,
},
);
let snapshot = rendered(&app, 80, 20);
assert!(snapshot.contains("empty [empty]"));
}
#[test]
fn snapshot_contains_non_color_state_markers_and_hides_validators() {
let mut app = App::new("https://example.test/wip/");
app.connection = ConnectionState::Connected;
app.entries.get_mut("/").unwrap().state = ViewState::Stale;
app.push_history(HistoryItem {
kind: HistoryKind::OutcomeUnknown,
title: "replace".into(),
detail: "execution and side effects are unknown; refresh before deciding again".into(),
entry_target: None,
});
let snapshot = rendered(&app, 110, 30);
assert!(snapshot.contains("stale"));
assert!(snapshot.contains("OUTCOME UNKNOWN"));
assert!(!snapshot.contains("validator"));
}
#[test]
fn snapshots_cover_selected_operation_editor_and_failure_categories() {
let mut app = App::new("https://example.test/wip/");
app.connection = ConnectionState::Connected;
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(Object {
name: String::new(),
description: Some("public root description".into()),
interfaces: vec!["demo-interface".into()],
r#ref: None,
validator: Some(b"must-not-render".to_vec()),
}),
validator: Some(b"must-not-render".to_vec()),
state: ObservationState::Fresh,
});
let descriptor = InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types: vec![],
operations: vec![OperationDeclaration {
name: "run".into(),
documentation: None,
parameters: vec![ParameterDeclaration {
name: "count".into(),
required: true,
documentation: None,
r#type: TypeExpr::Integer,
}],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::String,
},
}],
};
app.apply_interface(InterfaceObservation {
reference: "demo-interface".into(),
descriptor: Some(descriptor.clone()),
validator: Some(b"must-not-render".to_vec()),
state: ObservationState::Fresh,
});
for (kind, title) in [
(HistoryKind::Success, "result"),
(HistoryKind::ProtocolError, "invalid response"),
(HistoryKind::TransportFailure, "network"),
(HistoryKind::ClientFailure, "local"),
] {
app.push_history(HistoryItem {
kind,
title: title.into(),
detail: "bounded detail".into(),
entry_target: None,
});
}
let snapshot = rendered(&app, 140, 40);
assert!(snapshot.contains("public root description"));
assert!(snapshot.contains("(demo-interface, run)"));
assert!(snapshot.contains("SUCCESS"));
assert!(snapshot.contains("PROTOCOL ERROR"));
assert!(snapshot.contains("TRANSPORT FAILURE"));
assert!(snapshot.contains("CLIENT FAILURE"));
assert!(!snapshot.contains("must-not-render"));
let mut editor = ArgumentEditor::new(
"demo-interface",
descriptor.clone(),
descriptor.operations[0].clone(),
);
editor.fields[0].diagnostic = Some("expected integer".into());
app.modal = Modal::Editor(editor);
let snapshot = rendered(&app, 140, 40);
assert!(snapshot.contains("Argument editor"));
assert!(snapshot.contains("count [required, Integer]"));
assert!(snapshot.contains("ERROR: expected integer"));
}
#[test]
fn list_panes_keep_the_active_row_inside_the_bounded_viewport() {
let mut app = App::new("https://example.test/wip/");
app.connection = ConnectionState::Connected;
let children = (0..40)
.map(|index| format!("/tree-row-{index:02}"))
.collect::<Vec<_>>();
{
let root = app.entries.get_mut("/").unwrap();
root.children = children.clone();
root.tree_state = ViewState::Fresh;
root.expanded = true;
}
for child in &children {
app.entries.insert(
child.clone(),
EntryView {
path: child.clone(),
object: None,
state: ViewState::Unloaded,
children: vec![],
tree_state: ViewState::Unloaded,
expanded: false,
},
);
}
app.selected_path = children.last().unwrap().clone();
app.focus = Focus::Tree;
let snapshot = rendered(&app, 100, 30);
let tree_pane = snapshot
.lines()
.map(|line| line.chars().take(38).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
assert!(tree_pane.contains("tree-row-39"));
app.selected_path = "/".into();
app.apply_object(ObjectObservation {
path: "/".into(),
object: Some(Object {
name: String::new(),
description: None,
interfaces: vec!["many".into()],
r#ref: None,
validator: None,
}),
validator: None,
state: ObservationState::Fresh,
});
let operations = (0..20)
.map(|index| OperationDeclaration {
name: format!("operation-{index:02}"),
documentation: None,
parameters: vec![],
returns: ReturnDeclaration {
documentation: None,
r#type: TypeExpr::Unit,
},
})
.collect::<Vec<_>>();
app.apply_interface(InterfaceObservation {
reference: "many".into(),
descriptor: Some(InterfaceDescriptor {
format: INTERFACE_FORMAT_V1.into(),
documentation: None,
types: vec![],
operations,
}),
validator: None,
state: ObservationState::Fresh,
});
app.focus = Focus::Operations;
app.operation_cursor = app.operation_rows().len() - 1;
let snapshot = rendered(&app, 100, 30);
assert!(snapshot.contains("(many, operation-19)"));
for index in 0..20 {
app.push_history(HistoryItem {
kind: HistoryKind::Information,
title: format!("history-{index:02}"),
detail: "diagnostic".into(),
entry_target: None,
});
}
app.focus = Focus::History;
app.history_cursor = app.history.len() - 1;
let snapshot = rendered(&app, 100, 30);
assert!(snapshot.contains("[INFO] history-00"));
}
#[test]
fn tiny_terminal_has_a_safe_fallback() {
let snapshot = rendered(&App::new("https://example.test/"), 30, 8);
assert!(snapshot.contains("too small"));
}
#[test]
fn control_characters_and_large_bytes_are_bounded() {
assert_eq!(sanitize("safe\u{1b}[31m"), "safe�[31m");
let display = bounded_value(&wip_protocol::Value::Bytes(vec![7; 1000]));
assert!(display.starts_with("bytes[1000]"));
assert!(display.ends_with('…'));
}
#[test]
fn entry_view_type_remains_constructible_for_external_snapshots() {
let entry = EntryView {
path: "/".into(),
object: None,
state: ViewState::Unloaded,
children: vec![],
tree_state: ViewState::Unloaded,
expanded: false,
};
assert_eq!(entry.path, "/");
}
}
File diff suppressed because it is too large Load Diff
+131
View File
@@ -0,0 +1,131 @@
//! Terminal lifecycle guard and crossterm input translation.
use std::io::{self, Stdout};
use std::sync::Arc;
use crossterm::cursor::{Hide, Show};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use crate::app::InputKey;
type PanicHook = dyn for<'a> Fn(&std::panic::PanicHookInfo<'a>) + Send + Sync + 'static;
/// RAII owner of raw mode, alternate screen, cursor visibility, and panic recovery.
pub struct TerminalGuard {
terminal: Terminal<CrosstermBackend<Stdout>>,
previous_hook: Arc<PanicHook>,
}
impl TerminalGuard {
/// Enters terminal UI mode, restoring partial setup on failure.
pub fn enter() -> io::Result<Self> {
enable_raw_mode()?;
let mut stdout = io::stdout();
if let Err(error) = execute!(stdout, EnterAlternateScreen, Hide) {
let _ = disable_raw_mode();
return Err(error);
}
let terminal = match Terminal::new(CrosstermBackend::new(stdout)) {
Ok(terminal) => terminal,
Err(error) => {
restore_terminal();
return Err(error);
}
};
let previous_hook: Arc<PanicHook> = std::panic::take_hook().into();
let panic_hook = Arc::clone(&previous_hook);
let terminal_owner = std::thread::current().id();
std::panic::set_hook(Box::new(move |information| {
if std::thread::current().id() == terminal_owner {
restore_terminal();
}
panic_hook(information);
}));
Ok(Self {
terminal,
previous_hook,
})
}
/// Returns the ratatui terminal for drawing.
pub fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
&mut self.terminal
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let previous = Arc::clone(&self.previous_hook);
std::panic::set_hook(Box::new(move |information| previous(information)));
restore_terminal();
}
}
fn restore_terminal() {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
}
/// Converts one crossterm key event into a terminal-independent reducer key.
///
/// When `editing` is true, printable command letters remain text input and only
/// Ctrl-C/Escape retain global meaning.
#[must_use]
pub fn translate_key(event: KeyEvent, editing: bool) -> Option<InputKey> {
if event.modifiers.contains(KeyModifiers::CONTROL) && event.code == KeyCode::Char('c') {
return Some(InputKey::Quit);
}
let key = match event.code {
KeyCode::Up => InputKey::Up,
KeyCode::Down => InputKey::Down,
KeyCode::Left => InputKey::Left,
KeyCode::Right => InputKey::Right,
KeyCode::Tab => InputKey::Tab,
KeyCode::Enter => InputKey::Enter,
KeyCode::Esc => InputKey::Escape,
KeyCode::Backspace => InputKey::Backspace,
KeyCode::Char(character) if editing => InputKey::Character(character),
KeyCode::Char('k') => InputKey::Up,
KeyCode::Char('j') => InputKey::Down,
KeyCode::Char('h') => InputKey::Left,
KeyCode::Char('l') => InputKey::Right,
KeyCode::Char('r') => InputKey::Refresh,
KeyCode::Char('R') => InputKey::Reconnect,
KeyCode::Char('c') => InputKey::CancelRead,
KeyCode::Char('?') => InputKey::Help,
KeyCode::Char('q') => InputKey::Quit,
KeyCode::Char(character) => InputKey::Character(character),
_ => return None,
};
Some(key)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn editing_keeps_command_letters_as_text_but_ctrl_c_quits() {
assert_eq!(
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), true),
Some(InputKey::Character('q'))
);
assert_eq!(
translate_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE), false),
Some(InputKey::Quit)
);
assert_eq!(
translate_key(
KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
true
),
Some(InputKey::Quit)
);
}
}
+205
View File
@@ -0,0 +1,205 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::tempdir;
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
use wip_tui::app::{Focus, HistoryKind, InputKey, Modal, ViewState};
use wip_tui::config::Config;
use wip_tui::runtime::{HttpTransport, Runtime, default_wire_limits};
#[test]
fn real_http_filesystem_workflow_is_lazy_validator_safe_and_symlink_confined() {
let temporary = tempdir().expect("temporary root");
let outside = tempdir().expect("outside root");
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
std::fs::create_dir(temporary.path().join("nested")).expect("create nested directory");
std::fs::write(outside.path().join("secret.txt"), b"outside-secret").expect("outside file");
#[cfg(unix)]
std::os::unix::fs::symlink(outside.path(), temporary.path().join("outside-link"))
.expect("create symlink");
let mut server_config = ServerConfig::for_root(temporary.path());
server_config.access = AccessMode::ReadWrite;
let bound = Arc::new(
WipFsServer::new(server_config)
.expect("build filesystem server")
.bind()
.expect("bind filesystem server"),
);
let shutdown = Arc::new(AtomicBool::new(false));
let worker = {
let bound = Arc::clone(&bound);
let shutdown = Arc::clone(&shutdown);
thread::spawn(move || bound.serve_until(shutdown))
};
let endpoint = format!("http://127.0.0.1:{}/wip", bound.local_addr().port());
let config = Config::parse([endpoint], None, Some("filesystem-test".into()), |_| None)
.expect("development config");
let transport = HttpTransport::new(&config, default_wire_limits().max_response_bytes())
.expect("HTTP transport");
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
assert_eq!(runtime.app().selected_path, "/");
assert!(runtime.app().entries.contains_key("/hello.txt"));
assert!(runtime.app().entries.contains_key("/nested"));
assert!(runtime.app().entries.contains_key("/outside-link"));
let empty_directory = &runtime.app().entries["/nested"];
assert_eq!(empty_directory.tree_state, ViewState::Fresh);
assert!(empty_directory.children.is_empty());
assert!(!empty_directory.expanded);
// Visible Objects have their interface descriptors prefetched before selection.
let file_interfaces = runtime.app().entries["/hello.txt"]
.object
.as_ref()
.expect("file object")
.interfaces
.clone();
assert!(!file_interfaces.is_empty());
for reference in &file_interfaces {
assert_eq!(runtime.app().interfaces[reference].state, ViewState::Fresh);
assert!(runtime.app().interfaces[reference].descriptor.is_some());
}
let read_reference = file_interfaces[0].clone();
assert_eq!(
runtime.app().interfaces[&read_reference]
.descriptor
.as_ref()
.expect("read descriptor")
.operations[0]
.name,
"read"
);
// Keyboard-select the already prefetched read operation.
runtime.app_mut().selected_path = "/hello.txt".into();
runtime.app_mut().focus = Focus::Operations;
runtime.app_mut().operation_cursor = 1;
assert!(!runtime.handle_key(InputKey::Enter));
// Descriptor-driven read editor, explicit confirmation, and execution.
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
runtime.handle_key(InputKey::Enter);
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
assert!(
runtime.app().history[0]
.detail
.contains("68656c6c6f20776f726c64")
);
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Fresh);
runtime.app_mut().focus = Focus::Operations;
// Use the separately-qualified prefetched write interface and replace with the
// automatically attached observed validator.
runtime.app_mut().operation_cursor = 3;
runtime.handle_key(InputKey::Enter);
set_only_field(&mut runtime, "dXBkYXRlZA=="); // "updated"
confirm_and_execute(&mut runtime);
settle(&mut runtime);
assert_eq!(
std::fs::read(temporary.path().join("hello.txt")).expect("updated file"),
b"updated"
);
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Fresh);
// Prepare another replacement using the post-operation validator, then mutate
// the file externally before explicit execution. The stale validator is rejected,
// the Entry becomes stale, and no automatic call is created.
runtime.app_mut().focus = Focus::Operations;
runtime.app_mut().operation_cursor = 3;
runtime.handle_key(InputKey::Enter);
set_only_field(&mut runtime, "c3RhbGUtd3JpdGU=");
runtime.handle_key(InputKey::Enter); // confirmation fixes user input only
std::fs::write(temporary.path().join("hello.txt"), b"external").expect("external change");
let history_before = runtime.app().history.len();
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
assert_eq!(
std::fs::read(temporary.path().join("hello.txt")).expect("externally changed file"),
b"external"
);
assert_eq!(runtime.app().entries["/hello.txt"].state, ViewState::Stale);
assert!(runtime.app().in_flight.is_empty());
assert_eq!(runtime.app().history.len(), history_before + 1);
assert_eq!(runtime.app().history[0].kind, HistoryKind::DomainFailure);
assert!(
runtime.app().history[0]
.detail
.contains("no automatic retry")
);
// Refresh enables a new, separately confirmed execution.
runtime.app_mut().focus = Focus::Tree;
runtime.handle_key(InputKey::Refresh);
settle(&mut runtime);
runtime.app_mut().focus = Focus::Operations;
runtime.app_mut().operation_cursor = 3;
runtime.handle_key(InputKey::Enter);
set_only_field(&mut runtime, "ZmluYWw=");
confirm_and_execute(&mut runtime);
settle(&mut runtime);
assert_eq!(
std::fs::read(temporary.path().join("hello.txt")).expect("final file"),
b"final"
);
// Symlink inspection exposes the link payload only. It never traverses or
// materializes the target directory outside the configured root.
#[cfg(unix)]
{
runtime.app_mut().selected_path = "/outside-link".into();
runtime.app_mut().focus = Focus::Operations;
runtime.app_mut().operation_cursor = 0;
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
runtime.app_mut().operation_cursor = 1;
runtime.handle_key(InputKey::Enter);
runtime.handle_key(InputKey::Enter);
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
assert_eq!(runtime.app().history[0].kind, HistoryKind::Success);
assert!(!runtime.app().history[0].detail.contains("outside-secret"));
assert!(
!runtime
.app()
.entries
.contains_key("/outside-link/secret.txt")
);
}
shutdown.store(true, Ordering::Release);
worker
.join()
.expect("join filesystem listener")
.expect("filesystem listener exits");
}
fn settle(runtime: &mut Runtime<HttpTransport>) {
let deadline = Instant::now() + Duration::from_secs(5);
while !runtime.app().in_flight.is_empty() {
assert!(Instant::now() < deadline, "runtime requests did not settle");
runtime.wait_and_poll(Duration::from_millis(20));
}
}
fn set_only_field(runtime: &mut Runtime<HttpTransport>, input: &str) {
let Modal::Editor(editor) = &mut runtime.app_mut().modal else {
panic!("operation editor was not open")
};
assert_eq!(editor.fields.len(), 1);
editor.fields[0].input = input.into();
}
fn confirm_and_execute(runtime: &mut Runtime<HttpTransport>) {
runtime.handle_key(InputKey::Enter);
assert!(matches!(runtime.app().modal, Modal::Confirm { .. }));
runtime.handle_key(InputKey::Enter);
}
+329
View File
@@ -0,0 +1,329 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::tempdir;
use wip_fs_server::{ServerConfig, WipFsServer};
use wip_http::encode_protocol_error_response;
use wip_http::http::{Request, Response};
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
use wip_tui::app::{ConnectionState, Focus, HistoryKind, InputKey, Modal, ViewState};
use wip_tui::config::Config;
use wip_tui::runtime::{
Runtime, Transport, TransportError, TransportErrorKind, default_wire_limits,
};
struct ScriptedTransport {
server: Arc<WipFsServer>,
sequence: Arc<AtomicUsize>,
delayed_after_startup: bool,
unknown_calls: bool,
fail_call_prepare: bool,
fail_tree_prepare: bool,
panic_calls: bool,
root_tree_protocol_failures: Arc<AtomicUsize>,
}
impl ScriptedTransport {
fn new(server: Arc<WipFsServer>) -> Self {
Self {
server,
sequence: Arc::new(AtomicUsize::new(0)),
delayed_after_startup: false,
unknown_calls: false,
fail_call_prepare: false,
fail_tree_prepare: false,
panic_calls: false,
root_tree_protocol_failures: Arc::new(AtomicUsize::new(0)),
}
}
}
impl Transport for ScriptedTransport {
type Prepared = Request<Vec<u8>>;
fn prepare(&self, request: Request<Vec<u8>>) -> Result<Self::Prepared, TransportError> {
if self.fail_call_prepare && request.uri().path().ends_with("/v1/call_operation") {
return Err(TransportError {
kind: TransportErrorKind::Disconnect,
detail: "scripted local conversion failure".into(),
});
}
if self.fail_tree_prepare && request.uri().path().ends_with("/v1/observe") {
return Err(TransportError {
kind: TransportErrorKind::Disconnect,
detail: "scripted tree conversion failure".into(),
});
}
Ok(request)
}
fn execute(&self, request: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError> {
let sequence = self.sequence.fetch_add(1, Ordering::AcqRel);
if request.uri().path().ends_with("/v1/observe")
&& self
.root_tree_protocol_failures
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| {
remaining.checked_sub(1)
})
.is_ok()
{
return Ok(encode_protocol_error_response(
ProtocolInteraction::Observe,
&ProtocolError {
code: ProtocolErrorCode::Internal,
message: "scripted startup failure".into(),
},
default_wire_limits(),
)
.expect("encode tree failure"));
}
if self.delayed_after_startup && sequence > 0 {
// Delay the first refresh so the second wins and exercises exact
// RequestId ownership.
let delay = if sequence == 1 { 80 } else { 5 };
thread::sleep(Duration::from_millis(delay));
}
if self.panic_calls && request.uri().path().ends_with("/v1/call_operation") {
panic!("scripted transport worker panic");
}
if self.unknown_calls && request.uri().path().ends_with("/v1/call_operation") {
return Ok(encode_protocol_error_response(
ProtocolInteraction::CallOperation,
&ProtocolError {
code: ProtocolErrorCode::OperationOutcomeUnknown,
message: "scripted commit uncertainty".into(),
},
default_wire_limits(),
)
.expect("encode unknown outcome"));
}
Ok(self.server.handle_http(request))
}
}
#[test]
fn out_of_order_refresh_and_cancel_keep_request_identity_safe() {
let temporary = tempdir().expect("temporary root");
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let mut transport = ScriptedTransport::new(server);
transport.delayed_after_startup = true;
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
runtime.app_mut().focus = Focus::Tree;
runtime.handle_key(InputKey::Refresh);
runtime.handle_key(InputKey::Refresh);
settle(&mut runtime);
assert_eq!(runtime.app().entries["/"].state, ViewState::Fresh);
assert!(runtime.app().history.iter().any(|item| {
item.kind == HistoryKind::Information && item.title.contains("stale response")
}));
runtime.handle_key(InputKey::Refresh);
runtime.handle_key(InputKey::CancelRead);
runtime.handle_key(InputKey::CancelRead);
settle(&mut runtime);
assert!(runtime.app().in_flight.is_empty());
assert!(
runtime
.app()
.history
.iter()
.any(|item| item.title == "retrieval canceled")
);
// When a refreshed tree omits a formerly selected Entry, the client marks
// it stale and the presentation no longer exposes old metadata/operations
// as current.
std::fs::remove_file(temporary.path().join("file")).expect("remove file");
runtime.app_mut().selected_path = "/".into();
runtime.handle_key(InputKey::Refresh);
settle(&mut runtime);
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
runtime.app_mut().selected_path = "/file".into();
assert!(runtime.app().operation_rows().is_empty());
}
#[test]
fn startup_transport_preparation_failure_enters_failed_state() {
let temporary = tempdir().expect("temporary root");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let mut transport = ScriptedTransport::new(server);
transport.fail_tree_prepare = true;
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
assert!(matches!(
runtime.app().connection,
ConnectionState::Failed(ref detail) if detail.contains("scripted tree conversion failure")
));
assert!(runtime.app().status.contains("press R to reconnect"));
assert!(runtime.app().in_flight.is_empty());
}
#[test]
fn startup_protocol_failure_enters_failed_state_and_reconnects() {
let temporary = tempdir().expect("temporary root");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let transport = ScriptedTransport::new(server);
transport
.root_tree_protocol_failures
.store(1, Ordering::Release);
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
assert!(matches!(
runtime.app().connection,
ConnectionState::Failed(ref detail) if detail.contains("scripted startup failure")
));
assert!(runtime.app().status.contains("press R to reconnect"));
assert!(runtime.app().history.iter().any(|item| {
item.kind == HistoryKind::DomainFailure && item.detail.contains("scripted startup failure")
}));
runtime.handle_key(InputKey::Reconnect);
settle(&mut runtime);
assert_eq!(runtime.app().connection, ConnectionState::Connected);
}
#[test]
fn local_transport_preparation_failure_is_definitely_not_dispatched() {
let temporary = tempdir().expect("temporary root");
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let mut transport = ScriptedTransport::new(server);
transport.fail_call_prepare = true;
let execute_calls = Arc::clone(&transport.sequence);
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
open_read_editor(&mut runtime);
let calls_before_operation = execute_calls.load(Ordering::Acquire);
runtime.handle_key(InputKey::Enter);
runtime.handle_key(InputKey::Enter);
assert_eq!(
execute_calls.load(Ordering::Acquire),
calls_before_operation,
"preparation failure must not invoke transport I/O"
);
assert!(runtime.app().in_flight.is_empty());
assert_eq!(runtime.app().history[0].kind, HistoryKind::TransportFailure);
assert!(runtime.app().history[0].detail.contains("not dispatched"));
assert_eq!(
runtime.app().status,
"operation not dispatched; not executed"
);
assert_eq!(runtime.app().entries["/file"].state, ViewState::Fresh);
}
#[test]
fn worker_panic_settles_as_unknown_instead_of_stranding_the_main_loop() {
let temporary = tempdir().expect("temporary root");
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let mut transport = ScriptedTransport::new(server);
transport.panic_calls = true;
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
open_read_editor(&mut runtime);
runtime.handle_key(InputKey::Enter);
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
assert!(runtime.app().in_flight.is_empty());
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
assert!(
runtime.app().history[0]
.detail
.contains("transport worker failed")
);
}
#[test]
fn post_dispatch_unknown_is_prominent_stale_and_never_retried() {
let temporary = tempdir().expect("temporary root");
std::fs::write(temporary.path().join("file"), b"contents").expect("file");
let server = Arc::new(
WipFsServer::new(ServerConfig::for_root(temporary.path())).expect("filesystem server"),
);
let mut transport = ScriptedTransport::new(server);
transport.unknown_calls = true;
let config = config();
let mut runtime = Runtime::new(&config, transport).expect("runtime");
runtime.connect();
settle(&mut runtime);
open_read_editor(&mut runtime);
runtime.handle_key(InputKey::Enter);
runtime.handle_key(InputKey::Enter);
settle(&mut runtime);
assert_eq!(runtime.app().history[0].kind, HistoryKind::OutcomeUnknown);
assert!(
runtime.app().history[0]
.detail
.contains("side effects are unknown")
);
assert_eq!(runtime.app().entries["/file"].state, ViewState::Stale);
assert!(runtime.app().in_flight.is_empty());
let history = runtime.app().history.len();
thread::sleep(Duration::from_millis(20));
runtime.poll();
assert_eq!(
runtime.app().history.len(),
history,
"no retry was manufactured"
);
}
fn config() -> Config {
Config::parse(
["https://example.test/wip"],
None,
Some("scripted-test".into()),
|_| None,
)
.expect("config")
}
fn open_read_editor(runtime: &mut Runtime<ScriptedTransport>) {
runtime.app_mut().selected_path = "/file".into();
runtime.app_mut().focus = Focus::Operations;
runtime.app_mut().operation_cursor = 0;
runtime.handle_key(InputKey::Enter);
settle(runtime);
runtime.app_mut().operation_cursor = 1;
runtime.handle_key(InputKey::Enter);
assert!(matches!(runtime.app().modal, Modal::Editor(_)));
}
fn settle(runtime: &mut Runtime<ScriptedTransport>) {
let deadline = Instant::now() + Duration::from_secs(5);
while !runtime.app().in_flight.is_empty() {
assert!(Instant::now() < deadline, "scripted runtime did not settle");
runtime.wait_and_poll(Duration::from_millis(10));
}
}