Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1998fb8fd | ||
|
|
b4e38fc2c2 | ||
|
|
f207b71f83 | ||
|
|
e5162339e9 | ||
|
|
20b3986ab6 | ||
|
|
2da2a28a67 | ||
|
|
96db3dd6a8 | ||
|
|
625f4c148d | ||
|
|
beeffae9c5 | ||
|
|
56923c1160 | ||
|
|
6de58da17d | ||
|
|
027555eb4e | ||
|
|
75119f23e5 |
Generated
+321
@@ -2,12 +2,44 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.22.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes"
|
||||||
|
version = "1.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "displaydoc"
|
||||||
|
version = "0.2.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "equivalent"
|
name = "equivalent"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "form_urlencoded"
|
||||||
|
version = "1.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||||
|
dependencies = [
|
||||||
|
"percent-encoding",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "glob"
|
name = "glob"
|
||||||
version = "0.3.4"
|
version = "0.3.4"
|
||||||
@@ -20,6 +52,120 @@ version = "0.17.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "http"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"itoa",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_collections"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"potential_utf",
|
||||||
|
"utf8_iter",
|
||||||
|
"yoke",
|
||||||
|
"zerofrom",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_locale_core"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"litemap",
|
||||||
|
"tinystr",
|
||||||
|
"writeable",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_normalizer"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
|
||||||
|
dependencies = [
|
||||||
|
"icu_collections",
|
||||||
|
"icu_normalizer_data",
|
||||||
|
"icu_properties",
|
||||||
|
"icu_provider",
|
||||||
|
"smallvec",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_normalizer_data"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_properties"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"icu_collections",
|
||||||
|
"icu_locale_core",
|
||||||
|
"icu_properties_data",
|
||||||
|
"icu_provider",
|
||||||
|
"zerotrie",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_properties_data"
|
||||||
|
version = "2.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "icu_provider"
|
||||||
|
version = "2.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"icu_locale_core",
|
||||||
|
"writeable",
|
||||||
|
"yoke",
|
||||||
|
"zerofrom",
|
||||||
|
"zerotrie",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "idna"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
|
||||||
|
dependencies = [
|
||||||
|
"idna_adapter",
|
||||||
|
"smallvec",
|
||||||
|
"utf8_iter",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "idna_adapter"
|
||||||
|
version = "1.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
|
||||||
|
dependencies = [
|
||||||
|
"icu_normalizer",
|
||||||
|
"icu_properties",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "indexmap"
|
name = "indexmap"
|
||||||
version = "2.14.2"
|
version = "2.14.2"
|
||||||
@@ -36,12 +182,33 @@ version = "1.0.18"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "litemap"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memchr"
|
name = "memchr"
|
||||||
version = "2.8.3"
|
version = "2.8.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "percent-encoding"
|
||||||
|
version = "2.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "potential_utf"
|
||||||
|
version = "0.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
|
||||||
|
dependencies = [
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proc-macro2"
|
name = "proc-macro2"
|
||||||
version = "1.0.107"
|
version = "1.0.107"
|
||||||
@@ -111,6 +278,18 @@ dependencies = [
|
|||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.16.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "stable_deref_trait"
|
||||||
|
version = "1.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.119"
|
version = "2.0.119"
|
||||||
@@ -133,6 +312,17 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "synstructure"
|
||||||
|
version = "0.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "target-tuple"
|
name = "target-tuple"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -148,6 +338,16 @@ dependencies = [
|
|||||||
"winapi-util",
|
"winapi-util",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tinystr"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"zerovec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml"
|
name = "toml"
|
||||||
version = "1.1.6+spec-1.1.0"
|
version = "1.1.6+spec-1.1.0"
|
||||||
@@ -208,6 +408,24 @@ version = "1.0.26"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "url"
|
||||||
|
version = "2.5.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||||
|
dependencies = [
|
||||||
|
"form_urlencoded",
|
||||||
|
"idna",
|
||||||
|
"percent-encoding",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8_iter"
|
||||||
|
version = "1.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi-util"
|
name = "winapi-util"
|
||||||
version = "0.1.11"
|
version = "0.1.11"
|
||||||
@@ -238,6 +456,14 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wip-client"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"wip-https",
|
||||||
|
"wip-protocol",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wip-host"
|
name = "wip-host"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -247,6 +473,18 @@ dependencies = [
|
|||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wip-https"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"http",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"url",
|
||||||
|
"wip-protocol",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wip-interface"
|
name = "wip-interface"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -278,6 +516,89 @@ dependencies = [
|
|||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "writeable"
|
||||||
|
version = "0.6.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yoke"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
||||||
|
dependencies = [
|
||||||
|
"stable_deref_trait",
|
||||||
|
"yoke-derive",
|
||||||
|
"zerofrom",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yoke-derive"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
"synstructure",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerofrom"
|
||||||
|
version = "0.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||||
|
dependencies = [
|
||||||
|
"zerofrom-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerofrom-derive"
|
||||||
|
version = "0.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
"synstructure",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerotrie"
|
||||||
|
version = "0.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||||
|
dependencies = [
|
||||||
|
"displaydoc",
|
||||||
|
"yoke",
|
||||||
|
"zerofrom",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerovec"
|
||||||
|
version = "0.11.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
|
||||||
|
dependencies = [
|
||||||
|
"yoke",
|
||||||
|
"zerofrom",
|
||||||
|
"zerovec-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerovec-derive"
|
||||||
|
version = "0.11.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.6",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zmij"
|
name = "zmij"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
|
|||||||
+1
-20
@@ -1,22 +1,3 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = ["crates/*"]
|
||||||
".",
|
|
||||||
"crates/wip-host",
|
|
||||||
"crates/wip-interface",
|
|
||||||
"crates/wip-interface-macros",
|
|
||||||
"crates/wip-protocol",
|
|
||||||
]
|
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[package]
|
|
||||||
name = "wip-public-api-example"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
description = "End-to-end example of the public WIP Rust APIs"
|
|
||||||
license = "MIT OR Apache-2.0"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
wip-host = { path = "crates/wip-host" }
|
|
||||||
wip-interface = { path = "crates/wip-interface" }
|
|
||||||
wip-protocol = { path = "crates/wip-protocol" }
|
|
||||||
|
|||||||
@@ -2,15 +2,22 @@
|
|||||||
|
|
||||||
Rust building blocks for the Web Interface Protocol (WIP).
|
Rust building blocks for the Web Interface Protocol (WIP).
|
||||||
|
|
||||||
The repository currently provides a transport-independent protocol model, a
|
The repository is a resolver-3 virtual Cargo workspace whose packages all live
|
||||||
Rust interface-authoring facade, and a request-scoped host runtime. HTTP and
|
under `crates/*`. It provides a transport-independent protocol model, the
|
||||||
other transport bindings are intentionally outside the supported slice.
|
standard framework-independent WIP over HTTPS v1 binding, a stateful
|
||||||
|
presentation-independent client runtime, a Rust interface-authoring facade, a
|
||||||
|
request-scoped host runtime, and a private public-API conformance consumer. The
|
||||||
|
repository root is not itself a package.
|
||||||
## Crate graph and responsibilities
|
## Crate graph and responsibilities
|
||||||
|
|
||||||
```text
|
```text
|
||||||
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
||||||
├── wip-protocol logical declarations, values, calls, and validation
|
├── wip-protocol logical declarations, values, calls, and validation
|
||||||
|
├── wip-https standard HTTPS v1 routes, JSON codecs, envelopes, and batching
|
||||||
|
│ └── wip-protocol
|
||||||
|
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
|
||||||
|
│ ├── wip-https
|
||||||
|
│ └── wip-protocol
|
||||||
├── wip-interface application DTO codecs and interface authoring facade
|
├── wip-interface application DTO codecs and interface authoring facade
|
||||||
│ ├── wip-protocol
|
│ ├── wip-protocol
|
||||||
│ └── wip-interface-macros proc-macro implementation detail
|
│ └── wip-interface-macros proc-macro implementation detail
|
||||||
@@ -22,33 +29,42 @@ wip-public-api-example (workspace-only executable, integration tests, doctest)
|
|||||||
| Crate | Responsibility | Does not own |
|
| Crate | Responsibility | Does not own |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
||||||
|
| `wip-https` | Standard HTTPS v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, TLS termination, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
||||||
|
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, lazy entry trees, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
||||||
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
||||||
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
||||||
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, and interface-qualified dispatch against one host-owned instance. | Backend atomicity, global object lookup, or network serving. |
|
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, and interface-qualified dispatch against one host-owned instance. | Backend atomicity, global object lookup, or network serving. |
|
||||||
| `wip-public-api-example` | An independently compiled consumer of only the three public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
|
| `wip-public-api-example` | An independently compiled consumer of the protocol, authoring, and host public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
|
||||||
|
|
||||||
The boundary is intentional: protocol types describe what can cross a
|
The boundary is intentional: protocol types describe what can cross a
|
||||||
transport; application DTOs opt into that model with `WipType`; a host-private
|
transport; application DTOs opt into that model with `WipType`; a host-private
|
||||||
implementation owns credentials, handles, and backend state; and a future
|
implementation owns credentials, handles, and backend state; and `wip-https`
|
||||||
transport maps its own routes/envelopes to `CallOperationRequest` and
|
maps standard routes/envelopes to `CallOperationRequest` and
|
||||||
`CallOperationResponse` without placing transport-specific types in descriptors
|
`CallOperationResponse` without placing transport-specific types in descriptors
|
||||||
or application traits.
|
or application traits.
|
||||||
|
|
||||||
## End-to-end example
|
## End-to-end example
|
||||||
|
|
||||||
[`src/lib.rs`](src/lib.rs) is the complete public-API example and
|
[`crates/wip-public-api-example/src/lib.rs`](crates/wip-public-api-example/src/lib.rs)
|
||||||
[`src/main.rs`](src/main.rs) runs it. It demonstrates all of the following:
|
is the complete public-API example and
|
||||||
|
[`crates/wip-public-api-example/src/main.rs`](crates/wip-public-api-example/src/main.rs)
|
||||||
|
runs it. It demonstrates all of the following:
|
||||||
|
|
||||||
1. public application DTOs derived as `WipType` records and unions;
|
1. public application DTOs derived as `WipType` records, enums, and unions,
|
||||||
|
including canonical entry paths and schema-opaque JSON;
|
||||||
2. two public traits declared with `#[wip::interface]`;
|
2. two public traits declared with `#[wip::interface]`;
|
||||||
3. a private host struct implementing both traits;
|
3. a private host struct implementing both traits;
|
||||||
4. explicit publication of both interfaces on one object;
|
4. explicit publication of both interfaces as an ordered set on one object;
|
||||||
5. registry observation and validation of generated descriptors;
|
5. separate observation of opaque interface references, descriptors, and
|
||||||
6. calls made with interface references, operation names, and `Value` arguments;
|
descriptor validators;
|
||||||
|
6. calls qualified by `target.path`, object validator, interface reference and
|
||||||
|
validator, operation, and schema-neutral `Value` arguments;
|
||||||
7. validated result values decoded back to the typed application result;
|
7. validated result values decoded back to the typed application result;
|
||||||
8. independent dispatch of the same `status` operation name on both interfaces;
|
8. independent dispatch of the same `status` operation name on both interfaces;
|
||||||
9. a domain rejection returned as data and a backend failure returned as a host
|
9. distinct domain rejection, rollback-confirmed and outcome-unknown
|
||||||
error.
|
host/backend failures, `PermissionDenied`, stale validator recovery, interface
|
||||||
|
membership, and lookup failure codes; and
|
||||||
|
10. canonical failure precedence when several request fields are invalid.
|
||||||
|
|
||||||
Run it inside the development shell:
|
Run it inside the development shell:
|
||||||
|
|
||||||
@@ -57,10 +73,17 @@ nix develop
|
|||||||
cargo run --package wip-public-api-example
|
cargo run --package wip-public-api-example
|
||||||
```
|
```
|
||||||
|
|
||||||
The normal integration test is in [`tests/end_to_end.rs`](tests/end_to_end.rs).
|
The public-only conformance suite is in
|
||||||
Unit tests beside the example additionally cover every host dispatch failure,
|
[`crates/wip-public-api-example/tests/end_to_end.rs`](crates/wip-public-api-example/tests/end_to_end.rs).
|
||||||
invalid arguments and results, interface membership, validators, and
|
It covers canonical object/descriptor shape, ordered interfaces,
|
||||||
same-named operations.
|
schema-neutral record/enum/union/entry/JSON values, fully qualified calls, and
|
||||||
|
the distinct domain, host, authorization, validator-recovery, and interface
|
||||||
|
failure classes. Exhaustive public type construction and matching make legacy
|
||||||
|
ObjectId, descriptor `name`, and semantic `Value` variants compile-time
|
||||||
|
regressions. Unit tests in the public crates additionally cover every host
|
||||||
|
dispatch failure, `InvalidRequest` versus descriptor-bound `InvalidArguments`,
|
||||||
|
invalid local responses, validators, same-named operations, and exhaustive
|
||||||
|
per-interaction protocol error-code sets.
|
||||||
|
|
||||||
## Interface authoring
|
## Interface authoring
|
||||||
|
|
||||||
@@ -185,19 +208,39 @@ are never projected by `WipObject`; host-private fields and backend handles are
|
|||||||
also excluded.
|
also excluded.
|
||||||
|
|
||||||
Application domain failures belong in a derived result union and are returned
|
Application domain failures belong in a derived result union and are returned
|
||||||
through `Ok`. `wip::HostError` is reserved for runtime/backend failures. Invalid
|
through `Ok`. `wip::HostError` is reserved for runtime/backend failures. A
|
||||||
arguments are rejected before invocation; malformed encoded results are
|
structurally malformed call is `InvalidRequest`; only argument values checked
|
||||||
reported as `InvalidResult` and never returned as application data. Validator,
|
after the current Interface Descriptor is fixed are `InvalidArguments`. A Host
|
||||||
membership, authorization, and result failures retain their distinct canonical
|
must never return a wire `InvalidResult`: Clients keep invalid Object,
|
||||||
protocol error codes.
|
Descriptor, operation-result, and error responses as local `InvalidResponse`
|
||||||
|
failures, while unsupported descriptor formats remain local
|
||||||
|
`UnsupportedDescriptorFormat` failures.
|
||||||
|
|
||||||
Providers remain responsible for backend atomicity. Enter a transaction, lock,
|
For operation calls, `Internal` and `ResourceLimitExceeded` guarantee that the
|
||||||
stable-handle scope, or conditional-update primitive before invoking the
|
operation did not run or that its effects were rolled back.
|
||||||
`with_object` callback, and retain it until the callback returns. Mutable
|
`OperationOutcomeUnknown` is the only protocol code that makes no such
|
||||||
operations must make validator comparison and backend commit atomic and return a
|
guarantee, so Clients must not automatically retry it. `wip::HostError`
|
||||||
validator for the committed state. The runtime never validates one object and
|
therefore requires both a `HostErrorKind` and an `EffectGuarantee`; implementation
|
||||||
then resolves a second snapshot, but it cannot make an arbitrary external
|
panic, result encoding, and result validation default to an unknown outcome.
|
||||||
backend atomic by itself.
|
Host-private diagnostics are bounded locally but never copied into protocol
|
||||||
|
messages.
|
||||||
|
|
||||||
|
`ExecutionContext` carries a runtime-neutral cancellation token, monotonic
|
||||||
|
deadline, and optional Host-defined resource budget through resolution and
|
||||||
|
execution. Cancellation and deadlines are cooperative: the runtime checks them
|
||||||
|
immediately before typed invocation, while providers enforce them during backend
|
||||||
|
work. A pre-invocation limit failure is `ResourceLimitExceeded`; after invocation
|
||||||
|
it is safe to use that code only when non-commit or rollback is confirmed.
|
||||||
|
|
||||||
|
Providers remain responsible for backend atomicity. `with_object` returns a typed
|
||||||
|
`ProviderResult`, and `execute_operation` receives an `OperationAttempt` that
|
||||||
|
separates `NotStarted` from `Started`. A transactional provider holds its
|
||||||
|
transaction across the callback, commits successful attempts, and may call
|
||||||
|
`OperationAttempt::confirm_rollback` only after every operation effect has been
|
||||||
|
rolled back. Without that proof, post-invocation failures remain
|
||||||
|
`OperationOutcomeUnknown`. Mutable operations must still make validator
|
||||||
|
comparison and backend commit atomic and return a validator describing the state
|
||||||
|
that becomes committed.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
@@ -208,10 +251,14 @@ nix develop
|
|||||||
cargo fmt --all -- --check
|
cargo fmt --all -- --check
|
||||||
cargo check --workspace --all-targets
|
cargo check --workspace --all-targets
|
||||||
cargo test --workspace --all-targets
|
cargo test --workspace --all-targets
|
||||||
|
cargo test --workspace --doc
|
||||||
cargo clippy --workspace --all-targets -- -D warnings
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps
|
||||||
|
cargo run --package wip-public-api-example
|
||||||
|
git diff --check
|
||||||
```
|
```
|
||||||
|
|
||||||
`cargo test --workspace --all-targets` includes the public example integration
|
`cargo test --workspace --all-targets` includes the public-only conformance
|
||||||
test, runtime failure tests, and `trybuild` compile-fail suites. Run
|
consumer, runtime failure tests, and `trybuild` compile-fail suites. The separate
|
||||||
`cargo test --workspace --doc` when validating the checked rustdoc examples
|
doctest, rustdoc, executable, and whitespace checks are all required acceptance
|
||||||
separately.
|
steps.
|
||||||
|
|||||||
@@ -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-https = { path = "../wip-https" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,247 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use wip_client::{
|
||||||
|
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
|
||||||
|
ObservationState, OutcomeUnknownReason, SecurityContext,
|
||||||
|
};
|
||||||
|
use wip_https::http::{Response, StatusCode};
|
||||||
|
use wip_https::{
|
||||||
|
Limits, encode_fetch_interface_response, encode_fetch_response, encode_protocol_error_response,
|
||||||
|
};
|
||||||
|
use wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, FetchRequest, INTERFACE_FORMAT_V1,
|
||||||
|
InterfaceDescriptor, Object, 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.prepare_fetch(&session, "/item").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.prepare_fetch(&session, "/item").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.prepare_fetch(&session, "/item").unwrap();
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Fetch, &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.prepare_fetch(&session, "/item").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 fetch = client.prepare_fetch(&session, "/item").unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
fetch.id,
|
||||||
|
encode_fetch_response(
|
||||||
|
&FetchRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
},
|
||||||
|
&object(),
|
||||||
|
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
+489
-81
@@ -18,11 +18,14 @@
|
|||||||
//!
|
//!
|
||||||
//! A provider is responsible for entering a backend transaction, lock,
|
//! A provider is responsible for entering a backend transaction, lock,
|
||||||
//! stable-handle scope, or conditional-update primitive before invoking the
|
//! stable-handle scope, or conditional-update primitive before invoking the
|
||||||
//! callback and retaining it until the callback returns. The runtime does not
|
//! operation callback and retaining it through commit or rollback. The typed
|
||||||
//! reopen the path or select another implementation after checking validators,
|
//! [`OperationAttempt`] boundary distinguishes pre-dispatch rejection from started
|
||||||
//! but cannot make an arbitrary external backend atomic on its own. Mutable
|
//! execution. Only an implementation-supplied non-commit guarantee or a
|
||||||
//! operations must make object-validator comparison and backend commit atomic;
|
//! provider-confirmed rollback allows a post-invocation failure to become
|
||||||
//! the validator returned after dispatch must describe the committed state.
|
//! `Internal` or `ResourceLimitExceeded`; every other outcome is
|
||||||
|
//! `OperationOutcomeUnknown`. Mutable operations must make object-validator
|
||||||
|
//! comparison and backend commit atomic, and the validator returned after dispatch
|
||||||
|
//! must describe the state that becomes committed.
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
@@ -31,19 +34,23 @@ use std::collections::{BTreeMap, HashMap, HashSet};
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
use wip_interface::DispatchError;
|
use wip_interface::DispatchError;
|
||||||
pub use wip_interface::{InterfaceDefinition, InterfaceImplementation};
|
pub use wip_interface::{
|
||||||
|
EffectGuarantee, HostError, HostErrorKind, InterfaceDefinition, InterfaceImplementation,
|
||||||
|
};
|
||||||
pub use wip_protocol;
|
pub use wip_protocol;
|
||||||
pub use wip_protocol::{
|
pub use wip_protocol::{
|
||||||
CallOperationRequest as CallRequest, CallOperationResponse as CallResult, InterfaceTarget,
|
CallOperationRequest as CallRequest, CallOperationResponse as CallResult, InterfaceTarget,
|
||||||
Target,
|
Target,
|
||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
FetchInterfaceResponse, InterfaceDescriptor, Object, ProtocolError, ProtocolErrorCode,
|
FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor, Object, ProtocolError,
|
||||||
ValidationError, Value,
|
ProtocolErrorCode, ValidationError, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Opaque bytes used as a conditional execution precondition.
|
/// Opaque bytes used as a conditional execution precondition.
|
||||||
@@ -64,6 +71,122 @@ impl Validator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Runtime-neutral cooperative cancellation signal.
|
||||||
|
///
|
||||||
|
/// Clones observe the same atomic state, so transports, providers, and worker
|
||||||
|
/// runtimes can share the token without depending on a particular async runtime.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct CancellationToken(Arc<AtomicBool>);
|
||||||
|
|
||||||
|
impl CancellationToken {
|
||||||
|
/// Creates a cancellation token in the active state.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Requests cooperative cancellation.
|
||||||
|
pub fn cancel(&self) {
|
||||||
|
self.0.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns whether cancellation has been requested.
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_cancelled(&self) -> bool {
|
||||||
|
self.0.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execution controls propagated through object resolution and operation dispatch.
|
||||||
|
///
|
||||||
|
/// Cancellation and deadlines are checked immediately before typed implementation
|
||||||
|
/// invocation. Providers also receive the complete context and remain responsible
|
||||||
|
/// for enforcing controls while backend work is in progress. `resource_budget` is
|
||||||
|
/// an opaque Host-defined work-unit ceiling; this crate deliberately does not
|
||||||
|
/// prescribe an async runtime or accounting mechanism.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ExecutionContext {
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
deadline: Option<Instant>,
|
||||||
|
resource_budget: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ExecutionContext {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
cancellation: CancellationToken::new(),
|
||||||
|
deadline: None,
|
||||||
|
resource_budget: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExecutionContext {
|
||||||
|
/// Creates an execution context without a deadline or resource budget.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uses `cancellation` as this call's cooperative cancellation signal.
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_cancellation(mut self, cancellation: CancellationToken) -> Self {
|
||||||
|
self.cancellation = cancellation;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the monotonic deadline for this call.
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_deadline(mut self, deadline: Instant) -> Self {
|
||||||
|
self.deadline = Some(deadline);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets an opaque Host-defined work-unit ceiling for this call.
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_resource_budget(mut self, resource_budget: u64) -> Self {
|
||||||
|
self.resource_budget = Some(resource_budget);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the shared cooperative cancellation token.
|
||||||
|
#[must_use]
|
||||||
|
pub fn cancellation(&self) -> &CancellationToken {
|
||||||
|
&self.cancellation
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the monotonic deadline, if one was supplied.
|
||||||
|
#[must_use]
|
||||||
|
pub fn deadline(&self) -> Option<Instant> {
|
||||||
|
self.deadline
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the opaque Host-defined work-unit ceiling, if one was supplied.
|
||||||
|
#[must_use]
|
||||||
|
pub fn resource_budget(&self) -> Option<u64> {
|
||||||
|
self.resource_budget
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preflight(&self) -> Result<(), CallError> {
|
||||||
|
if self.cancellation.is_cancelled() {
|
||||||
|
return Err(CallError::new(
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
"operation was cancelled before execution",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.deadline
|
||||||
|
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||||
|
{
|
||||||
|
return Err(CallError::new(
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
"operation deadline elapsed before execution",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Opaque host-assigned reference to one registered interface artifact.
|
/// Opaque host-assigned reference to one registered interface artifact.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct InterfaceRef(String);
|
pub struct InterfaceRef(String);
|
||||||
@@ -88,14 +211,26 @@ pub struct InterfaceObservation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl InterfaceObservation {
|
impl InterfaceObservation {
|
||||||
/// Converts this host observation to the canonical protocol response.
|
/// Converts this host observation to a validated canonical protocol response.
|
||||||
#[must_use]
|
///
|
||||||
pub fn protocol_response(&self) -> FetchInterfaceResponse {
|
/// A Host-side response construction failure is returned as `Internal`; it is
|
||||||
FetchInterfaceResponse {
|
/// never emitted as a successful response for a Client to reinterpret as a
|
||||||
|
/// local validation error.
|
||||||
|
pub fn protocol_response(&self) -> Result<FetchInterfaceResponse, ProtocolError> {
|
||||||
|
let response = FetchInterfaceResponse {
|
||||||
interface: self.reference.0.clone(),
|
interface: self.reference.0.clone(),
|
||||||
descriptor: self.descriptor.clone(),
|
descriptor: self.descriptor.clone(),
|
||||||
validator: self.validator.as_ref().map(|validator| validator.0.clone()),
|
validator: self.validator.as_ref().map(|validator| validator.0.clone()),
|
||||||
}
|
};
|
||||||
|
response
|
||||||
|
.validate_for(&FetchInterfaceRequest {
|
||||||
|
interface: self.reference.0.clone(),
|
||||||
|
})
|
||||||
|
.map_err(|_| ProtocolError {
|
||||||
|
code: ProtocolErrorCode::Internal,
|
||||||
|
message: "Host produced an invalid interface response".into(),
|
||||||
|
})?;
|
||||||
|
Ok(response)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,26 +532,29 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
|
|
||||||
fn dispatch_resolved(
|
fn dispatch_resolved(
|
||||||
&self,
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
request: CallRequest,
|
request: CallRequest,
|
||||||
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
|
authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
|
||||||
) -> Result<CallResult, CallError> {
|
) -> OperationAttempt {
|
||||||
|
let pre_dispatch_failure =
|
||||||
|
|kind, message: &str| OperationAttempt::NotStarted(CallError::new(kind, message));
|
||||||
let current_object_validator = self.implementation.validator();
|
let current_object_validator = self.implementation.validator();
|
||||||
if let Some(supplied) = request.target.validator.as_deref()
|
if let Some(supplied) = request.target.validator.as_deref()
|
||||||
&& current_object_validator.map(Validator::as_bytes) != Some(supplied)
|
&& current_object_validator.map(Validator::as_bytes) != Some(supplied)
|
||||||
{
|
{
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::ValidatorMismatch,
|
CallErrorKind::ValidatorMismatch,
|
||||||
"object validator does not match current object state",
|
"object validator does not match current object state",
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(bound) = self.interfaces.iter().find(|bound| {
|
let Some(bound) = self.interfaces.iter().find(|bound| {
|
||||||
bound.artifact.reference.as_str() == request.interface.reference.as_str()
|
bound.artifact.reference.as_str() == request.interface.reference.as_str()
|
||||||
}) else {
|
}) else {
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::InterfaceMismatch,
|
CallErrorKind::InterfaceMismatch,
|
||||||
"interface is not a member of the current object publication",
|
"interface is not a member of the current object publication",
|
||||||
));
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
match (
|
match (
|
||||||
@@ -424,16 +562,16 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
request.interface.validator.as_deref(),
|
request.interface.validator.as_deref(),
|
||||||
) {
|
) {
|
||||||
(Some(_), None) => {
|
(Some(_), None) => {
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::InterfaceValidatorRequired,
|
CallErrorKind::InterfaceValidatorRequired,
|
||||||
"registered interface requires a validator",
|
"registered interface requires a validator",
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
(expected, Some(actual)) if expected.map(Validator::as_bytes) != Some(actual) => {
|
(expected, Some(actual)) if expected.map(Validator::as_bytes) != Some(actual) => {
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::InterfaceValidatorMismatch,
|
CallErrorKind::InterfaceValidatorMismatch,
|
||||||
"interface validator does not match the registered descriptor",
|
"interface validator does not match the registered descriptor",
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@@ -445,10 +583,10 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|operation| operation.name == request.operation)
|
.any(|operation| operation.name == request.operation)
|
||||||
{
|
{
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::OperationNotFound,
|
CallErrorKind::OperationNotFound,
|
||||||
format!("operation `{}` is not declared", request.operation),
|
&format!("operation `{}` is not declared", request.operation),
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if request.target.validator.is_none()
|
if request.target.validator.is_none()
|
||||||
@@ -456,45 +594,67 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
.implementation
|
.implementation
|
||||||
.requires_validator(&bound.artifact.reference, &request.operation)
|
.requires_validator(&bound.artifact.reference, &request.operation)
|
||||||
{
|
{
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::ValidatorRequired,
|
CallErrorKind::ValidatorRequired,
|
||||||
"this operation requires an object validator",
|
"this operation requires an object validator",
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bound
|
if let Err(error) = bound
|
||||||
.artifact
|
.artifact
|
||||||
.descriptor
|
.descriptor
|
||||||
.validate_arguments(&request.operation, &request.arguments)
|
.validate_arguments(&request.operation, &request.arguments)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidArguments, error.to_string()))?;
|
{
|
||||||
|
return pre_dispatch_failure(CallErrorKind::InvalidArguments, &error.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
if !authorize(
|
if !authorize(
|
||||||
&self.implementation,
|
&self.implementation,
|
||||||
&bound.artifact.reference,
|
&bound.artifact.reference,
|
||||||
&request.operation,
|
&request.operation,
|
||||||
) {
|
) {
|
||||||
return Err(CallError::new(
|
return pre_dispatch_failure(
|
||||||
CallErrorKind::PermissionDenied,
|
CallErrorKind::PermissionDenied,
|
||||||
"operation is not permitted for this caller",
|
"operation is not permitted for this caller",
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let value = (bound.dispatch)(&self.implementation, &request.operation, request.arguments)
|
if let Err(error) = context.preflight() {
|
||||||
.map_err(CallError::from_dispatch)?;
|
return OperationAttempt::NotStarted(error);
|
||||||
|
}
|
||||||
|
|
||||||
bound
|
let value =
|
||||||
|
match (bound.dispatch)(&self.implementation, &request.operation, request.arguments) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(
|
||||||
|
error @ (DispatchError::UnknownOperation(_)
|
||||||
|
| DispatchError::InvalidArguments(_)
|
||||||
|
| DispatchError::Decode(_)),
|
||||||
|
) => return OperationAttempt::NotStarted(CallError::from_pre_dispatch(error)),
|
||||||
|
Err(error) => {
|
||||||
|
return OperationAttempt::Started(Err(OperationFailure::from_dispatch(error)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if bound
|
||||||
.artifact
|
.artifact
|
||||||
.descriptor
|
.descriptor
|
||||||
.validate_result(&request.operation, &value)
|
.validate_result(&request.operation, &value)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidResult, error.to_string()))?;
|
.is_err()
|
||||||
|
{
|
||||||
|
return OperationAttempt::Started(Err(OperationFailure::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"operation implementation produced an invalid result",
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(CallResult {
|
OperationAttempt::Started(Ok(CallResult {
|
||||||
result: value,
|
result: value,
|
||||||
validator: self
|
validator: self
|
||||||
.implementation
|
.implementation
|
||||||
.validator()
|
.validator()
|
||||||
.map(|validator| validator.0.clone()),
|
.map(|validator| validator.0.clone()),
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Consumes the publication and returns its host-private implementation.
|
/// Consumes the publication and returns its host-private implementation.
|
||||||
@@ -504,24 +664,158 @@ impl<T: WipObject> PublishedObject<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A post-invocation failure awaiting final provider effect disposition.
|
||||||
|
///
|
||||||
|
/// Providers may upgrade an unknown failure with [`confirm_rollback`](Self::confirm_rollback)
|
||||||
|
/// only after the backend transaction has definitely rolled back. Diagnostics are
|
||||||
|
/// intentionally generic and safe for protocol exposure.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct OperationFailure {
|
||||||
|
kind: HostErrorKind,
|
||||||
|
effect_guarantee: EffectGuarantee,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperationFailure {
|
||||||
|
fn internal(effect_guarantee: EffectGuarantee, message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: HostErrorKind::Internal,
|
||||||
|
effect_guarantee,
|
||||||
|
message: bounded_message(message.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_dispatch(error: DispatchError) -> Self {
|
||||||
|
match error {
|
||||||
|
DispatchError::Host(error) => Self {
|
||||||
|
kind: error.kind(),
|
||||||
|
effect_guarantee: error.effect_guarantee(),
|
||||||
|
message: match error.kind() {
|
||||||
|
HostErrorKind::Internal => "operation implementation failed".into(),
|
||||||
|
HostErrorKind::ResourceLimitExceeded => {
|
||||||
|
"operation resource limit was exceeded".into()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
DispatchError::Panic => Self::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"operation implementation panicked",
|
||||||
|
),
|
||||||
|
DispatchError::Encode(_) => Self::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"operation result could not be encoded",
|
||||||
|
),
|
||||||
|
DispatchError::InvalidResult(_) => Self::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"operation implementation produced an invalid result",
|
||||||
|
),
|
||||||
|
DispatchError::UnknownOperation(_)
|
||||||
|
| DispatchError::InvalidArguments(_)
|
||||||
|
| DispatchError::Decode(_) => {
|
||||||
|
unreachable!("pre-dispatch failures are classified before OperationFailure")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the Host failure category used when effects are not committed.
|
||||||
|
#[must_use]
|
||||||
|
pub fn kind(&self) -> HostErrorKind {
|
||||||
|
self.kind
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the current effect guarantee.
|
||||||
|
#[must_use]
|
||||||
|
pub fn effect_guarantee(&self) -> EffectGuarantee {
|
||||||
|
self.effect_guarantee
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Confirms that the provider rolled back all operation effects.
|
||||||
|
///
|
||||||
|
/// Calling this method is a semantic assertion by the provider and must occur
|
||||||
|
/// only after its atomic backend boundary has completed rollback.
|
||||||
|
#[must_use]
|
||||||
|
pub fn confirm_rollback(mut self) -> Self {
|
||||||
|
self.effect_guarantee = EffectGuarantee::NotCommitted;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dispatch progress returned to the provider's atomic execution boundary.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OperationAttempt {
|
||||||
|
/// A canonical precondition failed and typed implementation code did not run.
|
||||||
|
NotStarted(CallError),
|
||||||
|
/// Typed implementation invocation began, with either a result or a typed
|
||||||
|
/// post-invocation failure.
|
||||||
|
Started(Result<CallResult, OperationFailure>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OperationAttempt {
|
||||||
|
/// Marks a post-invocation failure as fully rolled back.
|
||||||
|
///
|
||||||
|
/// Successful attempts and pre-dispatch failures are returned unchanged.
|
||||||
|
#[must_use]
|
||||||
|
pub fn confirm_rollback(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Self::Started(Err(error)) => Self::Started(Err(error.confirm_rollback())),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of one provider resolution or execution boundary.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ProviderResult<T> {
|
||||||
|
/// The path resolved and the provider callback completed.
|
||||||
|
Found(T),
|
||||||
|
/// The path is not currently published to this caller.
|
||||||
|
NotFound,
|
||||||
|
/// Provider or backend execution failed.
|
||||||
|
///
|
||||||
|
/// During `call_operation`, the embedded effect guarantee determines whether
|
||||||
|
/// the failure is safe to expose as `Internal`/`ResourceLimitExceeded` or must
|
||||||
|
/// become `OperationOutcomeUnknown`.
|
||||||
|
Failure(HostError),
|
||||||
|
}
|
||||||
|
|
||||||
/// A request-scoped Worldspace resolver and execution boundary.
|
/// A request-scoped Worldspace resolver and execution boundary.
|
||||||
///
|
///
|
||||||
/// `with_object` must resolve the current object at `path` exactly once and pass
|
/// `with_object` must resolve the current object at `path` exactly once and pass
|
||||||
/// a publication that pins its current interface set, implementations, and
|
/// a publication that pins its current interface set, implementations, and
|
||||||
/// backend target for the duration of `operation`. Implementations may hold a
|
/// backend target for the duration of `operation`. The execution context is the
|
||||||
/// transaction or lock around the callback. Returning `None` means the path is
|
/// runtime-neutral carrier for cancellation, deadline, and resource controls.
|
||||||
/// not published to the caller. The borrowed publication cannot escape the
|
/// The borrowed publication cannot escape the callback.
|
||||||
/// callback, so the default call path cannot outlive that provider boundary.
|
///
|
||||||
|
/// Providers that can roll back mutable operations should override
|
||||||
|
/// [`ObjectProvider::execute_operation`], hold their transaction across the
|
||||||
|
/// callback, and call [`OperationAttempt::confirm_rollback`] only after rollback
|
||||||
|
/// succeeds. The default boundary conservatively preserves unknown outcomes.
|
||||||
pub trait ObjectProvider {
|
pub trait ObjectProvider {
|
||||||
/// Host-private object type produced by this provider.
|
/// Host-private object type produced by this provider.
|
||||||
type Object: WipObject;
|
type Object: WipObject;
|
||||||
|
|
||||||
/// Runs an operation against the single object snapshot resolved at `path`.
|
/// Runs a callback against the single object snapshot resolved at `path`.
|
||||||
fn with_object<R>(
|
fn with_object<R>(
|
||||||
&self,
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
path: &str,
|
path: &str,
|
||||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||||
) -> Option<R>;
|
) -> ProviderResult<R>;
|
||||||
|
|
||||||
|
/// Runs one operation attempt inside the provider's atomic backend boundary.
|
||||||
|
///
|
||||||
|
/// The default implementation delegates to [`ObjectProvider::with_object`]
|
||||||
|
/// and therefore does not add a rollback guarantee. Transactional providers
|
||||||
|
/// can override this method, inspect the returned [`OperationAttempt`], roll
|
||||||
|
/// back a failed started attempt, and return its confirmed form.
|
||||||
|
fn execute_operation(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
path: &str,
|
||||||
|
operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
|
||||||
|
) -> ProviderResult<OperationAttempt> {
|
||||||
|
self.with_object(context, path, operation)
|
||||||
|
}
|
||||||
|
|
||||||
/// Decides whether a declared operation may execute for the current caller.
|
/// Decides whether a declared operation may execute for the current caller.
|
||||||
///
|
///
|
||||||
@@ -540,16 +834,43 @@ pub trait ObjectProvider {
|
|||||||
|
|
||||||
/// Fetches the canonical object projection currently published at `path`.
|
/// Fetches the canonical object projection currently published at `path`.
|
||||||
fn fetch(&self, path: &str) -> Result<Object, CallError> {
|
fn fetch(&self, path: &str) -> Result<Object, CallError> {
|
||||||
|
self.fetch_with_context(&ExecutionContext::default(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches an object while propagating runtime execution controls.
|
||||||
|
fn fetch_with_context(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
path: &str,
|
||||||
|
) -> Result<Object, CallError> {
|
||||||
wip_protocol::validate_path(path)
|
wip_protocol::validate_path(path)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
self.with_object(path, PublishedObject::protocol_object)
|
let resolved = catch_unwind(AssertUnwindSafe(|| {
|
||||||
.ok_or_else(|| CallError::new(CallErrorKind::NotFound, "target path is not published"))
|
self.with_object(context, path, PublishedObject::protocol_object)
|
||||||
.and_then(|object| {
|
}))
|
||||||
object.validate_at_path(path).map_err(|error| {
|
.map_err(|_| {
|
||||||
CallError::new(CallErrorKind::InvalidResult, error.to_string())
|
CallError::new(
|
||||||
})?;
|
CallErrorKind::Internal,
|
||||||
Ok(object)
|
"provider panicked while fetching an object",
|
||||||
})
|
)
|
||||||
|
})?;
|
||||||
|
let object = match resolved {
|
||||||
|
ProviderResult::Found(object) => object,
|
||||||
|
ProviderResult::NotFound => {
|
||||||
|
return Err(CallError::new(
|
||||||
|
CallErrorKind::NotFound,
|
||||||
|
"target path is not published",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
ProviderResult::Failure(error) => return Err(CallError::from_read_failure(error)),
|
||||||
|
};
|
||||||
|
object.validate_at_path(path).map_err(|_| {
|
||||||
|
CallError::new(
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
"Host produced an invalid object response",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(object)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves and executes a canonical path-targeted operation request.
|
/// Resolves and executes a canonical path-targeted operation request.
|
||||||
@@ -559,17 +880,47 @@ pub trait ObjectProvider {
|
|||||||
/// supplied object validator mismatch, membership, interface validator
|
/// supplied object validator mismatch, membership, interface validator
|
||||||
/// requirement and mismatch, operation existence, object validator
|
/// requirement and mismatch, operation existence, object validator
|
||||||
/// requirement, arguments, then authorization. No failed precondition
|
/// requirement, arguments, then authorization. No failed precondition
|
||||||
/// invokes the provider callback or typed implementation.
|
/// invokes typed implementation code.
|
||||||
fn call_operation(&self, request: CallRequest) -> Result<CallResult, CallError> {
|
fn call_operation(&self, request: CallRequest) -> Result<CallResult, CallError> {
|
||||||
|
self.call_operation_with_context(&ExecutionContext::default(), request)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Executes an operation while propagating cancellation, deadline, and
|
||||||
|
/// resource-budget controls to the provider and runtime preflight check.
|
||||||
|
fn call_operation_with_context(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
request: CallRequest,
|
||||||
|
) -> Result<CallResult, CallError> {
|
||||||
wip_protocol::validate_path(&request.target.path)
|
wip_protocol::validate_path(&request.target.path)
|
||||||
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
.map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
|
||||||
let path = request.target.path.clone();
|
let path = request.target.path.clone();
|
||||||
self.with_object(&path, |publication| {
|
let execution = catch_unwind(AssertUnwindSafe(|| {
|
||||||
publication.dispatch_resolved(request, |object, interface, operation| {
|
self.execute_operation(context, &path, |publication| {
|
||||||
self.authorize(&path, object, interface, operation)
|
publication.dispatch_resolved(context, request, |object, interface, operation| {
|
||||||
|
self.authorize(&path, object, interface, operation)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
}));
|
||||||
.ok_or_else(|| CallError::new(CallErrorKind::NotFound, "target path is not published"))?
|
|
||||||
|
let execution = execution.map_err(|_| {
|
||||||
|
CallError::from_operation_failure(OperationFailure::internal(
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
"provider execution panicked",
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
match execution {
|
||||||
|
ProviderResult::Found(OperationAttempt::NotStarted(error)) => Err(error),
|
||||||
|
ProviderResult::Found(OperationAttempt::Started(Ok(result))) => Ok(result),
|
||||||
|
ProviderResult::Found(OperationAttempt::Started(Err(error))) => {
|
||||||
|
Err(CallError::from_operation_failure(error))
|
||||||
|
}
|
||||||
|
ProviderResult::NotFound => Err(CallError::new(
|
||||||
|
CallErrorKind::NotFound,
|
||||||
|
"target path is not published",
|
||||||
|
)),
|
||||||
|
ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -594,7 +945,7 @@ impl Display for PublicationError {
|
|||||||
|
|
||||||
impl Error for PublicationError {}
|
impl Error for PublicationError {}
|
||||||
|
|
||||||
/// Stable host dispatch failure kind.
|
/// Stable Host dispatch failure kind.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum CallErrorKind {
|
pub enum CallErrorKind {
|
||||||
/// The request is structurally invalid.
|
/// The request is structurally invalid.
|
||||||
@@ -607,8 +958,13 @@ pub enum CallErrorKind {
|
|||||||
OperationNotFound,
|
OperationNotFound,
|
||||||
/// Supplied named values do not satisfy the operation declaration.
|
/// Supplied named values do not satisfy the operation declaration.
|
||||||
InvalidArguments,
|
InvalidArguments,
|
||||||
/// The encoded implementation result violates its declaration.
|
/// A bounded cancellation, deadline, or resource limit was exceeded and the
|
||||||
InvalidResult,
|
/// operation effects are guaranteed not committed.
|
||||||
|
ResourceLimitExceeded,
|
||||||
|
/// The Host failed and operation effects are guaranteed not committed.
|
||||||
|
Internal,
|
||||||
|
/// The Host cannot guarantee whether operation effects were committed.
|
||||||
|
OperationOutcomeUnknown,
|
||||||
/// This operation requires a validator and the call omitted it.
|
/// This operation requires a validator and the call omitted it.
|
||||||
ValidatorRequired,
|
ValidatorRequired,
|
||||||
/// The supplied object validator is stale or belongs to another object.
|
/// The supplied object validator is stale or belongs to another object.
|
||||||
@@ -619,11 +975,9 @@ pub enum CallErrorKind {
|
|||||||
InterfaceValidatorMismatch,
|
InterfaceValidatorMismatch,
|
||||||
/// The operation is declared but not authorized for the caller.
|
/// The operation is declared but not authorized for the caller.
|
||||||
PermissionDenied,
|
PermissionDenied,
|
||||||
/// The typed implementation reported a host/backend failure.
|
|
||||||
Implementation,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A dispatch failure with a stable kind and non-normative diagnostic.
|
/// A dispatch failure with a stable kind and bounded non-normative diagnostic.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct CallError {
|
pub struct CallError {
|
||||||
kind: CallErrorKind,
|
kind: CallErrorKind,
|
||||||
@@ -634,11 +988,11 @@ impl CallError {
|
|||||||
fn new(kind: CallErrorKind, message: impl Into<String>) -> Self {
|
fn new(kind: CallErrorKind, message: impl Into<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
kind,
|
kind,
|
||||||
message: message.into(),
|
message: bounded_message(message.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_dispatch(error: DispatchError) -> Self {
|
fn from_pre_dispatch(error: DispatchError) -> Self {
|
||||||
match error {
|
match error {
|
||||||
DispatchError::UnknownOperation(operation) => Self::new(
|
DispatchError::UnknownOperation(operation) => Self::new(
|
||||||
CallErrorKind::OperationNotFound,
|
CallErrorKind::OperationNotFound,
|
||||||
@@ -647,34 +1001,63 @@ impl CallError {
|
|||||||
DispatchError::InvalidArguments(error) => {
|
DispatchError::InvalidArguments(error) => {
|
||||||
Self::new(CallErrorKind::InvalidArguments, error.to_string())
|
Self::new(CallErrorKind::InvalidArguments, error.to_string())
|
||||||
}
|
}
|
||||||
DispatchError::Decode(error) => {
|
DispatchError::Decode(_) => Self::new(
|
||||||
Self::new(CallErrorKind::InvalidArguments, error.to_string())
|
CallErrorKind::InvalidArguments,
|
||||||
}
|
"operation arguments could not be decoded",
|
||||||
DispatchError::Host(error) => {
|
),
|
||||||
Self::new(CallErrorKind::Implementation, error.to_string())
|
DispatchError::Host(_)
|
||||||
}
|
| DispatchError::Panic
|
||||||
DispatchError::Encode(error) => {
|
| DispatchError::Encode(_)
|
||||||
Self::new(CallErrorKind::InvalidResult, error.to_string())
|
| DispatchError::InvalidResult(_) => {
|
||||||
}
|
unreachable!("post-invocation failure used as a pre-dispatch failure")
|
||||||
DispatchError::InvalidResult(error) => {
|
|
||||||
Self::new(CallErrorKind::InvalidResult, error.to_string())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn from_read_failure(error: HostError) -> Self {
|
||||||
|
match error.kind() {
|
||||||
|
HostErrorKind::Internal => Self::new(
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
"provider failed while fetching data",
|
||||||
|
),
|
||||||
|
HostErrorKind::ResourceLimitExceeded => Self::new(
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
"provider resource limit was exceeded while fetching data",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_host_failure(error: HostError) -> Self {
|
||||||
|
let kind = classified_host_kind(error.kind(), error.effect_guarantee());
|
||||||
|
let message = match error.kind() {
|
||||||
|
HostErrorKind::Internal => "provider execution failed",
|
||||||
|
HostErrorKind::ResourceLimitExceeded => {
|
||||||
|
"provider execution resource limit was exceeded"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Self::new(kind, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_operation_failure(error: OperationFailure) -> Self {
|
||||||
|
Self::new(
|
||||||
|
classified_host_kind(error.kind, error.effect_guarantee),
|
||||||
|
error.message,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the stable failure kind.
|
/// Returns the stable failure kind.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn kind(&self) -> CallErrorKind {
|
pub fn kind(&self) -> CallErrorKind {
|
||||||
self.kind
|
self.kind
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the human-readable diagnostic.
|
/// Returns the bounded protocol-safe human-readable diagnostic.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn message(&self) -> &str {
|
pub fn message(&self) -> &str {
|
||||||
&self.message
|
&self.message
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Maps this host failure to the canonical protocol error taxonomy.
|
/// Maps this Host failure to the canonical protocol error taxonomy.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn protocol_error(&self) -> ProtocolError {
|
pub fn protocol_error(&self) -> ProtocolError {
|
||||||
let code = match self.kind {
|
let code = match self.kind {
|
||||||
@@ -683,7 +1066,9 @@ impl CallError {
|
|||||||
CallErrorKind::InterfaceMismatch => ProtocolErrorCode::InterfaceMismatch,
|
CallErrorKind::InterfaceMismatch => ProtocolErrorCode::InterfaceMismatch,
|
||||||
CallErrorKind::OperationNotFound => ProtocolErrorCode::OperationNotFound,
|
CallErrorKind::OperationNotFound => ProtocolErrorCode::OperationNotFound,
|
||||||
CallErrorKind::InvalidArguments => ProtocolErrorCode::InvalidArguments,
|
CallErrorKind::InvalidArguments => ProtocolErrorCode::InvalidArguments,
|
||||||
CallErrorKind::InvalidResult => ProtocolErrorCode::InvalidResult,
|
CallErrorKind::ResourceLimitExceeded => ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
CallErrorKind::Internal => ProtocolErrorCode::Internal,
|
||||||
|
CallErrorKind::OperationOutcomeUnknown => ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
CallErrorKind::ValidatorRequired => ProtocolErrorCode::ValidatorRequired,
|
CallErrorKind::ValidatorRequired => ProtocolErrorCode::ValidatorRequired,
|
||||||
CallErrorKind::ValidatorMismatch => ProtocolErrorCode::ValidatorMismatch,
|
CallErrorKind::ValidatorMismatch => ProtocolErrorCode::ValidatorMismatch,
|
||||||
CallErrorKind::InterfaceValidatorRequired => {
|
CallErrorKind::InterfaceValidatorRequired => {
|
||||||
@@ -693,7 +1078,6 @@ impl CallError {
|
|||||||
ProtocolErrorCode::InterfaceValidatorMismatch
|
ProtocolErrorCode::InterfaceValidatorMismatch
|
||||||
}
|
}
|
||||||
CallErrorKind::PermissionDenied => ProtocolErrorCode::PermissionDenied,
|
CallErrorKind::PermissionDenied => ProtocolErrorCode::PermissionDenied,
|
||||||
CallErrorKind::Implementation => ProtocolErrorCode::Internal,
|
|
||||||
};
|
};
|
||||||
ProtocolError {
|
ProtocolError {
|
||||||
code,
|
code,
|
||||||
@@ -702,6 +1086,30 @@ impl CallError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn classified_host_kind(kind: HostErrorKind, effect_guarantee: EffectGuarantee) -> CallErrorKind {
|
||||||
|
match effect_guarantee {
|
||||||
|
EffectGuarantee::Unknown => CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
EffectGuarantee::NotCommitted => match kind {
|
||||||
|
HostErrorKind::Internal => CallErrorKind::Internal,
|
||||||
|
HostErrorKind::ResourceLimitExceeded => CallErrorKind::ResourceLimitExceeded,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_PROTOCOL_MESSAGE_BYTES: usize = 512;
|
||||||
|
|
||||||
|
fn bounded_message(mut message: String) -> String {
|
||||||
|
if message.len() <= MAX_PROTOCOL_MESSAGE_BYTES {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
let mut end = MAX_PROTOCOL_MESSAGE_BYTES;
|
||||||
|
while !message.is_char_boundary(end) {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
message.truncate(end);
|
||||||
|
message
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for CallError {
|
impl Display for CallError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
write!(
|
write!(
|
||||||
|
|||||||
+340
-13
@@ -1,13 +1,16 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use wip_host::{
|
use wip_host::{
|
||||||
CallError, CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget,
|
CallError, CallErrorKind, CallRequest, CancellationToken, ExecutionContext, InterfaceRef,
|
||||||
ObjectProvider, PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
InterfaceRegistry, InterfaceTarget, ObjectProvider, OperationAttempt, ProviderResult,
|
||||||
|
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
||||||
};
|
};
|
||||||
use wip_interface::{
|
use wip_interface::{
|
||||||
CodecError, HostError, OperationResult, TypeDeclaration, TypeExpr, Value, WipType, interface,
|
CodecError, EffectGuarantee, HostError, OperationResult, TypeDeclaration, TypeExpr, Value,
|
||||||
|
WipType, interface,
|
||||||
};
|
};
|
||||||
use wip_protocol::ProtocolErrorCode;
|
use wip_protocol::ProtocolErrorCode;
|
||||||
|
|
||||||
@@ -39,6 +42,24 @@ pub trait Hidden {
|
|||||||
pub trait Broken {
|
pub trait Broken {
|
||||||
/// Returns a deliberately invalid encoded value.
|
/// Returns a deliberately invalid encoded value.
|
||||||
fn broken(&self) -> OperationResult<BadValue>;
|
fn broken(&self) -> OperationResult<BadValue>;
|
||||||
|
|
||||||
|
/// Produces a result codec failure after implementation invocation.
|
||||||
|
fn encode_failure(&self) -> OperationResult<EncodeFailure>;
|
||||||
|
|
||||||
|
/// Panics after implementation invocation begins.
|
||||||
|
fn panic_after_call(&self) -> OperationResult<String>;
|
||||||
|
|
||||||
|
/// Reports an internal failure without an effect guarantee.
|
||||||
|
fn unknown_internal(&self) -> OperationResult<String>;
|
||||||
|
|
||||||
|
/// Reports an internal failure with a non-commit guarantee.
|
||||||
|
fn safe_internal(&self) -> OperationResult<String>;
|
||||||
|
|
||||||
|
/// Reports a resource failure without an effect guarantee.
|
||||||
|
fn unknown_resource(&self) -> OperationResult<String>;
|
||||||
|
|
||||||
|
/// Reports a resource failure with a non-commit guarantee.
|
||||||
|
fn safe_resource(&self) -> OperationResult<String>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -60,6 +81,25 @@ impl WipType for BadValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EncodeFailure;
|
||||||
|
|
||||||
|
impl WipType for EncodeFailure {
|
||||||
|
fn type_expr() -> TypeExpr {
|
||||||
|
TypeExpr::String
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}
|
||||||
|
|
||||||
|
fn encode(self) -> Result<Value, CodecError> {
|
||||||
|
Err(CodecError::new("private://backend/result could not encode"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(_: Value) -> Result<Self, CodecError> {
|
||||||
|
Ok(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Document {
|
struct Document {
|
||||||
name: String,
|
name: String,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
@@ -135,7 +175,10 @@ impl Reader for Document {
|
|||||||
|
|
||||||
fn fail(&self) -> OperationResult<String> {
|
fn fail(&self) -> OperationResult<String> {
|
||||||
self.record_call();
|
self.record_call();
|
||||||
Err(HostError::new("backend unavailable"))
|
Err(HostError::internal(
|
||||||
|
"backend unavailable",
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,6 +201,48 @@ impl Broken for Document {
|
|||||||
self.record_call();
|
self.record_call();
|
||||||
Ok(BadValue)
|
Ok(BadValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn encode_failure(&self) -> OperationResult<EncodeFailure> {
|
||||||
|
self.record_call();
|
||||||
|
Ok(EncodeFailure)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn panic_after_call(&self) -> OperationResult<String> {
|
||||||
|
self.record_call();
|
||||||
|
panic!("private://backend panic with credential=secret")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unknown_internal(&self) -> OperationResult<String> {
|
||||||
|
self.record_call();
|
||||||
|
Err(HostError::internal(
|
||||||
|
"private://backend/path credential=secret",
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_internal(&self) -> OperationResult<String> {
|
||||||
|
self.record_call();
|
||||||
|
Err(HostError::internal(
|
||||||
|
"private://backend/path credential=secret",
|
||||||
|
EffectGuarantee::NotCommitted,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unknown_resource(&self) -> OperationResult<String> {
|
||||||
|
self.record_call();
|
||||||
|
Err(HostError::resource_limit(
|
||||||
|
"private scheduler deadline details",
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_resource(&self) -> OperationResult<String> {
|
||||||
|
self.record_call();
|
||||||
|
Err(HostError::resource_limit(
|
||||||
|
"private scheduler deadline details",
|
||||||
|
EffectGuarantee::NotCommitted,
|
||||||
|
))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct TestProvider {
|
struct TestProvider {
|
||||||
@@ -169,6 +254,11 @@ struct TestProvider {
|
|||||||
authorization_checks: Cell<usize>,
|
authorization_checks: Cell<usize>,
|
||||||
deny: Cell<bool>,
|
deny: Cell<bool>,
|
||||||
switched: Cell<bool>,
|
switched: Cell<bool>,
|
||||||
|
confirm_rollback: Cell<bool>,
|
||||||
|
provider_failure: Cell<Option<(bool, EffectGuarantee)>>,
|
||||||
|
observed_budget: Cell<Option<u64>>,
|
||||||
|
observed_deadline: Cell<Option<Instant>>,
|
||||||
|
observed_cancelled: Cell<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TestProvider {
|
impl TestProvider {
|
||||||
@@ -186,6 +276,11 @@ impl TestProvider {
|
|||||||
authorization_checks: Cell::new(0),
|
authorization_checks: Cell::new(0),
|
||||||
deny: Cell::new(false),
|
deny: Cell::new(false),
|
||||||
switched: Cell::new(false),
|
switched: Cell::new(false),
|
||||||
|
confirm_rollback: Cell::new(false),
|
||||||
|
provider_failure: Cell::new(None),
|
||||||
|
observed_budget: Cell::new(None),
|
||||||
|
observed_deadline: Cell::new(None),
|
||||||
|
observed_cancelled: Cell::new(false),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,9 +290,14 @@ impl ObjectProvider for TestProvider {
|
|||||||
|
|
||||||
fn with_object<R>(
|
fn with_object<R>(
|
||||||
&self,
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
path: &str,
|
path: &str,
|
||||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||||
) -> Option<R> {
|
) -> ProviderResult<R> {
|
||||||
|
self.observed_budget.set(context.resource_budget());
|
||||||
|
self.observed_deadline.set(context.deadline());
|
||||||
|
self.observed_cancelled
|
||||||
|
.set(context.cancellation().is_cancelled());
|
||||||
self.resolutions.set(self.resolutions.get() + 1);
|
self.resolutions.set(self.resolutions.get() + 1);
|
||||||
let (document, interfaces) = match path {
|
let (document, interfaces) = match path {
|
||||||
"/document" => (
|
"/document" => (
|
||||||
@@ -235,11 +335,15 @@ impl ObjectProvider for TestProvider {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
"/empty" => (Document::open("empty", None, Rc::clone(&self.calls)), 0),
|
"/empty" => (Document::open("empty", None, Rc::clone(&self.calls)), 0),
|
||||||
|
"/invalid-object" => (
|
||||||
|
Document::open("wrong-name", None, Rc::clone(&self.calls)),
|
||||||
|
0,
|
||||||
|
),
|
||||||
"/broken" => (
|
"/broken" => (
|
||||||
Document::open("broken", Some("broken-ref"), Rc::clone(&self.calls)),
|
Document::open("broken", Some("broken-ref"), Rc::clone(&self.calls)),
|
||||||
3,
|
3,
|
||||||
),
|
),
|
||||||
_ => return None,
|
_ => return ProviderResult::NotFound,
|
||||||
};
|
};
|
||||||
|
|
||||||
let publication = PublishedObject::new(document);
|
let publication = PublishedObject::new(document);
|
||||||
@@ -253,7 +357,32 @@ impl ObjectProvider for TestProvider {
|
|||||||
3 => publication.expose(&self.broken).unwrap(),
|
3 => publication.expose(&self.broken).unwrap(),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
Some(operation(&publication))
|
ProviderResult::Found(operation(&publication))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute_operation(
|
||||||
|
&self,
|
||||||
|
context: &ExecutionContext,
|
||||||
|
path: &str,
|
||||||
|
operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
|
||||||
|
) -> ProviderResult<OperationAttempt> {
|
||||||
|
let result = self.with_object(context, path, operation);
|
||||||
|
if let Some((resource, guarantee)) = self.provider_failure.get() {
|
||||||
|
let error = if resource {
|
||||||
|
HostError::resource_limit("private provider scheduler state", guarantee)
|
||||||
|
} else {
|
||||||
|
HostError::internal("private provider transaction path", guarantee)
|
||||||
|
};
|
||||||
|
return ProviderResult::Failure(error);
|
||||||
|
}
|
||||||
|
if self.confirm_rollback.get() {
|
||||||
|
match result {
|
||||||
|
ProviderResult::Found(attempt) => ProviderResult::Found(attempt.confirm_rollback()),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn authorize(&self, _: &str, _: &Document, _: &InterfaceRef, _: &str) -> bool {
|
fn authorize(&self, _: &str, _: &Document, _: &InterfaceRef, _: &str) -> bool {
|
||||||
@@ -316,12 +445,21 @@ fn registry_returns_atomic_canonical_observation_without_rewriting_descriptor()
|
|||||||
assert_eq!(observation.reference, *reference);
|
assert_eq!(observation.reference, *reference);
|
||||||
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
|
assert_eq!(observation.descriptor, ReaderDefinition::descriptor());
|
||||||
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
|
assert_eq!(observation.validator, Some(Validator::new(b"schema-v1")));
|
||||||
let response = observation.protocol_response();
|
let response = observation.protocol_response().unwrap();
|
||||||
assert_eq!(response.interface, reference.as_str());
|
assert_eq!(response.interface, reference.as_str());
|
||||||
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
|
assert_eq!(response.descriptor, ReaderDefinition::descriptor());
|
||||||
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
|
assert_eq!(response.validator.as_deref(), Some(b"schema-v1".as_slice()));
|
||||||
response.descriptor.validate().unwrap();
|
response.descriptor.validate().unwrap();
|
||||||
|
|
||||||
|
let mut invalid_observation = registry.fetch_interface(reference.as_str()).unwrap();
|
||||||
|
let duplicate_operation = invalid_observation.descriptor.operations[0].clone();
|
||||||
|
invalid_observation
|
||||||
|
.descriptor
|
||||||
|
.operations
|
||||||
|
.push(duplicate_operation);
|
||||||
|
let invalid_response = invalid_observation.protocol_response().unwrap_err();
|
||||||
|
assert_eq!(invalid_response.code, ProtocolErrorCode::Internal);
|
||||||
|
|
||||||
let error = registry.fetch_interface("unknown").unwrap_err();
|
let error = registry.fetch_interface("unknown").unwrap_err();
|
||||||
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
|
assert_eq!(error.code, ProtocolErrorCode::InterfaceNotFound);
|
||||||
}
|
}
|
||||||
@@ -624,9 +762,15 @@ fn immutable_interface_rejects_a_supplied_validator() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_results_and_backend_failures_keep_distinct_protocol_codes() {
|
fn invalid_host_responses_and_uncertain_operation_failures_use_canonical_codes() {
|
||||||
let (_, provider, _) = registry_and_provider();
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
|
||||||
|
assert_failure(
|
||||||
|
provider.fetch("/invalid-object").unwrap_err(),
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
);
|
||||||
|
|
||||||
assert_failure(
|
assert_failure(
|
||||||
provider
|
provider
|
||||||
.call_operation(request(
|
.call_operation(request(
|
||||||
@@ -638,8 +782,8 @@ fn invalid_results_and_backend_failures_keep_distinct_protocol_codes() {
|
|||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
))
|
))
|
||||||
.unwrap_err(),
|
.unwrap_err(),
|
||||||
CallErrorKind::InvalidResult,
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
ProtocolErrorCode::InvalidResult,
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
);
|
);
|
||||||
assert_failure(
|
assert_failure(
|
||||||
provider
|
provider
|
||||||
@@ -652,7 +796,190 @@ fn invalid_results_and_backend_failures_keep_distinct_protocol_codes() {
|
|||||||
BTreeMap::new(),
|
BTreeMap::new(),
|
||||||
))
|
))
|
||||||
.unwrap_err(),
|
.unwrap_err(),
|
||||||
CallErrorKind::Implementation,
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
ProtocolErrorCode::Internal,
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn call_broken(provider: &TestProvider, operation: &str) -> CallError {
|
||||||
|
provider
|
||||||
|
.call_operation(request(
|
||||||
|
"/broken",
|
||||||
|
None,
|
||||||
|
provider.broken.reference(),
|
||||||
|
None,
|
||||||
|
operation,
|
||||||
|
BTreeMap::new(),
|
||||||
|
))
|
||||||
|
.unwrap_err()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_implementation_failures_map_only_with_a_non_commit_guarantee() {
|
||||||
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
|
||||||
|
let unknown_internal = call_broken(&provider, "unknown_internal");
|
||||||
|
assert_failure(
|
||||||
|
unknown_internal.clone(),
|
||||||
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
);
|
||||||
|
assert!(!unknown_internal.message().contains("private://"));
|
||||||
|
assert!(
|
||||||
|
!unknown_internal
|
||||||
|
.protocol_error()
|
||||||
|
.message
|
||||||
|
.contains("credential")
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "safe_internal"),
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
);
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "unknown_resource"),
|
||||||
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
);
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "safe_resource"),
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn post_invocation_result_and_panic_failures_require_provider_rollback() {
|
||||||
|
for operation in ["broken", "encode_failure", "panic_after_call"] {
|
||||||
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
let error = call_broken(&provider, operation);
|
||||||
|
assert_failure(
|
||||||
|
error.clone(),
|
||||||
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
);
|
||||||
|
assert!(!error.message().contains("private://"));
|
||||||
|
assert!(!error.message().contains("credential"));
|
||||||
|
|
||||||
|
provider.confirm_rollback.set(true);
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, operation),
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_failures_after_invocation_use_the_provider_effect_guarantee() {
|
||||||
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
|
||||||
|
provider
|
||||||
|
.provider_failure
|
||||||
|
.set(Some((false, EffectGuarantee::Unknown)));
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "safe_internal"),
|
||||||
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
);
|
||||||
|
|
||||||
|
provider
|
||||||
|
.provider_failure
|
||||||
|
.set(Some((false, EffectGuarantee::NotCommitted)));
|
||||||
|
let internal = call_broken(&provider, "unknown_internal");
|
||||||
|
assert_failure(
|
||||||
|
internal.clone(),
|
||||||
|
CallErrorKind::Internal,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
);
|
||||||
|
assert!(!internal.message().contains("transaction"));
|
||||||
|
|
||||||
|
provider
|
||||||
|
.provider_failure
|
||||||
|
.set(Some((true, EffectGuarantee::Unknown)));
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "safe_resource"),
|
||||||
|
CallErrorKind::OperationOutcomeUnknown,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
);
|
||||||
|
|
||||||
|
provider
|
||||||
|
.provider_failure
|
||||||
|
.set(Some((true, EffectGuarantee::NotCommitted)));
|
||||||
|
assert_failure(
|
||||||
|
call_broken(&provider, "unknown_resource"),
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn execution_context_is_propagated_and_preflight_prevents_invocation() {
|
||||||
|
let (_, provider, _) = registry_and_provider();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(60);
|
||||||
|
let context = ExecutionContext::new()
|
||||||
|
.with_deadline(deadline)
|
||||||
|
.with_resource_budget(17);
|
||||||
|
|
||||||
|
provider
|
||||||
|
.call_operation_with_context(
|
||||||
|
&context,
|
||||||
|
request(
|
||||||
|
"/open",
|
||||||
|
None,
|
||||||
|
provider.reader.reference(),
|
||||||
|
Some(b"schema-v1"),
|
||||||
|
"label",
|
||||||
|
BTreeMap::new(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(provider.observed_deadline.get(), Some(deadline));
|
||||||
|
assert_eq!(provider.observed_budget.get(), Some(17));
|
||||||
|
assert!(!provider.observed_cancelled.get());
|
||||||
|
|
||||||
|
let calls = provider.calls.get();
|
||||||
|
let cancellation = CancellationToken::new();
|
||||||
|
cancellation.cancel();
|
||||||
|
let cancelled = ExecutionContext::new().with_cancellation(cancellation);
|
||||||
|
assert_failure(
|
||||||
|
provider
|
||||||
|
.call_operation_with_context(
|
||||||
|
&cancelled,
|
||||||
|
request(
|
||||||
|
"/open",
|
||||||
|
None,
|
||||||
|
provider.reader.reference(),
|
||||||
|
Some(b"schema-v1"),
|
||||||
|
"label",
|
||||||
|
BTreeMap::new(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap_err(),
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
);
|
||||||
|
assert_eq!(provider.calls.get(), calls);
|
||||||
|
assert!(provider.observed_cancelled.get());
|
||||||
|
|
||||||
|
let expired = ExecutionContext::new().with_deadline(Instant::now() - Duration::from_secs(1));
|
||||||
|
assert_failure(
|
||||||
|
provider
|
||||||
|
.call_operation_with_context(
|
||||||
|
&expired,
|
||||||
|
request(
|
||||||
|
"/open",
|
||||||
|
None,
|
||||||
|
provider.reader.reference(),
|
||||||
|
Some(b"schema-v1"),
|
||||||
|
"label",
|
||||||
|
BTreeMap::new(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap_err(),
|
||||||
|
CallErrorKind::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
);
|
||||||
|
assert_eq!(provider.calls.get(), calls);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-https"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Framework-independent standard WIP over HTTPS v1 binding"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
|
http = "1"
|
||||||
|
serde = "1"
|
||||||
|
serde_json = "1"
|
||||||
|
url = "2"
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
@@ -0,0 +1,596 @@
|
|||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use http::header::{ACCEPT, CONTENT_TYPE};
|
||||||
|
use http::{Method, Request, Response, StatusCode};
|
||||||
|
use serde_json::{Map, Value as Json};
|
||||||
|
use wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, FetchRequest, FetchResponse, FetchTreeRequest,
|
||||||
|
FetchTreeResponse, INTERFACE_FORMAT_V1, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::response::{self, DecodedResponse};
|
||||||
|
use crate::{
|
||||||
|
BodyKind, ClientResponseError, CodecError, EncodeHttpError, Endpoint, InvalidResponseKind,
|
||||||
|
JSON_CONTENT_TYPE, Limits, ResourceLimitKind, Route, is_json_content_type, json,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A retrieval method accepted by the standard v1 batch endpoint.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum BatchMethod {
|
||||||
|
/// Fetch one object.
|
||||||
|
Fetch,
|
||||||
|
/// Fetch one bounded tree.
|
||||||
|
FetchTree,
|
||||||
|
/// Fetch one interface descriptor.
|
||||||
|
FetchInterface,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BatchMethod {
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Fetch => "fetch",
|
||||||
|
Self::FetchTree => "fetch_tree",
|
||||||
|
Self::FetchInterface => "fetch_interface",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interaction(self) -> ProtocolInteraction {
|
||||||
|
match self {
|
||||||
|
Self::Fetch => ProtocolInteraction::Fetch,
|
||||||
|
Self::FetchTree => ProtocolInteraction::FetchTree,
|
||||||
|
Self::FetchInterface => ProtocolInteraction::FetchInterface,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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),
|
||||||
|
/// Fetch one interface descriptor.
|
||||||
|
FetchInterface(FetchInterfaceRequest),
|
||||||
|
/// A known method whose `arguments` are not a valid logical request.
|
||||||
|
Invalid {
|
||||||
|
/// Method that was successfully identified from the item envelope.
|
||||||
|
method: BatchMethod,
|
||||||
|
/// Item-local `invalid_request` to return without rejecting other items.
|
||||||
|
error: ProtocolError,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BatchRequestKind {
|
||||||
|
fn interaction(&self) -> ProtocolInteraction {
|
||||||
|
match self {
|
||||||
|
Self::Fetch(_) => ProtocolInteraction::Fetch,
|
||||||
|
Self::FetchTree(_) => ProtocolInteraction::FetchTree,
|
||||||
|
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
|
||||||
|
Self::Invalid { method, .. } => method.interaction(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One uniquely identified batch subrequest.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct BatchRequestItem {
|
||||||
|
/// Identifier used only to correlate the corresponding subresponse.
|
||||||
|
pub id: String,
|
||||||
|
/// Retrieval interaction and arguments.
|
||||||
|
pub request: BatchRequestKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A standard v1 batch request.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct BatchRequest {
|
||||||
|
/// Independent subrequests. Identifiers must be unique.
|
||||||
|
pub requests: Vec<BatchRequestItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Successful result of one batch item.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum BatchSuccess {
|
||||||
|
/// Successful `fetch` result.
|
||||||
|
Fetch(FetchResponse),
|
||||||
|
/// Successful `fetch_tree` result.
|
||||||
|
FetchTree(FetchTreeResponse),
|
||||||
|
/// Successful `fetch_interface` result.
|
||||||
|
FetchInterface(FetchInterfaceResponse),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One batch subresponse, correlated by `id` rather than array position.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct BatchResponseItem {
|
||||||
|
/// Identifier copied from its subrequest.
|
||||||
|
pub id: String,
|
||||||
|
/// Direct interaction result or canonical item-local protocol failure.
|
||||||
|
pub outcome: Result<BatchSuccess, ProtocolError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A valid standard v1 batch response.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct BatchResponse {
|
||||||
|
/// Exactly one response for each requested identifier, in any order.
|
||||||
|
pub responses: Vec<BatchResponseItem>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Result<(), CodecError> {
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut count = 0;
|
||||||
|
for id in ids {
|
||||||
|
count += 1;
|
||||||
|
if !seen.insert(id) {
|
||||||
|
return Err(CodecError::DuplicateBatchId { id: id.into() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count > maximum {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: count,
|
||||||
|
maximum,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
|
||||||
|
let (method, arguments) = match &item.request {
|
||||||
|
BatchRequestKind::Fetch(value) => ("fetch", json::fetch_request_to_json(value)),
|
||||||
|
BatchRequestKind::FetchTree(value) => {
|
||||||
|
("fetch_tree", json::fetch_tree_request_to_json(value))
|
||||||
|
}
|
||||||
|
BatchRequestKind::FetchInterface(value) => (
|
||||||
|
"fetch_interface",
|
||||||
|
json::fetch_interface_request_to_json(value),
|
||||||
|
),
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "requests".into(),
|
||||||
|
reason: "item-local invalid requests cannot be encoded as client requests".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(serde_json::json!({"id": item.id, "method": method, "arguments": arguments}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, CodecError> {
|
||||||
|
validate_ids(
|
||||||
|
request.requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
for item in &request.requests {
|
||||||
|
match &item.request {
|
||||||
|
BatchRequestKind::Fetch(value) => value.validate()?,
|
||||||
|
BatchRequestKind::FetchTree(value) => value.validate()?,
|
||||||
|
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let requests = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(request_item_to_json)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
Ok(serde_json::json!({"requests": requests}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||||
|
let fields = exact_object(value, "batch", &["requests"])?;
|
||||||
|
let values = array(required(fields, "requests")?, "requests")?;
|
||||||
|
if values.len() > limits.max_batch_items {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: values.len(),
|
||||||
|
maximum: limits.max_batch_items,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut requests = Vec::with_capacity(values.len());
|
||||||
|
for (index, value) in values.iter().enumerate() {
|
||||||
|
let field = format!("requests[{index}]");
|
||||||
|
let fields = exact_object(value, &field, &["id", "method", "arguments"])?;
|
||||||
|
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||||
|
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
|
||||||
|
let arguments = required(fields, "arguments")?;
|
||||||
|
let method = match method_name.as_str() {
|
||||||
|
"fetch" => BatchMethod::Fetch,
|
||||||
|
"fetch_tree" => BatchMethod::FetchTree,
|
||||||
|
"fetch_interface" => BatchMethod::FetchInterface,
|
||||||
|
_ => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: format!("{field}.method"),
|
||||||
|
reason: "batch supports only fetch, fetch_tree, 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::FetchInterface => json::fetch_interface_request_from_json(arguments)
|
||||||
|
.map(BatchRequestKind::FetchInterface),
|
||||||
|
};
|
||||||
|
let request = decoded.unwrap_or_else(|error| BatchRequestKind::Invalid {
|
||||||
|
method,
|
||||||
|
error: ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: format!("invalid {} arguments: {error}", method.name()),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
requests.push(BatchRequestItem { id, request });
|
||||||
|
}
|
||||||
|
validate_ids(
|
||||||
|
requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
Ok(BatchRequest { requests })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a batch request using `POST v1/batch`.
|
||||||
|
pub fn encode_batch_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &BatchRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(&request_to_json(value, limits)?, BodyKind::Request, limits)?;
|
||||||
|
Ok(Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri(endpoint.route(Route::Batch).as_str())
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(ACCEPT, "application/json")
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and validates a batch request body.
|
||||||
|
pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
request_from_json(&value, limits)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn success_to_json(success: &BatchSuccess) -> Json {
|
||||||
|
match success {
|
||||||
|
BatchSuccess::Fetch(value) => json::object_to_json(value),
|
||||||
|
BatchSuccess::FetchTree(value) => json::fetch_tree_response_to_json(value),
|
||||||
|
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response_to_json(
|
||||||
|
request: &BatchRequest,
|
||||||
|
response: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Json, CodecError> {
|
||||||
|
correlate(request, response, limits)?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"responses": response.responses.iter().map(|item| {
|
||||||
|
let mut fields = Map::new();
|
||||||
|
fields.insert("id".into(), Json::String(item.id.clone()));
|
||||||
|
match &item.outcome {
|
||||||
|
Ok(success) => { fields.insert("result".into(), success_to_json(success)); }
|
||||||
|
Err(error) => { fields.insert("error".into(), response::item_error_to_json(error)); }
|
||||||
|
}
|
||||||
|
Json::Object(fields)
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn correlate(
|
||||||
|
request: &BatchRequest,
|
||||||
|
response: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<(), CodecError> {
|
||||||
|
validate_ids(
|
||||||
|
request.requests.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
validate_ids(
|
||||||
|
response.responses.iter().map(|item| item.id.as_str()),
|
||||||
|
limits.max_batch_items,
|
||||||
|
)?;
|
||||||
|
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(|item| (item.id.as_str(), &item.request))
|
||||||
|
.collect();
|
||||||
|
for item in &response.responses {
|
||||||
|
let Some(kind) = requested.get(item.id.as_str()) else {
|
||||||
|
return Err(CodecError::UnexpectedBatchId {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
match (&item.outcome, *kind) {
|
||||||
|
(Ok(BatchSuccess::Fetch(value)), BatchRequestKind::Fetch(request)) => {
|
||||||
|
request.validate_response(value)?;
|
||||||
|
}
|
||||||
|
(Ok(BatchSuccess::FetchTree(value)), BatchRequestKind::FetchTree(request)) => {
|
||||||
|
value.validate_for(request)?;
|
||||||
|
}
|
||||||
|
(
|
||||||
|
Ok(BatchSuccess::FetchInterface(value)),
|
||||||
|
BatchRequestKind::FetchInterface(request),
|
||||||
|
) => {
|
||||||
|
value.validate_for(request)?;
|
||||||
|
}
|
||||||
|
(
|
||||||
|
Err(error),
|
||||||
|
BatchRequestKind::Invalid {
|
||||||
|
error: expected, ..
|
||||||
|
},
|
||||||
|
) if error == expected => {}
|
||||||
|
(Err(error), kind)
|
||||||
|
if !matches!(kind, BatchRequestKind::Invalid { .. })
|
||||||
|
&& error.code.is_allowed_for(kind.interaction()) => {}
|
||||||
|
_ => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for item in &request.requests {
|
||||||
|
if !response.responses.iter().any(|other| other.id == item.id) {
|
||||||
|
return Err(CodecError::MissingBatchId {
|
||||||
|
id: item.id.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a valid batch response. Item failures remain inside HTTP 200.
|
||||||
|
pub fn encode_batch_response(
|
||||||
|
request: &BatchRequest,
|
||||||
|
value: &BatchResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(
|
||||||
|
&response_to_json(request, value, limits)?,
|
||||||
|
BodyKind::Response,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a top-level batch-envelope failure.
|
||||||
|
///
|
||||||
|
/// Item-local failures belong in [`BatchResponseItem`]. Only failures that can
|
||||||
|
/// reject the batch envelope before item execution are accepted here. A
|
||||||
|
/// resource-limit failure defaults to the logical-limit status; use
|
||||||
|
/// [`encode_batch_resource_limit_error_response`] when the concrete class is
|
||||||
|
/// known.
|
||||||
|
pub fn encode_batch_error_response(
|
||||||
|
error: &ProtocolError,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if !matches!(
|
||||||
|
error.code,
|
||||||
|
ProtocolErrorCode::InvalidRequest
|
||||||
|
| ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
| ProtocolErrorCode::Internal
|
||||||
|
) {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "code is not valid for a top-level batch failure".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(response::status_for_error(error.code))
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a class-specific top-level batch `resource_limit_exceeded` failure.
|
||||||
|
pub fn encode_batch_resource_limit_error_response(
|
||||||
|
error: &ProtocolError,
|
||||||
|
kind: ResourceLimitKind,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if error.code != ProtocolErrorCode::ResourceLimitExceeded {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(Response::builder()
|
||||||
|
.status(response::status_for_resource_limit(kind))
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response_from_json(
|
||||||
|
value: &Json,
|
||||||
|
request: &BatchRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<BatchResponse, CodecError> {
|
||||||
|
let fields = exact_object(value, "batch", &["responses"])?;
|
||||||
|
let values = array(required(fields, "responses")?, "responses")?;
|
||||||
|
if values.len() > limits.max_batch_items {
|
||||||
|
return Err(CodecError::TooManyBatchItems {
|
||||||
|
actual: values.len(),
|
||||||
|
maximum: limits.max_batch_items,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.map(|item| (item.id.as_str(), &item.request))
|
||||||
|
.collect();
|
||||||
|
let mut responses = Vec::with_capacity(values.len());
|
||||||
|
for (index, value) in values.iter().enumerate() {
|
||||||
|
let field = format!("responses[{index}]");
|
||||||
|
let fields = object(value, &field)?;
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !["id", "result", "error"].contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{field}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
||||||
|
let Some(kind) = requested.get(id.as_str()) else {
|
||||||
|
return Err(CodecError::UnexpectedBatchId { id });
|
||||||
|
};
|
||||||
|
let outcome = match (fields.get("result"), fields.get("error")) {
|
||||||
|
(Some(_), Some(_)) | (None, None) => {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field,
|
||||||
|
reason: "batch item must contain exactly one of result or error".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(None, Some(error)) => {
|
||||||
|
let error = response::item_error_from_json(error)?;
|
||||||
|
match kind {
|
||||||
|
BatchRequestKind::Invalid {
|
||||||
|
error: expected, ..
|
||||||
|
} if error == *expected => {}
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch { id });
|
||||||
|
}
|
||||||
|
kind if error.code.is_allowed_for(kind.interaction()) => {}
|
||||||
|
_ => return Err(CodecError::BatchInteractionMismatch { id }),
|
||||||
|
}
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
(Some(result), None) => Ok(match kind {
|
||||||
|
BatchRequestKind::Fetch(request) => {
|
||||||
|
let value = json::object_from_json(result, "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)
|
||||||
|
}
|
||||||
|
BatchRequestKind::FetchInterface(request) => {
|
||||||
|
let value = json::fetch_interface_response_from_json(result)?;
|
||||||
|
value.validate_for(request)?;
|
||||||
|
BatchSuccess::FetchInterface(value)
|
||||||
|
}
|
||||||
|
BatchRequestKind::Invalid { .. } => {
|
||||||
|
return Err(CodecError::BatchInteractionMismatch { id });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
responses.push(BatchResponseItem { id, outcome });
|
||||||
|
}
|
||||||
|
let response = BatchResponse { responses };
|
||||||
|
correlate(request, &response, limits)?;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a batch response, including item-local failures within HTTP 200.
|
||||||
|
pub fn decode_batch_response<B: AsRef<[u8]>>(
|
||||||
|
request: &BatchRequest,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<BatchResponse>, ClientResponseError> {
|
||||||
|
let valid_content_type = value
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if !valid_content_type {
|
||||||
|
if value.status().is_success() {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidBatch,
|
||||||
|
"missing or non-UTF-8 application/json Content-Type",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return Err(response::transport_failure(value.status()));
|
||||||
|
}
|
||||||
|
let decoded = response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::Fetch,
|
||||||
|
limits,
|
||||||
|
|json| response_from_json(json, request, limits),
|
||||||
|
)
|
||||||
|
.map_err(|error| match error {
|
||||||
|
ClientResponseError::InvalidResponse { detail, .. } => {
|
||||||
|
ClientResponseError::invalid(InvalidResponseKind::InvalidBatch, detail)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
})?;
|
||||||
|
if let DecodedResponse::ProtocolFailure { error, .. } = &decoded
|
||||||
|
&& !matches!(
|
||||||
|
error.code,
|
||||||
|
ProtocolErrorCode::InvalidRequest
|
||||||
|
| ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
| ProtocolErrorCode::Internal
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidBatch,
|
||||||
|
"protocol code is not valid for a top-level batch failure",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let DecodedResponse::Success(success) = &decoded {
|
||||||
|
for item in &success.responses {
|
||||||
|
if let Ok(BatchSuccess::FetchInterface(interface)) = &item.outcome
|
||||||
|
&& interface.descriptor.format != INTERFACE_FORMAT_V1
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||||
|
format: interface.descriptor.format.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object<'a>(value: &'a Json, field: &str) -> Result<&'a Map<String, Json>, CodecError> {
|
||||||
|
value.as_object().ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected object".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exact_object<'a>(
|
||||||
|
value: &'a Json,
|
||||||
|
field: &str,
|
||||||
|
allowed: &[&str],
|
||||||
|
) -> Result<&'a Map<String, Json>, CodecError> {
|
||||||
|
let fields = object(value, field)?;
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !allowed.contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{field}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a Json, CodecError> {
|
||||||
|
fields
|
||||||
|
.get(name)
|
||||||
|
.ok_or_else(|| CodecError::MissingField { field: name.into() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn string(value: &Json, field: &str) -> Result<String, CodecError> {
|
||||||
|
value
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected string".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn array<'a>(value: &'a Json, field: &str) -> Result<&'a [Json], CodecError> {
|
||||||
|
value
|
||||||
|
.as_array()
|
||||||
|
.map(Vec::as_slice)
|
||||||
|
.ok_or_else(|| CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: "expected array".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::response::{self, DecodedResponse};
|
||||||
|
use crate::{
|
||||||
|
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||||
|
Limits, ResourceLimitKind, Route, json,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
route: Route,
|
||||||
|
body: Vec<u8>,
|
||||||
|
) -> Result<Request<Vec<u8>>, http::Error> {
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri(endpoint.route(route).as_str())
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(ACCEPT, "application/json")
|
||||||
|
.body(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: StatusCode, body: Vec<u8>) -> Result<Response<Vec<u8>>, http::Error> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.body(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
||||||
|
let valid = response
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if valid {
|
||||||
|
Ok(())
|
||||||
|
} else if response.status().is_success() {
|
||||||
|
Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
"missing or non-UTF-8 application/json Content-Type",
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Err(response::transport_failure(response.status()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_utf8_charset(value: &str) -> bool {
|
||||||
|
let value = value.trim();
|
||||||
|
value.eq_ignore_ascii_case("utf-8")
|
||||||
|
|| value
|
||||||
|
.strip_prefix('"')
|
||||||
|
.and_then(|value| value.strip_suffix('"'))
|
||||||
|
.is_some_and(|value| value.eq_ignore_ascii_case("utf-8"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns whether a Content-Type value denotes UTF-8 `application/json`.
|
||||||
|
///
|
||||||
|
/// The charset parameter is optional because JSON exchanged by this binding is
|
||||||
|
/// always UTF-8; when present, its value must be `utf-8`. Other parameters are
|
||||||
|
/// rejected so intermediaries cannot silently select another representation.
|
||||||
|
#[must_use]
|
||||||
|
pub fn is_json_content_type(value: &str) -> bool {
|
||||||
|
let mut parts = value.split(';');
|
||||||
|
if !parts
|
||||||
|
.next()
|
||||||
|
.is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut saw_charset = false;
|
||||||
|
for parameter in parts {
|
||||||
|
let Some((name, value)) = parameter.trim().split_once('=') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if !name.trim().eq_ignore_ascii_case("charset") || !is_utf8_charset(value) || saw_charset {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
saw_charset = true;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accepts_json(headers: &HeaderMap) -> bool {
|
||||||
|
let mut present = false;
|
||||||
|
let mut best_match: Option<((u8, u8), f32)> = None;
|
||||||
|
for value in headers.get_all(ACCEPT) {
|
||||||
|
present = true;
|
||||||
|
let Ok(value) = value.to_str() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for range in value.split(',') {
|
||||||
|
let mut parts = range.split(';');
|
||||||
|
let media_range = parts.next().unwrap_or_default().trim();
|
||||||
|
let mut quality = 1.0_f32;
|
||||||
|
let mut saw_quality = false;
|
||||||
|
let mut saw_charset = false;
|
||||||
|
let mut media_parameter_count = 0;
|
||||||
|
let mut valid = true;
|
||||||
|
for parameter in parts {
|
||||||
|
let parameter = parameter.trim();
|
||||||
|
let (name, value) = parameter
|
||||||
|
.split_once('=')
|
||||||
|
.map_or((parameter, None), |(name, value)| {
|
||||||
|
(name.trim(), Some(value))
|
||||||
|
});
|
||||||
|
if name.is_empty() {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if saw_quality {
|
||||||
|
// Parameters after q are Accept extensions and do not
|
||||||
|
// constrain the selected representation.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if name.eq_ignore_ascii_case("q") {
|
||||||
|
let Some(value) = value else {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
saw_quality = true;
|
||||||
|
match value.trim().parse::<f32>() {
|
||||||
|
Ok(value) if (0.0..=1.0).contains(&value) => quality = value,
|
||||||
|
_ => {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let Some(value) = value else {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
if !name.eq_ignore_ascii_case("charset")
|
||||||
|
|| !is_utf8_charset(value)
|
||||||
|
|| saw_charset
|
||||||
|
{
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
saw_charset = true;
|
||||||
|
media_parameter_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let media_specificity = if media_range.eq_ignore_ascii_case("application/json") {
|
||||||
|
Some(2)
|
||||||
|
} else if media_range.eq_ignore_ascii_case("application/*") {
|
||||||
|
Some(1)
|
||||||
|
} else if media_range == "*/*" {
|
||||||
|
Some(0)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if valid && let Some(media_specificity) = media_specificity {
|
||||||
|
let specificity = (media_specificity, media_parameter_count);
|
||||||
|
match best_match {
|
||||||
|
Some((best_specificity, _)) if best_specificity > specificity => {}
|
||||||
|
Some((best_specificity, best_quality)) if best_specificity == specificity => {
|
||||||
|
best_match = Some((specificity, best_quality.max(quality)));
|
||||||
|
}
|
||||||
|
_ => best_match = Some((specificity, quality)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if present {
|
||||||
|
best_match.is_some_and(|(_, quality)| quality > 0.0)
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure while validating inbound HTTP request metadata.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum RequestMetadataError {
|
||||||
|
/// The method or route does not match the selected WIP interaction.
|
||||||
|
InvalidRequest(CodecError),
|
||||||
|
/// The request body does not use UTF-8 `application/json`.
|
||||||
|
UnsupportedMediaType,
|
||||||
|
/// The request's `Accept` metadata excludes `application/json`.
|
||||||
|
NotAcceptable,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestMetadataError {
|
||||||
|
/// Returns the HTTP status for this metadata failure.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||||
|
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for RequestMetadataError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(error) => error.fmt(formatter),
|
||||||
|
Self::UnsupportedMediaType => {
|
||||||
|
formatter.write_str("expected UTF-8 application/json Content-Type")
|
||||||
|
}
|
||||||
|
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for RequestMetadataError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRequest(error) => Some(error),
|
||||||
|
Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||||
|
///
|
||||||
|
/// Both absolute-form and origin-form request URIs are accepted, but the path
|
||||||
|
/// must exactly equal the selected endpoint route and a query is forbidden.
|
||||||
|
/// Unsupported content negotiation is reported as a Transport Binding metadata
|
||||||
|
/// failure rather than a Core `invalid_request`.
|
||||||
|
pub fn validate_http_request<B>(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
route: Route,
|
||||||
|
value: &Request<B>,
|
||||||
|
) -> Result<(), RequestMetadataError> {
|
||||||
|
if value.method() != Method::POST {
|
||||||
|
return Err(RequestMetadataError::InvalidRequest(
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: "method".into(),
|
||||||
|
reason: "standard WIP routes require POST".into(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let expected = endpoint.route(route);
|
||||||
|
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||||
|
return Err(RequestMetadataError::InvalidRequest(
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: "route".into(),
|
||||||
|
reason: "request URI does not match the selected standard route".into(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let valid_content_type = value
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(is_json_content_type);
|
||||||
|
if !valid_content_type {
|
||||||
|
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||||
|
}
|
||||||
|
if !accepts_json(value.headers()) {
|
||||||
|
return Err(RequestMetadataError::NotAcceptable);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a `fetch` HTTP request.
|
||||||
|
pub fn encode_fetch_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &FetchRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
value.validate().map_err(CodecError::from)?;
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::fetch_request_to_json(value),
|
||||||
|
BodyKind::Request,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(request(endpoint, Route::Fetch, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a `fetch` request body.
|
||||||
|
pub fn decode_fetch_request(body: &[u8], limits: Limits) -> Result<FetchRequest, 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a `fetch_interface` HTTP request.
|
||||||
|
pub fn encode_fetch_interface_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &FetchInterfaceRequest,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::fetch_interface_request_to_json(value),
|
||||||
|
BodyKind::Request,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(request(endpoint, Route::FetchInterface, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a `fetch_interface` request body.
|
||||||
|
pub fn decode_fetch_interface_request(
|
||||||
|
body: &[u8],
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<FetchInterfaceRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
json::fetch_interface_request_from_json(&value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Descriptor-independent fields needed to resolve a `call_operation` request.
|
||||||
|
///
|
||||||
|
/// A Host decodes this metadata first, fixes the current interface descriptor,
|
||||||
|
/// then passes the same body and descriptor to [`decode_call_operation_request`].
|
||||||
|
/// This preserves canonical path/interface/operation lookup and error precedence
|
||||||
|
/// without treating unvalidated argument JSON as a logical [`wip_protocol::Value`].
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CallOperationMetadata {
|
||||||
|
/// Path and optional object-state precondition.
|
||||||
|
pub target: Target,
|
||||||
|
/// Interface reference and optional interface precondition.
|
||||||
|
pub interface: InterfaceTarget,
|
||||||
|
/// Operation name used to select a declaration.
|
||||||
|
pub operation: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CallOperationMetadata {
|
||||||
|
/// Decodes the descriptor-bound request and verifies that routing metadata
|
||||||
|
/// still matches the values used to resolve `descriptor`.
|
||||||
|
pub fn decode_request(
|
||||||
|
&self,
|
||||||
|
body: &[u8],
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationRequest, CodecError> {
|
||||||
|
let request = decode_call_operation_request(body, descriptor, limits)?;
|
||||||
|
if request.target != self.target
|
||||||
|
|| request.interface != self.interface
|
||||||
|
|| request.operation != self.operation
|
||||||
|
{
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "request".into(),
|
||||||
|
reason: "call metadata changed after descriptor resolution".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes descriptor-independent `call_operation` routing metadata.
|
||||||
|
pub fn decode_call_operation_metadata(
|
||||||
|
body: &[u8],
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationMetadata, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
let (target, interface, operation) = json::call_request_metadata_from_json(&value)?;
|
||||||
|
Ok(CallOperationMetadata {
|
||||||
|
target,
|
||||||
|
interface,
|
||||||
|
operation,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a descriptor-bound `call_operation` HTTP request.
|
||||||
|
pub fn encode_call_operation_request(
|
||||||
|
endpoint: &Endpoint,
|
||||||
|
value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let value = json::call_request_to_json(value, descriptor)?;
|
||||||
|
let body = json::serialize(&value, BodyKind::Request, limits)?;
|
||||||
|
Ok(request(endpoint, Route::CallOperation, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes a descriptor-bound `call_operation` request body.
|
||||||
|
pub fn decode_call_operation_request(
|
||||||
|
body: &[u8],
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<CallOperationRequest, CodecError> {
|
||||||
|
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||||
|
json::call_request_from_json(&value, descriptor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `fetch` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_fetch_response(
|
||||||
|
request_value: &FetchRequest,
|
||||||
|
value: &FetchResponse,
|
||||||
|
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),
|
||||||
|
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,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<FetchTreeResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::FetchTree,
|
||||||
|
limits,
|
||||||
|
|json| {
|
||||||
|
let tree = json::fetch_tree_response_from_json(json)?;
|
||||||
|
tree.validate_for(request_value)?;
|
||||||
|
Ok(tree)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `fetch_interface` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_fetch_interface_response(
|
||||||
|
request_value: &FetchInterfaceRequest,
|
||||||
|
value: &FetchInterfaceResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
value
|
||||||
|
.validate_for(request_value)
|
||||||
|
.map_err(CodecError::from)?;
|
||||||
|
let body = json::serialize(
|
||||||
|
&json::fetch_interface_response_to_json(value),
|
||||||
|
BodyKind::Response,
|
||||||
|
limits,
|
||||||
|
)?;
|
||||||
|
Ok(response(StatusCode::OK, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and classifies a `fetch_interface` client response.
|
||||||
|
pub fn decode_fetch_interface_response<B: AsRef<[u8]>>(
|
||||||
|
request_value: &FetchInterfaceRequest,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<FetchInterfaceResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
let decoded = response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::FetchInterface,
|
||||||
|
limits,
|
||||||
|
|json| {
|
||||||
|
let interface = json::fetch_interface_response_from_json(json)?;
|
||||||
|
interface.validate_for(request_value)?;
|
||||||
|
Ok(interface)
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
if let DecodedResponse::Success(success) = &decoded
|
||||||
|
&& success.descriptor.format != INTERFACE_FORMAT_V1
|
||||||
|
{
|
||||||
|
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
||||||
|
format: success.descriptor.format.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a successful `call_operation` response as a direct body with HTTP 200.
|
||||||
|
pub fn encode_call_operation_response(
|
||||||
|
request_value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
value: &CallOperationResponse,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
let json = json::call_response_to_json(value, descriptor, &request_value.operation)?;
|
||||||
|
let body = json::serialize(&json, BodyKind::Response, limits)?;
|
||||||
|
Ok(response(StatusCode::OK, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes and classifies a descriptor-bound `call_operation` client response.
|
||||||
|
pub fn decode_call_operation_response<B: AsRef<[u8]>>(
|
||||||
|
request_value: &CallOperationRequest,
|
||||||
|
descriptor: &InterfaceDescriptor,
|
||||||
|
value: &Response<B>,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<DecodedResponse<CallOperationResponse>, ClientResponseError> {
|
||||||
|
require_response_content_type(value)?;
|
||||||
|
response::decode(
|
||||||
|
value.status(),
|
||||||
|
value.body().as_ref(),
|
||||||
|
ProtocolInteraction::CallOperation,
|
||||||
|
limits,
|
||||||
|
|json| json::call_response_from_json(json, descriptor, &request_value.operation),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_protocol_error(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
) -> Result<(), CodecError> {
|
||||||
|
if !error.code.is_allowed_for(interaction) {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: format!(
|
||||||
|
"code `{}` is not allowed for {interaction:?}",
|
||||||
|
response::error_code_name(error.code)
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_protocol_error_with_status(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
status: StatusCode,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
validate_protocol_error(interaction, error)?;
|
||||||
|
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
||||||
|
Ok(response(status, body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a canonical Host error envelope using its standard HTTP status.
|
||||||
|
///
|
||||||
|
/// The code must be allowed for `interaction`. This API accepts only
|
||||||
|
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
||||||
|
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
||||||
|
/// error envelopes. Resource-limit errors use the logical-limit status; callers
|
||||||
|
/// that know the concrete limit class should use
|
||||||
|
/// [`encode_resource_limit_error_response`].
|
||||||
|
pub fn encode_protocol_error_response(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
encode_protocol_error_with_status(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
response::status_for_error(error.code),
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes a `resource_limit_exceeded` envelope with its class-specific status.
|
||||||
|
pub fn encode_resource_limit_error_response(
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
error: &ProtocolError,
|
||||||
|
kind: ResourceLimitKind,
|
||||||
|
limits: Limits,
|
||||||
|
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||||
|
if error.code != wip_protocol::ProtocolErrorCode::ResourceLimitExceeded {
|
||||||
|
return Err(CodecError::InvalidField {
|
||||||
|
field: "error.code".into(),
|
||||||
|
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
encode_protocol_error_with_status(
|
||||||
|
interaction,
|
||||||
|
error,
|
||||||
|
response::status_for_resource_limit(kind),
|
||||||
|
limits,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure while building an outbound framework-neutral HTTP message.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EncodeHttpError {
|
||||||
|
/// JSON or protocol encoding failed.
|
||||||
|
Codec(CodecError),
|
||||||
|
/// The framework-neutral HTTP message builder rejected the URI or headers.
|
||||||
|
Http(http::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for EncodeHttpError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Codec(error) => error.fmt(formatter),
|
||||||
|
Self::Http(error) => error.fmt(formatter),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for EncodeHttpError {
|
||||||
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::Codec(error) => Some(error),
|
||||||
|
Self::Http(error) => Some(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CodecError> for EncodeHttpError {
|
||||||
|
fn from(value: CodecError) -> Self {
|
||||||
|
Self::Codec(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<http::Error> for EncodeHttpError {
|
||||||
|
fn from(value: http::Error) -> Self {
|
||||||
|
Self::Http(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// The media type emitted for every WIP request and every response with a body.
|
||||||
|
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
||||||
|
|
||||||
|
/// A fixed standard WIP over HTTPS v1 route.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Route {
|
||||||
|
/// Fetch one object.
|
||||||
|
Fetch,
|
||||||
|
/// Fetch a bounded object tree.
|
||||||
|
FetchTree,
|
||||||
|
/// Fetch an interface descriptor.
|
||||||
|
FetchInterface,
|
||||||
|
/// Call one operation.
|
||||||
|
CallOperation,
|
||||||
|
/// Package independent retrieval interactions.
|
||||||
|
Batch,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Route {
|
||||||
|
/// Returns the RFC 3986 relative reference used below an endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn relative_reference(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Fetch => "v1/fetch",
|
||||||
|
Self::FetchTree => "v1/fetch_tree",
|
||||||
|
Self::FetchInterface => "v1/fetch_interface",
|
||||||
|
Self::CallOperation => "v1/call_operation",
|
||||||
|
Self::Batch => "v1/batch",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A canonical absolute HTTPS 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.
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if url.query().is_some() {
|
||||||
|
return Err(EndpointError::HasQuery);
|
||||||
|
}
|
||||||
|
if url.fragment().is_some() {
|
||||||
|
return Err(EndpointError::HasFragment);
|
||||||
|
}
|
||||||
|
if !url.path().ends_with('/') {
|
||||||
|
let path = format!("{}/", url.path());
|
||||||
|
url.set_path(&path);
|
||||||
|
}
|
||||||
|
Ok(Self(url))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical base URL.
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_url(&self) -> &Url {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves one fixed v1 route below this endpoint prefix.
|
||||||
|
#[must_use]
|
||||||
|
pub fn route(&self, route: Route) -> Url {
|
||||||
|
self.0
|
||||||
|
.join(route.relative_reference())
|
||||||
|
.expect("fixed relative WIP routes are valid URL references")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recognizes an exact standard route below this endpoint.
|
||||||
|
///
|
||||||
|
/// Query strings, fragments, additional path segments, and Worldspace paths
|
||||||
|
/// are not route components and therefore never match.
|
||||||
|
#[must_use]
|
||||||
|
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
||||||
|
const ROUTES: [Route; 5] = [
|
||||||
|
Route::Fetch,
|
||||||
|
Route::FetchTree,
|
||||||
|
Route::FetchInterface,
|
||||||
|
Route::CallOperation,
|
||||||
|
Route::Batch,
|
||||||
|
];
|
||||||
|
if candidate.query().is_some() || candidate.fragment().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
ROUTES
|
||||||
|
.into_iter()
|
||||||
|
.find(|route| self.route(*route) == *candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Endpoint {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
self.0.fmt(formatter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&str> for Endpoint {
|
||||||
|
type Error = EndpointError;
|
||||||
|
|
||||||
|
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||||
|
Self::parse(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why an endpoint is not a valid standard WIP HTTPS 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.
|
||||||
|
HasQuery,
|
||||||
|
/// A fragment component was supplied.
|
||||||
|
HasFragment,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for EndpointError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
|
||||||
|
Self::NotHttps => formatter.write_str("WIP endpoint must use HTTPS"),
|
||||||
|
Self::NotAbsoluteBase => {
|
||||||
|
formatter.write_str("WIP endpoint must be an absolute base URL")
|
||||||
|
}
|
||||||
|
Self::HasQuery => formatter.write_str("WIP endpoint must not contain a query"),
|
||||||
|
Self::HasFragment => formatter.write_str("WIP endpoint must not contain a fragment"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for EndpointError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidUrl(error) => Some(error),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
/// Caller-selected hard limits applied before or while decoding JSON.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Limits {
|
||||||
|
/// Largest accepted request body in bytes.
|
||||||
|
pub(crate) max_request_bytes: usize,
|
||||||
|
/// Largest accepted response body in bytes.
|
||||||
|
pub(crate) max_response_bytes: usize,
|
||||||
|
/// Largest accepted JSON container nesting depth.
|
||||||
|
pub(crate) max_nesting: usize,
|
||||||
|
/// Largest accepted number of batch items.
|
||||||
|
pub(crate) max_batch_items: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Limits {
|
||||||
|
/// Creates a nonzero limit set.
|
||||||
|
pub fn new(
|
||||||
|
max_request_bytes: usize,
|
||||||
|
max_response_bytes: usize,
|
||||||
|
max_nesting: usize,
|
||||||
|
max_batch_items: usize,
|
||||||
|
) -> Result<Self, LimitConfigurationError> {
|
||||||
|
if max_request_bytes == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroRequestBytes);
|
||||||
|
}
|
||||||
|
if max_response_bytes == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroResponseBytes);
|
||||||
|
}
|
||||||
|
if max_nesting == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroNesting);
|
||||||
|
}
|
||||||
|
if max_batch_items == 0 {
|
||||||
|
return Err(LimitConfigurationError::ZeroBatchItems);
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
max_request_bytes,
|
||||||
|
max_response_bytes,
|
||||||
|
max_nesting,
|
||||||
|
max_batch_items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the request body byte limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_request_bytes(self) -> usize {
|
||||||
|
self.max_request_bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the response body byte limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_response_bytes(self) -> usize {
|
||||||
|
self.max_response_bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the JSON container nesting limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_nesting(self) -> usize {
|
||||||
|
self.max_nesting
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the batch item count limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_batch_items(self) -> usize {
|
||||||
|
self.max_batch_items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a [`Limits`] configuration is not bounded.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LimitConfigurationError {
|
||||||
|
/// Request-byte limit was zero.
|
||||||
|
ZeroRequestBytes,
|
||||||
|
/// Response-byte limit was zero.
|
||||||
|
ZeroResponseBytes,
|
||||||
|
/// Nesting limit was zero.
|
||||||
|
ZeroNesting,
|
||||||
|
/// Batch-item limit was zero.
|
||||||
|
ZeroBatchItems,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for LimitConfigurationError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
formatter.write_str(match self {
|
||||||
|
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
||||||
|
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
||||||
|
Self::ZeroNesting => "nesting limit must be nonzero",
|
||||||
|
Self::ZeroBatchItems => "batch item limit must be nonzero",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for LimitConfigurationError {}
|
||||||
|
|
||||||
|
/// Whether a body is being decoded as a request or response.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum BodyKind {
|
||||||
|
/// An inbound server request.
|
||||||
|
Request,
|
||||||
|
/// An inbound client response.
|
||||||
|
Response,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The class of a resource limit exceeded by a wire representation.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ResourceLimitKind {
|
||||||
|
/// A request or response representation exceeded its byte-size limit.
|
||||||
|
RepresentationBytes,
|
||||||
|
/// A logical limit such as nesting depth, batch count, or collection size was exceeded.
|
||||||
|
Logical,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A malformed or locally disallowed wire representation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum CodecError {
|
||||||
|
/// The body exceeds its configured byte limit.
|
||||||
|
BodyTooLarge {
|
||||||
|
/// Actual body size.
|
||||||
|
actual: usize,
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// JSON syntax is invalid.
|
||||||
|
InvalidJson(serde_json::Error),
|
||||||
|
/// A JSON container exceeds the configured nesting depth.
|
||||||
|
NestingTooDeep {
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// A required field is absent.
|
||||||
|
MissingField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// An undeclared field is present.
|
||||||
|
UnknownField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// A field has an invalid JSON type or semantic representation.
|
||||||
|
InvalidField {
|
||||||
|
/// Field name or value location.
|
||||||
|
field: String,
|
||||||
|
/// Stable human-readable reason.
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
|
/// An optional field was represented by JSON null rather than omission.
|
||||||
|
NullOptionalField {
|
||||||
|
/// Field name.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// Base64 is not canonical RFC 4648 Section 4 encoding.
|
||||||
|
InvalidBase64 {
|
||||||
|
/// Field name or value location.
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
/// Logical protocol validation rejected the decoded representation.
|
||||||
|
ProtocolValidation(wip_protocol::ValidationError),
|
||||||
|
/// The batch exceeds its configured item count.
|
||||||
|
TooManyBatchItems {
|
||||||
|
/// Actual item count.
|
||||||
|
actual: usize,
|
||||||
|
/// Configured maximum.
|
||||||
|
maximum: usize,
|
||||||
|
},
|
||||||
|
/// Batch item identifiers are not unique.
|
||||||
|
DuplicateBatchId {
|
||||||
|
/// Repeated identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A response contains a batch identifier that was not requested.
|
||||||
|
UnexpectedBatchId {
|
||||||
|
/// Unexpected identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A response omitted a requested batch identifier.
|
||||||
|
MissingBatchId {
|
||||||
|
/// Missing identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// A batch item result does not match its requested interaction.
|
||||||
|
BatchInteractionMismatch {
|
||||||
|
/// Item identifier.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CodecError {
|
||||||
|
/// Classifies this failure when it represents a canonical resource limit.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn resource_limit_kind(&self) -> Option<ResourceLimitKind> {
|
||||||
|
match self {
|
||||||
|
Self::BodyTooLarge { .. } => Some(ResourceLimitKind::RepresentationBytes),
|
||||||
|
Self::NestingTooDeep { .. } | Self::TooManyBatchItems { .. } => {
|
||||||
|
Some(ResourceLimitKind::Logical)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for CodecError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::BodyTooLarge { actual, maximum } => {
|
||||||
|
write!(formatter, "body has {actual} bytes; maximum is {maximum}")
|
||||||
|
}
|
||||||
|
Self::InvalidJson(error) => write!(formatter, "invalid JSON: {error}"),
|
||||||
|
Self::NestingTooDeep { maximum } => {
|
||||||
|
write!(formatter, "JSON nesting exceeds maximum {maximum}")
|
||||||
|
}
|
||||||
|
Self::MissingField { field } => write!(formatter, "missing field `{field}`"),
|
||||||
|
Self::UnknownField { field } => write!(formatter, "unknown field `{field}`"),
|
||||||
|
Self::InvalidField { field, reason } => {
|
||||||
|
write!(formatter, "invalid field `{field}`: {reason}")
|
||||||
|
}
|
||||||
|
Self::NullOptionalField { field } => {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"optional field `{field}` must be omitted instead of null"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Self::InvalidBase64 { field } => {
|
||||||
|
write!(formatter, "field `{field}` is not canonical base64")
|
||||||
|
}
|
||||||
|
Self::ProtocolValidation(error) => error.fmt(formatter),
|
||||||
|
Self::TooManyBatchItems { actual, maximum } => {
|
||||||
|
write!(formatter, "batch has {actual} items; maximum is {maximum}")
|
||||||
|
}
|
||||||
|
Self::DuplicateBatchId { id } => write!(formatter, "duplicate batch id `{id}`"),
|
||||||
|
Self::UnexpectedBatchId { id } => write!(formatter, "unexpected batch id `{id}`"),
|
||||||
|
Self::MissingBatchId { id } => write!(formatter, "missing batch id `{id}`"),
|
||||||
|
Self::BatchInteractionMismatch { id } => {
|
||||||
|
write!(formatter, "batch result does not match request `{id}`")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for CodecError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::InvalidJson(error) => Some(error),
|
||||||
|
Self::ProtocolValidation(error) => Some(error),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<wip_protocol::ValidationError> for CodecError {
|
||||||
|
fn from(value: wip_protocol::ValidationError) -> Self {
|
||||||
|
Self::ProtocolValidation(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,67 @@
|
|||||||
|
//! Framework-independent standard WIP over HTTPS 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.
|
||||||
|
//!
|
||||||
|
//! 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;
|
||||||
|
//!
|
||||||
|
//! let endpoint = Endpoint::parse("https://example.test/api/wip")?;
|
||||||
|
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
|
||||||
|
//! let request = encode_fetch_request(
|
||||||
|
//! &endpoint,
|
||||||
|
//! &FetchRequest { path: "/items/123".into() },
|
||||||
|
//! limits,
|
||||||
|
//! )?;
|
||||||
|
//! assert_eq!(request.uri(), "https://example.test/api/wip/v1/fetch");
|
||||||
|
//! assert_eq!(request.method(), http::Method::POST);
|
||||||
|
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
mod batch;
|
||||||
|
mod codec;
|
||||||
|
mod endpoint;
|
||||||
|
mod error;
|
||||||
|
mod json;
|
||||||
|
mod response;
|
||||||
|
|
||||||
|
pub use batch::{
|
||||||
|
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
||||||
|
BatchResponseItem, BatchSuccess, decode_batch_request, decode_batch_response,
|
||||||
|
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
||||||
|
encode_batch_response,
|
||||||
|
};
|
||||||
|
pub use codec::{
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||||
|
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
|
||||||
|
pub use response::{
|
||||||
|
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||||
|
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||||
|
status_for_resource_limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Framework-neutral HTTP types used by this binding's public API.
|
||||||
|
pub use http;
|
||||||
|
/// URL type used by [`Endpoint`].
|
||||||
|
pub use url;
|
||||||
|
/// Transport-independent logical protocol model used by this binding.
|
||||||
|
pub use wip_protocol;
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
|
use http::StatusCode;
|
||||||
|
use serde_json::{Map, Value as Json};
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
|
use crate::{BodyKind, CodecError, Limits, ResourceLimitKind, json};
|
||||||
|
|
||||||
|
/// A successfully classified client response.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum DecodedResponse<T> {
|
||||||
|
/// A successful direct response body.
|
||||||
|
Success(T),
|
||||||
|
/// A canonical Host protocol failure.
|
||||||
|
ProtocolFailure {
|
||||||
|
/// The authoritative protocol error decoded from the envelope.
|
||||||
|
error: ProtocolError,
|
||||||
|
/// A diagnostic when the HTTP status differs from the canonical mapping.
|
||||||
|
status_mismatch: Option<StatusMismatch>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Diagnostic evidence that HTTP metadata disagrees with a valid error envelope.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct StatusMismatch {
|
||||||
|
/// Status received from the peer.
|
||||||
|
pub actual: StatusCode,
|
||||||
|
/// Canonical status for the envelope's protocol code.
|
||||||
|
pub expected: StatusCode,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Class of non-protocol HTTP failure returned without a valid WIP envelope.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TransportFailureKind {
|
||||||
|
/// HTTP 401, commonly emitted by authentication infrastructure.
|
||||||
|
AuthenticationRequired,
|
||||||
|
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
||||||
|
EndpointForbidden,
|
||||||
|
/// Another non-success HTTP response without a WIP error envelope.
|
||||||
|
HttpStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-success HTTP response that is not a valid WIP protocol failure.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct TransportBindingFailure {
|
||||||
|
/// HTTP status returned by the peer or intermediary.
|
||||||
|
pub status: StatusCode,
|
||||||
|
/// Coarse classification which does not invent a protocol error code.
|
||||||
|
pub kind: TransportFailureKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a response violates the WIP v1 response contract.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum InvalidResponseKind {
|
||||||
|
/// A 2xx response contained an error envelope.
|
||||||
|
ErrorEnvelopeOnSuccessStatus,
|
||||||
|
/// A non-2xx response contained a valid success body.
|
||||||
|
SuccessBodyOnErrorStatus,
|
||||||
|
/// A valid error envelope used a code forbidden for the interaction.
|
||||||
|
DisallowedProtocolCode,
|
||||||
|
/// A valid success body used a 2xx status other than canonical HTTP 200.
|
||||||
|
NonCanonicalSuccessStatus,
|
||||||
|
/// A 2xx body was malformed or semantically invalid.
|
||||||
|
InvalidSuccessBody,
|
||||||
|
/// A batch response did not correlate exactly with its request.
|
||||||
|
InvalidBatch,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A local failure while classifying or validating a peer response.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ClientResponseError {
|
||||||
|
/// The HTTP exchange failed outside the protocol envelope.
|
||||||
|
TransportBinding(TransportBindingFailure),
|
||||||
|
/// The peer supplied a contradictory or invalid WIP response.
|
||||||
|
InvalidResponse {
|
||||||
|
/// Stable response-failure category.
|
||||||
|
kind: InvalidResponseKind,
|
||||||
|
/// Bounded diagnostic from local decoding.
|
||||||
|
detail: String,
|
||||||
|
},
|
||||||
|
/// The descriptor is structurally valid but uses an unsupported format.
|
||||||
|
UnsupportedDescriptorFormat {
|
||||||
|
/// Format identifier received from the Host.
|
||||||
|
format: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientResponseError {
|
||||||
|
pub(crate) fn invalid(kind: InvalidResponseKind, detail: impl Into<String>) -> Self {
|
||||||
|
Self::InvalidResponse {
|
||||||
|
kind,
|
||||||
|
detail: detail.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for ClientResponseError {
|
||||||
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::TransportBinding(failure) => write!(
|
||||||
|
formatter,
|
||||||
|
"transport binding failure ({:?}, HTTP {})",
|
||||||
|
failure.kind, failure.status
|
||||||
|
),
|
||||||
|
Self::InvalidResponse { kind, detail } => {
|
||||||
|
write!(formatter, "invalid WIP response ({kind:?}): {detail}")
|
||||||
|
}
|
||||||
|
Self::UnsupportedDescriptorFormat { format } => {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"unsupported interface descriptor format `{format}`"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ClientResponseError {}
|
||||||
|
|
||||||
|
/// Returns the canonical HTTP status for a wire-level protocol error.
|
||||||
|
///
|
||||||
|
/// [`ProtocolErrorCode::ResourceLimitExceeded`] defaults to the logical-limit
|
||||||
|
/// status. Use [`status_for_resource_limit`] when the concrete limit class is
|
||||||
|
/// known.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::InvalidRequest => StatusCode::BAD_REQUEST,
|
||||||
|
ProtocolErrorCode::NotFound | ProtocolErrorCode::InterfaceNotFound => StatusCode::NOT_FOUND,
|
||||||
|
ProtocolErrorCode::InterfaceMismatch => StatusCode::CONFLICT,
|
||||||
|
ProtocolErrorCode::OperationNotFound => StatusCode::NOT_FOUND,
|
||||||
|
ProtocolErrorCode::InvalidArguments => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ProtocolErrorCode::ValidatorRequired | ProtocolErrorCode::InterfaceValidatorRequired => {
|
||||||
|
StatusCode::PRECONDITION_REQUIRED
|
||||||
|
}
|
||||||
|
ProtocolErrorCode::ValidatorMismatch | ProtocolErrorCode::InterfaceValidatorMismatch => {
|
||||||
|
StatusCode::PRECONDITION_FAILED
|
||||||
|
}
|
||||||
|
ProtocolErrorCode::PermissionDenied => StatusCode::FORBIDDEN,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ProtocolErrorCode::Internal | ProtocolErrorCode::OperationOutcomeUnknown => {
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the canonical HTTP status for a concrete resource-limit class.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status_for_resource_limit(kind: ResourceLimitKind) -> StatusCode {
|
||||||
|
match kind {
|
||||||
|
ResourceLimitKind::RepresentationBytes => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
ResourceLimitKind::Logical => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => {
|
||||||
|
status == StatusCode::PAYLOAD_TOO_LARGE || status == StatusCode::UNPROCESSABLE_ENTITY
|
||||||
|
}
|
||||||
|
_ => status == status_for_error(code),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the stable snake-case wire spelling of a protocol code.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn error_code_name(code: ProtocolErrorCode) -> &'static str {
|
||||||
|
match code {
|
||||||
|
ProtocolErrorCode::InvalidRequest => "invalid_request",
|
||||||
|
ProtocolErrorCode::NotFound => "not_found",
|
||||||
|
ProtocolErrorCode::InterfaceNotFound => "interface_not_found",
|
||||||
|
ProtocolErrorCode::InterfaceMismatch => "interface_mismatch",
|
||||||
|
ProtocolErrorCode::OperationNotFound => "operation_not_found",
|
||||||
|
ProtocolErrorCode::InvalidArguments => "invalid_arguments",
|
||||||
|
ProtocolErrorCode::ValidatorRequired => "validator_required",
|
||||||
|
ProtocolErrorCode::ValidatorMismatch => "validator_mismatch",
|
||||||
|
ProtocolErrorCode::InterfaceValidatorRequired => "interface_validator_required",
|
||||||
|
ProtocolErrorCode::InterfaceValidatorMismatch => "interface_validator_mismatch",
|
||||||
|
ProtocolErrorCode::PermissionDenied => "permission_denied",
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded => "resource_limit_exceeded",
|
||||||
|
ProtocolErrorCode::Internal => "internal",
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown => "operation_outcome_unknown",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_code_from_name(name: &str) -> Option<ProtocolErrorCode> {
|
||||||
|
Some(match name {
|
||||||
|
"invalid_request" => ProtocolErrorCode::InvalidRequest,
|
||||||
|
"not_found" => ProtocolErrorCode::NotFound,
|
||||||
|
"interface_not_found" => ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
"interface_mismatch" => ProtocolErrorCode::InterfaceMismatch,
|
||||||
|
"operation_not_found" => ProtocolErrorCode::OperationNotFound,
|
||||||
|
"invalid_arguments" => ProtocolErrorCode::InvalidArguments,
|
||||||
|
"validator_required" => ProtocolErrorCode::ValidatorRequired,
|
||||||
|
"validator_mismatch" => ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
"interface_validator_required" => ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
|
"interface_validator_mismatch" => ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
|
"permission_denied" => ProtocolErrorCode::PermissionDenied,
|
||||||
|
"resource_limit_exceeded" => ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
"internal" => ProtocolErrorCode::Internal,
|
||||||
|
"operation_outcome_unknown" => ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn error_to_json(error: &ProtocolError) -> Json {
|
||||||
|
serde_json::json!({
|
||||||
|
"error": {
|
||||||
|
"code": error_code_name(error.code),
|
||||||
|
"message": error.message,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn item_error_to_json(error: &ProtocolError) -> Json {
|
||||||
|
serde_json::json!({
|
||||||
|
"code": error_code_name(error.code),
|
||||||
|
"message": error.message,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn item_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
||||||
|
let fields = value
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
||||||
|
exact(fields, &["code", "message"], "error")?;
|
||||||
|
let code_name = required_string(fields, "code")?;
|
||||||
|
let code = error_code_from_name(code_name)
|
||||||
|
.ok_or_else(|| invalid_field("error.code", "unknown protocol error code"))?;
|
||||||
|
let message = required_string(fields, "message")?.to_owned();
|
||||||
|
Ok(ProtocolError { code, message })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn envelope_error_from_json(value: &Json) -> Result<Option<ProtocolError>, CodecError> {
|
||||||
|
let Some(fields) = value.as_object() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if fields.len() != 1 || !fields.contains_key("error") {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
item_error_from_json(&fields["error"]).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
||||||
|
for name in fields.keys() {
|
||||||
|
if !allowed.contains(&name.as_str()) {
|
||||||
|
return Err(CodecError::UnknownField {
|
||||||
|
field: format!("{parent}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name in allowed {
|
||||||
|
if !fields.contains_key(*name) {
|
||||||
|
return Err(CodecError::MissingField {
|
||||||
|
field: format!("{parent}.{name}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_string<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a str, CodecError> {
|
||||||
|
fields
|
||||||
|
.get(name)
|
||||||
|
.and_then(Json::as_str)
|
||||||
|
.ok_or_else(|| invalid_field(&format!("error.{name}"), "expected string"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_field(field: &str, reason: &str) -> CodecError {
|
||||||
|
CodecError::InvalidField {
|
||||||
|
field: field.into(),
|
||||||
|
reason: reason.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn decode<T>(
|
||||||
|
status: StatusCode,
|
||||||
|
body: &[u8],
|
||||||
|
interaction: ProtocolInteraction,
|
||||||
|
limits: Limits,
|
||||||
|
success: impl FnOnce(&Json) -> Result<T, CodecError>,
|
||||||
|
) -> Result<DecodedResponse<T>, ClientResponseError> {
|
||||||
|
let value = match json::parse(body, BodyKind::Response, limits) {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(_) if !status.is_success() => {
|
||||||
|
return Err(transport_failure(status));
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match envelope_error_from_json(&value) {
|
||||||
|
Ok(Some(error)) => {
|
||||||
|
if status.is_success() {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||||
|
"protocol error envelope carried by a success status",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !error.code.is_allowed_for(interaction) {
|
||||||
|
return Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::DisallowedProtocolCode,
|
||||||
|
format!(
|
||||||
|
"code `{}` is not allowed for {interaction:?}",
|
||||||
|
error_code_name(error.code)
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let expected = status_for_error(error.code);
|
||||||
|
let status_mismatch =
|
||||||
|
(!status_matches_error(status, error.code)).then_some(StatusMismatch {
|
||||||
|
actual: status,
|
||||||
|
expected,
|
||||||
|
});
|
||||||
|
Ok(DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(_) if !status.is_success() => Err(transport_failure(status)),
|
||||||
|
Err(error) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)),
|
||||||
|
Ok(None) if status == StatusCode::OK => success(&value)
|
||||||
|
.map(DecodedResponse::Success)
|
||||||
|
.map_err(|error| {
|
||||||
|
ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
Ok(None) if status.is_success() => match success(&value) {
|
||||||
|
Ok(_) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||||
|
format!("success body carried by non-canonical HTTP {status}"),
|
||||||
|
)),
|
||||||
|
Err(error) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
error.to_string(),
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
Ok(None) => match success(&value) {
|
||||||
|
Ok(_) => Err(ClientResponseError::invalid(
|
||||||
|
InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||||
|
"valid success body carried by a non-success status",
|
||||||
|
)),
|
||||||
|
Err(_) => Err(transport_failure(status)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
||||||
|
let kind = match status {
|
||||||
|
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
||||||
|
StatusCode::FORBIDDEN => TransportFailureKind::EndpointForbidden,
|
||||||
|
_ => TransportFailureKind::HttpStatus,
|
||||||
|
};
|
||||||
|
ClientResponseError::TransportBinding(TransportBindingFailure { status, kind })
|
||||||
|
}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
use wip_https::http::StatusCode;
|
||||||
|
use wip_https::wip_protocol::{
|
||||||
|
FetchInterfaceRequest, FetchInterfaceResponse, FetchRequest, INTERFACE_FORMAT_V1,
|
||||||
|
InterfaceDescriptor, Object, ProtocolError, ProtocolErrorCode,
|
||||||
|
};
|
||||||
|
use wip_https::{
|
||||||
|
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
||||||
|
BatchResponseItem, BatchSuccess, ClientResponseError, DecodedResponse, Endpoint,
|
||||||
|
InvalidResponseKind, Limits, ResourceLimitKind, decode_batch_request, decode_batch_response,
|
||||||
|
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
||||||
|
encode_batch_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(100_000, 100_000, 64, 4).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request() -> BatchRequest {
|
||||||
|
BatchRequest {
|
||||||
|
requests: vec![
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "object".into(),
|
||||||
|
request: BatchRequestKind::Fetch(FetchRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_round_trips_by_unique_id_with_item_failures_and_validators() {
|
||||||
|
let request = request();
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
||||||
|
let encoded_request = encode_batch_request(&endpoint, &request, limits()).unwrap();
|
||||||
|
assert_eq!(encoded_request.uri().path(), "/wip/v1/batch");
|
||||||
|
assert_eq!(encoded_request.headers()["accept"], "application/json");
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Err(ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "gone".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Fetch(Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator: Some(vec![0, 1, 2, 255]),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("AAEC/w==")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_interface_validator_round_trips_in_item_body() {
|
||||||
|
let request = BatchRequest {
|
||||||
|
requests: vec![BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Ok(BatchSuccess::FetchInterface(FetchInterfaceResponse {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
descriptor: InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: None,
|
||||||
|
types: vec![],
|
||||||
|
operations: vec![],
|
||||||
|
},
|
||||||
|
validator: Some(vec![255, 254, 253]),
|
||||||
|
})),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("//79")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_known_method_arguments_are_item_local() {
|
||||||
|
let body = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"valid","method":"fetch","arguments":{"path":"/item"}},
|
||||||
|
{"id":"invalid","method":"fetch_tree","arguments":{"path":"/","depth":"deep","limit":1}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
let decoded = decode_batch_request(body, limits()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decoded.requests[0].request,
|
||||||
|
BatchRequestKind::Fetch(_)
|
||||||
|
));
|
||||||
|
let invalid = match &decoded.requests[1].request {
|
||||||
|
BatchRequestKind::Invalid { method, error } => {
|
||||||
|
assert_eq!(*method, BatchMethod::FetchTree);
|
||||||
|
assert_eq!(error.code, ProtocolErrorCode::InvalidRequest);
|
||||||
|
error.clone()
|
||||||
|
}
|
||||||
|
other => panic!("expected item-local invalid request, got {other:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "valid".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Fetch(Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "invalid".into(),
|
||||||
|
outcome: Err(invalid),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&decoded, &response, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&decoded, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(response)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_batch_envelopes_are_rejected_at_top_level() {
|
||||||
|
assert!(decode_batch_request(br#"{}"#, limits()).is_err());
|
||||||
|
|
||||||
|
let malformed_item = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"item","method":"fetch","arguments":{"path":"/"},"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"}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
assert!(decode_batch_request(duplicate, limits()).is_err());
|
||||||
|
|
||||||
|
let operation = br#"{
|
||||||
|
"requests": [
|
||||||
|
{"id":"call","method":"call_operation","arguments":{}}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
assert!(decode_batch_request(operation, limits()).is_err());
|
||||||
|
|
||||||
|
let too_many = Limits::new(100_000, 100_000, 64, 1).unwrap();
|
||||||
|
assert!(decode_batch_request(duplicate, too_many).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_resource_limits_use_413_or_422_and_never_429() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "bounded".into(),
|
||||||
|
};
|
||||||
|
for (kind, status) in [
|
||||||
|
(
|
||||||
|
ResourceLimitKind::RepresentationBytes,
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
),
|
||||||
|
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
] {
|
||||||
|
let encoded = encode_batch_resource_limit_error_response(&error, kind, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), status);
|
||||||
|
assert_ne!(encoded.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_success_body_requires_exactly_http_200() {
|
||||||
|
let request = request();
|
||||||
|
let response = BatchResponse {
|
||||||
|
responses: vec![
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Fetch(Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
BatchResponseItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
outcome: Err(ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "gone".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
||||||
|
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
||||||
|
let mut noncanonical = encoded.clone();
|
||||||
|
*noncanonical.status_mut() = status;
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request, &noncanonical, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn top_level_batch_errors_use_the_batch_allowed_code_set() {
|
||||||
|
let invalid = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
|
message: "bad envelope".into(),
|
||||||
|
};
|
||||||
|
let encoded = encode_batch_error_response(&invalid, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: invalid,
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let not_found = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::NOT_FOUND)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(br#"{"error":{"code":"not_found","message":"not a batch failure"}}"#.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), ¬_found, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
|
||||||
|
let duplicate = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future":true}}},{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), &duplicate, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let missing = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request(), &missing, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidBatch,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let request = BatchRequest {
|
||||||
|
requests: vec![BatchRequestItem {
|
||||||
|
id: "interface".into(),
|
||||||
|
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
decode_batch_response(&request, &missing, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { format }
|
||||||
|
if format == "wip-interface/2"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_response_must_have_exactly_the_requested_ids() {
|
||||||
|
let request = request();
|
||||||
|
let missing = BatchResponse {
|
||||||
|
responses: vec![BatchResponseItem {
|
||||||
|
id: "object".into(),
|
||||||
|
outcome: Ok(BatchSuccess::Fetch(Object {
|
||||||
|
name: "item".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec![],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
})),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
assert!(encode_batch_response(&request, &missing, limits()).is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,508 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use wip_https::http::StatusCode;
|
||||||
|
use wip_https::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,
|
||||||
|
};
|
||||||
|
use wip_https::{
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(1_000_000, 1_000_000, 100, 100).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint() -> Endpoint {
|
||||||
|
Endpoint::parse("https://example.test/wip").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object(name: &str, validator: &[u8]) -> Object {
|
||||||
|
Object {
|
||||||
|
name: name.into(),
|
||||||
|
description: Some("description".into()),
|
||||||
|
interfaces: vec!["interface-v1".into()],
|
||||||
|
r#ref: Some(format!("object:{name}")),
|
||||||
|
validator: Some(validator.to_vec()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn descriptor() -> InterfaceDescriptor {
|
||||||
|
InterfaceDescriptor {
|
||||||
|
format: INTERFACE_FORMAT_V1.into(),
|
||||||
|
documentation: Some(Documentation {
|
||||||
|
summary: "Codec fixture".into(),
|
||||||
|
details: None,
|
||||||
|
}),
|
||||||
|
types: vec![TypeDeclaration {
|
||||||
|
name: "Pair".into(),
|
||||||
|
documentation: None,
|
||||||
|
definition: TypeExpr::Record {
|
||||||
|
fields: vec![
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "required".into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "optional".into(),
|
||||||
|
required: false,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::String,
|
||||||
|
},
|
||||||
|
FieldDeclaration {
|
||||||
|
name: "optional_json".into(),
|
||||||
|
required: false,
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Json,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
operations: vec![OperationDeclaration {
|
||||||
|
name: "everything".into(),
|
||||||
|
documentation: None,
|
||||||
|
parameters: vec![
|
||||||
|
parameter("unit", TypeExpr::Unit),
|
||||||
|
parameter("boolean", TypeExpr::Boolean),
|
||||||
|
parameter("integer", TypeExpr::Integer),
|
||||||
|
parameter("number", TypeExpr::Number),
|
||||||
|
parameter("string", TypeExpr::String),
|
||||||
|
parameter("bytes", TypeExpr::Bytes),
|
||||||
|
parameter("entry", TypeExpr::Entry),
|
||||||
|
parameter(
|
||||||
|
"list",
|
||||||
|
TypeExpr::List {
|
||||||
|
items: Box::new(TypeExpr::Integer),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"record",
|
||||||
|
TypeExpr::Named {
|
||||||
|
name: "Pair".into(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"enum",
|
||||||
|
TypeExpr::Enum {
|
||||||
|
cases: vec![EnumCase {
|
||||||
|
name: "ready".into(),
|
||||||
|
documentation: None,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter(
|
||||||
|
"union",
|
||||||
|
TypeExpr::Union {
|
||||||
|
cases: vec![
|
||||||
|
UnionCase {
|
||||||
|
name: "empty".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: None,
|
||||||
|
},
|
||||||
|
UnionCase {
|
||||||
|
name: "found".into(),
|
||||||
|
documentation: None,
|
||||||
|
payload: Some(TypeExpr::Entry),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
parameter("json", TypeExpr::Json),
|
||||||
|
],
|
||||||
|
returns: ReturnDeclaration {
|
||||||
|
documentation: None,
|
||||||
|
r#type: TypeExpr::Bytes,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter(name: &str, r#type: TypeExpr) -> ParameterDeclaration {
|
||||||
|
ParameterDeclaration {
|
||||||
|
name: name.into(),
|
||||||
|
required: true,
|
||||||
|
documentation: None,
|
||||||
|
r#type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(fields: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||||
|
Value::Record(
|
||||||
|
fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, value)| (name.into(), value))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call_request() -> CallOperationRequest {
|
||||||
|
CallOperationRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "/items/123".into(),
|
||||||
|
validator: Some(vec![0, 1, 2, 255]),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: "interface-v1".into(),
|
||||||
|
validator: Some(vec![9, 8, 7]),
|
||||||
|
},
|
||||||
|
operation: "everything".into(),
|
||||||
|
arguments: BTreeMap::from([
|
||||||
|
("unit".into(), Value::Unit),
|
||||||
|
("boolean".into(), Value::Boolean(true)),
|
||||||
|
("integer".into(), Value::Integer(MAX_SAFE_INTEGER)),
|
||||||
|
("number".into(), Value::Number(1.5)),
|
||||||
|
("string".into(), Value::String("text".into())),
|
||||||
|
("bytes".into(), Value::Bytes(vec![0, 1, 2, 255])),
|
||||||
|
("entry".into(), Value::String("/items/123".into())),
|
||||||
|
(
|
||||||
|
"list".into(),
|
||||||
|
Value::List(vec![Value::Integer(1), Value::Integer(2)]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"record".into(),
|
||||||
|
record([("required", Value::String("present".into()))]),
|
||||||
|
),
|
||||||
|
("enum".into(), Value::String("ready".into())),
|
||||||
|
(
|
||||||
|
"union".into(),
|
||||||
|
record([
|
||||||
|
("$case", Value::String("found".into())),
|
||||||
|
("value", Value::String("/items/123".into())),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"json".into(),
|
||||||
|
record([
|
||||||
|
("null", Value::Unit),
|
||||||
|
("number", Value::Integer(2)),
|
||||||
|
("path_like", Value::String("/not-an-entry".into())),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_single_interaction_request_accepts_json() {
|
||||||
|
let fetch =
|
||||||
|
encode_fetch_request(&endpoint(), &FetchRequest { path: "/".into() }, limits()).unwrap();
|
||||||
|
let fetch_tree = encode_fetch_tree_request(
|
||||||
|
&endpoint(),
|
||||||
|
&FetchTreeRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 1,
|
||||||
|
limit: 1,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let fetch_interface = encode_fetch_interface_request(
|
||||||
|
&endpoint(),
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let call = encode_call_operation_request(&endpoint(), &call_request(), &descriptor(), limits())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for request in [fetch, fetch_tree, fetch_interface, call] {
|
||||||
|
assert_eq!(request.headers()["accept"], "application/json");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fetch_round_trips_direct_body_and_body_validator() {
|
||||||
|
let request = FetchRequest {
|
||||||
|
path: "/items/123".into(),
|
||||||
|
};
|
||||||
|
let encoded_request = encode_fetch_request(&endpoint(), &request, limits()).unwrap();
|
||||||
|
assert_eq!(encoded_request.uri().path(), "/wip/v1/fetch");
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = object("123", &[0, 1, 2, 255]);
|
||||||
|
let encoded = encode_fetch_response(&request, &expected, limits()).unwrap();
|
||||||
|
assert_eq!(encoded.status(), StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_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 {
|
||||||
|
path: "/items".into(),
|
||||||
|
depth: 1,
|
||||||
|
limit: 2,
|
||||||
|
};
|
||||||
|
let encoded_request = encode_fetch_tree_request(&endpoint(), &tree_request, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_tree_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
tree_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 encoded = encode_fetch_tree_response(&tree_request, &tree, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_tree_response(&tree_request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(tree)
|
||||||
|
);
|
||||||
|
|
||||||
|
let interface_request = FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
};
|
||||||
|
let encoded_request =
|
||||||
|
encode_fetch_interface_request(&endpoint(), &interface_request, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_interface_request(encoded_request.body(), limits()).unwrap(),
|
||||||
|
interface_request
|
||||||
|
);
|
||||||
|
let interface = FetchInterfaceResponse {
|
||||||
|
interface: interface_request.interface.clone(),
|
||||||
|
descriptor: descriptor(),
|
||||||
|
validator: Some(vec![4, 5, 6, 255]),
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_fetch_interface_response(&interface_request, &interface, limits()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_interface_response(&interface_request, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(interface)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn descriptor_guided_values_and_validators_round_trip_both_directions() {
|
||||||
|
let descriptor = descriptor();
|
||||||
|
let request = call_request();
|
||||||
|
let encoded =
|
||||||
|
encode_call_operation_request(&endpoint(), &request, &descriptor, limits()).unwrap();
|
||||||
|
let body = std::str::from_utf8(encoded.body()).unwrap();
|
||||||
|
assert!(body.contains("AAEC/w=="));
|
||||||
|
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||||
|
assert_eq!(metadata.target, request.target);
|
||||||
|
assert_eq!(metadata.interface, request.interface);
|
||||||
|
assert_eq!(metadata.operation, request.operation);
|
||||||
|
assert_eq!(
|
||||||
|
metadata
|
||||||
|
.decode_request(encoded.body(), &descriptor, limits())
|
||||||
|
.unwrap(),
|
||||||
|
request
|
||||||
|
);
|
||||||
|
let mut changed_route = request.clone();
|
||||||
|
changed_route.target.path = "/items/other".into();
|
||||||
|
let changed =
|
||||||
|
encode_call_operation_request(&endpoint(), &changed_route, &descriptor, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
metadata
|
||||||
|
.decode_request(changed.body(), &descriptor, limits())
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut null_json_request = request.clone();
|
||||||
|
null_json_request
|
||||||
|
.arguments
|
||||||
|
.insert("json".into(), Value::Unit);
|
||||||
|
null_json_request.arguments.insert(
|
||||||
|
"record".into(),
|
||||||
|
record([
|
||||||
|
("required", Value::String("present".into())),
|
||||||
|
("optional_json", Value::Unit),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
let null_json =
|
||||||
|
encode_call_operation_request(&endpoint(), &null_json_request, &descriptor, limits())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
decode_call_operation_request(null_json.body(), &descriptor, limits()).unwrap(),
|
||||||
|
null_json_request
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = CallOperationResponse {
|
||||||
|
result: Value::Bytes(vec![255, 0, 1]),
|
||||||
|
validator: Some(vec![3, 2, 1, 0]),
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_call_operation_response(&request, &descriptor, &expected, limits()).unwrap();
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(encoded.body())
|
||||||
|
.unwrap()
|
||||||
|
.contains("/wAB")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
decode_call_operation_response(&request, &descriptor, &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(expected)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
|
||||||
|
let limits = limits();
|
||||||
|
assert!(decode_fetch_request(br#"{"path":"/","extra":true}"#, limits).is_err());
|
||||||
|
assert!(decode_fetch_request(br#"{"path":"relative","path":"/"}"#, limits).is_err());
|
||||||
|
|
||||||
|
let request = call_request();
|
||||||
|
let descriptor = descriptor();
|
||||||
|
let body = serde_json::to_vec(&serde_json::json!({
|
||||||
|
"target": {"path": "/items/123", "validator": null},
|
||||||
|
"interface": {"reference": "interface-v1"},
|
||||||
|
"operation": "everything",
|
||||||
|
"arguments": {}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(decode_call_operation_request(&body, &descriptor, limits).is_err());
|
||||||
|
|
||||||
|
let mut json: serde_json::Value = serde_json::from_slice(
|
||||||
|
encode_call_operation_request(&endpoint(), &request, &descriptor, limits)
|
||||||
|
.unwrap()
|
||||||
|
.body(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
json["arguments"]["bytes"] = serde_json::Value::String("AAEC_w==".into());
|
||||||
|
assert!(
|
||||||
|
decode_call_operation_request(&serde_json::to_vec(&json).unwrap(), &descriptor, limits)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caller_limits_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();
|
||||||
|
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
too_large.resource_limit_kind(),
|
||||||
|
Some(ResourceLimitKind::RepresentationBytes)
|
||||||
|
);
|
||||||
|
|
||||||
|
let nested = br#"{"path":[[["/"]]]}"#;
|
||||||
|
let nesting_limited = Limits::new(1024, 1024, 2, 1).unwrap();
|
||||||
|
let too_deep = decode_fetch_request(nested, nesting_limited).unwrap_err();
|
||||||
|
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||||
|
assert_eq!(
|
||||||
|
too_deep.resource_limit_kind(),
|
||||||
|
Some(ResourceLimitKind::Logical)
|
||||||
|
);
|
||||||
|
|
||||||
|
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1, 10).unwrap();
|
||||||
|
assert!(
|
||||||
|
encode_call_operation_request(
|
||||||
|
&endpoint(),
|
||||||
|
&call_request(),
|
||||||
|
&descriptor(),
|
||||||
|
outbound_limited,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
encode_fetch_response(
|
||||||
|
&FetchRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
},
|
||||||
|
&object("item", b"validator"),
|
||||||
|
outbound_limited,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_descriptor_format_is_client_local() {
|
||||||
|
let request = FetchInterfaceRequest {
|
||||||
|
interface: "interface-v1".into(),
|
||||||
|
};
|
||||||
|
let mut interface = FetchInterfaceResponse {
|
||||||
|
interface: request.interface.clone(),
|
||||||
|
descriptor: descriptor(),
|
||||||
|
validator: None,
|
||||||
|
};
|
||||||
|
interface.descriptor.format = "future-format".into();
|
||||||
|
let response = encode_fetch_interface_response(&request, &interface, limits()).unwrap();
|
||||||
|
let error = decode_fetch_interface_response(&request, &response, limits()).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { .. }
|
||||||
|
));
|
||||||
|
|
||||||
|
let future_shape = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(
|
||||||
|
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future_shape":true}}"#
|
||||||
|
.to_vec(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_interface_response(&request, &future_shape, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::UnsupportedDescriptorFormat { format }
|
||||||
|
if format == "wip-interface/2"
|
||||||
|
));
|
||||||
|
|
||||||
|
for malformed in [
|
||||||
|
br#"{"interface":"wrong","descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
||||||
|
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
||||||
|
.as_slice(),
|
||||||
|
] {
|
||||||
|
let response = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(malformed.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_interface_response(&request, &response, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_success_is_classified_as_invalid_response() {
|
||||||
|
let response = wip_https::http::Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(br#"{"name":"wrong","interfaces":[]}"#.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
let error = decode_fetch_response(
|
||||||
|
&FetchRequest {
|
||||||
|
path: "/expected".into(),
|
||||||
|
},
|
||||||
|
&response,
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
use wip_https::http::{Response, StatusCode};
|
||||||
|
use wip_https::wip_protocol::{
|
||||||
|
FetchRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
|
};
|
||||||
|
use wip_https::{
|
||||||
|
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, ResourceLimitKind,
|
||||||
|
TransportFailureKind, decode_fetch_response, encode_protocol_error_response,
|
||||||
|
encode_resource_limit_error_response, error_code_name, is_json_content_type, status_for_error,
|
||||||
|
status_for_resource_limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn limits() -> Limits {
|
||||||
|
Limits::new(64 * 1024, 64 * 1024, 32, 16).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request() -> FetchRequest {
|
||||||
|
FetchRequest { path: "/".into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: StatusCode, body: impl Into<Vec<u8>>) -> Response<Vec<u8>> {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(body.into())
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_type_accepts_only_utf8_json_syntax() {
|
||||||
|
assert!(is_json_content_type("application/json"));
|
||||||
|
assert!(is_json_content_type("Application/JSON; Charset=\"UTF-8\""));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=utf-16"));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=\"utf-8"));
|
||||||
|
assert!(!is_json_content_type("application/json; charset=utf-8\""));
|
||||||
|
assert!(!is_json_content_type("application/json; profile=other"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_protocol_code_has_stable_name_and_status() {
|
||||||
|
let expected = [
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InvalidRequest,
|
||||||
|
"invalid_request",
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::NotFound,
|
||||||
|
"not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
"interface_not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceMismatch,
|
||||||
|
"interface_mismatch",
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::OperationNotFound,
|
||||||
|
"operation_not_found",
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InvalidArguments,
|
||||||
|
"invalid_arguments",
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ValidatorRequired,
|
||||||
|
"validator_required",
|
||||||
|
StatusCode::PRECONDITION_REQUIRED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
"validator_mismatch",
|
||||||
|
StatusCode::PRECONDITION_FAILED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
|
"interface_validator_required",
|
||||||
|
StatusCode::PRECONDITION_REQUIRED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
|
"interface_validator_mismatch",
|
||||||
|
StatusCode::PRECONDITION_FAILED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::PermissionDenied,
|
||||||
|
"permission_denied",
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
"resource_limit_exceeded",
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
"internal",
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
"operation_outcome_unknown",
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
assert_eq!(expected.len(), ProtocolErrorCode::ALL.len());
|
||||||
|
for (code, name, status) in expected {
|
||||||
|
assert_eq!(error_code_name(code), name);
|
||||||
|
assert_eq!(status_for_error(code), status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
message: "bounded".into(),
|
||||||
|
};
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
ResourceLimitKind::RepresentationBytes,
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
),
|
||||||
|
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
||||||
|
];
|
||||||
|
for (kind, status) in cases {
|
||||||
|
assert_eq!(status_for_resource_limit(kind), status);
|
||||||
|
let encoded = encode_resource_limit_error_response(
|
||||||
|
ProtocolInteraction::Fetch,
|
||||||
|
&error,
|
||||||
|
kind,
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(encoded.status(), status);
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let default =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).unwrap();
|
||||||
|
assert_eq!(default.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert_ne!(default.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
|
||||||
|
let response = Response::builder()
|
||||||
|
.status(StatusCode::TOO_MANY_REQUESTS)
|
||||||
|
.body(b"rate limited".to_vec())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_response(&request(), &response, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::TOO_MANY_REQUESTS
|
||||||
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_success_body_requires_exactly_http_200() {
|
||||||
|
let success_body = br#"{"name":"","interfaces":[]}"#;
|
||||||
|
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_response(&request(), &response(status, success_body), limits())
|
||||||
|
.unwrap_err(),
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_encoder_rejects_codes_disallowed_for_the_interaction() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
message: "not valid for fetch".into(),
|
||||||
|
};
|
||||||
|
assert!(encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_envelope_code_is_authoritative_when_status_mismatches() {
|
||||||
|
let error = ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_protocol_error_response(ProtocolInteraction::Fetch, &error, limits()).unwrap();
|
||||||
|
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
decode_fetch_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: Some(wip_https::StatusMismatch {
|
||||||
|
actual: StatusCode::IM_A_TEAPOT,
|
||||||
|
expected: StatusCode::NOT_FOUND,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn envelope_and_status_contradictions_are_invalid_responses() {
|
||||||
|
let error_body = br#"{"error":{"code":"not_found","message":"missing"}}"#;
|
||||||
|
let on_success =
|
||||||
|
decode_fetch_response(&request(), &response(StatusCode::OK, error_body), limits())
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
on_success,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let success_body = br#"{"name":"","interfaces":[]}"#;
|
||||||
|
let on_error = decode_fetch_response(
|
||||||
|
&request(),
|
||||||
|
&response(StatusCode::BAD_GATEWAY, success_body),
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
on_error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disallowed_protocol_code_is_invalid_instead_of_reclassified() {
|
||||||
|
let body = br#"{"error":{"code":"interface_not_found","message":"wrong interaction"}}"#;
|
||||||
|
let error = decode_fetch_response(&request(), &response(StatusCode::NOT_FOUND, body), limits())
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::InvalidResponse {
|
||||||
|
kind: InvalidResponseKind::DisallowedProtocolCode,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn proxy_authentication_and_endpoint_failures_stay_transport_failures() {
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
TransportFailureKind::HttpStatus,
|
||||||
|
b"proxy failure".as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
TransportFailureKind::AuthenticationRequired,
|
||||||
|
b"login required".as_slice(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
TransportFailureKind::EndpointForbidden,
|
||||||
|
b"denied".as_slice(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (status, expected_kind, body) in cases {
|
||||||
|
let response = Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.body(body.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
let error = decode_fetch_response(&request(), &response, limits()).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == status && failure.kind == expected_kind
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_non_success_envelope_is_transport_binding_failure() {
|
||||||
|
let malformed = response(
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
br#"{"error":{"code":"not_found","message":null}}"#,
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
decode_fetch_response(&request(), &malformed, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(_)
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
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());
|
||||||
|
}
|
||||||
@@ -647,14 +647,17 @@ fn dispatch_arm(operation: &Operation) -> TokenStream2 {
|
|||||||
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
.map_err(::wip_interface::DispatchError::InvalidArguments)?;
|
||||||
let decoded = #arguments_ident::decode(arguments)
|
let decoded = #arguments_ident::decode(arguments)
|
||||||
.map_err(::wip_interface::DispatchError::Decode)?;
|
.map_err(::wip_interface::DispatchError::Decode)?;
|
||||||
let result = implementation.#method_ident(#(#arguments),*)
|
::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
|
||||||
.map_err(::wip_interface::DispatchError::Host)?;
|
let result = implementation.#method_ident(#(#arguments),*)
|
||||||
let encoded = #arguments_ident::encode_result(result)
|
.map_err(::wip_interface::DispatchError::Host)?;
|
||||||
.map_err(::wip_interface::DispatchError::Encode)?;
|
let encoded = #arguments_ident::encode_result(result)
|
||||||
descriptor
|
.map_err(::wip_interface::DispatchError::Encode)?;
|
||||||
.validate_result(#operation_name, &encoded)
|
descriptor
|
||||||
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
.validate_result(#operation_name, &encoded)
|
||||||
::std::result::Result::Ok(encoded)
|
.map_err(::wip_interface::DispatchError::InvalidResult)?;
|
||||||
|
::std::result::Result::Ok(encoded)
|
||||||
|
}))
|
||||||
|
.map_err(|_| ::wip_interface::DispatchError::Panic)?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,8 +46,10 @@
|
|||||||
//! `Option<T>` is supported only directly as a record field or operation
|
//! `Option<T>` is supported only directly as a record field or operation
|
||||||
//! parameter. It means omission, not a null value. A domain failure belongs in
|
//! parameter. It means omission, not a null value. A domain failure belongs in
|
||||||
//! an application return enum/union and is returned as `Ok(value)`.
|
//! an application return enum/union and is returned as `Ok(value)`.
|
||||||
//! [`HostError`] is reserved for host/runtime failure, so the required
|
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
|
||||||
//! [`OperationResult`] convention keeps those two failure classes distinct.
|
//! [`HostErrorKind`] plus [`EffectGuarantee`]. The required [`OperationResult`]
|
||||||
|
//! convention therefore keeps domain failures separate from runtime failures and
|
||||||
|
//! makes outcome uncertainty visible to Host dispatch.
|
||||||
//!
|
//!
|
||||||
//! # Migration to canonical values
|
//! # Migration to canonical values
|
||||||
//!
|
//!
|
||||||
@@ -139,29 +141,107 @@ pub trait InterfaceImplementation<T>: InterfaceDefinition {
|
|||||||
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
/// `Err(HostError)` means the host or runtime could not perform the operation.
|
||||||
pub type OperationResult<T> = Result<T, HostError>;
|
pub type OperationResult<T> = Result<T, HostError>;
|
||||||
|
|
||||||
/// A host/runtime failure, kept separate from the operation's application
|
/// Whether an operation failure proves that no effects were committed.
|
||||||
|
///
|
||||||
|
/// This guarantee is consumed by Host dispatch when choosing a protocol failure:
|
||||||
|
/// only [`NotCommitted`](Self::NotCommitted) failures may become `Internal` or
|
||||||
|
/// `ResourceLimitExceeded`; [`Unknown`](Self::Unknown) failures must become
|
||||||
|
/// `OperationOutcomeUnknown`.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum EffectGuarantee {
|
||||||
|
/// The operation was not invoked, or every effect was rolled back.
|
||||||
|
NotCommitted,
|
||||||
|
/// The operation may have committed effects.
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Host/runtime failure category used when effects are known not to be committed.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum HostErrorKind {
|
||||||
|
/// The Host or backend encountered an internal failure.
|
||||||
|
Internal,
|
||||||
|
/// A cancellation, deadline, or bounded resource limit was exceeded.
|
||||||
|
ResourceLimitExceeded,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A typed host/runtime failure, kept separate from the operation's application
|
||||||
/// return type.
|
/// return type.
|
||||||
|
///
|
||||||
|
/// The effect guarantee is mandatory. Host runtimes must ignore the diagnostic
|
||||||
|
/// when producing a wire response; it is bounded here for local observability but
|
||||||
|
/// can still contain backend-private information.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct HostError {
|
pub struct HostError {
|
||||||
|
kind: HostErrorKind,
|
||||||
|
effect_guarantee: EffectGuarantee,
|
||||||
message: String,
|
message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HostError {
|
impl HostError {
|
||||||
/// Creates a host failure with a human-readable diagnostic.
|
/// Creates an internal Host failure with an explicit effect guarantee.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(message: impl Into<String>) -> Self {
|
pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||||
|
Self::new(HostErrorKind::Internal, effect_guarantee, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a resource-limit Host failure with an explicit effect guarantee.
|
||||||
|
#[must_use]
|
||||||
|
pub fn resource_limit(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
|
||||||
|
Self::new(
|
||||||
|
HostErrorKind::ResourceLimitExceeded,
|
||||||
|
effect_guarantee,
|
||||||
|
message,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new(
|
||||||
|
kind: HostErrorKind,
|
||||||
|
effect_guarantee: EffectGuarantee,
|
||||||
|
message: impl Into<String>,
|
||||||
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
message: message.into(),
|
kind,
|
||||||
|
effect_guarantee,
|
||||||
|
message: bounded_diagnostic(message.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the diagnostic message.
|
/// Returns the typed Host failure category.
|
||||||
|
#[must_use]
|
||||||
|
pub fn kind(&self) -> HostErrorKind {
|
||||||
|
self.kind
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the operation-effect guarantee attached by the implementation.
|
||||||
|
#[must_use]
|
||||||
|
pub fn effect_guarantee(&self) -> EffectGuarantee {
|
||||||
|
self.effect_guarantee
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the bounded local diagnostic message.
|
||||||
|
///
|
||||||
|
/// Host runtimes must not place this value in protocol responses because it
|
||||||
|
/// can contain backend paths, credentials, or other private details.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn message(&self) -> &str {
|
pub fn message(&self) -> &str {
|
||||||
&self.message
|
&self.message
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MAX_DIAGNOSTIC_BYTES: usize = 512;
|
||||||
|
|
||||||
|
fn bounded_diagnostic(mut message: String) -> String {
|
||||||
|
if message.len() <= MAX_DIAGNOSTIC_BYTES {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
let mut end = MAX_DIAGNOSTIC_BYTES;
|
||||||
|
while !message.is_char_boundary(end) {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
message.truncate(end);
|
||||||
|
message
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for HostError {
|
impl Display for HostError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
formatter.write_str(&self.message)
|
formatter.write_str(&self.message)
|
||||||
@@ -241,12 +321,59 @@ pub enum DispatchError {
|
|||||||
Decode(CodecError),
|
Decode(CodecError),
|
||||||
/// The implementation reported a host/runtime failure.
|
/// The implementation reported a host/runtime failure.
|
||||||
Host(HostError),
|
Host(HostError),
|
||||||
|
/// The implementation panicked after invocation began.
|
||||||
|
///
|
||||||
|
/// Panic payloads are deliberately discarded because they can contain
|
||||||
|
/// backend-private diagnostics.
|
||||||
|
Panic,
|
||||||
/// The Rust result could not be encoded.
|
/// The Rust result could not be encoded.
|
||||||
Encode(CodecError),
|
Encode(CodecError),
|
||||||
/// The encoded result did not match the generated declaration.
|
/// The encoded result did not match the generated declaration.
|
||||||
InvalidResult(wip_protocol::ValidationError),
|
InvalidResult(wip_protocol::ValidationError),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether generated dispatch failed before or after typed implementation
|
||||||
|
/// invocation began.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum DispatchPhase {
|
||||||
|
/// Typed implementation code was not invoked.
|
||||||
|
BeforeInvocation,
|
||||||
|
/// Typed implementation invocation began, so effects require an explicit
|
||||||
|
/// non-commit or rollback guarantee.
|
||||||
|
AfterInvocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DispatchError {
|
||||||
|
/// Returns the execution phase in which this dispatch failure occurred.
|
||||||
|
#[must_use]
|
||||||
|
pub fn phase(&self) -> DispatchPhase {
|
||||||
|
match self {
|
||||||
|
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => {
|
||||||
|
DispatchPhase::BeforeInvocation
|
||||||
|
}
|
||||||
|
Self::Host(_) | Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||||
|
DispatchPhase::AfterInvocation
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a post-invocation effect guarantee when the implementation
|
||||||
|
/// supplied one.
|
||||||
|
///
|
||||||
|
/// Panic, encode, and result-validation failures default to `Unknown` until
|
||||||
|
/// a provider confirms rollback. Pre-invocation failures return `None`.
|
||||||
|
#[must_use]
|
||||||
|
pub fn effect_guarantee(&self) -> Option<EffectGuarantee> {
|
||||||
|
match self {
|
||||||
|
Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => None,
|
||||||
|
Self::Host(error) => Some(error.effect_guarantee()),
|
||||||
|
Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
|
||||||
|
Some(EffectGuarantee::Unknown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for DispatchError {
|
impl Display for DispatchError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
@@ -256,6 +383,7 @@ impl Display for DispatchError {
|
|||||||
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
|
||||||
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
|
||||||
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
|
Self::Host(error) => write!(formatter, "host operation failed: {error}"),
|
||||||
|
Self::Panic => formatter.write_str("operation implementation panicked"),
|
||||||
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
|
||||||
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
|
||||||
}
|
}
|
||||||
@@ -265,7 +393,7 @@ impl Display for DispatchError {
|
|||||||
impl Error for DispatchError {
|
impl Error for DispatchError {
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
match self {
|
match self {
|
||||||
Self::UnknownOperation(_) => None,
|
Self::UnknownOperation(_) | Self::Panic => None,
|
||||||
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
|
||||||
Self::Decode(error) | Self::Encode(error) => Some(error),
|
Self::Decode(error) | Self::Encode(error) => Some(error),
|
||||||
Self::Host(error) => Some(error),
|
Self::Host(error) => Some(error),
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
use wip_interface::wip_protocol::{INTERFACE_FORMAT_V1, TypeExpr, Value};
|
||||||
use wip_interface::{DispatchError, HostError, OperationResult, WipType, interface};
|
use wip_interface::{
|
||||||
|
DispatchError, DispatchPhase, EffectGuarantee, HostError, HostErrorKind, OperationResult,
|
||||||
|
WipType, interface,
|
||||||
|
};
|
||||||
|
|
||||||
/// Publication request.
|
/// Publication request.
|
||||||
#[derive(Debug, Clone, PartialEq, WipType)]
|
#[derive(Debug, Clone, PartialEq, WipType)]
|
||||||
@@ -66,7 +69,10 @@ impl Catalog for AcceptingCatalog {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn host_value(&self) -> OperationResult<String> {
|
fn host_value(&self) -> OperationResult<String> {
|
||||||
Err(HostError::new("backend unavailable"))
|
Err(HostError::internal(
|
||||||
|
"backend unavailable",
|
||||||
|
EffectGuarantee::Unknown,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,6 +96,26 @@ impl Catalog for RejectingCatalog {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct PanickingCatalog;
|
||||||
|
|
||||||
|
impl Catalog for PanickingCatalog {
|
||||||
|
fn publish(
|
||||||
|
&self,
|
||||||
|
_request: PublishRequest,
|
||||||
|
_note: Option<String>,
|
||||||
|
) -> OperationResult<PublishOutcome> {
|
||||||
|
panic!("private panic payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ping(&self) -> OperationResult<()> {
|
||||||
|
panic!("private panic payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_value(&self) -> OperationResult<String> {
|
||||||
|
panic!("private panic payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
fn publish_arguments(with_note: bool) -> BTreeMap<String, Value> {
|
||||||
let mut arguments = BTreeMap::from([(
|
let mut arguments = BTreeMap::from([(
|
||||||
"request".into(),
|
"request".into(),
|
||||||
@@ -203,16 +229,41 @@ fn typed_dispatch_validates_decodes_invokes_encodes_and_validates() {
|
|||||||
let invalid =
|
let invalid =
|
||||||
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
CatalogDefinition::dispatch(&AcceptingCatalog, "publish", BTreeMap::new()).unwrap_err();
|
||||||
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
assert!(matches!(invalid, DispatchError::InvalidArguments(_)));
|
||||||
|
assert_eq!(invalid.phase(), DispatchPhase::BeforeInvocation);
|
||||||
|
assert_eq!(invalid.effect_guarantee(), None);
|
||||||
|
|
||||||
let host =
|
let host =
|
||||||
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
CatalogDefinition::dispatch(&AcceptingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||||
assert!(matches!(host, DispatchError::Host(error) if error.message() == "backend unavailable"));
|
assert!(
|
||||||
|
matches!(&host, DispatchError::Host(error) if error.message() == "backend unavailable")
|
||||||
|
);
|
||||||
|
assert_eq!(host.phase(), DispatchPhase::AfterInvocation);
|
||||||
|
assert_eq!(host.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||||
|
|
||||||
|
let panic =
|
||||||
|
CatalogDefinition::dispatch(&PanickingCatalog, "host_value", BTreeMap::new()).unwrap_err();
|
||||||
|
assert!(matches!(panic, DispatchError::Panic));
|
||||||
|
assert_eq!(panic.phase(), DispatchPhase::AfterInvocation);
|
||||||
|
assert_eq!(panic.effect_guarantee(), Some(EffectGuarantee::Unknown));
|
||||||
|
assert!(!panic.to_string().contains("private panic payload"));
|
||||||
|
|
||||||
let unknown =
|
let unknown =
|
||||||
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
CatalogDefinition::dispatch(&AcceptingCatalog, "missing", BTreeMap::new()).unwrap_err();
|
||||||
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
assert!(matches!(unknown, DispatchError::UnknownOperation(name) if name == "missing"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_errors_require_a_typed_kind_and_effect_guarantee() {
|
||||||
|
let internal = HostError::internal("x".repeat(4_096), EffectGuarantee::NotCommitted);
|
||||||
|
assert_eq!(internal.kind(), HostErrorKind::Internal);
|
||||||
|
assert_eq!(internal.effect_guarantee(), EffectGuarantee::NotCommitted);
|
||||||
|
assert!(internal.message().len() <= 512);
|
||||||
|
|
||||||
|
let resource = HostError::resource_limit("deadline", EffectGuarantee::Unknown);
|
||||||
|
assert_eq!(resource.kind(), HostErrorKind::ResourceLimitExceeded);
|
||||||
|
assert_eq!(resource.effect_guarantee(), EffectGuarantee::Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
/// Operations whose distinct source names normalize to the same PascalCase.
|
/// Operations whose distinct source names normalize to the same PascalCase.
|
||||||
#[interface]
|
#[interface]
|
||||||
pub trait DistinctOperations {
|
pub trait DistinctOperations {
|
||||||
|
|||||||
@@ -223,10 +223,29 @@ impl Display for ValidationError {
|
|||||||
|
|
||||||
impl Error for ValidationError {}
|
impl Error for ValidationError {}
|
||||||
|
|
||||||
/// Stable protocol failure code returned by a host or produced by a client.
|
/// One core interaction whose failure codes form a closed set.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ProtocolInteraction {
|
||||||
|
/// Fetch one object by its Worldspace path.
|
||||||
|
Fetch,
|
||||||
|
/// Fetch a bounded tree of objects.
|
||||||
|
FetchTree,
|
||||||
|
/// Fetch one interface descriptor by its opaque reference.
|
||||||
|
FetchInterface,
|
||||||
|
/// Invoke one operation on a path-targeted object.
|
||||||
|
CallOperation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable protocol failure code returned by a host.
|
||||||
|
///
|
||||||
|
/// This is the complete wire-level code set. A Client treats a malformed success
|
||||||
|
/// or failure response, including a code disallowed for its interaction, as a
|
||||||
|
/// Client-local `InvalidResponse`. An unsupported descriptor format is likewise
|
||||||
|
/// a Client-local `UnsupportedDescriptorFormat`; neither condition is a code a
|
||||||
|
/// Host can return.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ProtocolErrorCode {
|
pub enum ProtocolErrorCode {
|
||||||
/// The request is structurally invalid.
|
/// The request is structurally invalid before an operation descriptor is fixed.
|
||||||
InvalidRequest,
|
InvalidRequest,
|
||||||
/// The target object is not published.
|
/// The target object is not published.
|
||||||
NotFound,
|
NotFound,
|
||||||
@@ -236,10 +255,8 @@ pub enum ProtocolErrorCode {
|
|||||||
InterfaceMismatch,
|
InterfaceMismatch,
|
||||||
/// The selected operation is not declared by the current interface.
|
/// The selected operation is not declared by the current interface.
|
||||||
OperationNotFound,
|
OperationNotFound,
|
||||||
/// Supplied operation arguments are invalid.
|
/// Supplied arguments do not match the fixed operation declaration.
|
||||||
InvalidArguments,
|
InvalidArguments,
|
||||||
/// A host result does not satisfy the declaration.
|
|
||||||
InvalidResult,
|
|
||||||
/// The operation requires an object validator and none was supplied.
|
/// The operation requires an object validator and none was supplied.
|
||||||
ValidatorRequired,
|
ValidatorRequired,
|
||||||
/// The supplied object validator does not match current state.
|
/// The supplied object validator does not match current state.
|
||||||
@@ -251,9 +268,88 @@ pub enum ProtocolErrorCode {
|
|||||||
/// A published operation is not permitted for the caller.
|
/// A published operation is not permitted for the caller.
|
||||||
PermissionDenied,
|
PermissionDenied,
|
||||||
/// A bounded protocol resource limit was exceeded.
|
/// A bounded protocol resource limit was exceeded.
|
||||||
|
///
|
||||||
|
/// For `call_operation`, the Host guarantees that the operation was not run
|
||||||
|
/// or that all of its effects were rolled back.
|
||||||
ResourceLimitExceeded,
|
ResourceLimitExceeded,
|
||||||
/// The host encountered an internal failure.
|
/// The Host encountered an internal failure.
|
||||||
|
///
|
||||||
|
/// For `call_operation`, the Host guarantees that the operation was not run
|
||||||
|
/// or that all of its effects were rolled back.
|
||||||
Internal,
|
Internal,
|
||||||
|
/// The Host cannot guarantee that the operation was not run or rolled back.
|
||||||
|
///
|
||||||
|
/// A Client must not automatically retry because the operation may have
|
||||||
|
/// committed effects even though no success response was available.
|
||||||
|
OperationOutcomeUnknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProtocolErrorCode {
|
||||||
|
/// Every canonical wire-level error code.
|
||||||
|
pub const ALL: [Self; 14] = [
|
||||||
|
Self::InvalidRequest,
|
||||||
|
Self::NotFound,
|
||||||
|
Self::InterfaceNotFound,
|
||||||
|
Self::InterfaceMismatch,
|
||||||
|
Self::OperationNotFound,
|
||||||
|
Self::InvalidArguments,
|
||||||
|
Self::ValidatorRequired,
|
||||||
|
Self::ValidatorMismatch,
|
||||||
|
Self::InterfaceValidatorRequired,
|
||||||
|
Self::InterfaceValidatorMismatch,
|
||||||
|
Self::PermissionDenied,
|
||||||
|
Self::ResourceLimitExceeded,
|
||||||
|
Self::Internal,
|
||||||
|
Self::OperationOutcomeUnknown,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Whether a Host may return this code for `interaction`.
|
||||||
|
///
|
||||||
|
/// `false` identifies an invalid error response; it does not turn that
|
||||||
|
/// response into another wire-level protocol failure.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn is_allowed_for(self, interaction: ProtocolInteraction) -> bool {
|
||||||
|
use ProtocolErrorCode::{
|
||||||
|
InterfaceMismatch, InterfaceNotFound, InterfaceValidatorMismatch,
|
||||||
|
InterfaceValidatorRequired, Internal, InvalidArguments, InvalidRequest, NotFound,
|
||||||
|
OperationNotFound, OperationOutcomeUnknown, PermissionDenied, ResourceLimitExceeded,
|
||||||
|
ValidatorMismatch, ValidatorRequired,
|
||||||
|
};
|
||||||
|
use ProtocolInteraction::{CallOperation, Fetch, FetchInterface, FetchTree};
|
||||||
|
|
||||||
|
match (interaction, self) {
|
||||||
|
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
|
||||||
|
(Fetch | FetchTree, NotFound) => true,
|
||||||
|
(FetchInterface, InterfaceNotFound) => true,
|
||||||
|
(
|
||||||
|
CallOperation,
|
||||||
|
NotFound
|
||||||
|
| InterfaceMismatch
|
||||||
|
| OperationNotFound
|
||||||
|
| InvalidArguments
|
||||||
|
| ValidatorRequired
|
||||||
|
| ValidatorMismatch
|
||||||
|
| InterfaceValidatorRequired
|
||||||
|
| InterfaceValidatorMismatch
|
||||||
|
| PermissionDenied
|
||||||
|
| OperationOutcomeUnknown,
|
||||||
|
) => true,
|
||||||
|
(
|
||||||
|
_,
|
||||||
|
NotFound
|
||||||
|
| InterfaceNotFound
|
||||||
|
| InterfaceMismatch
|
||||||
|
| OperationNotFound
|
||||||
|
| InvalidArguments
|
||||||
|
| ValidatorRequired
|
||||||
|
| ValidatorMismatch
|
||||||
|
| InterfaceValidatorRequired
|
||||||
|
| InterfaceValidatorMismatch
|
||||||
|
| PermissionDenied
|
||||||
|
| OperationOutcomeUnknown,
|
||||||
|
) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport-independent protocol failure.
|
/// Transport-independent protocol failure.
|
||||||
|
|||||||
@@ -16,7 +16,20 @@
|
|||||||
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
||||||
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
||||||
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
||||||
//! | Stable failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
//! | Stable Host failure taxonomy | [`ProtocolErrorCode`] / [`ProtocolError`] |
|
||||||
|
//! | Per-interaction allowed failure codes | [`ProtocolInteraction`] / [`ProtocolErrorCode::is_allowed_for`] |
|
||||||
|
//!
|
||||||
|
//! [`ProtocolErrorCode`] is a closed set of Host-returned wire failures. After a
|
||||||
|
//! Client receives a response, an invalid Object, Descriptor, operation result,
|
||||||
|
//! malformed error, or error code disallowed by [`ProtocolInteraction`] is a
|
||||||
|
//! Client-local `InvalidResponse`, not another wire error. A descriptor whose
|
||||||
|
//! `format` is not supported is a Client-local `UnsupportedDescriptorFormat`.
|
||||||
|
//!
|
||||||
|
//! For `call_operation`, [`ProtocolErrorCode::Internal`] and
|
||||||
|
//! [`ProtocolErrorCode::ResourceLimitExceeded`] guarantee that the operation did
|
||||||
|
//! not run or that all effects were rolled back. Only
|
||||||
|
//! [`ProtocolErrorCode::OperationOutcomeUnknown`] means the Host cannot make that
|
||||||
|
//! guarantee; Clients must not automatically retry it.
|
||||||
//!
|
//!
|
||||||
//! Paths, object refs, interface refs, and validators remain separate concepts.
|
//! Paths, object refs, interface refs, and validators remain separate concepts.
|
||||||
//! They are represented by ordinary protocol strings/bytes in the corresponding
|
//! They are represented by ordinary protocol strings/bytes in the corresponding
|
||||||
@@ -35,8 +48,8 @@ mod model;
|
|||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub use error::{
|
pub use error::{
|
||||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ValidationError,
|
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
ValidationErrorKind, ValueKind,
|
ValidationError, ValidationErrorKind, ValueKind,
|
||||||
};
|
};
|
||||||
pub use model::{
|
pub use model::{
|
||||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
|
|||||||
@@ -379,6 +379,9 @@ impl FetchRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Validates an object returned for this request.
|
/// Validates an object returned for this request.
|
||||||
|
///
|
||||||
|
/// 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> {
|
pub fn validate_response(&self, response: &FetchResponse) -> Result<(), ValidationError> {
|
||||||
response.validate_at_path(&self.path)
|
response.validate_at_path(&self.path)
|
||||||
}
|
}
|
||||||
@@ -393,6 +396,9 @@ impl FetchTreeRequest {
|
|||||||
|
|
||||||
impl FetchTreeResponse {
|
impl FetchTreeResponse {
|
||||||
/// Validates tree shape, names, depth, and node limit for `request`.
|
/// 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> {
|
pub fn validate_for(&self, request: &FetchTreeRequest) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_fetch_tree_response(self, request)
|
crate::validation::validate_fetch_tree_response(self, request)
|
||||||
}
|
}
|
||||||
@@ -400,6 +406,11 @@ impl FetchTreeResponse {
|
|||||||
|
|
||||||
impl FetchInterfaceResponse {
|
impl FetchInterfaceResponse {
|
||||||
/// Validates request correspondence and descriptor semantics.
|
/// Validates request correspondence and descriptor semantics.
|
||||||
|
///
|
||||||
|
/// Failure means the Client received an invalid success response; it is not a
|
||||||
|
/// Host-returned [`crate::ProtocolErrorCode`]. Descriptor format support is a
|
||||||
|
/// separate Client concern: an otherwise valid descriptor with an unsupported
|
||||||
|
/// `format` is a Client-local `UnsupportedDescriptorFormat`.
|
||||||
pub fn validate_for(&self, request: &FetchInterfaceRequest) -> Result<(), ValidationError> {
|
pub fn validate_for(&self, request: &FetchInterfaceRequest) -> Result<(), ValidationError> {
|
||||||
crate::validation::validate_fetch_interface_response(self, request)
|
crate::validation::validate_fetch_interface_response(self, request)
|
||||||
}
|
}
|
||||||
@@ -414,6 +425,9 @@ impl CallOperationRequest {
|
|||||||
|
|
||||||
impl CallOperationResponse {
|
impl CallOperationResponse {
|
||||||
/// Validates this result against the named operation in `descriptor`.
|
/// Validates this result against the named operation in `descriptor`.
|
||||||
|
///
|
||||||
|
/// Failure means the Client received an invalid success response; it is not a
|
||||||
|
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||||
pub fn validate_for(
|
pub fn validate_for(
|
||||||
&self,
|
&self,
|
||||||
descriptor: &InterfaceDescriptor,
|
descriptor: &InterfaceDescriptor,
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ use wip_protocol::{
|
|||||||
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
|
FetchInterfaceResponse, FetchRequest, FetchTreeRequest, FetchTreeResponse, FieldDeclaration,
|
||||||
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace,
|
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace,
|
||||||
Object, ObjectTreeNode, OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError,
|
Object, ObjectTreeNode, OperationDeclaration, ParameterDeclaration, PathSegment, ProtocolError,
|
||||||
ProtocolErrorCode, ProtocolResult, ReturnDeclaration, Target, TypeDeclaration, TypeExpr,
|
ProtocolErrorCode, ProtocolInteraction, ProtocolResult, ReturnDeclaration, Target,
|
||||||
UnionCase, ValidationErrorKind, Value, ValueKind,
|
TypeDeclaration, TypeExpr, UnionCase, ValidationErrorKind, Value, ValueKind,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||||
@@ -729,24 +729,26 @@ fn fetch_tree_dtos_validate_names_depth_limit_and_siblings() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn protocol_result_and_every_canonical_error_code_are_available() {
|
fn protocol_result_exposes_the_exact_canonical_wire_error_codes() {
|
||||||
let codes = [
|
assert_eq!(
|
||||||
ProtocolErrorCode::InvalidRequest,
|
ProtocolErrorCode::ALL,
|
||||||
ProtocolErrorCode::NotFound,
|
[
|
||||||
ProtocolErrorCode::InterfaceNotFound,
|
ProtocolErrorCode::InvalidRequest,
|
||||||
ProtocolErrorCode::InterfaceMismatch,
|
ProtocolErrorCode::NotFound,
|
||||||
ProtocolErrorCode::OperationNotFound,
|
ProtocolErrorCode::InterfaceNotFound,
|
||||||
ProtocolErrorCode::InvalidArguments,
|
ProtocolErrorCode::InterfaceMismatch,
|
||||||
ProtocolErrorCode::InvalidResult,
|
ProtocolErrorCode::OperationNotFound,
|
||||||
ProtocolErrorCode::ValidatorRequired,
|
ProtocolErrorCode::InvalidArguments,
|
||||||
ProtocolErrorCode::ValidatorMismatch,
|
ProtocolErrorCode::ValidatorRequired,
|
||||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
ProtocolErrorCode::ValidatorMismatch,
|
||||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
ProtocolErrorCode::PermissionDenied,
|
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
ProtocolErrorCode::ResourceLimitExceeded,
|
ProtocolErrorCode::PermissionDenied,
|
||||||
ProtocolErrorCode::Internal,
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
];
|
ProtocolErrorCode::Internal,
|
||||||
assert_eq!(codes.len(), 14);
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
let failure: ProtocolResult<()> = ProtocolResult::Failure(ProtocolError {
|
let failure: ProtocolResult<()> = ProtocolResult::Failure(ProtocolError {
|
||||||
code: ProtocolErrorCode::InvalidArguments,
|
code: ProtocolErrorCode::InvalidArguments,
|
||||||
@@ -758,3 +760,127 @@ fn protocol_result_and_every_canonical_error_code_are_available() {
|
|||||||
ProtocolResult::Success(Value::Unit)
|
ProtocolResult::Success(Value::Unit)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn assert_allowed_codes(interaction: ProtocolInteraction, expected: &[ProtocolErrorCode]) {
|
||||||
|
let actual: Vec<_> = ProtocolErrorCode::ALL
|
||||||
|
.into_iter()
|
||||||
|
.filter(|code| code.is_allowed_for(interaction))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(actual, expected);
|
||||||
|
|
||||||
|
for code in ProtocolErrorCode::ALL {
|
||||||
|
assert_eq!(
|
||||||
|
code.is_allowed_for(interaction),
|
||||||
|
expected.contains(&code),
|
||||||
|
"unexpected {code:?} validity for {interaction:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fetch_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,
|
||||||
|
&[
|
||||||
|
ProtocolErrorCode::InvalidRequest,
|
||||||
|
ProtocolErrorCode::NotFound,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fetch_interface_error_codes_are_exhaustive() {
|
||||||
|
assert_allowed_codes(
|
||||||
|
ProtocolInteraction::FetchInterface,
|
||||||
|
&[
|
||||||
|
ProtocolErrorCode::InvalidRequest,
|
||||||
|
ProtocolErrorCode::InterfaceNotFound,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn call_operation_error_codes_are_exhaustive() {
|
||||||
|
assert_allowed_codes(
|
||||||
|
ProtocolInteraction::CallOperation,
|
||||||
|
&[
|
||||||
|
ProtocolErrorCode::InvalidRequest,
|
||||||
|
ProtocolErrorCode::NotFound,
|
||||||
|
ProtocolErrorCode::InterfaceMismatch,
|
||||||
|
ProtocolErrorCode::OperationNotFound,
|
||||||
|
ProtocolErrorCode::InvalidArguments,
|
||||||
|
ProtocolErrorCode::ValidatorRequired,
|
||||||
|
ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||||
|
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||||
|
ProtocolErrorCode::PermissionDenied,
|
||||||
|
ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
|
ProtocolErrorCode::Internal,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_success_payloads_remain_client_local_validation_failures() {
|
||||||
|
let fetch = FetchRequest {
|
||||||
|
path: "/articles/one".into(),
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
fetch.validate_response(&object("other")).unwrap_err().kind,
|
||||||
|
ValidationErrorKind::ObjectNameMismatch { .. }
|
||||||
|
));
|
||||||
|
|
||||||
|
let interface_request = FetchInterfaceRequest {
|
||||||
|
interface: "catalog-v1".into(),
|
||||||
|
};
|
||||||
|
let mut invalid_descriptor = descriptor();
|
||||||
|
invalid_descriptor
|
||||||
|
.operations
|
||||||
|
.push(invalid_descriptor.operations[0].clone());
|
||||||
|
assert!(matches!(
|
||||||
|
FetchInterfaceResponse {
|
||||||
|
interface: interface_request.interface.clone(),
|
||||||
|
descriptor: invalid_descriptor,
|
||||||
|
validator: None,
|
||||||
|
}
|
||||||
|
.validate_for(&interface_request)
|
||||||
|
.unwrap_err()
|
||||||
|
.kind,
|
||||||
|
ValidationErrorKind::DuplicateName {
|
||||||
|
namespace: NameNamespace::Operation,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
CallOperationResponse {
|
||||||
|
result: Value::String("not a boolean".into()),
|
||||||
|
validator: None,
|
||||||
|
}
|
||||||
|
.validate_for(&descriptor(), "publish")
|
||||||
|
.unwrap_err()
|
||||||
|
.kind,
|
||||||
|
ValidationErrorKind::TypeMismatch {
|
||||||
|
expected: ValueKind::Boolean,
|
||||||
|
actual: ValueKind::String,
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[package]
|
||||||
|
name = "wip-public-api-example"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Public-only end-to-end conformance consumer for the WIP Rust APIs"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
wip-host = { path = "../wip-host" }
|
||||||
|
wip-interface = { path = "../wip-interface" }
|
||||||
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
@@ -0,0 +1,541 @@
|
|||||||
|
//! Public-only conformance consumer for the WIP Rust crates.
|
||||||
|
//!
|
||||||
|
//! # Architectural boundary
|
||||||
|
//!
|
||||||
|
//! This package is an ordinary application consumer. Its direct dependencies are
|
||||||
|
//! the public `wip-protocol`, `wip-interface`, and `wip-host` crates; it neither
|
||||||
|
//! imports workspace-private modules nor depends on `wip-interface-macros`.
|
||||||
|
//! `wip-protocol` owns transport-independent DTOs and schema-neutral values,
|
||||||
|
//! while this package owns its application DTOs and interface traits. The
|
||||||
|
//! request-scoped implementation, backend handle, authorization policy, and
|
||||||
|
//! publication wiring remain host-private. A transport binding would translate
|
||||||
|
//! its own wire routes and envelopes to the protocol call DTOs; no HTTP type is
|
||||||
|
//! part of an application trait or interface descriptor.
|
||||||
|
//!
|
||||||
|
//! # Breaking migration exercised here
|
||||||
|
//!
|
||||||
|
//! The canonical API targets operations by `target.path` rather than a mandatory
|
||||||
|
//! object identifier. Object `ref` and object/interface validators are separate,
|
||||||
|
//! optional observation fields. Interface references are opaque values observed
|
||||||
|
//! separately from descriptors, and descriptors contain neither a Rust trait
|
||||||
|
//! name nor an opaque-reference `name` field. Application records, enums,
|
||||||
|
//! unions, entry paths, and JSON all encode through the schema-neutral [`Value`]
|
||||||
|
//! variants: entries and enums are strings, unions are discriminator records,
|
||||||
|
//! and JSON recursively uses ordinary records/lists/primitives. The former
|
||||||
|
//! `Entry<K, V>` and semantic `Value::Entry`, `Value::Enum`, `Value::Union`, and
|
||||||
|
//! `Value::Json` forms are intentionally unsupported.
|
||||||
|
//!
|
||||||
|
//! # Supported authoring subset
|
||||||
|
//!
|
||||||
|
//! Public, non-generic traits use immutable `&self` receivers, owned named
|
||||||
|
//! parameters, and explicit `wip::OperationResult<T>` returns. Derived DTOs are
|
||||||
|
//! named-field records, all-unit enums, or unions with unit and single-payload
|
||||||
|
//! cases. A direct `Option<T>` means field/argument omission, never protocol
|
||||||
|
//! null. See `wip-interface` for the complete rejected-syntax list.
|
||||||
|
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::error::Error;
|
||||||
|
use std::io;
|
||||||
|
|
||||||
|
use wip_host::{
|
||||||
|
CallErrorKind, CallRequest, ExecutionContext, InterfaceRef, InterfaceRegistry, InterfaceTarget,
|
||||||
|
ObjectProvider, ProviderResult, PublishedObject, RegisteredInterface, Target, Validator,
|
||||||
|
WipObject,
|
||||||
|
};
|
||||||
|
use wip_interface as wip;
|
||||||
|
use wip_interface::WipType;
|
||||||
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, Value};
|
||||||
|
|
||||||
|
const OBJECT_PATH: &str = "/article-service";
|
||||||
|
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
||||||
|
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
|
||||||
|
|
||||||
|
/// Publication visibility represented as a protocol enum string.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||||
|
pub enum Visibility {
|
||||||
|
/// Visible to every authorized caller.
|
||||||
|
Public,
|
||||||
|
/// Visible only inside the application domain.
|
||||||
|
Private,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An application-owned request DTO mapped to a protocol record.
|
||||||
|
#[derive(Debug, Clone, PartialEq, wip::WipType)]
|
||||||
|
pub struct PublishRequest {
|
||||||
|
/// Title of the article to publish.
|
||||||
|
pub title: String,
|
||||||
|
/// Optional article body; omission is distinct from JSON null.
|
||||||
|
pub body: Option<String>,
|
||||||
|
/// Canonical Worldspace path to the source entry.
|
||||||
|
pub source: wip::Entry,
|
||||||
|
/// Application enum represented by a schema-neutral string.
|
||||||
|
pub visibility: Visibility,
|
||||||
|
/// Schema-opaque JSON represented by ordinary protocol values.
|
||||||
|
pub metadata: wip::JsonValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The application domain result of a publication attempt.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
||||||
|
pub enum PublishOutcome {
|
||||||
|
/// Publication succeeded and returned its application identifier.
|
||||||
|
Published(String),
|
||||||
|
/// An application policy rejected the publication.
|
||||||
|
Rejected(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Article publication operations.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait Catalog {
|
||||||
|
/// Publishes an article or reports an application-domain rejection.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// The typed application outcome.
|
||||||
|
fn publish(
|
||||||
|
&self,
|
||||||
|
/// Application publication request.
|
||||||
|
request: PublishRequest,
|
||||||
|
) -> wip::OperationResult<PublishOutcome>;
|
||||||
|
|
||||||
|
/// Returns the catalog-qualified status.
|
||||||
|
fn status(&self) -> wip::OperationResult<String>;
|
||||||
|
|
||||||
|
/// Demonstrates a rollback-confirmed host/backend failure.
|
||||||
|
fn backend_status(&self) -> wip::OperationResult<String>;
|
||||||
|
|
||||||
|
/// Demonstrates a host/backend failure with an unknown operation outcome.
|
||||||
|
fn uncertain_backend_status(&self) -> wip::OperationResult<String>;
|
||||||
|
|
||||||
|
/// Demonstrates denial after every structural precondition succeeds.
|
||||||
|
fn restricted_status(&self) -> wip::OperationResult<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Audit operations exposed by the same object.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait Audit {
|
||||||
|
/// Returns the audit-qualified status.
|
||||||
|
fn status(&self) -> wip::OperationResult<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A registered but deliberately unexposed interface.
|
||||||
|
#[wip::interface]
|
||||||
|
pub trait Diagnostics {
|
||||||
|
/// Returns host-private diagnostics when explicitly exposed.
|
||||||
|
fn diagnostics(&self) -> wip::OperationResult<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Observable outcomes from the complete public-API scenario.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct DemoReport {
|
||||||
|
/// Path-segment name from the canonical object projection.
|
||||||
|
pub object_name: String,
|
||||||
|
/// Optional object identity, distinct from the resolution path.
|
||||||
|
pub object_reference: Option<String>,
|
||||||
|
/// Optional object-state validator.
|
||||||
|
pub object_validator: Option<Vec<u8>>,
|
||||||
|
/// Opaque interface references published by the object, in exposure order.
|
||||||
|
pub published_interfaces: Vec<String>,
|
||||||
|
/// Opaque reference assigned to the catalog descriptor.
|
||||||
|
pub catalog_interface_reference: String,
|
||||||
|
/// Opaque reference assigned to the audit descriptor.
|
||||||
|
pub audit_interface_reference: String,
|
||||||
|
/// Descriptor format observed separately for the catalog reference.
|
||||||
|
pub catalog_descriptor_format: String,
|
||||||
|
/// Descriptor format observed separately for the audit reference.
|
||||||
|
pub audit_descriptor_format: String,
|
||||||
|
/// Typed successful application result decoded from a validated [`Value`].
|
||||||
|
pub published: PublishOutcome,
|
||||||
|
/// Typed application-domain rejection decoded from a validated [`Value`].
|
||||||
|
pub rejected: PublishOutcome,
|
||||||
|
/// Result of the catalog-qualified `status` operation.
|
||||||
|
pub catalog_status: String,
|
||||||
|
/// Result of the audit-qualified `status` operation.
|
||||||
|
pub audit_status: String,
|
||||||
|
/// Stable failure kind produced by the deliberate host/backend failure.
|
||||||
|
pub host_failure: CallErrorKind,
|
||||||
|
/// Protocol failure whose operation effects are guaranteed not committed.
|
||||||
|
pub protocol_failure: ProtocolError,
|
||||||
|
/// Protocol failure whose operation effects cannot be proven absent.
|
||||||
|
pub unknown_protocol_failure: ProtocolError,
|
||||||
|
/// Authorization failure after a fully qualified valid request.
|
||||||
|
pub permission_failure: ProtocolErrorCode,
|
||||||
|
/// Recovery signal for a stale object validator.
|
||||||
|
pub validator_failure: ProtocolErrorCode,
|
||||||
|
/// Failure for a known but unexposed interface reference.
|
||||||
|
pub interface_mismatch: ProtocolErrorCode,
|
||||||
|
/// Failure for an unknown interface observation reference.
|
||||||
|
pub interface_not_found: ProtocolErrorCode,
|
||||||
|
/// First failure for a request with an invalid path and later invalid fields.
|
||||||
|
pub precedence_failure: ProtocolErrorCode,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the complete end-to-end conformance example.
|
||||||
|
///
|
||||||
|
/// The provider resolves the current object from a Worldspace path for each
|
||||||
|
/// call. Interface observations remain separate from object projection, and all
|
||||||
|
/// successful calls carry independent object and interface validators.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns an error if registration, observation, path resolution, dispatch, or
|
||||||
|
/// application-value decoding fails unexpectedly.
|
||||||
|
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
||||||
|
let mut registry = InterfaceRegistry::new();
|
||||||
|
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
|
||||||
|
let audit = registry.register(AuditDefinition, None)?;
|
||||||
|
let diagnostics = registry.register(DiagnosticsDefinition, None)?;
|
||||||
|
let provider = ApplicationProvider {
|
||||||
|
catalog: catalog.clone(),
|
||||||
|
audit: audit.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let object = provider.fetch(OBJECT_PATH)?;
|
||||||
|
let catalog_response = registry
|
||||||
|
.fetch_interface(
|
||||||
|
object
|
||||||
|
.interfaces
|
||||||
|
.first()
|
||||||
|
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
||||||
|
)?
|
||||||
|
.protocol_response()?;
|
||||||
|
let audit_response = registry
|
||||||
|
.fetch_interface(
|
||||||
|
object
|
||||||
|
.interfaces
|
||||||
|
.get(1)
|
||||||
|
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
|
||||||
|
)?
|
||||||
|
.protocol_response()?;
|
||||||
|
|
||||||
|
let published = dispatch_publish(
|
||||||
|
&provider,
|
||||||
|
catalog.reference(),
|
||||||
|
PublishRequest {
|
||||||
|
title: "Public APIs".into(),
|
||||||
|
body: Some("protocol values in, validated values out".into()),
|
||||||
|
source: wip::Entry::new("/drafts/public-apis")?,
|
||||||
|
visibility: Visibility::Public,
|
||||||
|
metadata: wip::JsonValue::Object(vec![wip::JsonMember {
|
||||||
|
name: "reviewed".into(),
|
||||||
|
value: wip::JsonValue::Boolean(true),
|
||||||
|
}]),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
let rejected = dispatch_publish(
|
||||||
|
&provider,
|
||||||
|
catalog.reference(),
|
||||||
|
PublishRequest {
|
||||||
|
title: String::new(),
|
||||||
|
body: None,
|
||||||
|
source: wip::Entry::new("/drafts/untitled")?,
|
||||||
|
visibility: Visibility::Private,
|
||||||
|
metadata: wip::JsonValue::Null,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
let catalog_status = dispatch_string(
|
||||||
|
&provider,
|
||||||
|
request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
catalog.reference(),
|
||||||
|
Some(CATALOG_VALIDATOR),
|
||||||
|
"status",
|
||||||
|
BTreeMap::new(),
|
||||||
|
),
|
||||||
|
)?;
|
||||||
|
let audit_status = dispatch_string(
|
||||||
|
&provider,
|
||||||
|
request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
audit.reference(),
|
||||||
|
None,
|
||||||
|
"status",
|
||||||
|
BTreeMap::new(),
|
||||||
|
),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let host_error = provider
|
||||||
|
.call_operation(request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
catalog.reference(),
|
||||||
|
Some(CATALOG_VALIDATOR),
|
||||||
|
"backend_status",
|
||||||
|
BTreeMap::new(),
|
||||||
|
))
|
||||||
|
.expect_err("backend_status must model a host failure");
|
||||||
|
ensure_kind(&host_error, CallErrorKind::Internal)?;
|
||||||
|
let protocol_failure = host_error.protocol_error();
|
||||||
|
|
||||||
|
let unknown_protocol_failure = provider
|
||||||
|
.call_operation(request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
catalog.reference(),
|
||||||
|
Some(CATALOG_VALIDATOR),
|
||||||
|
"uncertain_backend_status",
|
||||||
|
BTreeMap::new(),
|
||||||
|
))
|
||||||
|
.expect_err("uncertain_backend_status must preserve an unknown outcome")
|
||||||
|
.protocol_error();
|
||||||
|
|
||||||
|
let permission_failure = provider
|
||||||
|
.call_operation(request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
catalog.reference(),
|
||||||
|
Some(CATALOG_VALIDATOR),
|
||||||
|
"restricted_status",
|
||||||
|
BTreeMap::new(),
|
||||||
|
))
|
||||||
|
.expect_err("restricted_status must be denied")
|
||||||
|
.protocol_error()
|
||||||
|
.code;
|
||||||
|
|
||||||
|
let validator_failure = provider
|
||||||
|
.call_operation(CallRequest {
|
||||||
|
target: Target {
|
||||||
|
path: OBJECT_PATH.into(),
|
||||||
|
validator: Some(b"stale-object".to_vec()),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: diagnostics.reference().as_str().to_owned(),
|
||||||
|
validator: Some(b"stale-interface".to_vec()),
|
||||||
|
},
|
||||||
|
operation: "missing".into(),
|
||||||
|
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||||
|
})
|
||||||
|
.expect_err("the stale object validator must fail first")
|
||||||
|
.protocol_error()
|
||||||
|
.code;
|
||||||
|
|
||||||
|
let interface_mismatch = provider
|
||||||
|
.call_operation(request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
diagnostics.reference(),
|
||||||
|
None,
|
||||||
|
"diagnostics",
|
||||||
|
BTreeMap::new(),
|
||||||
|
))
|
||||||
|
.expect_err("registered but unexposed interface must not dispatch")
|
||||||
|
.protocol_error()
|
||||||
|
.code;
|
||||||
|
|
||||||
|
let interface_not_found = registry
|
||||||
|
.fetch_interface("missing-interface")
|
||||||
|
.expect_err("unknown interface references must not resolve")
|
||||||
|
.code;
|
||||||
|
|
||||||
|
let precedence_failure = provider
|
||||||
|
.call_operation(CallRequest {
|
||||||
|
target: Target {
|
||||||
|
path: "relative/path".into(),
|
||||||
|
validator: Some(b"stale-object".to_vec()),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: diagnostics.reference().as_str().to_owned(),
|
||||||
|
validator: Some(b"stale-interface".to_vec()),
|
||||||
|
},
|
||||||
|
operation: "missing".into(),
|
||||||
|
arguments: BTreeMap::from([("unknown".into(), Value::Unit)]),
|
||||||
|
})
|
||||||
|
.expect_err("invalid path must have canonical precedence")
|
||||||
|
.protocol_error()
|
||||||
|
.code;
|
||||||
|
|
||||||
|
Ok(DemoReport {
|
||||||
|
object_name: object.name,
|
||||||
|
object_reference: object.r#ref,
|
||||||
|
object_validator: object.validator,
|
||||||
|
published_interfaces: object.interfaces,
|
||||||
|
catalog_interface_reference: catalog.reference().as_str().to_owned(),
|
||||||
|
audit_interface_reference: audit.reference().as_str().to_owned(),
|
||||||
|
catalog_descriptor_format: catalog_response.descriptor.format,
|
||||||
|
audit_descriptor_format: audit_response.descriptor.format,
|
||||||
|
published,
|
||||||
|
rejected,
|
||||||
|
catalog_status,
|
||||||
|
audit_status,
|
||||||
|
host_failure: host_error.kind(),
|
||||||
|
protocol_failure,
|
||||||
|
unknown_protocol_failure,
|
||||||
|
permission_failure,
|
||||||
|
validator_failure,
|
||||||
|
interface_mismatch,
|
||||||
|
interface_not_found,
|
||||||
|
precedence_failure,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_kind(error: &wip_host::CallError, expected: CallErrorKind) -> Result<(), io::Error> {
|
||||||
|
if error.kind() == expected {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::other(format!(
|
||||||
|
"unexpected host failure kind: {:?}",
|
||||||
|
error.kind()
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_publish(
|
||||||
|
provider: &ApplicationProvider,
|
||||||
|
catalog: &InterfaceRef,
|
||||||
|
request_value: PublishRequest,
|
||||||
|
) -> Result<PublishOutcome, Box<dyn Error>> {
|
||||||
|
let encoded_request = request_value.encode()?;
|
||||||
|
let result = provider.call_operation(request(
|
||||||
|
OBJECT_PATH,
|
||||||
|
catalog,
|
||||||
|
Some(CATALOG_VALIDATOR),
|
||||||
|
"publish",
|
||||||
|
BTreeMap::from([("request".into(), encoded_request)]),
|
||||||
|
))?;
|
||||||
|
Ok(PublishOutcome::decode(result.result)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_string(
|
||||||
|
provider: &ApplicationProvider,
|
||||||
|
request: CallRequest,
|
||||||
|
) -> Result<String, Box<dyn Error>> {
|
||||||
|
let result = provider.call_operation(request)?;
|
||||||
|
Ok(String::decode(result.result)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(
|
||||||
|
path: &str,
|
||||||
|
interface: &InterfaceRef,
|
||||||
|
interface_validator: Option<&[u8]>,
|
||||||
|
operation: &str,
|
||||||
|
arguments: BTreeMap<String, Value>,
|
||||||
|
) -> CallRequest {
|
||||||
|
CallRequest {
|
||||||
|
target: Target {
|
||||||
|
path: path.into(),
|
||||||
|
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
||||||
|
},
|
||||||
|
interface: InterfaceTarget {
|
||||||
|
reference: interface.as_str().to_owned(),
|
||||||
|
validator: interface_validator.map(<[u8]>::to_vec),
|
||||||
|
},
|
||||||
|
operation: operation.into(),
|
||||||
|
arguments,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ApplicationProvider {
|
||||||
|
catalog: RegisteredInterface<CatalogDefinition>,
|
||||||
|
audit: RegisteredInterface<AuditDefinition>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObjectProvider for ApplicationProvider {
|
||||||
|
type Object = ApplicationService;
|
||||||
|
|
||||||
|
fn with_object<R>(
|
||||||
|
&self,
|
||||||
|
_context: &ExecutionContext,
|
||||||
|
path: &str,
|
||||||
|
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
||||||
|
) -> ProviderResult<R> {
|
||||||
|
if path != OBJECT_PATH {
|
||||||
|
return ProviderResult::NotFound;
|
||||||
|
}
|
||||||
|
let publication = PublishedObject::new(ApplicationService::new())
|
||||||
|
.expose(&self.catalog)
|
||||||
|
.expect("ApplicationService implements Catalog")
|
||||||
|
.expose(&self.audit)
|
||||||
|
.expect("ApplicationService implements Audit");
|
||||||
|
ProviderResult::Found(operation(&publication))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn authorize(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: &ApplicationService,
|
||||||
|
_: &InterfaceRef,
|
||||||
|
operation: &str,
|
||||||
|
) -> bool {
|
||||||
|
operation != "restricted_status"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ApplicationService {
|
||||||
|
object_validator: Validator,
|
||||||
|
backend_connection: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationService {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
object_validator: Validator::new(OBJECT_VALIDATOR),
|
||||||
|
backend_connection: "private://article-database".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WipObject for ApplicationService {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"article-service"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> Option<&str> {
|
||||||
|
Some("Article publication service")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reference(&self) -> Option<&str> {
|
||||||
|
Some("article-service-instance")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validator(&self) -> Option<&Validator> {
|
||||||
|
Some(&self.object_validator)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Catalog for ApplicationService {
|
||||||
|
fn publish(&self, request: PublishRequest) -> wip::OperationResult<PublishOutcome> {
|
||||||
|
if request.title.trim().is_empty() {
|
||||||
|
Ok(PublishOutcome::Rejected("a title is required".into()))
|
||||||
|
} else {
|
||||||
|
Ok(PublishOutcome::Published("article-1".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status(&self) -> wip::OperationResult<String> {
|
||||||
|
Ok("catalog-ready".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backend_status(&self) -> wip::OperationResult<String> {
|
||||||
|
if self.backend_connection.starts_with("private://") {
|
||||||
|
Err(wip::HostError::internal(
|
||||||
|
"backend unavailable",
|
||||||
|
wip::EffectGuarantee::NotCommitted,
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Ok("backend-ready".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uncertain_backend_status(&self) -> wip::OperationResult<String> {
|
||||||
|
Err(wip::HostError::internal(
|
||||||
|
"backend commit acknowledgement unavailable",
|
||||||
|
wip::EffectGuarantee::Unknown,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restricted_status(&self) -> wip::OperationResult<String> {
|
||||||
|
Ok("authorization hook should prevent this call".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Audit for ApplicationService {
|
||||||
|
fn status(&self) -> wip::OperationResult<String> {
|
||||||
|
Ok("audit-ready".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Diagnostics for ApplicationService {
|
||||||
|
fn diagnostics(&self) -> wip::OperationResult<String> {
|
||||||
|
Ok("host-private".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use wip_host::CallErrorKind;
|
||||||
|
use wip_interface::{Entry, JsonMember, JsonValue, WipType};
|
||||||
|
use wip_protocol::{INTERFACE_FORMAT_V1, InterfaceDescriptor, Object, ProtocolErrorCode, Value};
|
||||||
|
use wip_public_api_example::{CatalogDefinition, PublishOutcome, PublishRequest, Visibility, run};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn public_crates_support_the_complete_qualified_end_to_end_scenario() {
|
||||||
|
let report = run().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(report.object_name, "article-service");
|
||||||
|
assert_eq!(
|
||||||
|
report.object_reference.as_deref(),
|
||||||
|
Some("article-service-instance")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.object_validator.as_deref(),
|
||||||
|
Some(b"object-v1".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.published_interfaces,
|
||||||
|
[
|
||||||
|
report.catalog_interface_reference.clone(),
|
||||||
|
report.audit_interface_reference.clone(),
|
||||||
|
],
|
||||||
|
"interfaces must retain explicit publication order"
|
||||||
|
);
|
||||||
|
assert_ne!(
|
||||||
|
report.catalog_interface_reference, report.audit_interface_reference,
|
||||||
|
"interfaces form an ordered set of distinct opaque references"
|
||||||
|
);
|
||||||
|
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
||||||
|
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
|
||||||
|
assert_eq!(
|
||||||
|
report.published,
|
||||||
|
PublishOutcome::Published("article-1".into())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.rejected,
|
||||||
|
PublishOutcome::Rejected("a title is required".into())
|
||||||
|
);
|
||||||
|
assert_eq!(report.catalog_status, "catalog-ready");
|
||||||
|
assert_eq!(report.audit_status, "audit-ready");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn domain_host_permission_and_validator_failures_remain_distinct() {
|
||||||
|
let report = run().unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(report.rejected, PublishOutcome::Rejected(_)));
|
||||||
|
assert_eq!(report.host_failure, CallErrorKind::Internal);
|
||||||
|
assert_eq!(report.protocol_failure.code, ProtocolErrorCode::Internal);
|
||||||
|
assert_eq!(
|
||||||
|
report.unknown_protocol_failure.code,
|
||||||
|
ProtocolErrorCode::OperationOutcomeUnknown
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.permission_failure,
|
||||||
|
ProtocolErrorCode::PermissionDenied
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.validator_failure,
|
||||||
|
ProtocolErrorCode::ValidatorMismatch,
|
||||||
|
"validator recovery signals must not collapse to InvalidRequest"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn interface_mismatch_is_not_interface_not_found() {
|
||||||
|
let report = run().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
report.interface_mismatch,
|
||||||
|
ProtocolErrorCode::InterfaceMismatch
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
report.interface_not_found,
|
||||||
|
ProtocolErrorCode::InterfaceNotFound
|
||||||
|
);
|
||||||
|
assert_ne!(report.interface_mismatch, report.interface_not_found);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_path_keeps_canonical_failure_precedence() {
|
||||||
|
let report = run().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(report.precedence_failure, ProtocolErrorCode::InvalidRequest);
|
||||||
|
assert_ne!(report.precedence_failure, report.validator_failure);
|
||||||
|
assert_ne!(report.precedence_failure, report.interface_mismatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn object_fields_keep_path_context_and_optional_ref_separate() {
|
||||||
|
// Listing every field makes this test fail to compile if a mandatory
|
||||||
|
// ObjectId is reintroduced into the canonical object DTO.
|
||||||
|
let object = Object {
|
||||||
|
name: "article".into(),
|
||||||
|
description: None,
|
||||||
|
interfaces: vec!["catalog-ref".into(), "audit-ref".into()],
|
||||||
|
r#ref: None,
|
||||||
|
validator: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
object.validate_at_path("/library/article").unwrap();
|
||||||
|
assert_eq!(object.name, "article");
|
||||||
|
assert_eq!(object.r#ref, None);
|
||||||
|
assert_eq!(object.interfaces, ["catalog-ref", "audit-ref"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn interface_reference_is_observed_separately_from_descriptor_fields() {
|
||||||
|
// An exact destructuring pattern is compile-time coverage that the
|
||||||
|
// descriptor has no trait-name or opaque-reference `name` field.
|
||||||
|
let InterfaceDescriptor {
|
||||||
|
format,
|
||||||
|
documentation,
|
||||||
|
types,
|
||||||
|
operations,
|
||||||
|
} = CatalogDefinition::descriptor();
|
||||||
|
|
||||||
|
assert_eq!(format, INTERFACE_FORMAT_V1);
|
||||||
|
assert!(documentation.is_some());
|
||||||
|
assert!(!types.is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
operations
|
||||||
|
.iter()
|
||||||
|
.map(|operation| operation.name.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
[
|
||||||
|
"publish",
|
||||||
|
"status",
|
||||||
|
"backend_status",
|
||||||
|
"uncertain_backend_status",
|
||||||
|
"restricted_status",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn application_record_enum_union_entry_and_json_use_schema_neutral_values() {
|
||||||
|
let request = PublishRequest {
|
||||||
|
title: "Canonical values".into(),
|
||||||
|
body: None,
|
||||||
|
source: Entry::new("/drafts/canonical-values").unwrap(),
|
||||||
|
visibility: Visibility::Public,
|
||||||
|
metadata: JsonValue::Object(vec![
|
||||||
|
JsonMember {
|
||||||
|
name: "tags".into(),
|
||||||
|
value: JsonValue::Array(vec![JsonValue::String("wip".into()), JsonValue::Null]),
|
||||||
|
},
|
||||||
|
JsonMember {
|
||||||
|
name: "ready".into(),
|
||||||
|
value: JsonValue::Boolean(true),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
|
let encoded = request.encode().unwrap();
|
||||||
|
assert_schema_neutral(&encoded);
|
||||||
|
let Value::Record(fields) = encoded else {
|
||||||
|
panic!("derived DTO record must use Value::Record")
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
fields.get("title"),
|
||||||
|
Some(&Value::String("Canonical values".into()))
|
||||||
|
);
|
||||||
|
assert!(!fields.contains_key("body"));
|
||||||
|
assert_eq!(
|
||||||
|
fields.get("source"),
|
||||||
|
Some(&Value::String("/drafts/canonical-values".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fields.get("visibility"),
|
||||||
|
Some(&Value::String("Public".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fields.get("metadata"),
|
||||||
|
Some(&Value::Record(BTreeMap::from([
|
||||||
|
("ready".into(), Value::Boolean(true)),
|
||||||
|
(
|
||||||
|
"tags".into(),
|
||||||
|
Value::List(vec![Value::String("wip".into()), Value::Unit])
|
||||||
|
),
|
||||||
|
])))
|
||||||
|
);
|
||||||
|
|
||||||
|
let outcome = PublishOutcome::Rejected("policy".into()).encode().unwrap();
|
||||||
|
assert_schema_neutral(&outcome);
|
||||||
|
assert_eq!(
|
||||||
|
outcome,
|
||||||
|
Value::Record(BTreeMap::from([
|
||||||
|
("$case".into(), Value::String("Rejected".into())),
|
||||||
|
("value".into(), Value::String("policy".into())),
|
||||||
|
]))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entry_is_a_validated_canonical_absolute_path_string() {
|
||||||
|
let entry = Entry::new("/articles/one").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
entry.encode().unwrap(),
|
||||||
|
Value::String("/articles/one".into())
|
||||||
|
);
|
||||||
|
|
||||||
|
for invalid in [
|
||||||
|
"articles/one",
|
||||||
|
"/articles/",
|
||||||
|
"/articles//one",
|
||||||
|
"/articles/./one",
|
||||||
|
"/articles/../one",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
Entry::new(invalid).is_err(),
|
||||||
|
"accepted invalid path {invalid}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
Entry::decode(Value::String(invalid.into())).is_err(),
|
||||||
|
"decoded invalid path {invalid}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_schema_neutral(value: &Value) {
|
||||||
|
// This exhaustive match is a compile-time regression guard: reintroducing
|
||||||
|
// semantic Entry/Enum/Union/Json variants makes the consumer non-exhaustive.
|
||||||
|
match value {
|
||||||
|
Value::Unit
|
||||||
|
| Value::Boolean(_)
|
||||||
|
| Value::Integer(_)
|
||||||
|
| Value::Number(_)
|
||||||
|
| Value::String(_)
|
||||||
|
| Value::Bytes(_) => {}
|
||||||
|
Value::Record(fields) => {
|
||||||
|
for value in fields.values() {
|
||||||
|
assert_schema_neutral(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::List(values) => {
|
||||||
|
for value in values {
|
||||||
|
assert_schema_neutral(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
-360
@@ -1,360 +0,0 @@
|
|||||||
//! End-to-end use of the public WIP protocol, interface, and host APIs.
|
|
||||||
//!
|
|
||||||
//! This workspace package defines application DTOs and interfaces with
|
|
||||||
//! `wip-interface`, keeps its implementation private, publishes it through a
|
|
||||||
//! request-scoped `wip-host` provider, and crosses the call boundary only with
|
|
||||||
//! canonical `wip-protocol` values and path targets.
|
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::io;
|
|
||||||
|
|
||||||
use wip_host::{
|
|
||||||
CallErrorKind, CallRequest, InterfaceRef, InterfaceRegistry, InterfaceTarget, ObjectProvider,
|
|
||||||
PublishedObject, RegisteredInterface, Target, Validator, WipObject,
|
|
||||||
};
|
|
||||||
use wip_interface as wip;
|
|
||||||
use wip_interface::WipType;
|
|
||||||
use wip_protocol::ProtocolError;
|
|
||||||
|
|
||||||
const OBJECT_PATH: &str = "/article-service";
|
|
||||||
const OBJECT_VALIDATOR: &[u8] = b"object-v1";
|
|
||||||
const CATALOG_VALIDATOR: &[u8] = b"catalog-v1";
|
|
||||||
|
|
||||||
/// An application-owned request DTO mapped to a protocol record.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
|
||||||
pub struct PublishRequest {
|
|
||||||
/// Title of the article to publish.
|
|
||||||
pub title: String,
|
|
||||||
/// Optional article body; omission is distinct from JSON null.
|
|
||||||
pub body: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The application domain result of a publication attempt.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, wip::WipType)]
|
|
||||||
pub enum PublishOutcome {
|
|
||||||
/// Publication succeeded and returned its application identifier.
|
|
||||||
Published(String),
|
|
||||||
/// An application policy rejected the publication.
|
|
||||||
Rejected(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Article publication operations.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait Catalog {
|
|
||||||
/// Publishes an article or reports an application-domain rejection.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// The typed application outcome.
|
|
||||||
fn publish(
|
|
||||||
&self,
|
|
||||||
/// Application publication request.
|
|
||||||
request: PublishRequest,
|
|
||||||
) -> wip::OperationResult<PublishOutcome>;
|
|
||||||
|
|
||||||
/// Returns the catalog-qualified status.
|
|
||||||
fn status(&self) -> wip::OperationResult<String>;
|
|
||||||
|
|
||||||
/// Demonstrates a host/backend failure rather than a domain result.
|
|
||||||
fn backend_status(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Audit operations exposed by the same object.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait Audit {
|
|
||||||
/// Returns the audit-qualified status.
|
|
||||||
fn status(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A registered but deliberately unexposed interface.
|
|
||||||
#[wip::interface]
|
|
||||||
pub trait Diagnostics {
|
|
||||||
/// Returns host-private diagnostics when explicitly exposed.
|
|
||||||
fn diagnostics(&self) -> wip::OperationResult<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Observable outcomes from the complete public-API scenario.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct DemoReport {
|
|
||||||
/// Opaque interface references published by the object, in exposure order.
|
|
||||||
pub published_interfaces: Vec<String>,
|
|
||||||
/// Descriptor format observed for the catalog interface.
|
|
||||||
pub catalog_descriptor_format: String,
|
|
||||||
/// Descriptor format observed for the audit interface.
|
|
||||||
pub audit_descriptor_format: String,
|
|
||||||
/// Typed successful application result decoded from a validated `Value`.
|
|
||||||
pub published: PublishOutcome,
|
|
||||||
/// Typed application-domain rejection decoded from a validated `Value`.
|
|
||||||
pub rejected: PublishOutcome,
|
|
||||||
/// Result of the catalog-qualified `status` operation.
|
|
||||||
pub catalog_status: String,
|
|
||||||
/// Result of the audit-qualified `status` operation.
|
|
||||||
pub audit_status: String,
|
|
||||||
/// Stable failure kind produced by the deliberate host/backend failure.
|
|
||||||
pub host_failure: CallErrorKind,
|
|
||||||
/// A protocol-level failure built from the host failure.
|
|
||||||
pub protocol_failure: ProtocolError,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs the complete end-to-end example.
|
|
||||||
///
|
|
||||||
/// The provider resolves the current object from a Worldspace path for each
|
|
||||||
/// call. Interface observations remain separate from object projection, and all
|
|
||||||
/// calls carry independent object and interface validators.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
///
|
|
||||||
/// Returns an error if registration, observation, path resolution, dispatch, or
|
|
||||||
/// application-value decoding fails unexpectedly.
|
|
||||||
pub fn run() -> Result<DemoReport, Box<dyn Error>> {
|
|
||||||
let mut registry = InterfaceRegistry::new();
|
|
||||||
let catalog = registry.register(CatalogDefinition, Some(Validator::new(CATALOG_VALIDATOR)))?;
|
|
||||||
let audit = registry.register(AuditDefinition, None)?;
|
|
||||||
let _diagnostics = registry.register(DiagnosticsDefinition, None)?;
|
|
||||||
let provider = ApplicationProvider {
|
|
||||||
catalog: catalog.clone(),
|
|
||||||
audit: audit.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let object = provider.fetch(OBJECT_PATH)?;
|
|
||||||
let catalog_observation = registry.fetch_interface(
|
|
||||||
object
|
|
||||||
.interfaces
|
|
||||||
.first()
|
|
||||||
.ok_or_else(|| io::Error::other("catalog interface was not published"))?,
|
|
||||||
)?;
|
|
||||||
let audit_observation = registry.fetch_interface(
|
|
||||||
object
|
|
||||||
.interfaces
|
|
||||||
.get(1)
|
|
||||||
.ok_or_else(|| io::Error::other("audit interface was not published"))?,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let published = dispatch_publish(
|
|
||||||
&provider,
|
|
||||||
catalog.reference(),
|
|
||||||
PublishRequest {
|
|
||||||
title: "Public APIs".into(),
|
|
||||||
body: Some("protocol values in, validated values out".into()),
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let rejected = dispatch_publish(
|
|
||||||
&provider,
|
|
||||||
catalog.reference(),
|
|
||||||
PublishRequest {
|
|
||||||
title: String::new(),
|
|
||||||
body: None,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let catalog_status = dispatch_string(
|
|
||||||
&provider,
|
|
||||||
request(
|
|
||||||
catalog.reference(),
|
|
||||||
Some(CATALOG_VALIDATOR),
|
|
||||||
"status",
|
|
||||||
BTreeMap::new(),
|
|
||||||
),
|
|
||||||
)?;
|
|
||||||
let audit_status = dispatch_string(
|
|
||||||
&provider,
|
|
||||||
request(audit.reference(), None, "status", BTreeMap::new()),
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let host_error = provider
|
|
||||||
.call_operation(request(
|
|
||||||
catalog.reference(),
|
|
||||||
Some(CATALOG_VALIDATOR),
|
|
||||||
"backend_status",
|
|
||||||
BTreeMap::new(),
|
|
||||||
))
|
|
||||||
.unwrap_err();
|
|
||||||
if host_error.kind() != CallErrorKind::Implementation {
|
|
||||||
return Err(io::Error::other(format!(
|
|
||||||
"unexpected host failure kind: {:?}",
|
|
||||||
host_error.kind()
|
|
||||||
))
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let protocol_failure = host_error.protocol_error();
|
|
||||||
|
|
||||||
Ok(DemoReport {
|
|
||||||
published_interfaces: object.interfaces,
|
|
||||||
catalog_descriptor_format: catalog_observation.descriptor.format,
|
|
||||||
audit_descriptor_format: audit_observation.descriptor.format,
|
|
||||||
published,
|
|
||||||
rejected,
|
|
||||||
catalog_status,
|
|
||||||
audit_status,
|
|
||||||
host_failure: host_error.kind(),
|
|
||||||
protocol_failure,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_publish(
|
|
||||||
provider: &ApplicationProvider,
|
|
||||||
catalog: &InterfaceRef,
|
|
||||||
request_value: PublishRequest,
|
|
||||||
) -> Result<PublishOutcome, Box<dyn Error>> {
|
|
||||||
let encoded_request = request_value.encode()?;
|
|
||||||
let result = provider.call_operation(request(
|
|
||||||
catalog,
|
|
||||||
Some(CATALOG_VALIDATOR),
|
|
||||||
"publish",
|
|
||||||
BTreeMap::from([("request".into(), encoded_request)]),
|
|
||||||
))?;
|
|
||||||
Ok(PublishOutcome::decode(result.result)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_string(
|
|
||||||
provider: &ApplicationProvider,
|
|
||||||
request: CallRequest,
|
|
||||||
) -> Result<String, Box<dyn Error>> {
|
|
||||||
let result = provider.call_operation(request)?;
|
|
||||||
Ok(String::decode(result.result)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request(
|
|
||||||
interface: &InterfaceRef,
|
|
||||||
interface_validator: Option<&[u8]>,
|
|
||||||
operation: &str,
|
|
||||||
arguments: BTreeMap<String, wip_protocol::Value>,
|
|
||||||
) -> CallRequest {
|
|
||||||
CallRequest {
|
|
||||||
target: Target {
|
|
||||||
path: OBJECT_PATH.into(),
|
|
||||||
validator: Some(OBJECT_VALIDATOR.to_vec()),
|
|
||||||
},
|
|
||||||
interface: InterfaceTarget {
|
|
||||||
reference: interface.as_str().to_owned(),
|
|
||||||
validator: interface_validator.map(<[u8]>::to_vec),
|
|
||||||
},
|
|
||||||
operation: operation.into(),
|
|
||||||
arguments,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ApplicationProvider {
|
|
||||||
catalog: RegisteredInterface<CatalogDefinition>,
|
|
||||||
audit: RegisteredInterface<AuditDefinition>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ObjectProvider for ApplicationProvider {
|
|
||||||
type Object = ApplicationService;
|
|
||||||
|
|
||||||
fn with_object<R>(
|
|
||||||
&self,
|
|
||||||
path: &str,
|
|
||||||
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
|
|
||||||
) -> Option<R> {
|
|
||||||
if path != OBJECT_PATH {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let publication = PublishedObject::new(ApplicationService::new())
|
|
||||||
.expose(&self.catalog)
|
|
||||||
.expect("ApplicationService implements Catalog")
|
|
||||||
.expose(&self.audit)
|
|
||||||
.expect("ApplicationService implements Audit");
|
|
||||||
Some(operation(&publication))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ApplicationService {
|
|
||||||
object_validator: Validator,
|
|
||||||
backend_connection: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApplicationService {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
object_validator: Validator::new(OBJECT_VALIDATOR),
|
|
||||||
backend_connection: "private://article-database".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WipObject for ApplicationService {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"article-service"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn description(&self) -> Option<&str> {
|
|
||||||
Some("Article publication service")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reference(&self) -> Option<&str> {
|
|
||||||
Some("article-service-instance")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validator(&self) -> Option<&Validator> {
|
|
||||||
Some(&self.object_validator)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn requires_validator(&self, _: &InterfaceRef, _: &str) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Catalog for ApplicationService {
|
|
||||||
fn publish(&self, request: PublishRequest) -> wip::OperationResult<PublishOutcome> {
|
|
||||||
if request.title.trim().is_empty() {
|
|
||||||
Ok(PublishOutcome::Rejected("a title is required".into()))
|
|
||||||
} else {
|
|
||||||
Ok(PublishOutcome::Published("article-1".into()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status(&self) -> wip::OperationResult<String> {
|
|
||||||
Ok("catalog-ready".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn backend_status(&self) -> wip::OperationResult<String> {
|
|
||||||
if self.backend_connection.starts_with("private://") {
|
|
||||||
Err(wip::HostError::new("backend unavailable"))
|
|
||||||
} else {
|
|
||||||
Ok("backend-ready".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Audit for ApplicationService {
|
|
||||||
fn status(&self) -> wip::OperationResult<String> {
|
|
||||||
Ok("audit-ready".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Diagnostics for ApplicationService {
|
|
||||||
fn diagnostics(&self) -> wip::OperationResult<String> {
|
|
||||||
Ok("host-private".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use wip_protocol::ProtocolErrorCode;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unexposed_interfaces_are_membership_failures() {
|
|
||||||
let mut registry = InterfaceRegistry::new();
|
|
||||||
let catalog = registry.register(CatalogDefinition, None).unwrap();
|
|
||||||
let audit = registry.register(AuditDefinition, None).unwrap();
|
|
||||||
let diagnostics = registry.register(DiagnosticsDefinition, None).unwrap();
|
|
||||||
let provider = ApplicationProvider { catalog, audit };
|
|
||||||
|
|
||||||
let error = provider
|
|
||||||
.call_operation(request(
|
|
||||||
diagnostics.reference(),
|
|
||||||
None,
|
|
||||||
"diagnostics",
|
|
||||||
BTreeMap::new(),
|
|
||||||
))
|
|
||||||
.unwrap_err();
|
|
||||||
assert_eq!(error.kind(), CallErrorKind::InterfaceMismatch);
|
|
||||||
assert_eq!(
|
|
||||||
error.protocol_error().code,
|
|
||||||
ProtocolErrorCode::InterfaceMismatch
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
use wip_host::CallErrorKind;
|
|
||||||
use wip_protocol::{INTERFACE_FORMAT_V1, ProtocolErrorCode};
|
|
||||||
use wip_public_api_example::{PublishOutcome, run};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn public_crates_support_the_complete_end_to_end_scenario() {
|
|
||||||
let report = run().unwrap();
|
|
||||||
|
|
||||||
assert_eq!(report.published_interfaces.len(), 2);
|
|
||||||
assert_eq!(report.catalog_descriptor_format, INTERFACE_FORMAT_V1);
|
|
||||||
assert_eq!(report.audit_descriptor_format, INTERFACE_FORMAT_V1);
|
|
||||||
assert_eq!(
|
|
||||||
report.published,
|
|
||||||
PublishOutcome::Published("article-1".into())
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
report.rejected,
|
|
||||||
PublishOutcome::Rejected("a title is required".into())
|
|
||||||
);
|
|
||||||
assert_eq!(report.catalog_status, "catalog-ready");
|
|
||||||
assert_eq!(report.audit_status, "audit-ready");
|
|
||||||
assert_eq!(report.host_failure, CallErrorKind::Implementation);
|
|
||||||
assert_eq!(report.protocol_failure.code, ProtocolErrorCode::Internal);
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user