feat(wip): integrate scoped SDK and object-centered tools
Vendor the reproducible 1cbe03b4 Client/HTTP/Protocol/Text View snapshot with Cargo checksums and credential-free Nix dependency closure. Migrate native and compatibility publications to structured references and scope_ref, preserve target-first preconditions and frozen call descriptors, and expose Tree/Inspect/Invoke with complete edge coverage and official signatures. Validation: worker 888 unit + 110 integration tests; pinned upstream Client63, HTTP39, Protocol23, TextView20 tests/doctests; root cargo check --locked --offline; format/diff checks; 43-file vendor checksum verification; nix build --no-link .#yoi.cargoDeps. Details and provider migration seams: docs/development/wip-integration-validation.md.
This commit is contained in:
Generated
+8
-6
@@ -6340,8 +6340,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wip-client"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73a82416411af69b7eb4ad0ed9a954df062769d3a03b3a1c59b0b4bf617f3534"
|
||||
dependencies = [
|
||||
"wip-http",
|
||||
"wip-protocol",
|
||||
@@ -6350,8 +6348,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wip-http"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ec0d32d1e56e52fb9ce925db808354a3432b3ebbd112fab8c443c9b865c58c6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
@@ -6364,8 +6360,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wip-protocol"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "275ffaebf544a077de7578fd3674c062a098a72c5a904cf66e934f76bd9efbab"
|
||||
|
||||
[[package]]
|
||||
name = "wip-text-view"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"wip-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wiremock"
|
||||
@@ -6549,6 +6550,7 @@ dependencies = [
|
||||
"wip-client",
|
||||
"wip-http",
|
||||
"wip-protocol",
|
||||
"wip-text-view",
|
||||
"workdir",
|
||||
]
|
||||
|
||||
|
||||
+12
-3
@@ -1,4 +1,5 @@
|
||||
[workspace]
|
||||
exclude = ["vendor/wip-rs/wip-client", "vendor/wip-rs/wip-http", "vendor/wip-rs/wip-protocol", "vendor/wip-rs/wip-text-view"]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"crates/client",
|
||||
@@ -161,8 +162,16 @@ tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||
url = "2.5"
|
||||
uuid = "1.23"
|
||||
wip-client = "0.1.0"
|
||||
wip-http = "0.1.0"
|
||||
wip-protocol = "0.1.0"
|
||||
# Structured scope/lifetime contract and canonical Text View (Unreleased upstream).
|
||||
wip-client = { path = "vendor/wip-rs/wip-client", version = "=0.1.0" }
|
||||
wip-http = { path = "vendor/wip-rs/wip-http", version = "=0.1.0" }
|
||||
wip-protocol = { path = "vendor/wip-rs/wip-protocol", version = "=0.1.0" }
|
||||
wip-text-view = { path = "vendor/wip-rs/wip-text-view", version = "=0.1.0" }
|
||||
zeroize = "1"
|
||||
webauthn-rs = { version = "0.5.2", features = ["danger-allow-state-serialisation", "danger-credential-internals"] }
|
||||
|
||||
[workspace.metadata.wip-upstream]
|
||||
repository = "ssh://git@gitea.hareworks.net/Hare/wip-rs.git"
|
||||
revision = "1cbe03b49e48dd7e0be28b76fbc3c932f8920a36"
|
||||
reference-revision = "6086f3c5ef10aa1464ce9c824750d7f667217bfd"
|
||||
source = "vendor/wip-rs"
|
||||
|
||||
@@ -54,6 +54,7 @@ base64 = { workspace = true }
|
||||
wip-client = { workspace = true }
|
||||
wip-http = { workspace = true }
|
||||
wip-protocol = { workspace = true }
|
||||
wip-text-view = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
axum = { workspace = true }
|
||||
|
||||
@@ -90,7 +90,7 @@ manifests of already-running Workers.
|
||||
|
||||
Public integration seams: `WorkspaceConfigFeature::for_workspace`,
|
||||
`workspace_config::wip::mount_workspace_config_wip`, and
|
||||
`WipRuntime::from_mounts` plus `discover`/`inspect`/`call`. Worker tests exercise the
|
||||
`WipRuntime::from_mounts` plus `tree`/`inspect`/`invoke`. Worker tests exercise the
|
||||
real Feature registry, native mount and WIP Client/Host through a typed in-process
|
||||
contract router: deep discovery, slash/native attach, read/edit/write,
|
||||
create/delete, atomic multi-source updates, grant restrictions/revocation,
|
||||
|
||||
@@ -146,8 +146,10 @@ impl Provider {
|
||||
kind: &str,
|
||||
handler: Arc<dyn WipOperationHandler>,
|
||||
) -> WipProjection {
|
||||
let encoded: String = path.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
||||
let interface = format!("yoi.checkout/{}/{kind}/v1/@/{encoded}", self.incarnation);
|
||||
let interface = crate::wip::contextual_reference(
|
||||
&format!("yoi.checkout/{}/{kind}/v1", self.incarnation),
|
||||
path,
|
||||
);
|
||||
let interface_validator = Sha256::digest(format!("{descriptor:?}")).to_vec();
|
||||
WipProjection {
|
||||
route: path.into(),
|
||||
|
||||
@@ -320,8 +320,8 @@ fn native_runtime(remote: Arc<RemoteWorkdirSession>) -> (WipRuntime, Arc<Workdir
|
||||
(runtime, router)
|
||||
}
|
||||
|
||||
async fn observe_interface(runtime: &WipRuntime, path: &str) -> String {
|
||||
runtime.discover(path.into(), 0, true).await.unwrap();
|
||||
async fn observe_interface(runtime: &WipRuntime, path: &str) -> wip_protocol::InterfaceReference {
|
||||
runtime.tree(path.into(), 0, true).await.unwrap();
|
||||
// Select from the real Client's Known Space, not a direct handler invocation.
|
||||
let interface = {
|
||||
let state = runtime.state.lock().unwrap();
|
||||
@@ -337,7 +337,7 @@ async fn observe_interface(runtime: &WipRuntime, path: &str) -> String {
|
||||
.interfaces[0]
|
||||
.clone()
|
||||
};
|
||||
runtime.inspect(interface.clone(), true).await.unwrap();
|
||||
runtime.inspect(path.into(), true).await.unwrap();
|
||||
interface
|
||||
}
|
||||
|
||||
|
||||
@@ -33,10 +33,10 @@ fn runtime(
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
async fn interface(r: &WipRuntime, path: &str) -> String {
|
||||
r.discover(path.into(), 0, true).await.unwrap();
|
||||
async fn interface(r: &WipRuntime, path: &str) -> wip_protocol::InterfaceReference {
|
||||
r.tree(path.into(), 0, true).await.unwrap();
|
||||
let p = r.host.projection_live(path).await.unwrap().unwrap();
|
||||
r.inspect(p.interface.clone(), true).await.unwrap();
|
||||
r.inspect(path.into(), true).await.unwrap();
|
||||
p.interface
|
||||
}
|
||||
async fn call(
|
||||
|
||||
@@ -101,7 +101,8 @@ pub fn mount_workspace_workdir_wip(
|
||||
for domain in [Domain::Repository, Domain::Workdir, Domain::Attachment] {
|
||||
let namespace =
|
||||
registry.allocate_namespace(domain.owner(), domain.route().trim_start_matches('/'))?;
|
||||
let interface = format!("yoi.{}/collection/v1", domain.owner());
|
||||
let interface =
|
||||
crate::wip::root_reference(&format!("yoi.{}/collection/v1", domain.owner()));
|
||||
let handler = Arc::new(CollectionHandler {
|
||||
provider: provider.clone(),
|
||||
domain,
|
||||
@@ -130,7 +131,7 @@ pub fn mount_workspace_workdir_wip(
|
||||
handler,
|
||||
})?;
|
||||
}
|
||||
let item_interface = format!("yoi.{}/item/v1", domain.owner());
|
||||
let item_interface = crate::wip::root_reference(&format!("yoi.{}/item/v1", domain.owner()));
|
||||
let resolver = Arc::new(ItemResolver {
|
||||
provider: provider.clone(),
|
||||
domain,
|
||||
@@ -668,7 +669,7 @@ impl WipDynamicItemResolver for ItemResolver {
|
||||
}
|
||||
let raw = self.provider.raw_item(self.domain, &id).ok()?;
|
||||
let projected = self.provider.projected(self.domain, &raw).ok()?;
|
||||
let interface = format!("yoi.{}/item/v1", self.domain.owner());
|
||||
let interface = crate::wip::root_reference(&format!("yoi.{}/item/v1", self.domain.owner()));
|
||||
Some(WipDynamicItem {
|
||||
object: object(&item_path(self.domain, &id), &id, &interface, &projected),
|
||||
handler: Arc::new(ItemHandler {
|
||||
@@ -836,7 +837,12 @@ impl WipOperationHandler for ItemHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn object(path: &str, identity: &str, interface: &str, value: &Json) -> Object {
|
||||
fn object(
|
||||
path: &str,
|
||||
identity: &str,
|
||||
interface: &wip_protocol::InterfaceReference,
|
||||
value: &Json,
|
||||
) -> Object {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(path);
|
||||
digest.update([0]);
|
||||
@@ -844,7 +850,7 @@ fn object(path: &str, identity: &str, interface: &str, value: &Json) -> Object {
|
||||
Object {
|
||||
name: path.rsplit('/').next().unwrap_or_default().into(),
|
||||
description: Some(format!("Workspace authority Object: {identity}")),
|
||||
interfaces: vec![interface.into()],
|
||||
interfaces: vec![interface.clone()],
|
||||
r#ref: Some(identity.into()),
|
||||
validator: Some(digest.finalize().to_vec()),
|
||||
}
|
||||
@@ -1658,7 +1664,7 @@ pub(crate) mod tests {
|
||||
registry.contribute_operations(WipOperationContribution {
|
||||
route: WORKDIRS.into(),
|
||||
contributor: "another-feature".into(),
|
||||
interface: "yoi.workdir/collection/v1".into(),
|
||||
interface: crate::wip::root_reference("yoi.workdir/collection/v1"),
|
||||
descriptor: collection_descriptor(Domain::Workdir, true),
|
||||
handler: Arc::new(CollectionHandler {
|
||||
provider: provider(Arc::new(CatalogClient::default()), true, true, None),
|
||||
|
||||
@@ -559,14 +559,16 @@ pub fn mount_workspace_http_merge_request_wip(
|
||||
description: Some(
|
||||
"Authoritative Merge Request collection through scoped Backend authority".into(),
|
||||
),
|
||||
interfaces: vec![MERGE_REQUEST_COLLECTION_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(
|
||||
MERGE_REQUEST_COLLECTION_INTERFACE,
|
||||
)],
|
||||
r#ref: Some("merge-request:collection".into()),
|
||||
validator: Some(merge_request_route_validator(
|
||||
&collection_route,
|
||||
"collection",
|
||||
)),
|
||||
},
|
||||
interface: MERGE_REQUEST_COLLECTION_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(MERGE_REQUEST_COLLECTION_INTERFACE),
|
||||
interface_validator: Some(merge_request_descriptor_validator(&collection_descriptor)),
|
||||
descriptor: collection_descriptor,
|
||||
handler: Arc::new(MergeRequestCollectionWipHandler {
|
||||
@@ -585,7 +587,7 @@ pub fn mount_workspace_http_merge_request_wip(
|
||||
registry.mount_dynamic(WipDynamicMount {
|
||||
collection_route: collection_route.clone(),
|
||||
capability: "merge-request:item".into(),
|
||||
interface: MERGE_REQUEST_ITEM_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(MERGE_REQUEST_ITEM_INTERFACE),
|
||||
interface_validator: Some(merge_request_descriptor_validator(&item_descriptor)),
|
||||
descriptor: item_descriptor,
|
||||
resolver: Arc::new(MergeRequestItemResolver {
|
||||
@@ -683,7 +685,7 @@ impl WipDynamicItemResolver for MergeRequestItemResolver {
|
||||
object: Object {
|
||||
name: item_reference.into(),
|
||||
description: Some("Authoritative Merge Request bound to this object route".into()),
|
||||
interfaces: vec![MERGE_REQUEST_ITEM_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(MERGE_REQUEST_ITEM_INTERFACE)],
|
||||
r#ref: Some(format!("merge-request:{item_reference}")),
|
||||
validator: Some(merge_request_route_validator(&route, &revision)),
|
||||
},
|
||||
|
||||
@@ -578,11 +578,11 @@ pub fn mount_workspace_http_objective_wip(
|
||||
"Authoritative Objective collection; search and create through Backend authority"
|
||||
.into(),
|
||||
),
|
||||
interfaces: vec![OBJECTIVE_COLLECTION_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(OBJECTIVE_COLLECTION_INTERFACE)],
|
||||
r#ref: Some("objective:collection".into()),
|
||||
validator: Some(route_validator(&collection_route, "collection")),
|
||||
},
|
||||
interface: OBJECTIVE_COLLECTION_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(OBJECTIVE_COLLECTION_INTERFACE),
|
||||
descriptor: collection_descriptor,
|
||||
interface_validator: Some(collection_validator),
|
||||
handler: collection_handler,
|
||||
@@ -593,7 +593,7 @@ pub fn mount_workspace_http_objective_wip(
|
||||
registry.mount_dynamic(WipDynamicMount {
|
||||
collection_route: collection_route.clone(),
|
||||
capability: "objective:item".into(),
|
||||
interface: OBJECTIVE_ITEM_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(OBJECTIVE_ITEM_INTERFACE),
|
||||
descriptor: item_descriptor,
|
||||
interface_validator: Some(item_validator),
|
||||
resolver: Arc::new(ObjectiveItemResolver {
|
||||
@@ -744,7 +744,7 @@ impl WipDynamicItemResolver for ObjectiveItemResolver {
|
||||
object: Object {
|
||||
name: item_reference.to_string(),
|
||||
description: Some("Authoritative Objective bound to this object route".into()),
|
||||
interfaces: vec![OBJECTIVE_ITEM_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(OBJECTIVE_ITEM_INTERFACE)],
|
||||
r#ref: Some(format!("objective:{item_reference}")),
|
||||
validator: Some(route_validator(&route, &revision)),
|
||||
},
|
||||
|
||||
@@ -1814,11 +1814,11 @@ pub fn mount_workspace_http_ticket_wip(
|
||||
description: Some(
|
||||
"Authoritative Ticket collection through scoped Backend authority".into(),
|
||||
),
|
||||
interfaces: vec![TICKET_COLLECTION_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(TICKET_COLLECTION_INTERFACE)],
|
||||
r#ref: Some("ticket:collection".into()),
|
||||
validator: Some(route_validator(&collection_route, "collection")),
|
||||
},
|
||||
interface: TICKET_COLLECTION_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(TICKET_COLLECTION_INTERFACE),
|
||||
interface_validator: Some(descriptor_validator(&collection_descriptor)),
|
||||
descriptor: collection_descriptor,
|
||||
handler: Arc::new(TicketCollectionWipHandler {
|
||||
@@ -1837,7 +1837,7 @@ pub fn mount_workspace_http_ticket_wip(
|
||||
registry.mount_dynamic(WipDynamicMount {
|
||||
collection_route: collection_route.clone(),
|
||||
capability: "ticket:item".into(),
|
||||
interface: TICKET_ITEM_INTERFACE.into(),
|
||||
interface: crate::wip::root_reference(TICKET_ITEM_INTERFACE),
|
||||
interface_validator: Some(descriptor_validator(&item_descriptor)),
|
||||
descriptor: item_descriptor,
|
||||
resolver: Arc::new(TicketItemResolver {
|
||||
@@ -1923,7 +1923,7 @@ impl WipDynamicItemResolver for TicketItemResolver {
|
||||
object: Object {
|
||||
name: item_reference.into(),
|
||||
description: Some("Authoritative Ticket bound to this object route".into()),
|
||||
interfaces: vec![TICKET_ITEM_INTERFACE.into()],
|
||||
interfaces: vec![crate::wip::root_reference(TICKET_ITEM_INTERFACE)],
|
||||
r#ref: Some(format!("ticket:{item_reference}")),
|
||||
validator: Some(route_validator(&route, &revision)),
|
||||
},
|
||||
|
||||
@@ -318,7 +318,7 @@ impl FeatureInvocationHandler for WorkspaceConfigFeature {
|
||||
result.access.as_str()
|
||||
),
|
||||
context: Some(format!(
|
||||
"Workspace configuration is available as logical attachment `{ATTACHMENT_ALIAS}` at WIP `{CONTENT_ROOT}` with {} access. Discover structure through WIP; read and change bodies through published Operations. This attachment grants no OS paths or command execution. Backend validation, concurrency checks and activation rules apply; saving does not imply running Workers adopted new configuration.",
|
||||
"Workspace configuration is available as logical attachment `{ATTACHMENT_ALIAS}` at WIP `{CONTENT_ROOT}` with {} access. Use Tree for indexable structure, Inspect with a known Object path for its complete signatures, and Invoke for published Operations. This attachment grants no OS paths or command execution. Backend validation, concurrency checks and activation rules apply; saving does not imply running Workers adopted new configuration.",
|
||||
result.access.as_str()
|
||||
)),
|
||||
})
|
||||
|
||||
@@ -205,7 +205,7 @@ impl WipSubtreeProvider for ConfigProvider {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut projection = super::wip::attach_projection(&self.feature);
|
||||
projection.interface = contextual_reference(&projection.interface, path);
|
||||
projection.interface = contextual_reference(&projection.interface.name, path);
|
||||
projection.object.interfaces = vec![projection.interface.clone()];
|
||||
return Ok(Some(projection));
|
||||
};
|
||||
|
||||
@@ -428,7 +428,7 @@ fn runtime(client: Arc<dyn WorkspaceClient>) -> (WorkspaceConfigFeature, WipRunt
|
||||
let runtime = WipRuntime::from_mounts(mounts, "worker-1@workspace-1".into()).unwrap();
|
||||
(feature, runtime)
|
||||
}
|
||||
fn interface(path: &str, attached: bool) -> String {
|
||||
fn interface(path: &str, attached: bool) -> wip_protocol::InterfaceReference {
|
||||
crate::wip::contextual_reference(
|
||||
if attached {
|
||||
"yoi.workspace-config/node/v1"
|
||||
@@ -438,12 +438,9 @@ fn interface(path: &str, attached: bool) -> String {
|
||||
path,
|
||||
)
|
||||
}
|
||||
async fn observe_interface(runtime: &WipRuntime, path: &str, attached: bool) {
|
||||
runtime.discover(path.into(), 0, true).await.unwrap();
|
||||
runtime
|
||||
.inspect(interface(path, attached), true)
|
||||
.await
|
||||
.unwrap();
|
||||
async fn observe_interface(runtime: &WipRuntime, path: &str, _attached: bool) {
|
||||
runtime.tree(path.into(), 0, true).await.unwrap();
|
||||
runtime.inspect(path.into(), true).await.unwrap();
|
||||
}
|
||||
async fn call(
|
||||
runtime: &WipRuntime,
|
||||
@@ -497,7 +494,7 @@ async fn workspace_config_production_slash_deep_discover_read_edit_and_atomic_im
|
||||
.starts_with("Already attached")
|
||||
);
|
||||
let discovered = runtime
|
||||
.discover(CONTENT_ROOT.into(), 5, true)
|
||||
.tree(CONTENT_ROOT.into(), 5, true)
|
||||
.await
|
||||
.unwrap()
|
||||
.content
|
||||
@@ -606,7 +603,7 @@ async fn workspace_config_production_native_attach_create_delete_and_detach_end_
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.discover("/workspace-config/main.dcdl".into(), 0, true)
|
||||
.tree("/workspace-config/main.dcdl".into(), 0, true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
@@ -633,19 +630,15 @@ async fn workspace_config_production_revocation_ro_cross_workspace_and_cache_iso
|
||||
);
|
||||
observe_interface(&runtime, path, true).await;
|
||||
let descriptor = runtime
|
||||
.inspect(interface(path, true), true)
|
||||
.inspect(path.into(), true)
|
||||
.await
|
||||
.unwrap()
|
||||
.content
|
||||
.unwrap();
|
||||
let descriptor: Json = serde_json::from_str(&descriptor).unwrap();
|
||||
let names = descriptor["descriptor"]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|op| op["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(names, ["read"]);
|
||||
let signature = descriptor["interfaces"][0]["signature"].as_str().unwrap();
|
||||
assert!(signature.contains("operation read("));
|
||||
assert!(!signature.contains("operation write("));
|
||||
assert!(
|
||||
call(&runtime, path, "write", json!({"content":"DENIED"}))
|
||||
.await
|
||||
@@ -657,7 +650,7 @@ async fn workspace_config_production_revocation_ro_cross_workspace_and_cache_iso
|
||||
});
|
||||
let (feature, other) = runtime_for_cross(cross);
|
||||
assert!(feature.attach("cross", None).await.is_err());
|
||||
assert!(other.discover(path.into(), 0, false).await.is_err());
|
||||
assert!(other.tree(path.into(), 0, false).await.is_err());
|
||||
assert!(client.state.lock().unwrap().commits.is_empty());
|
||||
}
|
||||
fn runtime_for_cross(client: Arc<dyn WorkspaceClient>) -> (WorkspaceConfigFeature, WipRuntime) {
|
||||
@@ -760,21 +753,16 @@ async fn workspace_config_production_bounds_and_traversal_reject_before_content_
|
||||
let client = Router::new();
|
||||
let (feature, runtime) = runtime(client.clone());
|
||||
feature.attach("initial", None).await.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.discover(CONTENT_ROOT.into(), 9, true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(runtime.tree(CONTENT_ROOT.into(), 9, true).await.is_err());
|
||||
for path in [
|
||||
"/workspace-config/../secret",
|
||||
"/workspace-config//main.dcdl",
|
||||
"/workspace-config/./main.dcdl",
|
||||
] {
|
||||
assert!(runtime.discover(path.into(), 0, true).await.is_err());
|
||||
assert!(runtime.tree(path.into(), 0, true).await.is_err());
|
||||
}
|
||||
let path = format!("/workspace-config/{}", "a".repeat(513));
|
||||
assert!(runtime.discover(path, 0, true).await.is_err());
|
||||
assert!(runtime.tree(path, 0, true).await.is_err());
|
||||
assert!(client.state.lock().unwrap().commits.is_empty());
|
||||
}
|
||||
|
||||
@@ -837,7 +825,7 @@ async fn workspace_config_production_cumulative_node_limit_and_edit_growth_are_b
|
||||
// No individual depth-1 response exceeds the cap; the whole Host traversal
|
||||
// must nevertheless stop before exceeding 256 Objects.
|
||||
let error = runtime
|
||||
.discover(CONTENT_ROOT.into(), 4, true)
|
||||
.tree(CONTENT_ROOT.into(), 4, true)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("ResourceLimitExceeded"));
|
||||
@@ -849,7 +837,7 @@ async fn workspace_config_production_backend_failure_is_not_hidden_as_unauthoriz
|
||||
client.state.lock().unwrap().fail_current = true;
|
||||
let (_, runtime) = runtime(client);
|
||||
let error = runtime
|
||||
.discover(CONTENT_ROOT.into(), 0, true)
|
||||
.tree(CONTENT_ROOT.into(), 0, true)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let message = error.to_string();
|
||||
@@ -907,16 +895,11 @@ async fn workspace_config_production_ungranted_root_does_not_poison_worldspace_d
|
||||
let client = Router::new();
|
||||
client.state.lock().unwrap().granted = false;
|
||||
let (_, runtime) = runtime(client.clone());
|
||||
let discovery = runtime.discover("/".into(), 2, true).await.unwrap();
|
||||
let discovery = runtime.tree("/".into(), 2, true).await.unwrap();
|
||||
let discovery: Json = serde_json::from_str(discovery.content.as_deref().unwrap()).unwrap();
|
||||
assert_eq!(discovery["known_space"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(discovery["known_space"][0]["path"], "/");
|
||||
assert!(
|
||||
runtime
|
||||
.discover(CONTENT_ROOT.into(), 0, true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(discovery["tree"]["children"], json!([]));
|
||||
assert_eq!(discovery["tree"]["path"], "/");
|
||||
assert!(runtime.tree(CONTENT_ROOT.into(), 0, true).await.is_err());
|
||||
assert!(
|
||||
client
|
||||
.state
|
||||
|
||||
@@ -93,13 +93,13 @@ pub(super) fn attach_projection(feature: &WorkspaceConfigFeature) -> WipProjecti
|
||||
object: Object {
|
||||
name: ATTACHMENT_ALIAS.into(),
|
||||
description: Some("Logical Workspace configuration attachment entrance".into()),
|
||||
interfaces: vec![interface.into()],
|
||||
interfaces: vec![crate::wip::root_reference(interface)],
|
||||
r#ref: None,
|
||||
// Attaching does not modify config content. The content subtree will
|
||||
// supply its own Backend validators for file/directory Operations.
|
||||
validator: None,
|
||||
},
|
||||
interface: interface.into(),
|
||||
interface: crate::wip::root_reference(interface),
|
||||
descriptor,
|
||||
interface_validator,
|
||||
handler: Arc::new(AttachHandler(feature.clone())),
|
||||
|
||||
+537
-773
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,562 @@
|
||||
//! Scope publication and precondition tests through the actual Yoi HTTP adapter.
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
|
||||
struct ReadHandler(Arc<AtomicUsize>);
|
||||
#[async_trait]
|
||||
impl WipOperationHandler for ReadHandler {
|
||||
async fn call(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &BTreeMap<String, Value>,
|
||||
_: WipCallContext,
|
||||
) -> Result<WipOperationOutput, WipOperationError> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(WipOperationOutput::native(Value::String("value".into())))
|
||||
}
|
||||
}
|
||||
|
||||
fn projection(path: &str, scope: &str, name: &str, calls: Arc<AtomicUsize>) -> WipProjection {
|
||||
let interface = InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
};
|
||||
WipProjection {
|
||||
route: path.into(),
|
||||
capability: "scope:object".into(),
|
||||
kind: WipProjectionKind::Native,
|
||||
object: Object {
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
description: None,
|
||||
interfaces: vec![interface.clone()],
|
||||
r#ref: Some(format!("object:{path}")),
|
||||
validator: None,
|
||||
},
|
||||
interface,
|
||||
descriptor: InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "read".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::String,
|
||||
},
|
||||
}],
|
||||
},
|
||||
interface_validator: None,
|
||||
handler: Arc::new(ReadHandler(calls)),
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_request(
|
||||
path: &str,
|
||||
reference: Json,
|
||||
object_validator: Option<&str>,
|
||||
scope_ref: Option<&str>,
|
||||
) -> Request<Vec<u8>> {
|
||||
let mut target = json!({"path": path});
|
||||
if let Some(v) = object_validator {
|
||||
target["validator"] = json!(v);
|
||||
}
|
||||
let mut interface = json!({"reference": reference});
|
||||
if let Some(v) = scope_ref {
|
||||
interface["scope_ref"] = json!(v);
|
||||
}
|
||||
Request::builder()
|
||||
.body(
|
||||
serde_json::to_vec(
|
||||
&json!({"target":target,"interface":interface,"operation":"read","arguments":{}}),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn rejected_code(runtime: &WipRuntime, request: Request<Vec<u8>>) -> String {
|
||||
let (response, passthrough, outcome) = runtime
|
||||
.dispatch_call(&request, ToolExecutionContext::direct())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(passthrough.is_none());
|
||||
assert_eq!(outcome, WipAuditOutcome::Rejected);
|
||||
let json: Json = serde_json::from_slice(response.body()).unwrap();
|
||||
json["error"]["code"].as_str().unwrap().into()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adapter_preconditions_preserve_shape_target_validator_and_scope_precedence() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
let mut p = projection("/github/item", "/github/item", "read", calls.clone());
|
||||
p.object.validator = Some(vec![1]);
|
||||
registry.mount(p).unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request("/missing", json!("legacy"), None, None)
|
||||
)
|
||||
.await,
|
||||
"invalid_request"
|
||||
);
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
"/missing",
|
||||
json!({"scope":"/sibling","name":"read"}),
|
||||
Some("AA=="),
|
||||
None
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"not_found"
|
||||
);
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
"/github/item",
|
||||
json!({"scope":"/sibling","name":"read"}),
|
||||
Some("AA=="),
|
||||
None
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"validator_mismatch"
|
||||
);
|
||||
for scope in ["/sibling", "/github/item/child", "/github-extra"] {
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
"/github/item",
|
||||
json!({"scope":scope,"name":"read"}),
|
||||
Some("AQ=="),
|
||||
None
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"interface_mismatch"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
"/github/item",
|
||||
json!({"scope":"/github/item","name":"read"}),
|
||||
Some("AQ=="),
|
||||
Some("old")
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"interface_mismatch"
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_provider_root_and_self_scope_inspect_invoke_preserve_optional_refs() {
|
||||
for path in ["/", "/github"] {
|
||||
for with_ref in [true, false] {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
let mut p = projection(path, path, "read", calls.clone());
|
||||
if !with_ref {
|
||||
p.object.r#ref = None;
|
||||
}
|
||||
let reference = p.interface.clone();
|
||||
registry.mount(p).unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
let fetched = runtime.host.fetch_interface_live(&reference).await.unwrap();
|
||||
assert_eq!(
|
||||
fetched.scope_ref,
|
||||
with_ref.then(|| format!("object:{path}"))
|
||||
);
|
||||
runtime.inspect(path.into(), false).await.unwrap();
|
||||
runtime
|
||||
.invoke(
|
||||
path.into(),
|
||||
reference.clone(),
|
||||
"read".into(),
|
||||
json!({}),
|
||||
ToolExecutionContext::direct(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
let state = runtime.state.lock().unwrap();
|
||||
let history = state.client.call_history(&state.session).unwrap();
|
||||
assert_eq!(
|
||||
history
|
||||
.back()
|
||||
.unwrap()
|
||||
.context
|
||||
.request()
|
||||
.interface
|
||||
.scope_ref,
|
||||
fetched.scope_ref
|
||||
);
|
||||
drop(state);
|
||||
if !with_ref {
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
path,
|
||||
json!({"scope":path,"name":"read"}),
|
||||
None,
|
||||
Some("invented")
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"interface_mismatch"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multiple_interfaces_same_operation_are_inspected_and_dispatched_without_flattening() {
|
||||
let a = Arc::new(AtomicUsize::new(0));
|
||||
let b = Arc::new(AtomicUsize::new(0));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
let owner = projection("/github", "/", "same", a.clone());
|
||||
let other = projection("/github", "/github", "same", b.clone());
|
||||
let refs = [owner.interface.clone(), other.interface.clone()];
|
||||
registry.mount(owner).unwrap();
|
||||
registry.mount_interface(other).unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
let inspected = runtime.inspect("/github".into(), false).await.unwrap();
|
||||
let inspected: Json = serde_json::from_str(inspected.content.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(inspected["interfaces"].as_array().unwrap().len(), 2);
|
||||
for reference in refs {
|
||||
runtime
|
||||
.invoke(
|
||||
"/github".into(),
|
||||
reference,
|
||||
"read".into(),
|
||||
json!({}),
|
||||
ToolExecutionContext::direct(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(a.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(b.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
struct Publication {
|
||||
visible: Arc<AtomicBool>,
|
||||
identity: Arc<Mutex<Option<String>>>,
|
||||
validator: Arc<Mutex<Option<Vec<u8>>>>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
impl WipDynamicItemResolver for Publication {
|
||||
fn contextual_interface(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn resolve(&self, item: &str) -> Option<WipDynamicItem> {
|
||||
if item != "item" || !self.visible.load(Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
let mut p = projection("/github/item", "/", "read", self.calls.clone());
|
||||
p.object.r#ref = self.identity.lock().unwrap().clone();
|
||||
p.object.validator = self.validator.lock().unwrap().clone();
|
||||
Some(WipDynamicItem {
|
||||
object: p.object,
|
||||
handler: p.handler,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn current_self_scope_fetch_does_not_attach_a_new_ref_to_an_old_target_snapshot() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let visible = Arc::new(AtomicBool::new(true));
|
||||
let identity = Arc::new(Mutex::new(Some("first".into())));
|
||||
let validator = Arc::new(Mutex::new(None));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
registry
|
||||
.mount(projection("/github", "/", "collection", calls.clone()))
|
||||
.unwrap();
|
||||
let p = projection("/github/item", "/", "read", calls.clone());
|
||||
registry
|
||||
.mount_dynamic(WipDynamicMount {
|
||||
collection_route: "/github".into(),
|
||||
capability: "scope:item".into(),
|
||||
interface: p.interface,
|
||||
descriptor: p.descriptor,
|
||||
interface_validator: None,
|
||||
resolver: Arc::new(Publication {
|
||||
visible: visible.clone(),
|
||||
identity: identity.clone(),
|
||||
validator: validator.clone(),
|
||||
calls: calls.clone(),
|
||||
}),
|
||||
})
|
||||
.unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
let reference = contextual_reference("read", "/github/item");
|
||||
runtime.inspect("/github/item".into(), false).await.unwrap();
|
||||
assert_eq!(
|
||||
runtime
|
||||
.host
|
||||
.fetch_interface_live(&reference)
|
||||
.await
|
||||
.unwrap()
|
||||
.scope_ref
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
// Ordinary content-state updates do not change the scope Object identity.
|
||||
*validator.lock().unwrap() = Some(vec![2]);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.host
|
||||
.fetch_interface_live(&reference)
|
||||
.await
|
||||
.unwrap()
|
||||
.scope_ref
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
*validator.lock().unwrap() = None;
|
||||
*identity.lock().unwrap() = Some("second".into());
|
||||
let error = runtime
|
||||
.invoke(
|
||||
"/github/item".into(),
|
||||
reference.clone(),
|
||||
"read".into(),
|
||||
json!({}),
|
||||
ToolExecutionContext::direct(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("InterfaceMismatch"));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
// Both target and Interface are invalidated; retrievals are not reexecution.
|
||||
let state = runtime.state.lock().unwrap();
|
||||
assert_eq!(
|
||||
state
|
||||
.client
|
||||
.object(&state.session, "/github/item")
|
||||
.unwrap()
|
||||
.state,
|
||||
ObservationState::Stale
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.client
|
||||
.interface(&state.session, &reference)
|
||||
.unwrap()
|
||||
.state,
|
||||
ObservationState::Stale
|
||||
);
|
||||
drop(state);
|
||||
runtime
|
||||
.invoke(
|
||||
"/github/item".into(),
|
||||
reference.clone(),
|
||||
"read".into(),
|
||||
json!({}),
|
||||
ToolExecutionContext::direct(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
visible.store(false, Ordering::SeqCst);
|
||||
assert!(runtime.host.fetch_interface_live(&reference).await.is_err());
|
||||
assert!(runtime.inspect("/github/item".into(), true).await.is_err());
|
||||
let state = runtime.state.lock().unwrap();
|
||||
assert!(state.client.interface(&state.session, &reference).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn supplied_validators_require_current_values_and_required_object_validator_is_late() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
registry
|
||||
.mount(projection("/github", "/github", "read", calls.clone()))
|
||||
.unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
let reference = json!({"scope":"/github","name":"read"});
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request("/github", reference.clone(), Some("AQ=="), None)
|
||||
)
|
||||
.await,
|
||||
"validator_mismatch"
|
||||
);
|
||||
let mut request = metadata_request("/github", reference, None, None);
|
||||
let mut body: Json = serde_json::from_slice(request.body()).unwrap();
|
||||
body["interface"]["validator"] = json!("AQ==");
|
||||
*request.body_mut() = serde_json::to_vec(&body).unwrap();
|
||||
assert_eq!(
|
||||
rejected_code(&runtime, request).await,
|
||||
"interface_validator_mismatch"
|
||||
);
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
let mut p = projection("/github", "/github", "read", calls.clone());
|
||||
p.object.validator = Some(vec![1]);
|
||||
registry.mount(p).unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
assert_eq!(
|
||||
rejected_code(
|
||||
&runtime,
|
||||
metadata_request(
|
||||
"/github",
|
||||
json!({"scope":"/wrong","name":"read"}),
|
||||
None,
|
||||
None
|
||||
)
|
||||
)
|
||||
.await,
|
||||
"interface_mismatch"
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
struct ChangingProvider {
|
||||
generation: Arc<AtomicUsize>,
|
||||
started: Arc<tokio::sync::Notify>,
|
||||
release: Arc<tokio::sync::Notify>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
struct FrozenResultHandler {
|
||||
generation: usize,
|
||||
started: Arc<tokio::sync::Notify>,
|
||||
release: Arc<tokio::sync::Notify>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl WipOperationHandler for FrozenResultHandler {
|
||||
async fn call(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &BTreeMap<String, Value>,
|
||||
_: WipCallContext,
|
||||
) -> Result<WipOperationOutput, WipOperationError> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
if self.generation == 0 {
|
||||
self.started.notify_one();
|
||||
self.release.notified().await;
|
||||
Ok(WipOperationOutput::native(Value::String(
|
||||
"old result".into(),
|
||||
)))
|
||||
} else {
|
||||
Ok(WipOperationOutput::native(Value::Integer(2)))
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl WipSubtreeProvider for ChangingProvider {
|
||||
async fn projection(&self, path: &str) -> Result<Option<WipProjection>, ProtocolError> {
|
||||
if path != "/github" {
|
||||
return Ok(None);
|
||||
}
|
||||
let generation = self.generation.load(Ordering::SeqCst);
|
||||
let mut p = projection(path, path, "read", self.calls.clone());
|
||||
p.interface_validator = Some(vec![generation as u8]);
|
||||
if generation != 0 {
|
||||
p.descriptor.operations[0].returns.r#type = TypeExpr::Integer;
|
||||
}
|
||||
p.handler = Arc::new(FrozenResultHandler {
|
||||
generation,
|
||||
started: self.started.clone(),
|
||||
release: self.release.clone(),
|
||||
calls: self.calls.clone(),
|
||||
});
|
||||
Ok(Some(p))
|
||||
}
|
||||
async fn children(&self, _: &str) -> Result<Vec<String>, ProtocolError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn in_flight_result_uses_frozen_host_and_client_descriptors_after_refresh() {
|
||||
let generation = Arc::new(AtomicUsize::new(0));
|
||||
let started = Arc::new(tokio::sync::Notify::new());
|
||||
let release = Arc::new(tokio::sync::Notify::new());
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut registry = WipMountRegistry::new();
|
||||
registry.allocate_namespace("scope", "github").unwrap();
|
||||
registry
|
||||
.mount(projection("/github", "/github", "read", calls.clone()))
|
||||
.unwrap();
|
||||
registry
|
||||
.mount_subtree(WipSubtreeMount {
|
||||
root: "/github".into(),
|
||||
provider: Arc::new(ChangingProvider {
|
||||
generation: generation.clone(),
|
||||
started: started.clone(),
|
||||
release: release.clone(),
|
||||
calls: calls.clone(),
|
||||
}),
|
||||
})
|
||||
.unwrap();
|
||||
let runtime = WipRuntime::from_mounts(registry, "scope-test".into()).unwrap();
|
||||
runtime.inspect("/github".into(), false).await.unwrap();
|
||||
let pending = runtime.invoke(
|
||||
"/github".into(),
|
||||
contextual_reference("read", "/github"),
|
||||
"read".into(),
|
||||
json!({}),
|
||||
ToolExecutionContext::direct(),
|
||||
);
|
||||
let update = async {
|
||||
started.notified().await;
|
||||
generation.store(1, Ordering::SeqCst);
|
||||
let output = runtime.inspect("/github".into(), true).await.unwrap();
|
||||
assert!(output.content.unwrap().contains("integer"));
|
||||
release.notify_one();
|
||||
};
|
||||
let (old_result, ()) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
tokio::join!(pending, update)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
old_result.unwrap().content.as_deref(),
|
||||
Some("\"old result\"")
|
||||
);
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
let state = runtime.state.lock().unwrap();
|
||||
let record = state
|
||||
.client
|
||||
.call_history(&state.session)
|
||||
.unwrap()
|
||||
.back()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
record.context.descriptor().operations[0].returns.r#type,
|
||||
TypeExpr::String
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.client
|
||||
.interface(&state.session, &contextual_reference("read", "/github"))
|
||||
.unwrap()
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.operations[0]
|
||||
.returns
|
||||
.r#type,
|
||||
TypeExpr::Integer
|
||||
);
|
||||
}
|
||||
@@ -181,9 +181,9 @@ truncation under the existing search contract.
|
||||
|
||||
## Typical sequence
|
||||
|
||||
1. Discover `/checkouts` with depth 1; inspect its Interface and call `list`.
|
||||
2. Discover an entrance or known deep directory, inspect it, call `glob`/`grep`.
|
||||
3. Follow a returned file `path`, discover/inspect, call line `read`.
|
||||
1. Use Tree on `/checkouts` with depth 1; Inspect `/checkouts` directly and Invoke `list`.
|
||||
2. Inspect an entrance or a known deep directory directly; Invoke `glob`/`grep`.
|
||||
3. Follow a returned file `path`, Inspect that path and Invoke line `read`.
|
||||
4. Call `edit` or `write`; Client-managed validators protect the exact observed
|
||||
object while the shared tracker enforces the prior Read.
|
||||
5. Rediscover after external changes; a stale rejection is not permission to skip
|
||||
|
||||
@@ -165,16 +165,16 @@ Ticket/Objective/Merge Request routes retain their T-698 contracts.
|
||||
|
||||
## First-Workspace example
|
||||
|
||||
1. `Discover(path="/", depth=1)` finds `repositories`, `workdirs` and
|
||||
1. `Tree(path="/", depth=1)` finds `repositories`, `workdirs` and
|
||||
`workdir-attachments` when permitted.
|
||||
2. Inspect the returned Repository collection Interface and call `list` with a
|
||||
2. Inspect the Repository collection path and Invoke `list` with a
|
||||
bounded limit. An empty registered/visible catalog explicitly returns an empty
|
||||
list; do not invent a key. Follow `next_cursor` when supplied.
|
||||
3. Discover the returned item `path`, inspect its Interface and call `read`.
|
||||
3. Inspect the returned item `path` directly and Invoke `read`.
|
||||
`default_selector: null` means no configured default, not `main`.
|
||||
4. Inspect the Workdir collection and `create` using the discovered formal key,
|
||||
with optional selector, display name and Runtime under the existing contract.
|
||||
5. Follow created `item.path`, discover/inspect and `attach` with a chosen
|
||||
5. Follow created `item.path`, Inspect directly and Invoke `attach` with a chosen
|
||||
Worker-local alias. This is separate from creation.
|
||||
6. Follow `attachments_path`, `list`, then discover/read the returned connection
|
||||
path to confirm alias, Workdir and effective capabilities.
|
||||
|
||||
@@ -24,15 +24,17 @@ worker = { mode = "wip" }
|
||||
|
||||
Omission resolves to `tools`, so existing manifests, profiles, persisted snapshots, and restored Workers retain the ordinary individual-tool surface. A direct Internal SubWorker selected with `profile = "inherit"` inherits the parent mode as reusable behavior. `default` and named profile selections use that profile's own mode and do not implicitly inherit WIP.
|
||||
|
||||
The implementation uses the crates.io `wip-client`, `wip-protocol`, and `wip-http` **0.1.0** releases. It does not use Git/path dependencies or the old `wip-https` name. Those releases require Rust 1.88; the workspace declares `rust-version = "1.88"`, and the changed crates inherit it. WIP Host/interface crates are not needed for the async compatibility adapter: the published client/protocol/HTTP state machines remain authoritative while Yoi supplies an in-process async Host transport.
|
||||
The implementation uses a reproducible, checked-in snapshot of upstream wip-rs at **1cbe03b49e48dd7e0be28b76fbc3c932f8920a36**, aligned with canonical wip-reference **6086f3c5ef10aa1464ce9c824750d7f667217bfd**. Client, HTTP, Protocol and Text View use the same source and Protocol types. Upstream calls the changes Unreleased despite version 0.1.0: the old registry release is not interchangeable. See [source provenance and regeneration](../../vendor/wip-rs/README.md). CI/builds use committed path dependencies, never a Worker attachment or upstream credentials. Yoi retains its async provider/transport and existing execution boundaries; upstream owns Client cache/lifecycle, codecs and signatures.
|
||||
|
||||
## LLM surface and route contract
|
||||
|
||||
A WIP Worker exposes exactly these generic LLM tools instead of exposing every enabled ordinary tool twice:
|
||||
|
||||
- `Discover`: observe an object path and bounded descendants, beginning at `/`.
|
||||
- `Inspect`: fetch the descriptor for an opaque interface reference returned by discovery.
|
||||
- `Call`: call an operation using fresh object and interface observations.
|
||||
- `Tree(path, depth)`: retrieve the full indexable range within depth 0..8, or report incomplete/loading/failed/limited coverage as an error. Children at the requested boundary remain unobserved (null), not empty. Cached nonindexable paths are never included by prefix scanning Known Space.
|
||||
- `Inspect(path)`: directly acquire an Object, then every published Interface, and return complete official Object/Interface signatures in declaration order. It requires no prior Tree or manual descriptor fetching. The path is explicit JSON envelope context outside the path-free signature. Summaries are complete; runtime metadata and documentation details are not appended to signatures.
|
||||
- `Invoke(path, interface, operation, arguments)`: use a structured `{scope, name}` reference and named argument record. The Client owns validators and observed scope_ref. Missing/stale/failed observations are recovered with at most one pre-dispatch retrieval per subject. A dispatched operation is never automatically retried.
|
||||
|
||||
Tree and Inspect accept explicit `refresh: true` for blocked observations. An ensure API returning None is never itself readiness evidence: freshness, complete edge coverage and retained data are checked. Loading and capacity pressure are reported rather than superseded or busy-looped.
|
||||
|
||||
The compatibility projection mounts enabled ordinary tools at:
|
||||
|
||||
@@ -40,13 +42,13 @@ The compatibility projection mounts enabled ordinary tools at:
|
||||
/tools/<exact-tool-registration-name>
|
||||
```
|
||||
|
||||
Each object has one opaque interface reference:
|
||||
Each compatibility Object publishes an explicit root-scoped reference:
|
||||
|
||||
```text
|
||||
yoi.tool/<exact-tool-registration-name>/v1
|
||||
{"scope":"/", "name":"yoi.tool/<exact-tool-registration-name>/v1"}
|
||||
```
|
||||
|
||||
Its single operation is `call`. For this compatibility route, `Call.arguments` is the original ordinary tool argument object. Native projections instead receive a JSON object keyed by the descriptor's declared parameter names. Native input is decoded with the published `wip-http` descriptor-bound codec, so named and composite types are resolved, an integral JSON number remains a WIP `Number` when declared as such, and WIP `Bytes` use the codec's canonical RFC 4648 base64 JSON representation. Tool argument IDs remain JSON values; the adapter never infers a domain object or Worldspace route from them.
|
||||
Its single operation is `call`. For this compatibility route, `Invoke.arguments` is `{ "input": <original ordinary tool argument object> }`, matching the descriptor's named Json parameter. Native projections instead receive a JSON object keyed by the descriptor's declared parameter names. Native input is decoded with the published `wip-http` descriptor-bound codec, so named and composite types are resolved, an integral JSON number remains a WIP `Number` when declared as such, and WIP `Bytes` use the codec's canonical RFC 4648 base64 JSON representation. Tool argument IDs remain JSON values; the adapter never infers a domain object or Worldspace route from them.
|
||||
|
||||
The interface descriptor uses WIP `Json` for compatibility input and includes the exact original JSON Schema in descriptor documentation. Before execution, the Host validates the JSON value with that original schema and then delegates to the original async `Tool`. Constraints are therefore neither approximated nor silently dropped. A schema that cannot be compiled prevents WIP startup instead of creating a weaker projection.
|
||||
|
||||
@@ -65,7 +67,7 @@ Object resolution and operations are separate contracts. One mounted `WipProject
|
||||
- A native projection replaces a compatibility projection either by the original same-route semantic capability or by an explicit registry capability claim owned by a mounted native route.
|
||||
- Conflicting native claims fail startup. When native is selected, the claimed compatibility tool is hidden rather than exposed through a second entry. Normal Tool mode is unaffected because it does not install the WIP registry.
|
||||
|
||||
`Inspect` renders the complete effective descriptor, including contributed operations, descriptor-local named declarations, and recursive record, list, enum, and union shapes with required flags and declaration documentation. The tests `host_namespace_object_resolution_and_operation_contributions_are_independent`, `operation_contributions_reject_interface_and_target_conflicts`, and `native_projection_preserves_descriptor_and_decodes_typed_arguments_end_to_end` demonstrate root allocation, unique resolution, contribution merging, collision rejection, current call-time authorization, complete descriptor inspection, and descriptor-typed invocation.
|
||||
`Inspect` delegates to official `wip-text-view::render_object` and `render_interface`; it renders the complete effective descriptor, including contributed operations, descriptor-local named declarations, and recursive record, list, enum, and union shapes with required flags and declaration documentation. The tests `host_namespace_object_resolution_and_operation_contributions_are_independent`, `operation_contributions_reject_interface_and_target_conflicts`, and `native_projection_preserves_descriptor_and_decodes_typed_arguments_end_to_end` demonstrate root allocation, unique resolution, contribution merging, collision rejection, current call-time authorization, complete descriptor inspection, and descriptor-typed invocation.
|
||||
|
||||
The built-in native route migration is:
|
||||
|
||||
@@ -83,7 +85,7 @@ The built-in Repository/Workdir reference provider allocates `/repositories`, `/
|
||||
2. Mount a native collection `WipProjection` at that root with capability `repository:collection`, matching Object name and one declared interface. Static Objects underneath the root use the same capability owner prefix. A mounted collection retains its own identity, interfaces, and validator even when it has static children.
|
||||
3. For dynamic items, register one `WipDynamicMount` on the collection with capability `repository:item`. A foreign capability owner is rejected. Its `WipDynamicItemResolver` owns reference acceptance, Object identity, and current Object validator. It returns only a bounded direct child; it must not reinterpret a reference as another namespace or grant permission from existence.
|
||||
4. The reference provider supplies its read operations and handlers independently of management Feature enablement. An Object-only provider may use an empty operation descriptor. Enabled management Features register `WipOperationContribution` for static Objects or `WipDynamicOperationContribution` for a dynamic family; they do not allocate the namespace again or replace its resolver.
|
||||
5. Contributions use the existing interface reference and identical format, documentation, and type declarations, supplying only their new operations. Interface references are global: extending a descriptor that is also mounted elsewhere must not create different descriptors/validators under the same reference (registration fails). Use separate references for collection and item contracts. Failed contributions leave the registry unchanged.
|
||||
5. Contributions use the existing interface reference and identical format, documentation, and type declarations, supplying only their new operations. Interface references are exact (scope, name) keys: extending a descriptor that is also mounted elsewhere must not create different descriptors/validators under the same reference (registration fails). Use separate references for collection and item contracts. Failed contributions leave the registry unchanged.
|
||||
6. Handlers are responsible for checking current target capability and current subject authorization before dispatch. Registration/discovery is metadata, not a grant. A resolver/handler must retain the original permission identity and domain audit/failure contracts. Revocation after discovery must fail before provider dispatch. Compatibility mounts are restricted to `/tools/<tool-name>` and cannot bypass namespace ownership or republish legacy routes.
|
||||
|
||||
Tests `management_enablement_is_independent_of_read_and_operation_permissions` and `contributed_interface_invalidates_observations_and_restore_requires_discovery` cover all eight enablement/read/manage combinations, direct-call rejection, effective descriptor changes, fresh runtime isolation under the same Worker identity, reset, and post-observation revocation.
|
||||
@@ -103,13 +105,13 @@ The Worldspace contains only the operations registered from enabled Features and
|
||||
|
||||
Filesystem scope, provider Workdir capability checks, Backend Workspace authority, Feature enablement, and input-specific restrictions stay in the original tool implementation and are checked again at invocation. `ask` permissions remain denied fail-closed because the runtime has no approval protocol. The gateway does not mint authority or expose authentication material.
|
||||
|
||||
Pre/post Engine history still records one bounded `Call` result, while the compatibility result retains the original `ToolOutput`, including attachments and normal Engine output pruning. WIP call audit records retain the route, operation, request identity, and terminal classification.
|
||||
Pre/post Engine history still records one bounded `Invoke` result, while the compatibility result retains the original `ToolOutput`, including attachments and normal Engine output pruning. WIP call audit records retain the route, operation, request identity, and terminal classification.
|
||||
|
||||
## Client lifetime, restoration, and compaction
|
||||
|
||||
The stateful `wip-client::Client` is owned by one Worker WIP runtime. Sessions are keyed by the canonical endpoint and an opaque security-context identity derived by the Host from Workspace, Worker, and session identity. Authentication credentials are not included in that identity and are never emitted to descriptors, tool output, or history.
|
||||
|
||||
Known Space and interface observations are therefore not shared across Workers, endpoints, or security contexts. A restored Worker creates a new runtime/client and must explore again. `Discover(reset = true)` drops all observations before reconnect/authority-change exploration; `refresh = true` explicitly supersedes one cached observation. A normal compaction keeps the live runtime but the three gateway schemas are supplied again on every LLM request, including the instruction to begin discovery at `/`; the compacted transcript is not treated as cache authority.
|
||||
Known Space and interface observations are therefore not shared across Workers, endpoints, or security contexts. A restored Worker creates a new runtime/client and must explore again. `refresh = true` explicitly supersedes requested retrievals. Old string references in saved history remain historical text, not cache/wire authority; observations are runtime-only and are not persisted or restored. Resume by inspecting the target path, not by migrating an opaque display string. A normal compaction keeps the live runtime but the three gateway schemas are supplied again on every LLM request, including direct Inspect and indexable Tree semantics; the compacted transcript is not treated as cache authority.
|
||||
|
||||
Saved Session/history entries remain append-only evidence and are never rewritten or replayed as calls. In particular, historical `/features/<feature>/...` text stays displayable but is not a current route alias. Passing such a legacy path to discovery or call returns `NotFound` with guidance to rediscover from `/`; the Host does not translate it, resolve it under another namespace, or expose old and new routes in parallel.
|
||||
|
||||
@@ -138,3 +140,13 @@ The runtime tracks bounded counters for:
|
||||
- successful operations.
|
||||
|
||||
These values are returned with discovery/inspection output and are intended for comparing prompt input volume, exploration round trips, and representative operation success with ordinary Tool mode. No fixed reduction percentage is promised.
|
||||
|
||||
## Scoped publication and display boundaries
|
||||
|
||||
References are structured everywhere; wire requests reject legacy/display strings. Root and self scopes are valid; ancestry uses canonical path segments, not string prefixes. Contextual descriptors use the resolved Object path as their explicit self scope, not an encoded suffix on the local name. Fetching a self-scoped Interface freezes descriptor/validator and optional scope Object ref from the same live projection. A scope without a ref is valid; the adapter does not invent one. Calls check target existence, Object preconditions, scope/membership/ref, then Interface preconditions and arguments, with the selected descriptor and handler pinned for execution/result validation. Existing providers repeat current authorization and their captured Workdir/Workspace metadata checks at their execution/commit boundary. The registered artifacts alone are not call authority.
|
||||
|
||||
Separate Interface namespaces on one static Object can be registered with `mount_interface`; the owner/identity cannot be replaced and duplicate Interface keys fail. Inspect preserves each Interface reference, even with identical operation names, and Invoke selects the exact namespace. Contribution merging retains one Interface and disjoint operation names.
|
||||
|
||||
Official signature quoting, escapes and summary layout are preserved verbatim. Host documentation is untrusted data in Tool output, not instructions. RenderError categories and the failed path/reference are reported as display failures. Library input limits and Yoi envelope limits reject the entire display rather than truncating it or reporting no operations. No signature parser, shorthand-input parser, independent lexer, or custom escape engine is installed.
|
||||
|
||||
Typed Entry results remain values; no eager result acquisition, guessed string-path conversion, or inferred indexable edges occur. A later Inspect failure never reclassifies a completed successful operation. FS indexable/list policy is a separate provider concern (T-714), not Client-side search/ranking.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# Scoped WIP integration validation
|
||||
|
||||
Adoption: wip-rs `1cbe03b49e48dd7e0be28b76fbc3c932f8920a36`, canonical
|
||||
wip-reference `6086f3c5ef10aa1464ce9c824750d7f667217bfd`. See
|
||||
[`vendor/wip-rs/README.md`](../../vendor/wip-rs/README.md) for provenance and
|
||||
regeneration. All four WIP packages are committed path dependencies; Cargo
|
||||
metadata resolves exactly one Protocol type source and no old registry WIP package.
|
||||
|
||||
## Executed checks
|
||||
|
||||
- `cargo test -p worker --locked --offline`: **888 unit + 110 integration tests
|
||||
passed**, no ignored/failed tests. This includes ordinary Tools mode, Feature
|
||||
permission/revocation, restore, session/history and controller integration.
|
||||
- Narrow development checks: `wip::binding` (25), `wip::provider_tests` (6), existing
|
||||
`wip::tests` and workdir projection tests (43), checkout transports/providers
|
||||
(20), workspace-config production/authority tests (19). These are also included
|
||||
in the complete worker run.
|
||||
- Official packages, using `cargo test --offline --manifest-path
|
||||
vendor/wip-rs/<package>/Cargo.toml --target-dir target/wip-upstream`:
|
||||
Text View **16 public signature/token/golden tests + 4 doctests**;
|
||||
Client **63 adapter/runtime tests**;
|
||||
HTTP **38 tests + 1 doctest**;
|
||||
Protocol **22 tests + 1 doctest**. Vendored source and tests are unmodified.
|
||||
- Root `cargo check --locked --offline` passed, including normal TUI, CLI,
|
||||
Runtime and Workspace Server compile closure.
|
||||
- `cargo fmt --all -- --check` and `git diff --check HEAD` passed.
|
||||
- `node scripts/verify-wip-vendor.mjs`: all **43** Cargo-checksummed upstream files
|
||||
passed. No custom renderer or lexer replaces official signatures.
|
||||
- `nix build --no-link .#yoi.cargoDeps` passed with the updated registry dependency
|
||||
hash. This validates credential-free dependency acquisition, not a full Nix
|
||||
binary/image build or deployment update.
|
||||
|
||||
## Contract evidence
|
||||
|
||||
`crates/worker/src/wip/binding.rs` tests exercise fresh/loading/stale/failed and
|
||||
capacity-blocked acquisition, explicit refresh, superseded responses, retrieval
|
||||
ownership cleanup, output limits, direct unseen-path Inspect, official unmodified
|
||||
signature/path envelopes, structured Interface input and complete edge-only trees.
|
||||
They invoke the registered three-tool surface for a search returning typed Entry
|
||||
paths, inspect only a selected nonindexable path, dispatch the selected operation,
|
||||
and verify that a later Inspect failure neither fails nor replays an earlier
|
||||
successful operation. Interface acquisition failures are not empty operation lists.
|
||||
|
||||
`provider_tests.rs` exercises the actual Yoi adapter for root/self scope, optional
|
||||
refs, copied scope_ref, different scopes with identical names/operations, shape vs
|
||||
membership errors, validator/ref absence/mismatch and protocol failure precedence.
|
||||
It replaces a dynamic scope Object identity, observes both stale sides after
|
||||
InterfaceMismatch, reacquires without replay, and confirms direct NotFound ends
|
||||
safe Interface reuse. An in-flight operation survives descriptor refresh using
|
||||
its exact frozen Host and Client descriptors rather than the newer return type.
|
||||
|
||||
Existing checkout tests retain commit-time captured Workdir/connection/validator
|
||||
checks, alias reuse/restore fencing, inode replacement rejection, authorization,
|
||||
shared prior-read tracking, exact post-operation validators, cooperative
|
||||
cancellation and unknown/lost/malformed responses without retries. Existing native
|
||||
Ticket/Objective/Merge Request tests retain scoped Workspace authority and Feature
|
||||
permission separation; compatibility Invoke retains original schema validation,
|
||||
permission identity and ToolOutput/attachments.
|
||||
|
||||
## Downstream provider seams
|
||||
|
||||
- Public projection/contribution Interface fields now use
|
||||
`wip_protocol::InterfaceReference { scope, name }`.
|
||||
- Contextual/self-scope references are explicit paths, not the old encoded `/@/`
|
||||
suffix. Their fetch uses one live Object/descriptor/validator snapshot and its
|
||||
optional Object ref. Checkout's ref-less publication remains legitimate; its
|
||||
existing captured connection and provider validators still fence execution.
|
||||
- `WipRuntime::{tree, inspect, invoke}` is the object-centered integration seam.
|
||||
Inspect uses official summary-only signatures and typed rendering failures.
|
||||
- `WipMountRegistry::mount_interface` adds a separate Interface namespace without
|
||||
replacing Object ownership or flattening same-named operations.
|
||||
- FS indexable boundaries and directory.list remain provider policy. This change
|
||||
deliberately does not implement the separate T-714 boundary/list migration.
|
||||
The relevant transport/commit tests are `checkout_wip_tests.rs`,
|
||||
`checkout_http_tests.rs`, and `checkout_race_tests.rs`.
|
||||
- Worldspace state is runtime-only. Historical opaque references in append-only
|
||||
session/tool history are not migrated into cache or parsed for a guessed scope;
|
||||
a restored Client starts with fresh observations and direct path Inspect.
|
||||
+2
-1
@@ -43,7 +43,8 @@ rustPlatform.buildRustPackage rec {
|
||||
filter = sourceFilter;
|
||||
};
|
||||
|
||||
cargoHash = "sha256-LjswbsalQA0Yny0DIBJg3FiqwdmTADZ1CnqNJ9oo9Kw=";
|
||||
# WIP SDK source is pinned in vendor/wip-rs; this hash covers registry deps only.
|
||||
cargoHash = "sha256-bKRHNyEHqI/xW8J7s5PgQgxerKaUVG0dRs0sHWKutmc=";
|
||||
|
||||
depsExtraArgs = {
|
||||
# Older fetchCargoVendor utilities used crates.io's API download endpoint,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
// Verify the unmodified Cargo-vendored WIP source snapshot, including its tests.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const packages = ['wip-client', 'wip-http', 'wip-protocol', 'wip-text-view'];
|
||||
let files = 0;
|
||||
for (const name of packages) {
|
||||
const directory = resolve(root, 'vendor/wip-rs', name);
|
||||
const checksum = JSON.parse(readFileSync(resolve(directory, '.cargo-checksum.json'), 'utf8'));
|
||||
for (const [file, expected] of Object.entries(checksum.files)) {
|
||||
const actual = createHash('sha256').update(readFileSync(resolve(directory, file))).digest('hex');
|
||||
if (actual !== expected) throw new Error(`Changed upstream source: ${name}/${file}`);
|
||||
files++;
|
||||
}
|
||||
}
|
||||
console.log(`Verified ${files} files in ${packages.length} packages from wip-rs 1cbe03b49e48dd7e0be28b76fbc3c932f8920a36`);
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+51
@@ -0,0 +1,51 @@
|
||||
# Pinned WIP SDK source
|
||||
|
||||
These four packages were produced by `cargo vendor` from upstream
|
||||
`ssh://git@gitea.hareworks.net/Hare/wip-rs.git` at
|
||||
**`1cbe03b49e48dd7e0be28b76fbc3c932f8920a36`**:
|
||||
|
||||
- `wip-protocol`
|
||||
- `wip-http`
|
||||
- `wip-client`
|
||||
- `wip-text-view`
|
||||
|
||||
Upstream still calls this breaking contract **Unreleased** and uses version
|
||||
`0.1.0`. It is not the old crates.io `0.1.0` contract. The corresponding canonical
|
||||
reference revision is `6086f3c5ef10aa1464ce9c824750d7f667217bfd`; see upstream
|
||||
`MIGRATION.md` and Text View crate documentation. The adopted source includes
|
||||
structured InterfaceReference, scope_ref, Client invalidation/CallContext, and
|
||||
complete canonical signatures. This is a source snapshot, not a claim that a new
|
||||
registry release exists.
|
||||
|
||||
The root workspace's exact path dependencies and lockfile resolve all WIP types
|
||||
from this committed snapshot. There are no dependencies on attached Workdir host
|
||||
paths or on an SSH checkout in CI. This also allows the Nix dependency fetcher to
|
||||
fetch only normal registry dependencies. The packages are excluded from Yoi's
|
||||
workspace membership; their upstream public-API tests remain available separately.
|
||||
|
||||
Source files, upstream tests, README files, and Cargo-generated normalized
|
||||
manifests are unchanged. Each package retains the `.cargo-checksum.json` emitted
|
||||
by Cargo; `scripts/verify-wip-vendor.mjs` verifies every listed file. License texts
|
||||
are retained in the upstream packages (also copied at this directory's root for
|
||||
the Text View package's MIT-or-Apache-2.0 license).
|
||||
|
||||
## Reproducing or updating
|
||||
|
||||
Use a temporary standalone Cargo project with a `[workspace]` table and
|
||||
`wip-client` / `wip-text-view` dependencies on the exact Git URL/revision above.
|
||||
Run `CARGO_NET_GIT_FETCH_WITH_CLI=true cargo vendor --manifest-path <temporary-project>/Cargo.toml <temporary-project>/vendor`.
|
||||
Copy only its four `wip-*` directories here, retaining their checksums. Do not edit
|
||||
vendored sources or normalize their manifests by hand. Update all four packages,
|
||||
root `workspace.metadata.wip-upstream`, the lockfile, documentation and Nix
|
||||
registry-dependency hash together for a future adoption.
|
||||
|
||||
Verify with:
|
||||
|
||||
```sh
|
||||
node scripts/verify-wip-vendor.mjs
|
||||
cargo tree --locked --offline -p worker
|
||||
cargo test --manifest-path vendor/wip-rs/wip-text-view/Cargo.toml --target-dir target/wip-upstream
|
||||
```
|
||||
|
||||
A future update must reread the canonical reference and migration contracts, not
|
||||
infer compatibility from the unchanged `0.1.0` version string.
|
||||
@@ -0,0 +1 @@
|
||||
{"files":{"Cargo.toml":"bd8c8ea10f364e9bdf38f574da57bc30dfbd73f28e0e32e19076bb2c8176474e","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"75b552e04aa4e3530b5159154649e5acf433a0dab7164ff849b2e63cc632d240","README.md":"c873b18952f4db490acb48c7c7499fbd5385cb3e247c95184d63e414237203b1","src/lib.rs":"f0fba0e5f0513defdd9adfd3a7a94a11f187a8bb0ddc2c5a4d1f6e7e7e5b9efe","tests/adapter.rs":"2a00b9096e2b15f81c36cca44f88477c7eff420760ab8f73e5a88c97c156d2ce","tests/runtime.rs":"25da7cdef812f6c4438b68e326e72a94883ad4abbd929f4237470075721d33d0"},"package":null}
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "wip-client"
|
||||
version = "0.1.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Presentation-independent stateful WIP client runtime"
|
||||
documentation = "https://docs.rs/wip-client"
|
||||
readme = "README.md"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://gitea.hareworks.net/Hare/wip-rs"
|
||||
|
||||
[lib]
|
||||
name = "wip_client"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "adapter"
|
||||
path = "tests/adapter.rs"
|
||||
|
||||
[[test]]
|
||||
name = "runtime"
|
||||
path = "tests/runtime.rs"
|
||||
|
||||
[dependencies.wip-http]
|
||||
version = "0.1.0"
|
||||
path = "../wip-http"
|
||||
|
||||
[dependencies.wip-protocol]
|
||||
version = "0.1.0"
|
||||
path = "../wip-protocol"
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
# wip-client
|
||||
|
||||
Presentation-independent stateful runtime for Web Interface Protocol (WIP) clients.
|
||||
|
||||
`wip-client` manages endpoint- and security-context-isolated Known Space, object and Interface Descriptor observations, bounded request ownership, supersession, out-of-order response suppression, validator recovery, and operation call contexts. It produces and consumes framework-neutral `wip-http` messages but performs no network I/O and contains no UI types.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-client = "0.1.0"
|
||||
```
|
||||
|
||||
Applications provide the HTTP adapter and presentation layer, send each prepared request exactly as owned by the runtime, then return the corresponding response for completion.
|
||||
|
||||
## Interface identity and scope lifetime
|
||||
|
||||
Interface acquisition and call APIs use `wip_protocol::InterfaceReference { scope, name }` directly. Within an endpoint/security-context session, the complete scoped pair is the cache key and the Object membership key: equal names in different scopes remain distinct. A scope is a canonical absolute Worldspace path and must be an ancestor of, or equal to, the call target path. Root scope (`/`) and self scope are valid; clients must not rewrite either into a different reference.
|
||||
|
||||
`InterfaceObservation::scope_ref` is optional opaque metadata identifying the scope Object, not a third reference component, a path, or an Interface Descriptor validator. Its absence does not prevent acquisition or calls. Calls copy the exact observed reference, optional `scope_ref`, and optional Interface Descriptor validator into `InterfaceTarget`; the target Object validator is copied separately. The `CallContext` fixes those observations, the descriptor, and the operation declaration before dispatch.
|
||||
|
||||
A descriptor without an Interface Descriptor validator is immutable only within the lifetime of its scope Object, not forever at that path. Descriptors with validators are also bound to that scope lifetime. When accepted observations establish that a known scope binding has changed or been lost, dependent cached interface state is invalidated and cannot authorize a new call until explicitly reacquired. A superseded interface response must not restore an observation from the old lifetime. A previously prepared call retains its original context rather than silently adopting a new scope identity or descriptor.
|
||||
|
||||
Scope binding evidence is shared across Interface names at the same scope path: a new binding learned by fetching one name retires older descriptors for the other names too. Separately observed Object refs also provide lifetime evidence even when a descriptor's `scope_ref` was omitted. This corroboration is private bounded cache state, not an invented identity, and never fills in missing call metadata. Same-lifetime descriptor validation still applies; a detected ref change or loss retires the old lifetime instead.
|
||||
|
||||
Object deletion, entry-edge removal, and local cache eviction are different events. A direct observe `NotFound` confirms unavailability at the requested scope path and removes cached interfaces scoped to that path; it does not guarantee identity-wide Object deletion or unavailability through every alias. Removing one entry edge likewise does not prove that the Object was deleted or invalidate every remaining alias. Cache eviction is local loss of retained knowledge, not evidence of Host deletion. Losing a known binding at an interface's scope path nevertheless ends safe reuse of descriptors dependent on that binding, even if the same Object remains reachable elsewhere. Optional `scope_ref` can provide identity evidence, but clients do not fabricate it when it is absent.
|
||||
|
||||
Without Object `ref` or `scope_ref` identity evidence, a replacement at the same scope path can be indistinguishable from the previous Object. The runtime cannot detect every ref-less replacement from path and descriptor contents alone; absence of detectable change is not proof that the scope lifetime continued.
|
||||
|
||||
## Explicit recovery and operation outcomes
|
||||
|
||||
`ensure_observed` and `ensure_interface` avoid duplicate fresh or loading work; they do not automatically refresh retained stale or failed observations. Use the explicit object/children refresh APIs and `prepare_interface` to recover the observations required for a new call. An operation `InterfaceMismatch` invalidates both sides of the call's assumptions: it marks the target Object observation stale and invalidates the selected cached interface observation, so recovery requires reobserving membership and reacquiring the descriptor. Reobserving an Object and reacquiring its interface are retrievals, not a retry of an operation.
|
||||
|
||||
The runtime never automatically retries an operation. Mark a call dispatched when handing it to the transport and report completion or transport failure with its original `RequestId`. A timeout, disconnect, or invalid response after dispatch can leave the outcome unknown: execution or commit cannot be ruled out. Refreshing stale state does not resolve that uncertainty and must not automatically resubmit the call; any new operation is an explicit application decision.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-client) for session, acquisition, cache, and call APIs.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
Vendored
+2325
File diff suppressed because it is too large
Load Diff
+713
@@ -0,0 +1,713 @@
|
||||
fn root_reference(name: &str) -> wip_protocol::InterfaceReference {
|
||||
wip_protocol::InterfaceReference {
|
||||
scope: "/".into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_client::{
|
||||
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
|
||||
ObservationState, OutcomeUnknownReason, SecurityContext,
|
||||
};
|
||||
use wip_http::http::{Response, StatusCode};
|
||||
use wip_http::{
|
||||
Limits, decode_call_operation_request, decode_fetch_interface_request,
|
||||
encode_fetch_interface_response, encode_observe_response, encode_protocol_error_response,
|
||||
};
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1,
|
||||
InterfaceDescriptor, InterfaceReference, InterfaceTarget, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ParameterDeclaration, ProtocolError, ProtocolErrorCode,
|
||||
ProtocolInteraction, ReturnDeclaration, Target, TypeExpr, Value,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 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![root_reference("math")],
|
||||
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,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn observe(client: &mut Client, session: &wip_client::SessionId, path: &str, value: Object) {
|
||||
let request = client.refresh_object(session, path).unwrap();
|
||||
client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: path.into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: value,
|
||||
children: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn fetch(
|
||||
client: &mut Client,
|
||||
session: &wip_client::SessionId,
|
||||
value: FetchInterfaceResponse,
|
||||
) -> Completion {
|
||||
let request = client
|
||||
.prepare_interface(session, value.interface.clone())
|
||||
.unwrap();
|
||||
let logical = FetchInterfaceRequest {
|
||||
interface: value.interface.clone(),
|
||||
};
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(request.request.body(), limits()).unwrap(),
|
||||
logical
|
||||
);
|
||||
client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_fetch_interface_response(&logical, &value, limits()).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_accepts_same_name_interfaces_in_different_scopes() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_object(&session, "/item").unwrap();
|
||||
let completion = client
|
||||
.complete(
|
||||
request.id,
|
||||
response(
|
||||
StatusCode::OK,
|
||||
br#"{"object":{"name":"item","interfaces":[{"scope":"/","name":"math"},{"scope":"/item","name":"math"}]}}"#,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let expected = vec![root_reference("math"), reference("/item", "math")];
|
||||
assert!(matches!(
|
||||
completion,
|
||||
Completion::Object(observation)
|
||||
if observation.state == ObservationState::Fresh
|
||||
&& observation.object.as_ref().unwrap().interfaces == expected
|
||||
));
|
||||
let cached = client.object(&session, "/item").unwrap();
|
||||
assert_eq!(cached.state, ObservationState::Fresh);
|
||||
assert_eq!(cached.object.unwrap().interfaces, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_different_scopes_have_independent_requests_and_cached_descriptors() {
|
||||
let (mut client, session) = setup();
|
||||
let root = root_reference("math");
|
||||
let scoped = reference("/area", "math");
|
||||
let root_request = client
|
||||
.ensure_interface(&session, root.clone())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let scoped_request = client
|
||||
.ensure_interface(&session, scoped.clone())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_ne!(root_request.id, scoped_request.id);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(root_request.request.body(), limits()).unwrap(),
|
||||
FetchInterfaceRequest {
|
||||
interface: root.clone(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(scoped_request.request.body(), limits()).unwrap(),
|
||||
FetchInterfaceRequest {
|
||||
interface: scoped.clone(),
|
||||
}
|
||||
);
|
||||
for selected in [&root, &scoped] {
|
||||
assert!(
|
||||
client
|
||||
.ensure_interface(&session, selected.clone())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(client.in_flight_len(), 2);
|
||||
|
||||
// Reverse completion order must not supersede the other scope's request.
|
||||
for (request, selected, documentation, scope_ref, validator) in [
|
||||
(
|
||||
scoped_request,
|
||||
&scoped,
|
||||
"area math",
|
||||
Some("area-object"),
|
||||
Some(b"area-v1".to_vec()),
|
||||
),
|
||||
(root_request, &root, "root math", None, None),
|
||||
] {
|
||||
let mut expected_descriptor = descriptor(INTERFACE_FORMAT_V1);
|
||||
expected_descriptor.documentation = Some(wip_protocol::Documentation {
|
||||
summary: documentation.into(),
|
||||
details: None,
|
||||
});
|
||||
let value = FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
descriptor: expected_descriptor.clone(),
|
||||
validator: validator.clone(),
|
||||
};
|
||||
let completion = client
|
||||
.complete(
|
||||
request.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: selected.clone(),
|
||||
},
|
||||
&value,
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(completion, Completion::Interface(_)));
|
||||
let cached = client.interface(&session, selected).unwrap();
|
||||
assert_eq!(cached.reference, *selected);
|
||||
assert_eq!(cached.descriptor, Some(expected_descriptor));
|
||||
assert_eq!(cached.scope_ref, value.scope_ref);
|
||||
assert_eq!(cached.validator, validator);
|
||||
assert_eq!(cached.state, ObservationState::Fresh);
|
||||
}
|
||||
for selected in [&root, &scoped] {
|
||||
assert!(
|
||||
client
|
||||
.ensure_interface(&session, selected.clone())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
assert_eq!(
|
||||
client
|
||||
.interface(&session, &root)
|
||||
.unwrap()
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.map(|documentation| documentation.summary.as_str()),
|
||||
Some("root math")
|
||||
);
|
||||
assert_eq!(
|
||||
client
|
||||
.interface(&session, &scoped)
|
||||
.unwrap()
|
||||
.descriptor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.documentation
|
||||
.as_ref()
|
||||
.map(|documentation| documentation.summary.as_str()),
|
||||
Some("area math")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_completion_retains_optional_scope_ref_independently_of_validator() {
|
||||
for scope_ref in [None, Some("opaque scope identity / not a path")] {
|
||||
for validator in [None, Some(b"interface-v1".to_vec())] {
|
||||
let (mut client, session) = setup();
|
||||
let selected = reference("/area", "math");
|
||||
let expected = wip_client::InterfaceObservation {
|
||||
reference: selected.clone(),
|
||||
descriptor: Some(descriptor(INTERFACE_FORMAT_V1)),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: validator.clone(),
|
||||
state: ObservationState::Fresh,
|
||||
};
|
||||
let completion = fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: expected.descriptor.clone().unwrap(),
|
||||
scope_ref: expected.scope_ref.clone(),
|
||||
validator,
|
||||
},
|
||||
);
|
||||
assert_eq!(completion, Completion::Interface(expected.clone()));
|
||||
assert_eq!(client.interface(&session, &selected), Some(&expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_membership_requires_the_complete_scope_and_name_pair() {
|
||||
let (mut client, session) = setup();
|
||||
let member = reference("/item", "math");
|
||||
let same_name = root_reference("math");
|
||||
let mut value = object();
|
||||
value.interfaces = vec![member.clone()];
|
||||
observe(&mut client, &session, "/item", value);
|
||||
for selected in [&member, &same_name] {
|
||||
fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
scope_ref: None,
|
||||
validator: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let arguments = BTreeMap::from([("value".into(), Value::Integer(2))]);
|
||||
assert_eq!(
|
||||
client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&same_name,
|
||||
"calculate",
|
||||
arguments.clone(),
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ClientErrorKind::InvalidRequest
|
||||
);
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
let call = client
|
||||
.prepare_call(&session, "/item", &member, "calculate", arguments)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_request(
|
||||
call.request.body(),
|
||||
&descriptor(INTERFACE_FORMAT_V1),
|
||||
limits(),
|
||||
)
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
member
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_copy_exact_observed_references_metadata_and_validators_for_root_ancestor_and_self_scopes()
|
||||
{
|
||||
for (path, scope) in [
|
||||
("/", "/"),
|
||||
("/item", "/"),
|
||||
("/item", "/item"),
|
||||
("/area/item", "/area"),
|
||||
("/area/item", "/area/item"),
|
||||
] {
|
||||
for scope_ref in [None, Some("opaque scope identity / not a path")] {
|
||||
for interface_validator in [None, Some(b"interface-v1".to_vec())] {
|
||||
for object_validator in [None, Some(b"object-v1".to_vec())] {
|
||||
let (mut client, session) = setup();
|
||||
let selected = reference(scope, "math");
|
||||
let expected_descriptor = descriptor(INTERFACE_FORMAT_V1);
|
||||
let mut value = object();
|
||||
value.name = path.rsplit('/').next().unwrap().into();
|
||||
value.interfaces = vec![selected.clone()];
|
||||
value.validator = object_validator.clone();
|
||||
if path == scope {
|
||||
value.r#ref = scope_ref.map(str::to_owned);
|
||||
}
|
||||
observe(&mut client, &session, path, value.clone());
|
||||
fetch(
|
||||
&mut client,
|
||||
&session,
|
||||
FetchInterfaceResponse {
|
||||
interface: selected.clone(),
|
||||
descriptor: expected_descriptor.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: interface_validator.clone(),
|
||||
},
|
||||
);
|
||||
let expected_interface = client.interface(&session, &selected).unwrap().clone();
|
||||
let expected_object = client.object(&session, path).unwrap();
|
||||
let arguments = BTreeMap::from([("value".into(), Value::Integer(2))]);
|
||||
let expected = CallOperationRequest {
|
||||
target: Target {
|
||||
path: path.into(),
|
||||
validator: object_validator,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference: selected.clone(),
|
||||
scope_ref: scope_ref.map(str::to_owned),
|
||||
validator: interface_validator.clone(),
|
||||
},
|
||||
operation: "calculate".into(),
|
||||
arguments: arguments.clone(),
|
||||
};
|
||||
let call = client
|
||||
.prepare_call(&session, path, &selected, "calculate", arguments)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_request(
|
||||
call.request.body(),
|
||||
&expected_descriptor,
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
let context = client.pending_call_context(call.id).unwrap();
|
||||
assert_eq!(context.request(), &expected);
|
||||
assert_eq!(context.interface(), &expected_interface);
|
||||
assert_eq!(context.object(), &expected_object);
|
||||
assert_eq!(context.object().object.as_ref(), Some(&value));
|
||||
assert_eq!(context.descriptor(), &expected_descriptor);
|
||||
assert_eq!(context.operation(), &expected_descriptor.operations[0]);
|
||||
assert_eq!(context.session(), &session);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
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":[{"scope":"/","name":"math"},{"scope":"/","name":"math"}]}"#,
|
||||
br#"{"name":"wrong","interfaces":[]}"#,
|
||||
];
|
||||
for body in cases {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = client
|
||||
.complete(request.id, response(StatusCode::OK, body))
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ClientErrorKind::InvalidResponse);
|
||||
assert!(matches!(
|
||||
client.object(&session, "/item").unwrap().state,
|
||||
ObservationState::Error(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disallowed_code_and_status_success_contradictions_are_invalid_response() {
|
||||
let cases = [
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
br#"{"error":{"code":"interface_not_found","message":"wrong"}}"#.as_slice(),
|
||||
),
|
||||
(
|
||||
StatusCode::OK,
|
||||
br#"{"error":{"code":"not_found","message":"wrong status"}}"#.as_slice(),
|
||||
),
|
||||
(
|
||||
StatusCode::CREATED,
|
||||
br#"{"name":"item","interfaces":[]}"#.as_slice(),
|
||||
),
|
||||
];
|
||||
for (status, body) in cases {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
assert_eq!(
|
||||
client
|
||||
.complete(request.id, response(status, body))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ClientErrorKind::InvalidResponse
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_error_envelope_is_authoritative_and_status_mismatch_is_diagnostic() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::NotFound,
|
||||
message: "missing".into(),
|
||||
};
|
||||
let mut encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
|
||||
|
||||
assert_eq!(
|
||||
client.complete(request.id, encoded).unwrap(),
|
||||
Completion::ProtocolFailure(error)
|
||||
);
|
||||
assert_eq!(
|
||||
client.object(&session, "/item").unwrap().state,
|
||||
ObservationState::Stale
|
||||
);
|
||||
assert_eq!(
|
||||
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||
DiagnosticKind::HttpStatusMismatch
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_envelope_on_413_uses_code_and_records_canonical_422_mismatch() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||
message: "logical observation limit exceeded".into(),
|
||||
};
|
||||
let mut encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||
*encoded.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||
|
||||
assert_eq!(
|
||||
client.complete(request.id, encoded).unwrap(),
|
||||
Completion::ProtocolFailure(error)
|
||||
);
|
||||
assert_eq!(
|
||||
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||
DiagnosticKind::HttpStatusMismatch
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_success_without_valid_envelope_remains_transport_failure() {
|
||||
for status in [StatusCode::BAD_GATEWAY, StatusCode::PAYLOAD_TOO_LARGE] {
|
||||
let (mut client, session) = setup();
|
||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
let error = client
|
||||
.complete(request.id, response(status, b"infrastructure failure"))
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ClientErrorKind::Transport);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_descriptor_format_is_distinct_from_invalid_response() {
|
||||
let (mut client, session) = setup();
|
||||
let request = client
|
||||
.prepare_interface(&session, root_reference("math"))
|
||||
.unwrap();
|
||||
let logical = FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
};
|
||||
let value = FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
descriptor: descriptor("future-format/2"),
|
||||
validator: Some(b"v2".to_vec()),
|
||||
};
|
||||
let encoded = encode_fetch_interface_response(&logical, &value, limits()).unwrap();
|
||||
let error = client.complete(request.id, encoded).unwrap_err();
|
||||
assert_eq!(error.kind, ClientErrorKind::UnsupportedDescriptorFormat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object() {
|
||||
let (mut client, session) = setup();
|
||||
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
client
|
||||
.complete(
|
||||
observation.id,
|
||||
encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: "/item".into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: object(),
|
||||
children: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let interface = client
|
||||
.prepare_interface(&session, root_reference("math"))
|
||||
.unwrap();
|
||||
client
|
||||
.complete(
|
||||
interface.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
validator: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let call = client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&root_reference("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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
||||
let (mut client, session) = setup();
|
||||
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||
client
|
||||
.complete(
|
||||
observation.id,
|
||||
encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: "/item".into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: object(),
|
||||
children: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let interface = client
|
||||
.prepare_interface(&session, root_reference("math"))
|
||||
.unwrap();
|
||||
client
|
||||
.complete(
|
||||
interface.id,
|
||||
encode_fetch_interface_response(
|
||||
&FetchInterfaceRequest {
|
||||
interface: root_reference("math"),
|
||||
},
|
||||
&FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: root_reference("math"),
|
||||
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||
validator: None,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let call = client
|
||||
.prepare_call(
|
||||
&session,
|
||||
"/item",
|
||||
&root_reference("math"),
|
||||
"calculate",
|
||||
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||
)
|
||||
.unwrap();
|
||||
client.mark_dispatched(call.id).unwrap();
|
||||
|
||||
let completion = client
|
||||
.complete(
|
||||
call.id,
|
||||
Response::builder()
|
||||
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
completion,
|
||||
Completion::Call(record)
|
||||
if matches!(
|
||||
&record.outcome,
|
||||
CallOutcome::Unknown {
|
||||
reason: OutcomeUnknownReason::ResponseDecode,
|
||||
failure: Some(failure),
|
||||
} if failure.kind == ClientErrorKind::Transport
|
||||
)
|
||||
));
|
||||
assert_eq!(
|
||||
client.object(&session, "/item").unwrap().state,
|
||||
ObservationState::Stale
|
||||
);
|
||||
assert_eq!(client.in_flight_len(), 0);
|
||||
}
|
||||
+3391
File diff suppressed because it is too large
Load Diff
+1
@@ -0,0 +1 @@
|
||||
{"files":{"Cargo.toml":"aca561a80b7b0949aa29c7ca8915a17aa0b7767c6851f39ed8c7d571a4a04f9b","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"75b552e04aa4e3530b5159154649e5acf433a0dab7164ff849b2e63cc632d240","README.md":"81bf51248d4bc160fc29dd2739732567b382e6f0a0d2270e51c66f4aa44b2e40","src/codec.rs":"d4dc34ee54d909ad9196d3ede2f3dd556fc9715d405c5f43cc4a347493dd8069","src/endpoint.rs":"99309946c7fef520ffe4fd9a423ea13518b59b9b9f989a1d01b1cb656b940299","src/error.rs":"5f88daaa48cfc19b10efa88c176e19e7364df3d252c11bf6360045f2d80a5d64","src/json.rs":"d2af427e029f34ee051d41c4de8c087b11923cc1bf26cbeb1269d56f5847fc78","src/lib.rs":"6fd285a5c3fa9a5e35f79715389899cde4224c20b16143467188edd024e9f8a0","src/response.rs":"dcc68d7b35b6505a90f74805d94f5b3fbe3f89057760add7aba7a9a0a4de27a2","tests/codecs.rs":"73e45c099b01c4fb55ff89aafeb039604caffadd7d5313e8469746d71674ddc8","tests/references.rs":"ebba14f3cfbc783b5c97c9b9b52d5ea46148e9e483cfbe419f6a4084a923572f","tests/responses.rs":"562866790c83ad4aa40bed0cbc59fc11fb55f1862d6d040fdf58c8a9627cd679","tests/routes.rs":"b3eed4aa6661bda67492415356d0af49ab4871214542375a7db604d64c5c64f0"},"package":null}
|
||||
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "wip-http"
|
||||
version = "0.1.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Framework-independent standard WIP over HTTP v1 binding"
|
||||
documentation = "https://docs.rs/wip-http"
|
||||
readme = "README.md"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://gitea.hareworks.net/Hare/wip-rs"
|
||||
|
||||
[lib]
|
||||
name = "wip_http"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "codecs"
|
||||
path = "tests/codecs.rs"
|
||||
|
||||
[[test]]
|
||||
name = "references"
|
||||
path = "tests/references.rs"
|
||||
|
||||
[[test]]
|
||||
name = "responses"
|
||||
path = "tests/responses.rs"
|
||||
|
||||
[[test]]
|
||||
name = "routes"
|
||||
path = "tests/routes.rs"
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
http = "1"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
url = "2"
|
||||
|
||||
[dependencies.wip-protocol]
|
||||
version = "0.1.0"
|
||||
path = "../wip-protocol"
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
# wip-http
|
||||
|
||||
Framework-independent WIP over HTTP v1 endpoint, route, JSON codec, and response-classification support.
|
||||
|
||||
The crate maps the three WIP Core interactions to fixed HTTP routes and strict UTF-8 JSON representations. It constructs and validates `http` request and response values but deliberately performs no network I/O and does not define TLS, authentication, proxy, or connection policy.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-http = "0.1.0"
|
||||
```
|
||||
|
||||
```rust
|
||||
use wip_http::wip_protocol::ObserveRequest;
|
||||
use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let endpoint = Endpoint::parse("https://example.test/wip")?;
|
||||
let limits = Limits::new(64 * 1024, 1024 * 1024, 64)?;
|
||||
let request = encode_observe_request(
|
||||
&endpoint,
|
||||
&ObserveRequest { path: "/".into(), depth: 0 },
|
||||
limits,
|
||||
)?;
|
||||
assert_eq!(request.uri(), "https://example.test/wip/v1/observe");
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Interface references and scope identity
|
||||
|
||||
Every interface reference is encoded as an exact JSON object with required
|
||||
`scope` and `name` strings, for example `{"scope":"/github","name":"issue.read"}`.
|
||||
This applies to `Object.interfaces` elements, fetch request/response `interface`,
|
||||
and call `interface.reference`. Scope must be a canonical absolute Worldspace
|
||||
path and name must be nonempty. Legacy opaque strings, short-form strings,
|
||||
relative scopes, missing fields, and extra members are rejected. Unicode, `::`,
|
||||
and `#` in names remain literal data; comparison uses decoded field values,
|
||||
independent of JSON member order and escapes. HTTP endpoint prefixes do not
|
||||
change Worldspace scope.
|
||||
|
||||
Fetch responses and call interface targets additionally carry optional
|
||||
`scope_ref`, an opaque string copied from the scope Object's `ref` observation.
|
||||
It is not base64 and is not part of interface identity. Absent values are omitted;
|
||||
null and nonstring values are rejected. Descriptor-independent call metadata
|
||||
validates reference shape, but leaves scope ancestry and identity preconditions
|
||||
to the Host's `InterfaceMismatch` check, preserving protocol error precedence.
|
||||
Invalid success responses remain client-local `InvalidResponse` errors; protocol
|
||||
error envelopes and transport failures retain their existing classification.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-http) for codec and failure-boundary details.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
Vendored
+598
@@ -0,0 +1,598 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use http::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE};
|
||||
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
||||
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceTarget, ObserveRequest, ObserveResponse,
|
||||
ProtocolError, ProtocolInteraction, Target,
|
||||
};
|
||||
|
||||
use crate::response::{self, DecodedResponse};
|
||||
use crate::{
|
||||
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||
Limits, 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> {
|
||||
if !has_supported_content_coding(response.headers()) {
|
||||
return Err(response::unsupported_content_coding(response.status()));
|
||||
}
|
||||
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 request URI does not exactly identify the selected standard route.
|
||||
NotFound,
|
||||
/// A known standard route was requested with a method other than `POST`.
|
||||
MethodNotAllowed,
|
||||
/// The request body does not use UTF-8 `application/json` or identity coding.
|
||||
UnsupportedMediaType,
|
||||
/// 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::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
|
||||
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the value for an `Allow` response header, when required.
|
||||
#[must_use]
|
||||
pub const fn allow(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::MethodNotAllowed => Some("POST"),
|
||||
Self::NotFound | Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RequestMetadataError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotFound => formatter.write_str("request URI is not a standard WIP route"),
|
||||
Self::MethodNotAllowed => formatter.write_str("standard WIP routes require POST"),
|
||||
Self::UnsupportedMediaType => {
|
||||
formatter.write_str("expected identity-coded UTF-8 application/json Content-Type")
|
||||
}
|
||||
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RequestMetadataError {}
|
||||
|
||||
pub(crate) fn has_supported_content_coding(headers: &HeaderMap) -> bool {
|
||||
headers.get_all(CONTENT_ENCODING).iter().all(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
let mut codings = value.split(',').map(str::trim);
|
||||
let first = codings.next();
|
||||
first.is_some_and(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||
&& codings.all(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||
///
|
||||
/// 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> {
|
||||
let expected = endpoint.route(route);
|
||||
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||
return Err(RequestMetadataError::NotFound);
|
||||
}
|
||||
if value.method() != Method::POST {
|
||||
return Err(RequestMetadataError::MethodNotAllowed);
|
||||
}
|
||||
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 || !has_supported_content_coding(value.headers()) {
|
||||
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||
}
|
||||
if !accepts_json(value.headers()) {
|
||||
return Err(RequestMetadataError::NotAcceptable);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes an `observe` HTTP request.
|
||||
pub fn encode_observe_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &ObserveRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
value.validate().map_err(CodecError::from)?;
|
||||
let body = json::serialize(
|
||||
&json::observe_request_to_json(value),
|
||||
BodyKind::Request,
|
||||
limits,
|
||||
)?;
|
||||
Ok(request(endpoint, Route::Observe, body)?)
|
||||
}
|
||||
|
||||
/// Decodes an `observe` request body.
|
||||
pub fn decode_observe_request(body: &[u8], limits: Limits) -> Result<ObserveRequest, CodecError> {
|
||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
||||
json::observe_request_from_json(&value)
|
||||
}
|
||||
|
||||
/// Encodes a `fetch_interface` HTTP request.
|
||||
///
|
||||
/// Validates reference shape without requiring a target Object path.
|
||||
pub fn encode_fetch_interface_request(
|
||||
endpoint: &Endpoint,
|
||||
value: &FetchInterfaceRequest,
|
||||
limits: Limits,
|
||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
||||
value.interface.validate().map_err(CodecError::from)?;
|
||||
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.
|
||||
///
|
||||
/// Reference shape is validated, but scope ancestry and `scope_ref` identity
|
||||
/// are left to Host resolution so `NotFound`, validator failures, and
|
||||
/// `InterfaceMismatch` retain their protocol precedence.
|
||||
pub fn decode_call_operation_metadata(
|
||||
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 `observe` response as a direct body with HTTP 200.
|
||||
pub fn encode_observe_response(
|
||||
request_value: &ObserveRequest,
|
||||
value: &ObserveResponse,
|
||||
limits: Limits,
|
||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
||||
request_value
|
||||
.validate_response(value)
|
||||
.map_err(CodecError::from)?;
|
||||
let body = json::serialize(
|
||||
&json::observe_response_to_json(value),
|
||||
BodyKind::Response,
|
||||
limits,
|
||||
)?;
|
||||
Ok(response(StatusCode::OK, body)?)
|
||||
}
|
||||
|
||||
/// Decodes and classifies an `observe` client response.
|
||||
pub fn decode_observe_response<B: AsRef<[u8]>>(
|
||||
request_value: &ObserveRequest,
|
||||
value: &Response<B>,
|
||||
limits: Limits,
|
||||
) -> Result<DecodedResponse<ObserveResponse>, ClientResponseError> {
|
||||
require_response_content_type(value)?;
|
||||
response::decode(
|
||||
value.status(),
|
||||
value.body().as_ref(),
|
||||
ProtocolInteraction::Observe,
|
||||
limits,
|
||||
|json| {
|
||||
let observation = json::observe_response_from_json(json)?;
|
||||
request_value.validate_response(&observation)?;
|
||||
Ok(observation)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// 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. Logical `resource_limit_exceeded` failures use HTTP 422;
|
||||
/// representation and deployment limits are not protocol errors.
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
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 HTTP v1 route.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Route {
|
||||
/// Observe one object and its indexable descendants.
|
||||
Observe,
|
||||
/// Fetch an interface descriptor.
|
||||
FetchInterface,
|
||||
/// Call one operation.
|
||||
CallOperation,
|
||||
}
|
||||
|
||||
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::Observe => "v1/observe",
|
||||
Self::FetchInterface => "v1/fetch_interface",
|
||||
Self::CallOperation => "v1/call_operation",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A canonical absolute hierarchical base URL whose path always ends in `/`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Endpoint(Url);
|
||||
|
||||
impl Endpoint {
|
||||
/// Parses and canonicalizes an endpoint.
|
||||
///
|
||||
/// The input must be an absolute hierarchical URL with a host and without a
|
||||
/// query or fragment. Its path is an endpoint prefix, not a Worldspace path.
|
||||
/// A trailing slash is appended when absent so RFC 3986 relative-reference
|
||||
/// resolution preserves the final prefix segment. The supplied scheme is
|
||||
/// preserved; scheme and transport security are deployment concerns.
|
||||
pub fn parse(input: &str) -> Result<Self, EndpointError> {
|
||||
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
|
||||
if url.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; 3] = [Route::Observe, Route::FetchInterface, Route::CallOperation];
|
||||
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 over HTTP base.
|
||||
#[derive(Debug)]
|
||||
pub enum EndpointError {
|
||||
/// URL parsing failed.
|
||||
InvalidUrl(url::ParseError),
|
||||
/// 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::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,
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+180
@@ -0,0 +1,180 @@
|
||||
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,
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
/// Creates a nonzero limit set.
|
||||
pub fn new(
|
||||
max_request_bytes: usize,
|
||||
max_response_bytes: usize,
|
||||
max_nesting: 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);
|
||||
}
|
||||
Ok(Self {
|
||||
max_request_bytes,
|
||||
max_response_bytes,
|
||||
max_nesting,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
Vendored
+1334
File diff suppressed because it is too large
Load Diff
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
//! Framework-independent standard WIP over HTTP v1 binding.
|
||||
//!
|
||||
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
||||
//! success and error response handling, HTTP status mapping, descriptor-guided
|
||||
//! operation-value conversion. It deliberately performs no I/O and depends on no
|
||||
//! server framework, TLS implementation, filesystem projection, client cache, or
|
||||
//! presentation layer. URL schemes, TLS, certificates, authentication mechanisms,
|
||||
//! proxies, and caches are selected by the HTTP implementation and deployment
|
||||
//! rather than by WIP conformance.
|
||||
//!
|
||||
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
||||
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
||||
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
||||
//!
|
||||
//! Interface references use exact JSON objects with required `scope` and `name`
|
||||
//! strings in every position. Legacy strings and display shorthand are rejected.
|
||||
//! Scope is a canonical absolute Worldspace path, not an HTTP endpoint prefix.
|
||||
//! Optional `scope_ref` metadata on fetch responses and call interface targets is
|
||||
//! an opaque string, never base64; absent fields are omitted and null is rejected.
|
||||
//! Call metadata validates reference shape without resolving scope ancestry or
|
||||
//! identity, which remain Host checks with `InterfaceMismatch` precedence.
|
||||
//!
|
||||
//! ```
|
||||
//! use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||
//! use wip_protocol::ObserveRequest;
|
||||
//!
|
||||
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
||||
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64)?;
|
||||
//! let request = encode_observe_request(
|
||||
//! &endpoint,
|
||||
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
||||
//! limits,
|
||||
//! )?;
|
||||
//! assert_eq!(request.uri(), "http://example.test/api/wip/v1/observe");
|
||||
//! assert_eq!(request.method(), http::Method::POST);
|
||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
//! ```
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod codec;
|
||||
mod endpoint;
|
||||
mod error;
|
||||
mod json;
|
||||
mod 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_observe_request, decode_observe_response,
|
||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||
encode_protocol_error_response, is_json_content_type, validate_http_request,
|
||||
};
|
||||
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits};
|
||||
pub use response::{
|
||||
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||
};
|
||||
|
||||
/// 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;
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
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, 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,
|
||||
/// The response uses a content coding the client does not support.
|
||||
UnsupportedContentCoding,
|
||||
/// 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 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.
|
||||
#[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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||
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,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_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);
|
||||
}
|
||||
protocol_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 unsupported_content_coding(status: StatusCode) -> ClientResponseError {
|
||||
ClientResponseError::TransportBinding(TransportBindingFailure {
|
||||
status,
|
||||
kind: TransportFailureKind::UnsupportedContentCoding,
|
||||
})
|
||||
}
|
||||
|
||||
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 })
|
||||
}
|
||||
+528
@@ -0,0 +1,528 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_http::http::StatusCode;
|
||||
use wip_http::wip_protocol::{
|
||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target,
|
||||
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||
decode_call_operation_metadata, decode_call_operation_request, decode_call_operation_response,
|
||||
decode_fetch_interface_request, decode_fetch_interface_response, decode_observe_request,
|
||||
decode_observe_response, encode_call_operation_request, encode_call_operation_response,
|
||||
encode_fetch_interface_request, encode_fetch_interface_response, encode_observe_request,
|
||||
encode_observe_response,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(1_000_000, 1_000_000, 100).unwrap()
|
||||
}
|
||||
|
||||
fn endpoint() -> Endpoint {
|
||||
Endpoint::parse("https://example.test/wip").unwrap()
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(name: &str, validator: &[u8]) -> Object {
|
||||
Object {
|
||||
name: name.into(),
|
||||
description: Some("description".into()),
|
||||
interfaces: vec![reference("/", "interface-v1")],
|
||||
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: reference("/", "interface-v1"),
|
||||
scope_ref: None,
|
||||
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 observe = encode_observe_request(
|
||||
&endpoint(),
|
||||
&ObserveRequest {
|
||||
path: "/".into(),
|
||||
depth: 0,
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap();
|
||||
let fetch_interface = encode_fetch_interface_request(
|
||||
&endpoint(),
|
||||
&FetchInterfaceRequest {
|
||||
interface: reference("/", "interface-v1"),
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap();
|
||||
let call = encode_call_operation_request(&endpoint(), &call_request(), &descriptor(), limits())
|
||||
.unwrap();
|
||||
|
||||
for request in [observe, fetch_interface, call] {
|
||||
assert_eq!(request.headers()["accept"], "application/json");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_zero_observe_round_trips_direct_body_and_validator() {
|
||||
let request = ObserveRequest {
|
||||
path: "/items/123".into(),
|
||||
depth: 0,
|
||||
};
|
||||
let encoded_request = encode_observe_request(&endpoint(), &request, limits()).unwrap();
|
||||
assert_eq!(encoded_request.uri().path(), "/wip/v1/observe");
|
||||
assert_eq!(
|
||||
decode_observe_request(encoded_request.body(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
|
||||
let expected = ObjectObservation {
|
||||
object: object("123", &[0, 1, 2, 255]),
|
||||
children: None,
|
||||
};
|
||||
let encoded = encode_observe_response(&request, &expected, limits()).unwrap();
|
||||
assert_eq!(encoded.status(), StatusCode::OK);
|
||||
assert!(
|
||||
!std::str::from_utf8(encoded.body())
|
||||
.unwrap()
|
||||
.contains("children")
|
||||
);
|
||||
assert_eq!(
|
||||
decode_observe_response(&request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(expected)
|
||||
);
|
||||
assert!(encoded.headers().get("etag").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_and_interface_round_trip_nested_logical_models() {
|
||||
let observe_request = ObserveRequest {
|
||||
path: "/items".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let encoded_request = encode_observe_request(&endpoint(), &observe_request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_observe_request(encoded_request.body(), limits()).unwrap(),
|
||||
observe_request
|
||||
);
|
||||
let observation = ObjectObservation {
|
||||
object: object("items", b"root-validator"),
|
||||
children: Some(vec![ObjectObservation {
|
||||
object: object("123", b"child-validator"),
|
||||
children: None,
|
||||
}]),
|
||||
};
|
||||
let encoded = encode_observe_response(&observe_request, &observation, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_observe_response(&observe_request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(observation)
|
||||
);
|
||||
|
||||
let empty = ObjectObservation {
|
||||
object: object("items", b"root-validator"),
|
||||
children: Some(vec![]),
|
||||
};
|
||||
let encoded_empty = encode_observe_response(&observe_request, &empty, limits()).unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(encoded_empty.body())
|
||||
.unwrap()
|
||||
.contains("\"children\":[]")
|
||||
);
|
||||
|
||||
let interface_request = FetchInterfaceRequest {
|
||||
interface: reference("/", "interface-v1"),
|
||||
};
|
||||
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(),
|
||||
scope_ref: None,
|
||||
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_observe_request(br#"{"path":"/","depth":0,"extra":true}"#, limits).is_err());
|
||||
assert!(
|
||||
decode_observe_request(br#"{"path":"relative","path":"/","depth":0}"#, limits).is_err()
|
||||
);
|
||||
|
||||
let request = call_request();
|
||||
let descriptor = descriptor();
|
||||
let body = serde_json::to_vec(&serde_json::json!({
|
||||
"target": {"path": "/items/123", "validator": null},
|
||||
"interface": {"reference": {"scope": "/", "name": "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_remain_local_codec_failures() {
|
||||
let tiny = Limits::new(8, 8, 2).unwrap();
|
||||
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
||||
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||
|
||||
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
||||
let nesting_limited = Limits::new(1024, 1024, 2).unwrap();
|
||||
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
||||
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||
|
||||
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1).unwrap();
|
||||
assert!(
|
||||
encode_call_operation_request(
|
||||
&endpoint(),
|
||||
&call_request(),
|
||||
&descriptor(),
|
||||
outbound_limited,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
encode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: "/item".into(),
|
||||
depth: 0,
|
||||
},
|
||||
&ObjectObservation {
|
||||
object: object("item", b"validator"),
|
||||
children: None,
|
||||
},
|
||||
outbound_limited,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_descriptor_format_is_client_local() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "interface-v1"),
|
||||
};
|
||||
let mut interface = FetchInterfaceResponse {
|
||||
interface: request.interface.clone(),
|
||||
scope_ref: None,
|
||||
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_http::http::Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("content-type", "application/json; charset=utf-8")
|
||||
.body(
|
||||
br#"{"interface":{"scope":"/","name":"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":{"scope":"/","name":"wrong"},"descriptor":{"format":"wip-interface/2"}}"#.as_slice(),
|
||||
br#"{"interface":{"scope":"/","name":"interface-v1"},"descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
||||
.as_slice(),
|
||||
] {
|
||||
let response = wip_http::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_http::http::Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("content-type", "application/json; charset=utf-8")
|
||||
.body(br#"{"object":{"name":"wrong","interfaces":[]}}"#.to_vec())
|
||||
.unwrap();
|
||||
let error = decode_observe_response(
|
||||
&ObserveRequest {
|
||||
path: "/expected".into(),
|
||||
depth: 0,
|
||||
},
|
||||
&response,
|
||||
limits(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
+740
@@ -0,0 +1,740 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value as Json, json};
|
||||
use wip_http::http::{Response, StatusCode};
|
||||
use wip_http::wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1,
|
||||
InterfaceDescriptor, InterfaceReference, InterfaceTarget, Object, ObjectObservation,
|
||||
ObserveRequest, OperationDeclaration, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
ReturnDeclaration, Target, TypeExpr,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||
TransportFailureKind, decode_call_operation_metadata, decode_call_operation_request,
|
||||
decode_call_operation_response, decode_fetch_interface_request,
|
||||
decode_fetch_interface_response, decode_observe_response, encode_call_operation_request,
|
||||
encode_fetch_interface_request, encode_fetch_interface_response, encode_observe_response,
|
||||
encode_protocol_error_response,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||
}
|
||||
|
||||
fn endpoint() -> Endpoint {
|
||||
Endpoint::parse("https://example.test/deployment/prefix").unwrap()
|
||||
}
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "run#::操作".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn call(reference: InterfaceReference, scope_ref: Option<String>) -> CallOperationRequest {
|
||||
CallOperationRequest {
|
||||
target: Target {
|
||||
path: "/世界::#/item".into(),
|
||||
validator: Some(vec![0, 255]),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference,
|
||||
scope_ref,
|
||||
validator: Some(vec![1, 255]),
|
||||
},
|
||||
operation: "run#::操作".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn observation(references: Vec<InterfaceReference>) -> ObjectObservation {
|
||||
ObjectObservation {
|
||||
object: Object {
|
||||
name: "item".into(),
|
||||
description: None,
|
||||
interfaces: references,
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
},
|
||||
children: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn observe_request() -> ObserveRequest {
|
||||
ObserveRequest {
|
||||
path: "/世界::#/item".into(),
|
||||
depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn response(status: StatusCode, value: Json) -> Response<Vec<u8>> {
|
||||
raw_response(status, &serde_json::to_vec(&value).unwrap())
|
||||
}
|
||||
|
||||
fn raw_response(status: StatusCode, body: &[u8]) -> Response<Vec<u8>> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header("content-type", "application/json")
|
||||
.body(body.to_vec())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn fetch_json(interface: Json) -> Json {
|
||||
json!({
|
||||
"interface": interface,
|
||||
"descriptor": {"format": INTERFACE_FORMAT_V1, "types": [], "operations": []}
|
||||
})
|
||||
}
|
||||
|
||||
fn call_json(reference: Json) -> Json {
|
||||
json!({
|
||||
"target": {"path": "/世界::#/item"},
|
||||
"interface": {"reference": reference},
|
||||
"operation": "run#::操作",
|
||||
"arguments": {}
|
||||
})
|
||||
}
|
||||
|
||||
fn invalid_success<T: std::fmt::Debug>(result: Result<T, ClientResponseError>) {
|
||||
assert!(matches!(
|
||||
result.unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::InvalidSuccessBody,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_structured_reference_is_encoded_and_round_tripped_in_every_position() {
|
||||
let interface_ref = reference("/世界::#", "é::接口#read/with\"quote\\slash");
|
||||
let expected = json!({"scope": interface_ref.scope, "name": interface_ref.name});
|
||||
let fetch_request = FetchInterfaceRequest {
|
||||
interface: interface_ref.clone(),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &fetch_request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
encoded.uri().path(),
|
||||
"/deployment/prefix/v1/fetch_interface"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Json>(encoded.body()).unwrap(),
|
||||
json!({"interface": expected})
|
||||
);
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
fetch_request
|
||||
);
|
||||
|
||||
let fetch_response = FetchInterfaceResponse {
|
||||
interface: interface_ref.clone(),
|
||||
scope_ref: Some("opaque:世界::# not base64!".into()),
|
||||
descriptor: descriptor(),
|
||||
validator: Some(vec![1, 255]),
|
||||
};
|
||||
let encoded =
|
||||
encode_fetch_interface_response(&fetch_request, &fetch_response, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(body["interface"], expected);
|
||||
assert_eq!(body["scope_ref"], "opaque:世界::# not base64!");
|
||||
assert_eq!(body["validator"], "Af8=");
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&fetch_request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(fetch_response)
|
||||
);
|
||||
|
||||
let observation = observation(vec![interface_ref.clone(), reference("/", "root")]);
|
||||
let encoded = encode_observe_response(&observe_request(), &observation, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body["object"]["interfaces"],
|
||||
json!([expected, {"scope": "/", "name": "root"}])
|
||||
);
|
||||
assert_eq!(
|
||||
decode_observe_response(&observe_request(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(observation)
|
||||
);
|
||||
|
||||
let request = call(interface_ref, Some("opaque:世界::# not base64!".into()));
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(body["interface"]["reference"], expected);
|
||||
assert_eq!(body["interface"]["scope_ref"], "opaque:世界::# not base64!");
|
||||
assert_eq!(body["interface"]["validator"], "Af8=");
|
||||
assert_eq!(body["target"]["validator"], "AP8=");
|
||||
assert_eq!(body["operation"], "run#::操作");
|
||||
assert_eq!(
|
||||
decode_call_operation_request(encoded.body(), &descriptor(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(encoded.body(), limits())
|
||||
.unwrap()
|
||||
.interface,
|
||||
request.interface
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_reference_corpus_is_rejected_in_all_positions() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "interface-v1"),
|
||||
};
|
||||
for bad in [
|
||||
json!("interface-v1"),
|
||||
json!("/::interface-v1"),
|
||||
json!("interface-v1#run"),
|
||||
Json::Null,
|
||||
json!(false),
|
||||
json!(1),
|
||||
json!([]),
|
||||
json!({}),
|
||||
json!({"name": "interface-v1"}),
|
||||
json!({"scope": "/"}),
|
||||
json!({"scope": null, "name": "interface-v1"}),
|
||||
json!({"scope": 1, "name": "interface-v1"}),
|
||||
json!({"scope": "/", "name": null}),
|
||||
json!({"scope": "/", "name": []}),
|
||||
json!({"scope": "/", "name": ""}),
|
||||
json!({"scope": "/", "name": "interface-v1", "extra": true}),
|
||||
json!({"scope": "/", "name": "interface-v1", "scope_ref": "identity"}),
|
||||
json!({"Scope": "/", "name": "interface-v1"}),
|
||||
json!({"scope": "", "name": "interface-v1"}),
|
||||
json!({"scope": "relative", "name": "interface-v1"}),
|
||||
json!({"scope": ".", "name": "interface-v1"}),
|
||||
json!({"scope": "..", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/", "name": "interface-v1"}),
|
||||
json!({"scope": "//a", "name": "interface-v1"}),
|
||||
json!({"scope": "/a//b", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/./b", "name": "interface-v1"}),
|
||||
json!({"scope": "/a/../b", "name": "interface-v1"}),
|
||||
] {
|
||||
let body = serde_json::to_vec(&json!({"interface": bad})).unwrap();
|
||||
assert!(
|
||||
decode_fetch_interface_request(&body, limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
let body = serde_json::to_vec(&call_json(bad.clone())).unwrap();
|
||||
assert!(
|
||||
decode_call_operation_metadata(&body, limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(
|
||||
decode_call_operation_request(&body, &descriptor(), limits()).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch_json(bad.clone())),
|
||||
limits(),
|
||||
));
|
||||
let mut future = fetch_json(bad.clone());
|
||||
future["descriptor"] = json!({"format": "future-format", "future": true});
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, future),
|
||||
limits(),
|
||||
));
|
||||
invalid_success(decode_observe_response(
|
||||
&observe_request(),
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
json!({"object": {"name": "item", "interfaces": [bad]}}),
|
||||
),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_reference_members_are_rejected_even_when_escaped_or_equal() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
for bad in [
|
||||
r#"{"scope":"/","scope":"/","name":"x"}"#,
|
||||
r#"{"scope":"/","name":"x","name":"x"}"#,
|
||||
r#"{"scope":"/","name":"x","na\u006de":"x"}"#,
|
||||
] {
|
||||
let fetch = format!(r#"{{"interface":{bad}}}"#);
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_request(fetch.as_bytes(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
let call = format!(
|
||||
r#"{{"target":{{"path":"/"}},"interface":{{"reference":{bad}}},"operation":"run","arguments":{{}}}}"#
|
||||
);
|
||||
assert!(matches!(
|
||||
decode_call_operation_metadata(call.as_bytes(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_call_operation_request(call.as_bytes(), &descriptor(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
let fetch_response = format!(
|
||||
r#"{{"interface":{bad},"descriptor":{{"format":"wip-interface/1","types":[],"operations":[]}}}}"#
|
||||
);
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&raw_response(StatusCode::OK, fetch_response.as_bytes()),
|
||||
limits(),
|
||||
));
|
||||
let observe = format!(r#"{{"object":{{"name":"item","interfaces":[{bad}]}}}}"#);
|
||||
invalid_success(decode_observe_response(
|
||||
&observe_request(),
|
||||
&raw_response(StatusCode::OK, observe.as_bytes()),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_order_and_json_escapes_do_not_change_reference_identity() {
|
||||
let expected = reference("/世界::#", "é::接口#");
|
||||
let raw_reference = r#"{"name":"\u00e9::\u63a5\u53e3#","scope":"\/\u4e16\u754c::#"}"#;
|
||||
let fetch = format!(r#"{{"interface":{raw_reference}}}"#);
|
||||
let request = decode_fetch_interface_request(fetch.as_bytes(), limits()).unwrap();
|
||||
assert_eq!(request.interface, expected);
|
||||
let fetch_response = format!(
|
||||
r#"{{"descriptor":{{"operations":[],"types":[],"format":"wip-interface/1"}},"interface":{raw_reference}}}"#
|
||||
);
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &raw_response(StatusCode::OK, fetch_response.as_bytes()), limits()).unwrap(), DecodedResponse::Success(value) if value.interface == expected)
|
||||
);
|
||||
let call = format!(
|
||||
r#"{{"arguments":{{}},"operation":"run#::操作","interface":{{"reference":{raw_reference}}},"target":{{"path":"/世界::#/item"}}}}"#
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(call.as_bytes(), limits())
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_request(call.as_bytes(), &descriptor(), limits())
|
||||
.unwrap()
|
||||
.interface
|
||||
.reference,
|
||||
expected
|
||||
);
|
||||
let observe = format!(r#"{{"object":{{"interfaces":[{raw_reference}],"name":"item"}}}}"#);
|
||||
assert!(
|
||||
matches!(decode_observe_response(&observe_request(), &raw_response(StatusCode::OK, observe.as_bytes()), limits()).unwrap(), DecodedResponse::Success(value) if value.object.interfaces == vec![expected])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_comparison_is_exact_without_normalization_case_or_url_decoding() {
|
||||
for different in [
|
||||
reference("/", "e\u{301}"),
|
||||
reference("/", "É"),
|
||||
reference("/", "%C3%A9"),
|
||||
reference("/other", "é"),
|
||||
] {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "é"),
|
||||
};
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
fetch_json(json!({"scope": different.scope, "name": different.name})),
|
||||
),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/%2E", "é"),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "."),
|
||||
};
|
||||
assert!(encode_fetch_interface_request(&endpoint(), &request, limits()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_encoding_rejects_invalid_reference_shape_without_needing_a_fetch_target() {
|
||||
for bad in [
|
||||
reference("relative", "x"),
|
||||
reference("", "x"),
|
||||
reference("/a/../b", "x"),
|
||||
reference("/", ""),
|
||||
] {
|
||||
assert!(
|
||||
encode_fetch_interface_request(
|
||||
&endpoint(),
|
||||
&FetchInterfaceRequest {
|
||||
interface: bad.clone()
|
||||
},
|
||||
limits()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
encode_call_operation_request(&endpoint(), &call(bad, None), &descriptor(), limits())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/unrelated/scope", "x"),
|
||||
};
|
||||
let encoded = encode_fetch_interface_request(&endpoint(), &request, limits()).unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_request(encoded.body(), limits()).unwrap(),
|
||||
request
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_metadata_leaves_valid_out_of_scope_references_and_identity_to_host_resolution() {
|
||||
let request = call(
|
||||
reference("/elsewhere", "x"),
|
||||
Some("not-current-identity".into()),
|
||||
);
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||
assert_eq!(metadata.interface, request.interface);
|
||||
assert_eq!(
|
||||
metadata
|
||||
.decode_request(encoded.body(), &descriptor(), limits())
|
||||
.unwrap(),
|
||||
request
|
||||
);
|
||||
|
||||
// Neither an unknown operation nor descriptor-bound argument values are
|
||||
// resolved by the metadata boundary before Host precondition checks.
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["operation"] = json!("missing");
|
||||
body["arguments"] = json!({"not_declared": [null, {"anything": true}]});
|
||||
let metadata =
|
||||
decode_call_operation_metadata(&serde_json::to_vec(&body).unwrap(), limits()).unwrap();
|
||||
assert_eq!(metadata.operation, "missing");
|
||||
assert_eq!(metadata.interface, request.interface);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observation_scope_validation_uses_each_nodes_path_and_structural_duplicates() {
|
||||
let request = ObserveRequest {
|
||||
path: "/a".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let valid = json!({
|
||||
"object": {"name": "a", "interfaces": [{"scope": "/", "name": "x"}, {"scope": "/a", "name": "x"}]},
|
||||
"children": [{"object": {"name": "b", "interfaces": [{"scope": "/a/b", "name": "x"}]}}]
|
||||
});
|
||||
assert!(
|
||||
decode_observe_response(&request, &response(StatusCode::OK, valid.clone()), limits())
|
||||
.is_ok()
|
||||
);
|
||||
for scope in ["/ab", "/elsewhere", "/a/b/c"] {
|
||||
let mut bad = valid.clone();
|
||||
bad["children"][0]["object"]["interfaces"][0]["scope"] = json!(scope);
|
||||
invalid_success(decode_observe_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, bad),
|
||||
limits(),
|
||||
));
|
||||
}
|
||||
let mut duplicate = valid;
|
||||
duplicate["object"]["interfaces"] =
|
||||
json!([{"scope": "/a", "name": "x"}, {"name": "x", "scope": "/a"}]);
|
||||
invalid_success(decode_observe_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, duplicate),
|
||||
limits(),
|
||||
));
|
||||
let root_request = ObserveRequest {
|
||||
path: "/".into(),
|
||||
depth: 0,
|
||||
};
|
||||
for (scope, valid) in [("/", true), ("/a", false)] {
|
||||
let result = decode_observe_response(
|
||||
&root_request,
|
||||
&response(
|
||||
StatusCode::OK,
|
||||
json!({"object": {"name": "", "interfaces": [{"scope": scope, "name": "x"}]}}),
|
||||
),
|
||||
limits(),
|
||||
);
|
||||
if valid {
|
||||
assert!(result.is_ok());
|
||||
} else {
|
||||
invalid_success(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_omission_and_opaque_strings_round_trip_in_both_positions() {
|
||||
for scope_ref in [
|
||||
None,
|
||||
Some(String::new()),
|
||||
Some("opaque::# 世界 ! not base64 /+=".into()),
|
||||
Some("\"\\\n\u{0}".into()),
|
||||
] {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let expected = FetchInterfaceResponse {
|
||||
interface: request.interface.clone(),
|
||||
scope_ref: scope_ref.clone(),
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
};
|
||||
let encoded = encode_fetch_interface_response(&request, &expected, limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body.get("scope_ref"),
|
||||
scope_ref
|
||||
.as_ref()
|
||||
.map(|value| Json::String(value.clone()))
|
||||
.as_ref()
|
||||
);
|
||||
assert!(body.get("validator").is_none());
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::Success(expected)
|
||||
);
|
||||
let call = call(request.interface, scope_ref);
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &call, &descriptor(), limits()).unwrap();
|
||||
let body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
assert_eq!(
|
||||
body["interface"].get("scope_ref"),
|
||||
call.interface
|
||||
.scope_ref
|
||||
.as_ref()
|
||||
.map(|value| Json::String(value.clone()))
|
||||
.as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_metadata(encoded.body(), limits())
|
||||
.unwrap()
|
||||
.interface,
|
||||
call.interface
|
||||
);
|
||||
assert_eq!(
|
||||
decode_call_operation_request(encoded.body(), &descriptor(), limits()).unwrap(),
|
||||
call
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_null_and_every_nonstring_type_are_rejected_before_descriptor_resolution() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
for bad in [Json::Null, json!(true), json!(0), json!([]), json!({})] {
|
||||
let mut fetch = fetch_json(json!({"scope": "/", "name": "x"}));
|
||||
fetch["scope_ref"] = bad.clone();
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch.clone()),
|
||||
limits(),
|
||||
));
|
||||
// Unknown format does not mask malformed common response fields.
|
||||
fetch["descriptor"] = json!({"format": "future-format", "future": true});
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&response(StatusCode::OK, fetch),
|
||||
limits(),
|
||||
));
|
||||
let mut call = call_json(json!({"scope": "/", "name": "x"}));
|
||||
call["interface"]["scope_ref"] = bad.clone();
|
||||
let body = serde_json::to_vec(&call).unwrap();
|
||||
let error = decode_call_operation_metadata(&body, limits()).unwrap_err();
|
||||
if bad.is_null() {
|
||||
assert!(matches!(error, CodecError::NullOptionalField { .. }));
|
||||
} else {
|
||||
assert!(matches!(error, CodecError::InvalidField { .. }));
|
||||
}
|
||||
assert!(decode_call_operation_request(&body, &descriptor(), limits()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_ref_is_only_allowed_on_fetch_responses_and_call_interface_targets() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let reference = json!({"scope": "/", "name": "x"});
|
||||
let fetch_request = json!({"interface": reference, "scope_ref": "identity"});
|
||||
assert!(
|
||||
decode_fetch_interface_request(&serde_json::to_vec(&fetch_request).unwrap(), limits())
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mut call = call_json(reference.clone());
|
||||
call["scope_ref"] = json!("identity");
|
||||
assert!(decode_call_operation_metadata(&serde_json::to_vec(&call).unwrap(), limits()).is_err());
|
||||
let mut call = call_json(reference);
|
||||
call["target"]["scope_ref"] = json!("identity");
|
||||
assert!(decode_call_operation_metadata(&serde_json::to_vec(&call).unwrap(), limits()).is_err());
|
||||
|
||||
let duplicate = br#"{"interface":{"scope":"/","name":"x"},"scope_ref":"identity","scope_ref":"identity","descriptor":{"format":"wip-interface/1","types":[],"operations":[]}}"#;
|
||||
invalid_success(decode_fetch_interface_response(
|
||||
&request,
|
||||
&raw_response(StatusCode::OK, duplicate),
|
||||
limits(),
|
||||
));
|
||||
let duplicate = br#"{"target":{"path":"/"},"interface":{"reference":{"scope":"/","name":"x"},"scope_ref":"identity","scope_ref":"identity"},"operation":"run#::\u64cd\u4f5c","arguments":{}}"#;
|
||||
assert!(matches!(
|
||||
decode_call_operation_metadata(duplicate, limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_call_operation_request(duplicate, &descriptor(), limits()).unwrap_err(),
|
||||
CodecError::InvalidJson(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_correspondence_includes_reference_and_scope_ref_but_not_wire_order() {
|
||||
let request = call(reference("/", "x"), Some("identity".into()));
|
||||
let encoded =
|
||||
encode_call_operation_request(&endpoint(), &request, &descriptor(), limits()).unwrap();
|
||||
let metadata = decode_call_operation_metadata(encoded.body(), limits()).unwrap();
|
||||
for (field, changed) in [
|
||||
("scope_ref", json!("other")),
|
||||
("reference", json!({"scope": "/", "name": "other"})),
|
||||
] {
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["interface"][field] = changed;
|
||||
assert!(
|
||||
matches!(metadata.decode_request(&serde_json::to_vec(&body).unwrap(), &descriptor(), limits()).unwrap_err(), CodecError::InvalidField { field, .. } if field == "request")
|
||||
);
|
||||
}
|
||||
let mut body: Json = serde_json::from_slice(encoded.body()).unwrap();
|
||||
body["interface"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("scope_ref");
|
||||
assert!(
|
||||
metadata
|
||||
.decode_request(&serde_json::to_vec(&body).unwrap(), &descriptor(), limits())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_classification_preserves_transport_status_and_error_envelope_semantics() {
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "x"),
|
||||
};
|
||||
let valid = fetch_json(json!({"scope": "/", "name": "x"}));
|
||||
for (status, kind) in [
|
||||
(
|
||||
StatusCode::CREATED,
|
||||
InvalidResponseKind::NonCanonicalSuccessStatus,
|
||||
),
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
InvalidResponseKind::SuccessBodyOnErrorStatus,
|
||||
),
|
||||
] {
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &response(status, valid.clone()), limits()).unwrap_err(), ClientResponseError::InvalidResponse { kind: actual, .. } if actual == kind)
|
||||
);
|
||||
}
|
||||
for status in [
|
||||
StatusCode::UNAUTHORIZED,
|
||||
StatusCode::FORBIDDEN,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
] {
|
||||
let malformed = response(status, fetch_json(json!("legacy")));
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &malformed, limits()).unwrap_err(), ClientResponseError::TransportBinding(failure) if failure.status == status)
|
||||
);
|
||||
}
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::InterfaceNotFound,
|
||||
message: "unpublished".into(),
|
||||
};
|
||||
let mut encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::FetchInterface, &error, limits())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error: error.clone(),
|
||||
status_mismatch: None
|
||||
}
|
||||
);
|
||||
*encoded.status_mut() = StatusCode::BAD_GATEWAY;
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &encoded, limits()).unwrap(), DecodedResponse::ProtocolFailure { error: actual, status_mismatch: Some(_) } if actual == error)
|
||||
);
|
||||
*encoded.status_mut() = StatusCode::OK;
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_response(&request, &encoded, limits()).unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||
..
|
||||
}
|
||||
));
|
||||
let disallowed = response(
|
||||
StatusCode::CONFLICT,
|
||||
json!({"error": {"code": "interface_mismatch", "message": "wrong interaction"}}),
|
||||
);
|
||||
assert!(matches!(
|
||||
decode_fetch_interface_response(&request, &disallowed, limits()).unwrap_err(),
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::DisallowedProtocolCode,
|
||||
..
|
||||
}
|
||||
));
|
||||
let mut coded = response(StatusCode::OK, valid);
|
||||
coded
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "gzip".parse().unwrap());
|
||||
assert!(
|
||||
matches!(decode_fetch_interface_response(&request, &coded, limits()).unwrap_err(), ClientResponseError::TransportBinding(failure) if failure.kind == TransportFailureKind::UnsupportedContentCoding)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_interface_mismatch_envelope_remains_protocol_failure_with_structured_metadata() {
|
||||
let request = call(reference("/unrelated", "x"), Some("stale identity".into()));
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::InterfaceMismatch,
|
||||
message: "interface precondition".into(),
|
||||
};
|
||||
let encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::CallOperation, &error, limits())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decode_call_operation_response(&request, &descriptor(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: None
|
||||
}
|
||||
);
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
use wip_http::http::{Response, StatusCode};
|
||||
use wip_http::wip_protocol::{
|
||||
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
};
|
||||
use wip_http::{
|
||||
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, TransportFailureKind,
|
||||
decode_observe_response, encode_protocol_error_response, error_code_name, is_json_content_type,
|
||||
status_for_error,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::new(64 * 1024, 64 * 1024, 32).unwrap()
|
||||
}
|
||||
|
||||
fn request() -> ObserveRequest {
|
||||
ObserveRequest {
|
||||
path: "/".into(),
|
||||
depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
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 logical_resource_limit_uses_only_422_and_bare_413_is_transport_failure() {
|
||||
let error = ProtocolError {
|
||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||
message: "logical observation limit exceeded".into(),
|
||||
};
|
||||
let encoded =
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||
assert_eq!(encoded.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert_eq!(
|
||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error: error.clone(),
|
||||
status_mismatch: None,
|
||||
}
|
||||
);
|
||||
|
||||
let mut noncanonical = encoded;
|
||||
*noncanonical.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||
assert_eq!(
|
||||
decode_observe_response(&request(), &noncanonical, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: Some(wip_http::StatusMismatch {
|
||||
actual: StatusCode::PAYLOAD_TOO_LARGE,
|
||||
expected: StatusCode::UNPROCESSABLE_ENTITY,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
let bare_413 = Response::builder()
|
||||
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &bare_413, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::PAYLOAD_TOO_LARGE
|
||||
&& failure.kind == TransportFailureKind::HttpStatus
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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_observe_response(&request(), &response, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::TOO_MANY_REQUESTS
|
||||
&& failure.kind == TransportFailureKind::HttpStatus
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_response_content_coding_is_transport_failure() {
|
||||
let mut encoded = encode_protocol_error_response(
|
||||
ProtocolInteraction::Observe,
|
||||
&ProtocolError {
|
||||
code: ProtocolErrorCode::NotFound,
|
||||
message: "missing".into(),
|
||||
},
|
||||
limits(),
|
||||
)
|
||||
.unwrap();
|
||||
encoded
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "gzip".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &encoded, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::NOT_FOUND
|
||||
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||
));
|
||||
|
||||
let success = response(StatusCode::OK, br#"{"object":{"name":"","interfaces":[]}}"#);
|
||||
let mut identity = success.clone();
|
||||
identity
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "identity".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &identity, limits()).unwrap(),
|
||||
DecodedResponse::Success(_)
|
||||
));
|
||||
|
||||
let mut unsupported = success;
|
||||
unsupported
|
||||
.headers_mut()
|
||||
.insert("content-encoding", "br".parse().unwrap());
|
||||
assert!(matches!(
|
||||
decode_observe_response(&request(), &unsupported, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(failure)
|
||||
if failure.status == StatusCode::OK
|
||||
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_success_body_requires_exactly_http_200() {
|
||||
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
||||
assert!(matches!(
|
||||
decode_observe_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 observe".into(),
|
||||
};
|
||||
assert!(
|
||||
encode_protocol_error_response(ProtocolInteraction::Observe, &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::Observe, &error, limits()).unwrap();
|
||||
*encoded.status_mut() = StatusCode::IM_A_TEAPOT;
|
||||
|
||||
assert_eq!(
|
||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||
DecodedResponse::ProtocolFailure {
|
||||
error,
|
||||
status_mismatch: Some(wip_http::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_observe_response(&request(), &response(StatusCode::OK, error_body), limits())
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
on_success,
|
||||
ClientResponseError::InvalidResponse {
|
||||
kind: InvalidResponseKind::ErrorEnvelopeOnSuccessStatus,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||
let on_error = decode_observe_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_observe_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_observe_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_observe_response(&request(), &malformed, limits()).unwrap_err(),
|
||||
ClientResponseError::TransportBinding(_)
|
||||
));
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
use wip_http::http::{Method, Request, StatusCode};
|
||||
use wip_http::{Endpoint, RequestMetadataError, Route, validate_http_request};
|
||||
|
||||
#[test]
|
||||
fn endpoint_preserves_http_and_https_when_resolving_canonical_routes() {
|
||||
for scheme in ["http", "https"] {
|
||||
let endpoint = Endpoint::parse(&format!("{scheme}://example.test/root/prefix")).unwrap();
|
||||
assert_eq!(
|
||||
endpoint.to_string(),
|
||||
format!("{scheme}://example.test/root/prefix/")
|
||||
);
|
||||
|
||||
let expected = [
|
||||
(Route::Observe, "v1/observe"),
|
||||
(Route::FetchInterface, "v1/fetch_interface"),
|
||||
(Route::CallOperation, "v1/call_operation"),
|
||||
];
|
||||
for (route, suffix) in expected {
|
||||
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
|
||||
assert_eq!(endpoint.route(route).as_str(), url);
|
||||
assert_eq!(
|
||||
endpoint.recognize(&wip_http::url::Url::parse(&url).unwrap()),
|
||||
Some(route)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
endpoint.recognize(
|
||||
&wip_http::url::Url::parse(&format!(
|
||||
"{scheme}://example.test/root/prefix/v1/observe?path=/items"
|
||||
))
|
||||
.unwrap()
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
|
||||
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
|
||||
let route = endpoint.route(Route::Observe);
|
||||
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/observe");
|
||||
assert!(!route.as_str().contains("items"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_http_metadata_enforces_post_route_and_json() {
|
||||
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
||||
let valid = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json; charset=utf-8")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(validate_http_request(&endpoint, Route::Observe, &valid).is_ok());
|
||||
|
||||
let wrong_method = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error = validate_http_request(&endpoint, Route::Observe, &wrong_method).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::MethodNotAllowed));
|
||||
assert_eq!(error.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
assert_eq!(error.allow(), Some("POST"));
|
||||
|
||||
let wrong_route = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/fetch_interface")
|
||||
.header("content-type", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error = validate_http_request(&endpoint, Route::Observe, &wrong_route).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::NotFound));
|
||||
assert_eq!(error.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(error.allow(), None);
|
||||
|
||||
let query_and_wrong_method = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/wip/v1/observe?unexpected=true")
|
||||
.header("content-type", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
validate_http_request(&endpoint, Route::Observe, &query_and_wrong_method).unwrap_err(),
|
||||
RequestMetadataError::NotFound
|
||||
));
|
||||
|
||||
for accept in [
|
||||
"text/plain, */*;q=1, application/json;q=0",
|
||||
"application/json; charset=utf-16",
|
||||
"application/json; profile=future",
|
||||
] {
|
||||
let incompatible_accept = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", accept)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error =
|
||||
validate_http_request(&endpoint, Route::Observe, &incompatible_accept).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
|
||||
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
for accept in [
|
||||
"application/json; charset=UTF-8",
|
||||
"application/json; q=1; profile=accept-extension",
|
||||
] {
|
||||
let compatible_accept = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", accept)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(validate_http_request(&endpoint, Route::Observe, &compatible_accept).is_ok());
|
||||
}
|
||||
|
||||
let unsupported_media_type = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "text/plain")
|
||||
.header("accept", "application/json")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error =
|
||||
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||
|
||||
for coding in ["gzip", "identity, gzip"] {
|
||||
let unsupported_coding = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("content-encoding", coding)
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
let error =
|
||||
validate_http_request(&endpoint, Route::Observe, &unsupported_coding).unwrap_err();
|
||||
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||
}
|
||||
|
||||
let identity_coding = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/wip/v1/observe")
|
||||
.header("content-type", "application/json")
|
||||
.header("content-encoding", "identity")
|
||||
.body(Vec::<u8>::new())
|
||||
.unwrap();
|
||||
assert!(validate_http_request(&endpoint, Route::Observe, &identity_coding).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_endpoint_components_and_non_routes_are_rejected() {
|
||||
assert!(Endpoint::parse("/relative").is_err());
|
||||
assert!(Endpoint::parse("file:///wip").is_err());
|
||||
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
|
||||
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
|
||||
|
||||
let deployment_endpoint = Endpoint::parse("http://user:secret@example.test/wip").unwrap();
|
||||
assert_eq!(deployment_endpoint.as_url().scheme(), "http");
|
||||
assert_eq!(deployment_endpoint.as_url().username(), "user");
|
||||
|
||||
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
|
||||
for outside in [
|
||||
"http://example.test/wip/v1/unknown",
|
||||
"http://example.test/wip/v1/batch",
|
||||
"http://example.test/wip/v1/observe/extra",
|
||||
"https://example.test/wip/v1/observe",
|
||||
"http://other.test/wip/v1/observe",
|
||||
] {
|
||||
assert_eq!(
|
||||
endpoint.recognize(&wip_http::url::Url::parse(outside).unwrap()),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"files":{"Cargo.toml":"a4dc98dfd70b159ccd61bf30ef2f9e5b0087e8b6cbc3442d0c5e3bd1ff10cb1d","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"75b552e04aa4e3530b5159154649e5acf433a0dab7164ff849b2e63cc632d240","README.md":"4eb91a64a516c04846a95e36866e90b8b2e54792a300e2aae488d377428fe018","src/error.rs":"0e00d2138be5ac02577c8ad28ca0342426b6285bd80327841e82bf47d14355fc","src/lib.rs":"9b87ef809908741971bbe2b213b42c635d6f2982609ba192d98a2de8bf5ac04e","src/model.rs":"3e2d822ed1ab5229500b2eae327707e3e5cdba3156c38d667b5c97dd6b4d21c4","src/validation.rs":"10773d2fadbd2b1cc37eacfcb7392072c576b9fb8d8a0d7ff7868c50734f5f7e","tests/interface_references.rs":"b8136b4a4ae8b9f5ae1ee60700e946f3d9030079cd23f796f00d154c5e608648","tests/validation.rs":"7d1d1cef128d18c8f1b753956eac56b99b4480579418e275d7db801aae92aa82"},"package":null}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "wip-protocol"
|
||||
version = "0.1.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Transport-independent logical model and validation for WIP"
|
||||
documentation = "https://docs.rs/wip-protocol"
|
||||
readme = "README.md"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://gitea.hareworks.net/Hare/wip-rs"
|
||||
|
||||
[lib]
|
||||
name = "wip_protocol"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "interface_references"
|
||||
path = "tests/interface_references.rs"
|
||||
|
||||
[[test]]
|
||||
name = "validation"
|
||||
path = "tests/validation.rs"
|
||||
|
||||
[dependencies]
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hare
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
# wip-protocol
|
||||
|
||||
Transport-independent logical types and validation for the Web Interface Protocol (WIP).
|
||||
|
||||
This crate defines the canonical Object and Interface Descriptor models, the three Core interaction request and response types, schema-neutral operation `Value`s, validators, protocol errors, and structural validation. It does not define an HTTP mapping, application DTOs, persistence, or network I/O.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
wip-protocol = "0.1.0"
|
||||
```
|
||||
|
||||
Interface identity is an exact `InterfaceReference { scope, name }` pair.
|
||||
`scope` is a canonical absolute Worldspace path and `name` is nonempty Unicode.
|
||||
Use `validate()` for shape, `validate_for_path()` for ancestor-or-self placement,
|
||||
and Object/interaction validation at response boundaries. Fetching needs no
|
||||
target Object path. Fetch responses and interface call targets carry optional
|
||||
opaque string `scope_ref` metadata, not a third identity field. Descriptors do
|
||||
not embed identity. See the repository's [migration guide](../../MIGRATION.md)
|
||||
for the breaking Rust and HTTP wire changes and deferred consumer semantics.
|
||||
|
||||
See the [API documentation](https://docs.rs/wip-protocol) for the complete model and validation rules.
|
||||
|
||||
Licensed under either of Apache-2.0 or MIT at your option.
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
/// Namespace in which a declaration name must be unique.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NameNamespace {
|
||||
/// Named types in an interface descriptor.
|
||||
TypeDeclaration,
|
||||
/// Operations in an interface descriptor.
|
||||
Operation,
|
||||
/// Fields in an inline or named record type.
|
||||
Field,
|
||||
/// Parameters in an operation declaration.
|
||||
Parameter,
|
||||
/// Cases in an enum type.
|
||||
EnumCase,
|
||||
/// Cases in a union type.
|
||||
UnionCase,
|
||||
/// Child object names beneath one tree node.
|
||||
ChildObject,
|
||||
}
|
||||
|
||||
/// Structural kind of a schema-neutral logical value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueKind {
|
||||
/// Unit value.
|
||||
Unit,
|
||||
/// Boolean value.
|
||||
Boolean,
|
||||
/// Integer value.
|
||||
Integer,
|
||||
/// Floating-point number value.
|
||||
Number,
|
||||
/// String value.
|
||||
String,
|
||||
/// Byte sequence.
|
||||
Bytes,
|
||||
/// Record value.
|
||||
Record,
|
||||
/// List value.
|
||||
List,
|
||||
}
|
||||
|
||||
/// A typed segment identifying a declaration or value location.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PathSegment {
|
||||
/// Descriptor root.
|
||||
Descriptor,
|
||||
/// Named type declaration.
|
||||
Declaration(String),
|
||||
/// Operation declaration or call.
|
||||
Operation(String),
|
||||
/// Record field declaration or value.
|
||||
Field(String),
|
||||
/// Operation parameter or argument.
|
||||
Parameter(String),
|
||||
/// Enum or union case.
|
||||
Case(String),
|
||||
/// List index.
|
||||
Index(usize),
|
||||
/// Operation return value.
|
||||
Return,
|
||||
/// Object at a Worldspace path.
|
||||
Object(String),
|
||||
/// Child object in an observation response.
|
||||
Child(String),
|
||||
}
|
||||
|
||||
/// Machine-readable reason why logical protocol validation failed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ValidationErrorKind {
|
||||
/// A name occurred more than once in one namespace.
|
||||
DuplicateName {
|
||||
/// Namespace containing the duplicate.
|
||||
namespace: NameNamespace,
|
||||
/// Duplicate name.
|
||||
name: String,
|
||||
},
|
||||
/// A named type was not declared in the descriptor.
|
||||
UnknownType {
|
||||
/// Missing descriptor-local type name.
|
||||
name: String,
|
||||
},
|
||||
/// Named declarations form a recursive cycle.
|
||||
RecursiveType {
|
||||
/// Cycle in traversal order, with the starting name repeated last.
|
||||
cycle: Vec<String>,
|
||||
},
|
||||
/// A value has the wrong structural kind.
|
||||
TypeMismatch {
|
||||
/// Expected kind.
|
||||
expected: ValueKind,
|
||||
/// Actual kind.
|
||||
actual: ValueKind,
|
||||
},
|
||||
/// A record value contains an undeclared field.
|
||||
UnknownField {
|
||||
/// Unknown field name.
|
||||
name: String,
|
||||
},
|
||||
/// A record value omitted a required field.
|
||||
MissingField {
|
||||
/// Missing field name.
|
||||
name: String,
|
||||
},
|
||||
/// An enum or union selected an undeclared case.
|
||||
UnknownCase {
|
||||
/// Unknown case name.
|
||||
name: String,
|
||||
},
|
||||
/// A payload-bearing union case omitted `value`.
|
||||
MissingUnionPayload,
|
||||
/// A payload-free union case supplied `value`.
|
||||
UnexpectedUnionPayload,
|
||||
/// An operation call contains an undeclared argument.
|
||||
UnknownParameter {
|
||||
/// Unknown parameter name.
|
||||
name: String,
|
||||
},
|
||||
/// An operation call omitted a required argument.
|
||||
MissingParameter {
|
||||
/// Missing parameter name.
|
||||
name: String,
|
||||
},
|
||||
/// An operation is not declared by the descriptor.
|
||||
UnknownOperation {
|
||||
/// Unknown operation name.
|
||||
name: String,
|
||||
},
|
||||
/// An integer is outside the interoperable safe range.
|
||||
IntegerOutOfRange {
|
||||
/// Rejected integer.
|
||||
value: i64,
|
||||
},
|
||||
/// A numeric value is NaN or infinite.
|
||||
NonFiniteNumber,
|
||||
/// A JSON-interpreted value tree contains protocol bytes.
|
||||
BytesInJson,
|
||||
/// An object name is not a valid root or non-root path segment.
|
||||
InvalidObjectName {
|
||||
/// Rejected object name.
|
||||
name: String,
|
||||
},
|
||||
/// An object's ordered interface set contains a duplicate.
|
||||
DuplicateInterface {
|
||||
/// Duplicate structured interface reference.
|
||||
reference: crate::InterfaceReference,
|
||||
},
|
||||
/// The local interface name is empty.
|
||||
EmptyInterfaceName,
|
||||
/// A valid scope is not an ancestor-or-self of the target path.
|
||||
InterfaceScopeMismatch {
|
||||
/// Selected scope path.
|
||||
scope: String,
|
||||
/// Target Object path.
|
||||
path: String,
|
||||
},
|
||||
/// A string is not a canonical absolute Worldspace path.
|
||||
InvalidPath {
|
||||
/// Rejected path.
|
||||
path: String,
|
||||
},
|
||||
/// An object name does not match the path where it was observed.
|
||||
ObjectNameMismatch {
|
||||
/// Name required by the observation path.
|
||||
expected: String,
|
||||
/// Name supplied by the object.
|
||||
actual: String,
|
||||
},
|
||||
/// Equivalent ref/validator observations disagree on object representation.
|
||||
InconsistentObjectObservation {
|
||||
/// Shared opaque object reference.
|
||||
reference: String,
|
||||
},
|
||||
/// An observation omitted children before reaching the requested depth.
|
||||
ChildrenMissingBeforeDepth {
|
||||
/// Node depth where children were required.
|
||||
depth: u32,
|
||||
},
|
||||
/// An observation included children at the requested depth boundary.
|
||||
ChildrenAtDepthBoundary {
|
||||
/// Boundary depth where children must be unobserved.
|
||||
depth: u32,
|
||||
},
|
||||
/// A response refers to a different interface than its request.
|
||||
InterfaceResponseMismatch {
|
||||
/// Requested structured reference (boxed to keep validation errors small).
|
||||
expected: Box<crate::InterfaceReference>,
|
||||
/// Returned structured reference (boxed to keep validation errors small).
|
||||
actual: Box<crate::InterfaceReference>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A validation failure with a typed path to the failing location.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ValidationError {
|
||||
/// Path from the validation root to the failure.
|
||||
pub path: Vec<PathSegment>,
|
||||
/// Machine-readable failure reason.
|
||||
pub kind: ValidationErrorKind,
|
||||
}
|
||||
|
||||
impl ValidationError {
|
||||
pub(crate) fn new(kind: ValidationErrorKind) -> Self {
|
||||
Self {
|
||||
path: Vec::new(),
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepend(mut self, segment: PathSegment) -> Self {
|
||||
self.path.insert(0, segment);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ValidationError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
if self.path.is_empty() {
|
||||
write!(formatter, "protocol validation failed: {:?}", self.kind)
|
||||
} else {
|
||||
write!(
|
||||
formatter,
|
||||
"protocol validation failed at {:?}: {:?}",
|
||||
self.path, self.kind
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ValidationError {}
|
||||
|
||||
/// One core interaction whose failure codes form a closed set.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProtocolInteraction {
|
||||
/// Observe one object and its indexable descendants to a requested depth.
|
||||
Observe,
|
||||
/// Fetch one interface descriptor by its structured 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)]
|
||||
pub enum ProtocolErrorCode {
|
||||
/// The request is structurally invalid before an operation descriptor is fixed.
|
||||
InvalidRequest,
|
||||
/// The target object is not published.
|
||||
NotFound,
|
||||
/// The interface reference is not currently published.
|
||||
InterfaceNotFound,
|
||||
/// The selected interface is not on the current object.
|
||||
InterfaceMismatch,
|
||||
/// The selected operation is not declared by the current interface.
|
||||
OperationNotFound,
|
||||
/// Supplied arguments do not match the fixed operation declaration.
|
||||
InvalidArguments,
|
||||
/// The operation requires an object validator and none was supplied.
|
||||
ValidatorRequired,
|
||||
/// The supplied object validator does not match current state.
|
||||
ValidatorMismatch,
|
||||
/// A mutable interface requires its validator and none was supplied.
|
||||
InterfaceValidatorRequired,
|
||||
/// The supplied interface validator does not match the descriptor.
|
||||
InterfaceValidatorMismatch,
|
||||
/// A published operation is not permitted for the caller.
|
||||
PermissionDenied,
|
||||
/// 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,
|
||||
/// 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,
|
||||
/// 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, FetchInterface, Observe};
|
||||
|
||||
match (interaction, self) {
|
||||
(_, InvalidRequest | ResourceLimitExceeded | Internal) => true,
|
||||
(Observe, 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.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProtocolError {
|
||||
/// Stable programmatic code. Consumers must branch on this field.
|
||||
pub code: ProtocolErrorCode,
|
||||
/// Bounded human-readable diagnostic. Consumers must not branch on it.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Display for ProtocolError {
|
||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"protocol failure ({:?}): {}",
|
||||
self.code, self.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ProtocolError {}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
//! Canonical transport-independent logical types for the Web Interface Protocol.
|
||||
//!
|
||||
//! This crate follows the Core Model and `3-protocol.md` without assigning HTTP
|
||||
//! routes, methods, headers, URL encodings, or JSON envelopes. The correspondence
|
||||
//! between canonical logical concepts and this crate is direct:
|
||||
//!
|
||||
//! | Canonical protocol concept | Rust API |
|
||||
//! | --- | --- |
|
||||
//! | Object projection and ordered interface set | [`Object`] |
|
||||
//! | Optional object identity / state precondition | `Object::ref` / [`Object::validator`] |
|
||||
//! | Interface Descriptor | [`InterfaceDescriptor`] |
|
||||
//! | Named declaration and all schema expressions | [`TypeDeclaration`] / [`TypeExpr`] |
|
||||
//! | Schema-neutral primitive/composite value | [`Value`] |
|
||||
//! | `observe` | [`ObserveRequest`] / [`ObserveResponse`] |
|
||||
//! | `fetch_interface` | [`FetchInterfaceRequest`] / [`FetchInterfaceResponse`] |
|
||||
//! | Object and interface call preconditions | [`Target`] / [`InterfaceTarget`] |
|
||||
//! | `call_operation` | [`CallOperationRequest`] / [`CallOperationResponse`] |
|
||||
//! | 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.
|
||||
//! Interface refs use [`InterfaceReference`]; other metadata use strings/bytes in their
|
||||
//! fields. In particular, object refs are optional, operation targeting uses a
|
||||
//! path, and this crate defines no interaction that fetches an object by ref.
|
||||
//!
|
||||
//! [`Value`] contains only the canonical raw value kinds. A descriptor interprets
|
||||
//! enum values as strings, entries as canonical-path strings, and unions as
|
||||
//! records with a `$case` string plus an optional `value` payload. JSON uses the
|
||||
//! same value tree (`Unit` is JSON null) and rejects bytes.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod error;
|
||||
mod model;
|
||||
mod validation;
|
||||
|
||||
pub use error::{
|
||||
NameNamespace, PathSegment, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||
ValidationError, ValidationErrorKind, ValueKind,
|
||||
};
|
||||
pub use model::{
|
||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FieldDeclaration, InterfaceDescriptor, InterfaceReference,
|
||||
InterfaceTarget, Object, ObjectObservation, ObserveRequest, ObserveResponse,
|
||||
OperationDeclaration, ParameterDeclaration, ProtocolResult, ReturnDeclaration, Target,
|
||||
TypeDeclaration, TypeExpr, UnionCase, Value,
|
||||
};
|
||||
|
||||
/// Validates a canonical absolute Worldspace path.
|
||||
pub fn validate_path(path: &str) -> Result<(), ValidationError> {
|
||||
validation::validate_path(path)
|
||||
}
|
||||
|
||||
/// Canonical format identifier for the first Interface Descriptor format.
|
||||
pub const INTERFACE_FORMAT_V1: &str = "wip-interface/1";
|
||||
|
||||
/// Discriminator field used by a union's raw record value.
|
||||
pub const UNION_CASE_FIELD: &str = "$case";
|
||||
|
||||
/// Optional payload field used by a union's raw record value.
|
||||
pub const UNION_VALUE_FIELD: &str = "value";
|
||||
|
||||
/// Largest integer exactly interoperable with a JavaScript `Number`.
|
||||
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
||||
|
||||
/// Smallest integer exactly interoperable with a JavaScript `Number`.
|
||||
pub const MIN_SAFE_INTEGER: i64 = -MAX_SAFE_INTEGER;
|
||||
+463
@@ -0,0 +1,463 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{ProtocolError, ValidationError};
|
||||
|
||||
/// Human-readable plain-text documentation attached to a protocol declaration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Documentation {
|
||||
/// A short, self-contained description.
|
||||
pub summary: String,
|
||||
/// Optional extended documentation.
|
||||
pub details: Option<String>,
|
||||
}
|
||||
|
||||
/// An interface identified by an exact `(scope, name)` pair in one Worldspace.
|
||||
///
|
||||
/// Neither field is normalized, case-folded, URL-decoded, or split on display
|
||||
/// delimiters. Descriptor identity is external to the descriptor itself.
|
||||
///
|
||||
/// ```
|
||||
/// use wip_protocol::{FetchInterfaceRequest, InterfaceReference};
|
||||
/// let reference = InterfaceReference {
|
||||
/// scope: "/世::界/#".into(),
|
||||
/// name: "read::書く#λ".into(),
|
||||
/// };
|
||||
/// reference.validate_for_path("/世::界/#/item")?;
|
||||
/// // Fetching is independent of an Object target path.
|
||||
/// FetchInterfaceRequest { interface: reference }.validate()?;
|
||||
/// # Ok::<(), wip_protocol::ValidationError>(())
|
||||
/// ```
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct InterfaceReference {
|
||||
/// Canonical absolute Worldspace path of the interface's scope Object.
|
||||
pub scope: String,
|
||||
/// Nonempty Unicode local name, with no delimiter restrictions.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl InterfaceReference {
|
||||
/// Validates reference shape without requiring a target Object path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_interface_reference(self)
|
||||
}
|
||||
|
||||
/// Validates shape and that scope is an ancestor-or-self of `path`.
|
||||
///
|
||||
/// This is independent of indexability. A Host maps a valid reference's
|
||||
/// scope mismatch to `InterfaceMismatch` at the interface-selection stage,
|
||||
/// not to the earlier shape-validation `InvalidRequest` stage.
|
||||
pub fn validate_for_path(&self, path: &str) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_interface_scope(self, path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol projection currently published at one Worldspace path.
|
||||
///
|
||||
/// `name` is a path segment, `interfaces` is an ordered set of structured interface
|
||||
/// references, `r#ref` is optional object identity, and `validator` is an
|
||||
/// independent optional observation precondition. In particular, neither the
|
||||
/// path nor `r#ref` is a mandatory object identifier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Object {
|
||||
/// Path-segment name. The root object's name is empty.
|
||||
pub name: String,
|
||||
/// Short public description of the object.
|
||||
pub description: Option<String>,
|
||||
/// Structured interface references in host publication order.
|
||||
pub interfaces: Vec<InterfaceReference>,
|
||||
/// Optional opaque identity within one client-facing Worldspace.
|
||||
pub r#ref: Option<String>,
|
||||
/// Optional opaque validator for the object's observed state.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Transport-independent description of one interface.
|
||||
///
|
||||
/// Interface identity is supplied by interaction fields such as
|
||||
/// [`FetchInterfaceResponse::interface`], not embedded in the descriptor.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InterfaceDescriptor {
|
||||
/// Descriptor format version understood by clients and hosts.
|
||||
pub format: String,
|
||||
/// Optional interface documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Named declarations local to this descriptor.
|
||||
pub types: Vec<TypeDeclaration>,
|
||||
/// Operations exposed by this interface.
|
||||
pub operations: Vec<OperationDeclaration>,
|
||||
}
|
||||
|
||||
/// A descriptor-local named type declaration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TypeDeclaration {
|
||||
/// Descriptor-local type name.
|
||||
pub name: String,
|
||||
/// Optional type documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Definition associated with `name`.
|
||||
pub definition: TypeExpr,
|
||||
}
|
||||
|
||||
/// A type expression used by declarations, fields, parameters, and returns.
|
||||
///
|
||||
/// [`TypeExpr::Named`] references are resolved only within the containing
|
||||
/// descriptor. Recursive references, including recursion through lists,
|
||||
/// records, and unions, are invalid.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TypeExpr {
|
||||
/// A value carrying no data.
|
||||
Unit,
|
||||
/// A boolean.
|
||||
Boolean,
|
||||
/// A JavaScript-lossless signed integer.
|
||||
Integer,
|
||||
/// A finite IEEE-754 binary64 number.
|
||||
Number,
|
||||
/// A Unicode string.
|
||||
String,
|
||||
/// An opaque byte sequence.
|
||||
Bytes,
|
||||
/// A schema-opaque JSON-compatible value tree.
|
||||
Json,
|
||||
/// A canonical absolute Worldspace path represented by a string value.
|
||||
Entry,
|
||||
/// A descriptor-local named declaration.
|
||||
Named {
|
||||
/// Referenced declaration name.
|
||||
name: String,
|
||||
},
|
||||
/// A record with named fields.
|
||||
Record {
|
||||
/// Fields in declaration order.
|
||||
fields: Vec<FieldDeclaration>,
|
||||
},
|
||||
/// An ordered list.
|
||||
List {
|
||||
/// Type of every list item.
|
||||
items: Box<TypeExpr>,
|
||||
},
|
||||
/// A closed set of payload-free cases represented by strings.
|
||||
Enum {
|
||||
/// Cases in declaration order.
|
||||
cases: Vec<EnumCase>,
|
||||
},
|
||||
/// A discriminated union represented by a record.
|
||||
Union {
|
||||
/// Cases in declaration order.
|
||||
cases: Vec<UnionCase>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Declaration of a record field.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FieldDeclaration {
|
||||
/// Field name.
|
||||
pub name: String,
|
||||
/// Whether the field must be present.
|
||||
pub required: bool,
|
||||
/// Optional field documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Field value type.
|
||||
pub r#type: TypeExpr,
|
||||
}
|
||||
|
||||
/// One payload-free enum case.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EnumCase {
|
||||
/// Case name.
|
||||
pub name: String,
|
||||
/// Optional case documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
}
|
||||
|
||||
/// One union case with zero or one payload.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UnionCase {
|
||||
/// Case name.
|
||||
pub name: String,
|
||||
/// Optional case documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Optional payload type.
|
||||
pub payload: Option<TypeExpr>,
|
||||
}
|
||||
|
||||
/// Declaration of one interface operation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OperationDeclaration {
|
||||
/// Operation name, unique within its descriptor.
|
||||
pub name: String,
|
||||
/// Optional operation documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Parameters in declaration order.
|
||||
pub parameters: Vec<ParameterDeclaration>,
|
||||
/// Return declaration. No-data operations return [`TypeExpr::Unit`].
|
||||
pub returns: ReturnDeclaration,
|
||||
}
|
||||
|
||||
/// Declaration of one operation parameter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParameterDeclaration {
|
||||
/// Parameter name.
|
||||
pub name: String,
|
||||
/// Whether the parameter must be present.
|
||||
pub required: bool,
|
||||
/// Optional parameter documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Parameter value type.
|
||||
pub r#type: TypeExpr,
|
||||
}
|
||||
|
||||
/// Declaration of an operation return value.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReturnDeclaration {
|
||||
/// Optional return-value documentation.
|
||||
pub documentation: Option<Documentation>,
|
||||
/// Return value type.
|
||||
pub r#type: TypeExpr,
|
||||
}
|
||||
|
||||
/// A schema-neutral logical protocol value.
|
||||
///
|
||||
/// Enum cases, union cases, entries, and JSON are interpretations imposed by a
|
||||
/// descriptor. They are deliberately not variants of this enum. Record key
|
||||
/// ordering is not protocol-significant.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
/// A value carrying no data; it also represents JSON null under `Json`.
|
||||
Unit,
|
||||
/// A boolean.
|
||||
Boolean(bool),
|
||||
/// A JavaScript-lossless integer.
|
||||
Integer(i64),
|
||||
/// A finite IEEE-754 binary64 number.
|
||||
Number(f64),
|
||||
/// A Unicode string.
|
||||
String(String),
|
||||
/// An opaque byte sequence.
|
||||
Bytes(Vec<u8>),
|
||||
/// String-keyed fields with order-insensitive semantics.
|
||||
Record(BTreeMap<String, Value>),
|
||||
/// An ordered sequence.
|
||||
List(Vec<Value>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// Returns the structural kind used by validation diagnostics.
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> crate::ValueKind {
|
||||
match self {
|
||||
Self::Unit => crate::ValueKind::Unit,
|
||||
Self::Boolean(_) => crate::ValueKind::Boolean,
|
||||
Self::Integer(_) => crate::ValueKind::Integer,
|
||||
Self::Number(_) => crate::ValueKind::Number,
|
||||
Self::String(_) => crate::ValueKind::String,
|
||||
Self::Bytes(_) => crate::ValueKind::Bytes,
|
||||
Self::Record(_) => crate::ValueKind::Record,
|
||||
Self::List(_) => crate::ValueKind::List,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request for the object currently published at one path and its indexable descendants.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObserveRequest {
|
||||
/// Canonical absolute path of the observation root.
|
||||
pub path: String,
|
||||
/// Maximum observed depth, where the requested object has depth zero.
|
||||
pub depth: u32,
|
||||
}
|
||||
|
||||
/// One node in an object observation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObjectObservation {
|
||||
/// Object observed at this Worldspace position.
|
||||
pub object: Object,
|
||||
/// Complete direct children when observed, or `None` at the requested depth boundary.
|
||||
pub children: Option<Vec<ObjectObservation>>,
|
||||
}
|
||||
|
||||
/// Successful `observe` response.
|
||||
pub type ObserveResponse = ObjectObservation;
|
||||
|
||||
/// Request for the current descriptor of one structured interface reference.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchInterfaceRequest {
|
||||
/// Structured interface reference obtained from an object.
|
||||
pub interface: InterfaceReference,
|
||||
}
|
||||
|
||||
/// Successful `fetch_interface` response.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FetchInterfaceResponse {
|
||||
/// Structured interface reference corresponding to the request.
|
||||
pub interface: InterfaceReference,
|
||||
/// Optional opaque ref of the scope Object, not part of interface identity.
|
||||
pub scope_ref: Option<String>,
|
||||
/// Current validated descriptor.
|
||||
pub descriptor: InterfaceDescriptor,
|
||||
/// Optional opaque validator for this descriptor observation.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Object portion of an operation target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
/// Canonical absolute path of the target object.
|
||||
pub path: String,
|
||||
/// Optional validator copied from the object observation.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Interface portion of an operation target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InterfaceTarget {
|
||||
/// Structured reference selected from the object's interface set.
|
||||
pub reference: InterfaceReference,
|
||||
/// Optional scope Object ref copied from the same interface observation.
|
||||
pub scope_ref: Option<String>,
|
||||
/// Optional validator copied from the interface observation.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Transport-independent request to execute one operation.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CallOperationRequest {
|
||||
/// Path and optional object-state precondition.
|
||||
pub target: Target,
|
||||
/// Interface reference and its independent optional precondition.
|
||||
pub interface: InterfaceTarget,
|
||||
/// Operation name within the selected descriptor.
|
||||
pub operation: String,
|
||||
/// Named arguments; map iteration order has no protocol meaning.
|
||||
pub arguments: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// Successful operation response.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CallOperationResponse {
|
||||
/// Application result validated against the operation return declaration.
|
||||
pub result: Value,
|
||||
/// Optional validator for the object state observed after execution.
|
||||
pub validator: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Logical outcome of any core interaction.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ProtocolResult<T> {
|
||||
/// The interaction succeeded.
|
||||
Success(T),
|
||||
/// The interaction failed at the protocol boundary.
|
||||
Failure(ProtocolError),
|
||||
}
|
||||
|
||||
impl Object {
|
||||
/// Validates the object-independent name and ordered-interface-set rules.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_object(self)
|
||||
}
|
||||
|
||||
/// Validates this object as the response observed at `path`.
|
||||
pub fn validate_at_path(&self, path: &str) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_object_at_path(self, path)
|
||||
}
|
||||
|
||||
/// Validates equal representations for a shared ref and present validator.
|
||||
pub fn validate_consistency_with(&self, other: &Self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_object_consistency(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl InterfaceDescriptor {
|
||||
/// Validates declaration structure, named references, and absence of cycles.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_descriptor(self)
|
||||
}
|
||||
|
||||
/// Validates a raw value against a type expression in this descriptor.
|
||||
pub fn validate_value(&self, r#type: &TypeExpr, value: &Value) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_root_value(self, r#type, value)
|
||||
}
|
||||
|
||||
/// Validates named arguments for one declared operation.
|
||||
pub fn validate_arguments(
|
||||
&self,
|
||||
operation: &str,
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_arguments(self, operation, arguments)
|
||||
}
|
||||
|
||||
/// Validates one operation result against its return declaration.
|
||||
pub fn validate_result(&self, operation: &str, result: &Value) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_result(self, operation, result)
|
||||
}
|
||||
|
||||
/// Validates the path, operation, and arguments in a call request.
|
||||
pub fn validate_call(&self, request: &CallOperationRequest) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_call(self, request)
|
||||
}
|
||||
}
|
||||
|
||||
impl ObserveRequest {
|
||||
/// Validates the request path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_path(&self.path)
|
||||
}
|
||||
|
||||
/// Validates observation shape, names, and requested depth.
|
||||
///
|
||||
/// Failure means the Client received an invalid success response; it is not a
|
||||
/// Host-returned [`crate::ProtocolErrorCode`].
|
||||
pub fn validate_response(&self, response: &ObserveResponse) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_observe_response(response, self)
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchInterfaceRequest {
|
||||
/// Validates reference shape; fetching an interface needs no target path.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
self.interface.validate()
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchInterfaceResponse {
|
||||
/// 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> {
|
||||
crate::validation::validate_fetch_interface_response(self, request)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallOperationRequest {
|
||||
/// Validates descriptor-independent request shape only.
|
||||
///
|
||||
/// Scope compatibility is deliberately deferred to interface selection so
|
||||
/// that `NotFound` precedes `InterfaceMismatch` at the Host boundary.
|
||||
pub fn validate(&self) -> Result<(), ValidationError> {
|
||||
crate::validation::validate_call_shape(self)
|
||||
}
|
||||
|
||||
/// Validates this call's shape and descriptor-bound operation/arguments.
|
||||
/// Scope compatibility and membership require Host publication context.
|
||||
pub fn validate_with(&self, descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||
descriptor.validate_call(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallOperationResponse {
|
||||
/// 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(
|
||||
&self,
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation: &str,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate_result(operation, &self.result)
|
||||
}
|
||||
}
|
||||
+735
@@ -0,0 +1,735 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
||||
InterfaceReference, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, NameNamespace, Object,
|
||||
ObjectObservation, ObserveRequest, PathSegment, TypeDeclaration, TypeExpr, UNION_CASE_FIELD,
|
||||
UNION_VALUE_FIELD, ValidationError, ValidationErrorKind, Value, ValueKind,
|
||||
};
|
||||
|
||||
pub(crate) fn validate_object(object: &Object) -> Result<(), ValidationError> {
|
||||
validate_object_name(&object.name, true)?;
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||
interface.validate().map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Index(index))
|
||||
.prepend(PathSegment::Field("interfaces".into()))
|
||||
})?;
|
||||
if !seen.insert(interface) {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::DuplicateInterface {
|
||||
reference: interface.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Field("interfaces".into())),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_object_name(name: &str, allow_root: bool) -> Result<(), ValidationError> {
|
||||
let valid =
|
||||
(allow_root || !name.is_empty()) && !name.contains('/') && name != "." && name != "..";
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new(
|
||||
ValidationErrorKind::InvalidObjectName {
|
||||
name: name.to_owned(),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_object_at_path(object: &Object, path: &str) -> Result<(), ValidationError> {
|
||||
validate_path(path)?;
|
||||
object
|
||||
.validate()
|
||||
.map_err(|error| error.prepend(PathSegment::Object(path.to_owned())))?;
|
||||
|
||||
let expected = if path == "/" {
|
||||
""
|
||||
} else {
|
||||
path.rsplit('/')
|
||||
.next()
|
||||
.expect("non-root path has a segment")
|
||||
};
|
||||
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||
interface.validate_for_path(path).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Index(index))
|
||||
.prepend(PathSegment::Field("interfaces".into()))
|
||||
.prepend(PathSegment::Object(path.to_owned()))
|
||||
})?;
|
||||
}
|
||||
if object.name == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(
|
||||
ValidationError::new(ValidationErrorKind::ObjectNameMismatch {
|
||||
expected: expected.to_owned(),
|
||||
actual: object.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Object(path.to_owned())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_object_consistency(
|
||||
left: &Object,
|
||||
right: &Object,
|
||||
) -> Result<(), ValidationError> {
|
||||
left.validate()?;
|
||||
right.validate()?;
|
||||
if let (Some(left_ref), Some(right_ref)) = (&left.r#ref, &right.r#ref)
|
||||
&& left_ref == right_ref
|
||||
&& left.validator.is_some()
|
||||
&& left.validator == right.validator
|
||||
&& left != right
|
||||
{
|
||||
return Err(ValidationError::new(
|
||||
ValidationErrorKind::InconsistentObjectObservation {
|
||||
reference: left_ref.clone(),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_path(path: &str) -> Result<(), ValidationError> {
|
||||
let valid = if path == "/" {
|
||||
true
|
||||
} else if let Some(remainder) = path.strip_prefix('/') {
|
||||
!remainder.is_empty()
|
||||
&& remainder
|
||||
.split('/')
|
||||
.all(|segment| !segment.is_empty() && segment != "." && segment != "..")
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new(ValidationErrorKind::InvalidPath {
|
||||
path: path.to_owned(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_interface_reference(
|
||||
reference: &InterfaceReference,
|
||||
) -> Result<(), ValidationError> {
|
||||
validate_path(&reference.scope)
|
||||
.map_err(|error| error.prepend(PathSegment::Field("scope".into())))?;
|
||||
if reference.name.is_empty() {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::EmptyInterfaceName)
|
||||
.prepend(PathSegment::Field("name".into())),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_interface_scope(
|
||||
reference: &InterfaceReference,
|
||||
path: &str,
|
||||
) -> Result<(), ValidationError> {
|
||||
reference.validate()?;
|
||||
validate_path(path)?;
|
||||
let scope = reference.scope.as_str();
|
||||
if scope == "/"
|
||||
|| path == scope
|
||||
|| path
|
||||
.strip_prefix(scope)
|
||||
.is_some_and(|rest| rest.starts_with('/'))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new(
|
||||
ValidationErrorKind::InterfaceScopeMismatch {
|
||||
scope: reference.scope.clone(),
|
||||
path: path.to_owned(),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_call_shape(request: &CallOperationRequest) -> Result<(), ValidationError> {
|
||||
validate_path(&request.target.path)
|
||||
.map_err(|error| error.prepend(PathSegment::Field("target".into())))?;
|
||||
request.interface.reference.validate().map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Field("reference".into()))
|
||||
.prepend(PathSegment::Field("interface".into()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_descriptor(descriptor: &InterfaceDescriptor) -> Result<(), ValidationError> {
|
||||
let declarations = declaration_map(descriptor)?;
|
||||
|
||||
for declaration in &descriptor.types {
|
||||
validate_type_expr(&declaration.definition, &declarations).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Declaration(declaration.name.clone()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})?;
|
||||
}
|
||||
|
||||
let mut operation_names = HashSet::new();
|
||||
for operation in &descriptor.operations {
|
||||
if !operation_names.insert(operation.name.as_str()) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Operation,
|
||||
name: operation.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor));
|
||||
}
|
||||
|
||||
let mut parameter_names = HashSet::new();
|
||||
for parameter in &operation.parameters {
|
||||
if !parameter_names.insert(parameter.name.as_str()) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Parameter,
|
||||
name: parameter.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Parameter(parameter.name.clone()))
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor));
|
||||
}
|
||||
validate_type_expr(¶meter.r#type, &declarations).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Parameter(parameter.name.clone()))
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})?;
|
||||
}
|
||||
validate_type_expr(&operation.returns.r#type, &declarations).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Return)
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})?;
|
||||
}
|
||||
|
||||
validate_no_cycles(descriptor, &declarations)
|
||||
}
|
||||
|
||||
fn declaration_map(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
) -> Result<HashMap<&str, &TypeDeclaration>, ValidationError> {
|
||||
let mut declarations = HashMap::new();
|
||||
for declaration in &descriptor.types {
|
||||
if declarations
|
||||
.insert(declaration.name.as_str(), declaration)
|
||||
.is_some()
|
||||
{
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::TypeDeclaration,
|
||||
name: declaration.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Declaration(declaration.name.clone()))
|
||||
.prepend(PathSegment::Descriptor));
|
||||
}
|
||||
}
|
||||
Ok(declarations)
|
||||
}
|
||||
|
||||
fn validate_type_expr(
|
||||
r#type: &TypeExpr,
|
||||
declarations: &HashMap<&str, &TypeDeclaration>,
|
||||
) -> Result<(), ValidationError> {
|
||||
match r#type {
|
||||
TypeExpr::Named { name } if !declarations.contains_key(name.as_str()) => {
|
||||
Err(ValidationError::new(ValidationErrorKind::UnknownType {
|
||||
name: name.clone(),
|
||||
}))
|
||||
}
|
||||
TypeExpr::Record { fields } => {
|
||||
let mut names = HashSet::new();
|
||||
for field in fields {
|
||||
if !names.insert(field.name.as_str()) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Field,
|
||||
name: field.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Field(field.name.clone())));
|
||||
}
|
||||
validate_type_expr(&field.r#type, declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Field(field.name.clone())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
TypeExpr::List { items } => validate_type_expr(items, declarations),
|
||||
TypeExpr::Enum { cases } => validate_case_names(
|
||||
cases.iter().map(|case| case.name.as_str()),
|
||||
NameNamespace::EnumCase,
|
||||
),
|
||||
TypeExpr::Union { cases } => {
|
||||
validate_case_names(
|
||||
cases.iter().map(|case| case.name.as_str()),
|
||||
NameNamespace::UnionCase,
|
||||
)?;
|
||||
for case in cases {
|
||||
if let Some(payload) = &case.payload {
|
||||
validate_type_expr(payload, declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Case(case.name.clone())))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_case_names<'a>(
|
||||
names: impl Iterator<Item = &'a str>,
|
||||
namespace: NameNamespace,
|
||||
) -> Result<(), ValidationError> {
|
||||
let mut seen = HashSet::new();
|
||||
for name in names {
|
||||
if !seen.insert(name) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace,
|
||||
name: name.to_owned(),
|
||||
})
|
||||
.prepend(PathSegment::Case(name.to_owned())));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_no_cycles(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
declarations: &HashMap<&str, &TypeDeclaration>,
|
||||
) -> Result<(), ValidationError> {
|
||||
let mut state: HashMap<&str, VisitState> = HashMap::new();
|
||||
let mut stack = Vec::new();
|
||||
for declaration in &descriptor.types {
|
||||
visit_declaration(
|
||||
declaration.name.as_str(),
|
||||
declarations,
|
||||
&mut state,
|
||||
&mut stack,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum VisitState {
|
||||
Visiting,
|
||||
Visited,
|
||||
}
|
||||
|
||||
fn visit_declaration<'a>(
|
||||
name: &'a str,
|
||||
declarations: &HashMap<&'a str, &'a TypeDeclaration>,
|
||||
state: &mut HashMap<&'a str, VisitState>,
|
||||
stack: &mut Vec<&'a str>,
|
||||
) -> Result<(), ValidationError> {
|
||||
match state.get(name) {
|
||||
Some(VisitState::Visited) => return Ok(()),
|
||||
Some(VisitState::Visiting) => {
|
||||
let start = stack.iter().position(|entry| *entry == name).unwrap_or(0);
|
||||
let mut cycle: Vec<String> = stack[start..]
|
||||
.iter()
|
||||
.map(|entry| (*entry).to_owned())
|
||||
.collect();
|
||||
cycle.push(name.to_owned());
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::RecursiveType { cycle })
|
||||
.prepend(PathSegment::Declaration(name.to_owned()))
|
||||
.prepend(PathSegment::Descriptor),
|
||||
);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
state.insert(name, VisitState::Visiting);
|
||||
stack.push(name);
|
||||
let mut references = Vec::new();
|
||||
collect_type_references(&declarations[name].definition, &mut references);
|
||||
for reference in references {
|
||||
visit_declaration(reference, declarations, state, stack)?;
|
||||
}
|
||||
stack.pop();
|
||||
state.insert(name, VisitState::Visited);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_type_references<'a>(r#type: &'a TypeExpr, references: &mut Vec<&'a str>) {
|
||||
match r#type {
|
||||
TypeExpr::Named { name } => references.push(name),
|
||||
TypeExpr::Record { fields } => {
|
||||
for field in fields {
|
||||
collect_type_references(&field.r#type, references);
|
||||
}
|
||||
}
|
||||
TypeExpr::List { items } => collect_type_references(items, references),
|
||||
TypeExpr::Union { cases } => {
|
||||
for case in cases {
|
||||
if let Some(payload) = &case.payload {
|
||||
collect_type_references(payload, references);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_root_value(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
r#type: &TypeExpr,
|
||||
value: &Value,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate()?;
|
||||
let declarations = declaration_map(descriptor)?;
|
||||
validate_type_expr(r#type, &declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Descriptor))?;
|
||||
validate_value(r#type, value, &declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Descriptor))
|
||||
}
|
||||
|
||||
fn validate_value(
|
||||
r#type: &TypeExpr,
|
||||
value: &Value,
|
||||
declarations: &HashMap<&str, &TypeDeclaration>,
|
||||
) -> Result<(), ValidationError> {
|
||||
match r#type {
|
||||
TypeExpr::Unit => expect_kind(value, ValueKind::Unit),
|
||||
TypeExpr::Boolean => expect_kind(value, ValueKind::Boolean),
|
||||
TypeExpr::Integer => validate_integer(value),
|
||||
TypeExpr::Number => validate_number(value),
|
||||
TypeExpr::String => expect_kind(value, ValueKind::String),
|
||||
TypeExpr::Bytes => expect_kind(value, ValueKind::Bytes),
|
||||
TypeExpr::Json => validate_json(value),
|
||||
TypeExpr::Entry => match value {
|
||||
Value::String(path) => validate_path(path),
|
||||
_ => expect_kind(value, ValueKind::String),
|
||||
},
|
||||
TypeExpr::Named { name } => {
|
||||
let Some(declaration) = declarations.get(name.as_str()) else {
|
||||
return Err(ValidationError::new(ValidationErrorKind::UnknownType {
|
||||
name: name.clone(),
|
||||
}));
|
||||
};
|
||||
validate_value(&declaration.definition, value, declarations)
|
||||
}
|
||||
TypeExpr::Record { fields } => validate_record(fields, value, declarations),
|
||||
TypeExpr::List { items } => match value {
|
||||
Value::List(values) => {
|
||||
for (index, item) in values.iter().enumerate() {
|
||||
validate_value(items, item, declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Index(index)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => expect_kind(value, ValueKind::List),
|
||||
},
|
||||
TypeExpr::Enum { cases } => match value {
|
||||
Value::String(case) if cases.iter().any(|declared| declared.name == *case) => Ok(()),
|
||||
Value::String(case) => {
|
||||
Err(
|
||||
ValidationError::new(ValidationErrorKind::UnknownCase { name: case.clone() })
|
||||
.prepend(PathSegment::Case(case.clone())),
|
||||
)
|
||||
}
|
||||
_ => expect_kind(value, ValueKind::String),
|
||||
},
|
||||
TypeExpr::Union { cases } => validate_union(cases, value, declarations),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_integer(value: &Value) -> Result<(), ValidationError> {
|
||||
match value {
|
||||
Value::Integer(integer) if (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(integer) => {
|
||||
Ok(())
|
||||
}
|
||||
Value::Integer(integer) => Err(ValidationError::new(
|
||||
ValidationErrorKind::IntegerOutOfRange { value: *integer },
|
||||
)),
|
||||
_ => expect_kind(value, ValueKind::Integer),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_number(value: &Value) -> Result<(), ValidationError> {
|
||||
match value {
|
||||
Value::Number(number) if number.is_finite() => Ok(()),
|
||||
Value::Number(_) => Err(ValidationError::new(ValidationErrorKind::NonFiniteNumber)),
|
||||
_ => expect_kind(value, ValueKind::Number),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_record(
|
||||
fields: &[crate::FieldDeclaration],
|
||||
value: &Value,
|
||||
declarations: &HashMap<&str, &TypeDeclaration>,
|
||||
) -> Result<(), ValidationError> {
|
||||
let Value::Record(values) = value else {
|
||||
return expect_kind(value, ValueKind::Record);
|
||||
};
|
||||
|
||||
for (name, field_value) in values {
|
||||
let Some(field) = fields.iter().find(|field| field.name == *name) else {
|
||||
return Err(ValidationError::new(ValidationErrorKind::UnknownField {
|
||||
name: name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Field(name.clone())));
|
||||
};
|
||||
validate_value(&field.r#type, field_value, declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Field(name.clone())))?;
|
||||
}
|
||||
|
||||
for field in fields {
|
||||
if field.required && !values.contains_key(&field.name) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::MissingField {
|
||||
name: field.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Field(field.name.clone())));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_union(
|
||||
cases: &[crate::UnionCase],
|
||||
value: &Value,
|
||||
declarations: &HashMap<&str, &TypeDeclaration>,
|
||||
) -> Result<(), ValidationError> {
|
||||
let Value::Record(fields) = value else {
|
||||
return expect_kind(value, ValueKind::Record);
|
||||
};
|
||||
|
||||
for name in fields.keys() {
|
||||
if name != UNION_CASE_FIELD && name != UNION_VALUE_FIELD {
|
||||
return Err(ValidationError::new(ValidationErrorKind::UnknownField {
|
||||
name: name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Field(name.clone())));
|
||||
}
|
||||
}
|
||||
|
||||
let Some(discriminator) = fields.get(UNION_CASE_FIELD) else {
|
||||
return Err(ValidationError::new(ValidationErrorKind::MissingField {
|
||||
name: UNION_CASE_FIELD.into(),
|
||||
})
|
||||
.prepend(PathSegment::Field(UNION_CASE_FIELD.into())));
|
||||
};
|
||||
let Value::String(case_name) = discriminator else {
|
||||
return expect_kind(discriminator, ValueKind::String)
|
||||
.map_err(|error| error.prepend(PathSegment::Field(UNION_CASE_FIELD.into())));
|
||||
};
|
||||
let Some(case) = cases.iter().find(|case| case.name == *case_name) else {
|
||||
return Err(ValidationError::new(ValidationErrorKind::UnknownCase {
|
||||
name: case_name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Case(case_name.clone())));
|
||||
};
|
||||
|
||||
match (&case.payload, fields.get(UNION_VALUE_FIELD)) {
|
||||
(None, None) => Ok(()),
|
||||
(None, Some(_)) => Err(
|
||||
ValidationError::new(ValidationErrorKind::UnexpectedUnionPayload)
|
||||
.prepend(PathSegment::Field(UNION_VALUE_FIELD.into())),
|
||||
),
|
||||
(Some(_), None) => Err(
|
||||
ValidationError::new(ValidationErrorKind::MissingUnionPayload)
|
||||
.prepend(PathSegment::Field(UNION_VALUE_FIELD.into())),
|
||||
),
|
||||
(Some(payload), Some(payload_value)) => {
|
||||
validate_value(payload, payload_value, declarations)
|
||||
.map_err(|error| error.prepend(PathSegment::Field(UNION_VALUE_FIELD.into())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_kind(value: &Value, expected: ValueKind) -> Result<(), ValidationError> {
|
||||
if value.kind() == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new(ValidationErrorKind::TypeMismatch {
|
||||
expected,
|
||||
actual: value.kind(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_json(value: &Value) -> Result<(), ValidationError> {
|
||||
match value {
|
||||
Value::Integer(_) => validate_integer(value),
|
||||
Value::Number(_) => validate_number(value),
|
||||
Value::Bytes(_) => Err(ValidationError::new(ValidationErrorKind::BytesInJson)),
|
||||
Value::Record(fields) => {
|
||||
for (name, field) in fields {
|
||||
validate_json(field)
|
||||
.map_err(|error| error.prepend(PathSegment::Field(name.clone())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::List(items) => {
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
validate_json(item).map_err(|error| error.prepend(PathSegment::Index(index)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::Unit | Value::Boolean(_) | Value::String(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_arguments(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation_name: &str,
|
||||
arguments: &BTreeMap<String, Value>,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate()?;
|
||||
let operation = find_operation(descriptor, operation_name)?;
|
||||
let declarations = declaration_map(descriptor)?;
|
||||
|
||||
for (name, value) in arguments {
|
||||
let Some(parameter) = operation
|
||||
.parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == *name)
|
||||
else {
|
||||
return Err(ValidationError::new(ValidationErrorKind::UnknownParameter {
|
||||
name: name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Parameter(name.clone()))
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor));
|
||||
};
|
||||
validate_value(¶meter.r#type, value, &declarations).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Parameter(name.clone()))
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})?;
|
||||
}
|
||||
|
||||
for parameter in &operation.parameters {
|
||||
if parameter.required && !arguments.contains_key(¶meter.name) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::MissingParameter {
|
||||
name: parameter.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Parameter(parameter.name.clone()))
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_result(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
operation_name: &str,
|
||||
result: &Value,
|
||||
) -> Result<(), ValidationError> {
|
||||
descriptor.validate()?;
|
||||
let operation = find_operation(descriptor, operation_name)?;
|
||||
let declarations = declaration_map(descriptor)?;
|
||||
validate_value(&operation.returns.r#type, result, &declarations).map_err(|error| {
|
||||
error
|
||||
.prepend(PathSegment::Return)
|
||||
.prepend(PathSegment::Operation(operation.name.clone()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_call(
|
||||
descriptor: &InterfaceDescriptor,
|
||||
request: &CallOperationRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
request.validate()?;
|
||||
validate_arguments(descriptor, &request.operation, &request.arguments)
|
||||
}
|
||||
|
||||
fn find_operation<'a>(
|
||||
descriptor: &'a InterfaceDescriptor,
|
||||
operation_name: &str,
|
||||
) -> Result<&'a crate::OperationDeclaration, ValidationError> {
|
||||
descriptor
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| operation.name == operation_name)
|
||||
.ok_or_else(|| {
|
||||
ValidationError::new(ValidationErrorKind::UnknownOperation {
|
||||
name: operation_name.to_owned(),
|
||||
})
|
||||
.prepend(PathSegment::Operation(operation_name.to_owned()))
|
||||
.prepend(PathSegment::Descriptor)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_observe_response(
|
||||
response: &ObjectObservation,
|
||||
request: &ObserveRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
request.validate()?;
|
||||
validate_observation_node(response, &request.path, 0, request.depth)
|
||||
}
|
||||
|
||||
fn validate_observation_node(
|
||||
node: &ObjectObservation,
|
||||
path: &str,
|
||||
depth: u32,
|
||||
maximum_depth: u32,
|
||||
) -> Result<(), ValidationError> {
|
||||
node.object.validate_at_path(path)?;
|
||||
|
||||
if depth == maximum_depth {
|
||||
if node.children.is_some() {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::ChildrenAtDepthBoundary { depth })
|
||||
.prepend(PathSegment::Object(path.to_owned())),
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let children = node.children.as_ref().ok_or_else(|| {
|
||||
ValidationError::new(ValidationErrorKind::ChildrenMissingBeforeDepth { depth })
|
||||
.prepend(PathSegment::Object(path.to_owned()))
|
||||
})?;
|
||||
let mut names = HashSet::new();
|
||||
for child in children {
|
||||
validate_object_name(&child.object.name, false)
|
||||
.map_err(|error| error.prepend(PathSegment::Child(child.object.name.clone())))?;
|
||||
if !names.insert(child.object.name.as_str()) {
|
||||
return Err(ValidationError::new(ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::ChildObject,
|
||||
name: child.object.name.clone(),
|
||||
})
|
||||
.prepend(PathSegment::Child(child.object.name.clone()))
|
||||
.prepend(PathSegment::Object(path.to_owned())));
|
||||
}
|
||||
let child_path = if path == "/" {
|
||||
format!("/{}", child.object.name)
|
||||
} else {
|
||||
format!("{path}/{}", child.object.name)
|
||||
};
|
||||
validate_observation_node(child, &child_path, depth + 1, maximum_depth)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_fetch_interface_response(
|
||||
response: &FetchInterfaceResponse,
|
||||
request: &FetchInterfaceRequest,
|
||||
) -> Result<(), ValidationError> {
|
||||
request.validate()?;
|
||||
response.interface.validate()?;
|
||||
if response.interface != request.interface {
|
||||
return Err(
|
||||
ValidationError::new(ValidationErrorKind::InterfaceResponseMismatch {
|
||||
expected: Box::new(request.interface.clone()),
|
||||
actual: Box::new(response.interface.clone()),
|
||||
})
|
||||
.prepend(PathSegment::Field("interface".into())),
|
||||
);
|
||||
}
|
||||
response.descriptor.validate()
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::collections::BTreeMap;
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor,
|
||||
InterfaceReference, InterfaceTarget, Object, ObjectObservation, ObserveRequest,
|
||||
OperationDeclaration, ReturnDeclaration, Target, TypeExpr, ValidationErrorKind,
|
||||
};
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn object(path: &str, interfaces: Vec<InterfaceReference>) -> Object {
|
||||
Object {
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
description: None,
|
||||
interfaces,
|
||||
r#ref: None,
|
||||
validator: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: wip_protocol::INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![],
|
||||
operations: vec![OperationDeclaration {
|
||||
name: "run".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_is_segment_based_ancestor_or_self_not_indexability() {
|
||||
for (scope, path) in [
|
||||
("/", "/"),
|
||||
("/", "/a/b"),
|
||||
("/a", "/a"),
|
||||
("/a", "/a/b"),
|
||||
("/a/b", "/a/b/c"),
|
||||
] {
|
||||
reference(scope, "read").validate_for_path(path).unwrap();
|
||||
object(path, vec![reference(scope, "read")])
|
||||
.validate_at_path(path)
|
||||
.unwrap();
|
||||
}
|
||||
for (scope, path) in [
|
||||
("/a", "/ab"),
|
||||
("/a", "/ab/c"),
|
||||
("/a/b", "/a/c"),
|
||||
("/a/b", "/a"),
|
||||
("/a", "/"),
|
||||
] {
|
||||
assert!(matches!(
|
||||
reference(scope, "read")
|
||||
.validate_for_path(path)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
// Without the placement context, the Object/reference shape is valid.
|
||||
let object = object(path, vec![reference(scope, "read")]);
|
||||
object.validate().unwrap();
|
||||
assert!(matches!(
|
||||
object.validate_at_path(path).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_validation_does_not_normalize_or_parse_fields() {
|
||||
for scope in ["", "relative", "//a", "/a/", "/a//b", "/a/./b", "/a/../b"] {
|
||||
let reference = reference(scope, "read");
|
||||
assert!(matches!(
|
||||
reference.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::InvalidPath { .. }
|
||||
));
|
||||
assert!(
|
||||
FetchInterfaceRequest {
|
||||
interface: reference.clone()
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(object("/a", vec![reference]).validate().is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
reference("/", "").validate().unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
for name in [".", "..", "a/b", "::", "#", "読み::書き#λ", "e\u{301}"] {
|
||||
let reference = reference("/世::界/#/%2F", name);
|
||||
reference.validate().unwrap();
|
||||
assert_eq!(reference.name, name);
|
||||
assert_eq!(reference.scope, "/世::界/#/%2F");
|
||||
}
|
||||
assert_ne!(reference("/", "é"), reference("/", "e\u{301}"));
|
||||
assert_ne!(reference("/A", "read"), reference("/a", "read"));
|
||||
assert_ne!(reference("/%61", "read"), reference("/a", "read"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_membership_and_correlation_use_complete_pair() {
|
||||
let root = reference("/", "read");
|
||||
let scoped = reference("/a", "read");
|
||||
let mut object = object("/a", vec![root.clone(), scoped.clone()]);
|
||||
object.validate_at_path("/a").unwrap();
|
||||
assert!(object.interfaces.contains(&scoped));
|
||||
assert!(!object.interfaces.contains(&reference("/b", "read")));
|
||||
object.interfaces.push(root.clone());
|
||||
assert_eq!(
|
||||
object.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateInterface {
|
||||
reference: root.clone()
|
||||
}
|
||||
);
|
||||
let request = FetchInterfaceRequest { interface: root };
|
||||
let mut response = FetchInterfaceResponse {
|
||||
interface: scoped,
|
||||
scope_ref: None,
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
response.validate_for(&request).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceResponseMismatch { .. }
|
||||
));
|
||||
response.interface = request.interface.clone();
|
||||
for scope_ref in [None, Some(String::new()), Some("opaque::世界#/%".into())] {
|
||||
response.scope_ref = scope_ref;
|
||||
response.validate_for(&request).unwrap();
|
||||
}
|
||||
response.interface.name.clear();
|
||||
assert_eq!(
|
||||
response.validate_for(&request).unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_checks_scope_at_every_node_including_depth_boundary() {
|
||||
let request = ObserveRequest {
|
||||
path: "/a".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let mut response = ObjectObservation {
|
||||
object: object("/a", vec![reference("/a", "read")]),
|
||||
children: Some(vec![ObjectObservation {
|
||||
object: object("/a/b", vec![reference("/a/b", "read")]),
|
||||
children: None,
|
||||
}]),
|
||||
};
|
||||
request.validate_response(&response).unwrap();
|
||||
response.children.as_mut().unwrap()[0].object.interfaces[0].scope = "/a/c".into();
|
||||
assert!(matches!(
|
||||
request.validate_response(&response).unwrap_err().kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_needs_no_target_path_and_call_separates_shape_from_scope_selection() {
|
||||
let reference = reference("/some/unrelated/scope", "read");
|
||||
let fetch = FetchInterfaceRequest {
|
||||
interface: reference.clone(),
|
||||
};
|
||||
fetch.validate().unwrap();
|
||||
FetchInterfaceResponse {
|
||||
interface: reference.clone(),
|
||||
scope_ref: None,
|
||||
descriptor: descriptor(),
|
||||
validator: None,
|
||||
}
|
||||
.validate_for(&fetch)
|
||||
.unwrap();
|
||||
let mut call = CallOperationRequest {
|
||||
target: Target {
|
||||
path: "/a".into(),
|
||||
validator: None,
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
reference,
|
||||
scope_ref: Some("opaque".into()),
|
||||
validator: None,
|
||||
},
|
||||
operation: "run".into(),
|
||||
arguments: BTreeMap::new(),
|
||||
};
|
||||
call.validate().unwrap();
|
||||
call.validate_with(&descriptor()).unwrap();
|
||||
// This stage is Host InterfaceMismatch, after NotFound, not shape InvalidRequest.
|
||||
assert!(matches!(
|
||||
call.interface
|
||||
.reference
|
||||
.validate_for_path(&call.target.path)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InterfaceScopeMismatch { .. }
|
||||
));
|
||||
call.interface.reference.name.clear();
|
||||
assert_eq!(
|
||||
call.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
assert_eq!(
|
||||
call.validate_with(&descriptor()).unwrap_err().kind,
|
||||
ValidationErrorKind::EmptyInterfaceName
|
||||
);
|
||||
}
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use wip_protocol::{
|
||||
CallOperationRequest, CallOperationResponse, EnumCase, FetchInterfaceRequest,
|
||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||
InterfaceReference, InterfaceTarget, MAX_SAFE_INTEGER, NameNamespace, Object,
|
||||
ObjectObservation, ObserveRequest, OperationDeclaration, ParameterDeclaration, PathSegment,
|
||||
ProtocolError, ProtocolErrorCode, ProtocolInteraction, ProtocolResult, ReturnDeclaration,
|
||||
Target, TypeDeclaration, TypeExpr, UnionCase, ValidationErrorKind, Value, ValueKind,
|
||||
};
|
||||
|
||||
fn reference(scope: &str, name: &str) -> InterfaceReference {
|
||||
InterfaceReference {
|
||||
scope: scope.into(),
|
||||
name: name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Value {
|
||||
Value::Record(
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name.to_owned(), value))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn field(name: &str, r#type: TypeExpr, required: bool) -> FieldDeclaration {
|
||||
FieldDeclaration {
|
||||
name: name.into(),
|
||||
required,
|
||||
documentation: None,
|
||||
r#type,
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor() -> InterfaceDescriptor {
|
||||
InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![
|
||||
TypeDeclaration {
|
||||
name: "Color".into(),
|
||||
documentation: None,
|
||||
definition: TypeExpr::Enum {
|
||||
cases: vec![
|
||||
EnumCase {
|
||||
name: "red".into(),
|
||||
documentation: None,
|
||||
},
|
||||
EnumCase {
|
||||
name: "blue".into(),
|
||||
documentation: None,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
TypeDeclaration {
|
||||
name: "Selection".into(),
|
||||
documentation: None,
|
||||
definition: TypeExpr::Union {
|
||||
cases: vec![
|
||||
UnionCase {
|
||||
name: "all".into(),
|
||||
documentation: None,
|
||||
payload: None,
|
||||
},
|
||||
UnionCase {
|
||||
name: "one".into(),
|
||||
documentation: None,
|
||||
payload: Some(TypeExpr::Entry),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
TypeDeclaration {
|
||||
name: "Payload".into(),
|
||||
documentation: None,
|
||||
definition: TypeExpr::Record {
|
||||
fields: vec![
|
||||
field("title", TypeExpr::String, true),
|
||||
field(
|
||||
"color",
|
||||
TypeExpr::Named {
|
||||
name: "Color".into(),
|
||||
},
|
||||
false,
|
||||
),
|
||||
field("metadata", TypeExpr::Json, false),
|
||||
field(
|
||||
"entries",
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Entry),
|
||||
},
|
||||
false,
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
operations: vec![
|
||||
OperationDeclaration {
|
||||
name: "publish".into(),
|
||||
documentation: None,
|
||||
parameters: vec![
|
||||
ParameterDeclaration {
|
||||
name: "payload".into(),
|
||||
required: true,
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Named {
|
||||
name: "Payload".into(),
|
||||
},
|
||||
},
|
||||
ParameterDeclaration {
|
||||
name: "selection".into(),
|
||||
required: false,
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Named {
|
||||
name: "Selection".into(),
|
||||
},
|
||||
},
|
||||
],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Boolean,
|
||||
},
|
||||
},
|
||||
OperationDeclaration {
|
||||
name: "refresh".into(),
|
||||
documentation: None,
|
||||
parameters: vec![],
|
||||
returns: ReturnDeclaration {
|
||||
documentation: None,
|
||||
r#type: TypeExpr::Unit,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn object(name: &str) -> Object {
|
||||
Object {
|
||||
name: name.into(),
|
||||
description: Some(format!("Object {name}")),
|
||||
interfaces: vec![reference("/", "catalog-v1"), reference("/", "search-v2")],
|
||||
r#ref: Some("opaque-object-ref".into()),
|
||||
validator: Some(vec![1, 2, 3]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_fields_have_canonical_identity_and_ordered_set_semantics() {
|
||||
let object = object("article");
|
||||
object.validate().unwrap();
|
||||
object.validate_at_path("/articles/article").unwrap();
|
||||
assert_eq!(
|
||||
object.interfaces,
|
||||
[reference("/", "catalog-v1"), reference("/", "search-v2")]
|
||||
);
|
||||
|
||||
let duplicate = Object {
|
||||
interfaces: vec![reference("/", "catalog-v1"), reference("/", "catalog-v1")],
|
||||
..object.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
duplicate.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateInterface {
|
||||
reference: reference("/", "catalog-v1")
|
||||
}
|
||||
);
|
||||
|
||||
for invalid in ["a/b", ".", ".."] {
|
||||
assert!(matches!(
|
||||
Object {
|
||||
name: invalid.into(),
|
||||
..object.clone()
|
||||
}
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InvalidObjectName { .. }
|
||||
));
|
||||
}
|
||||
|
||||
let root = Object {
|
||||
name: String::new(),
|
||||
..object.clone()
|
||||
};
|
||||
root.validate_at_path("/").unwrap();
|
||||
assert!(matches!(
|
||||
object.validate_at_path("/articles/other").unwrap_err().kind,
|
||||
ValidationErrorKind::ObjectNameMismatch { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_and_validator_consistency_is_independent_from_path() {
|
||||
let first = object("article");
|
||||
let same = first.clone();
|
||||
first.validate_consistency_with(&same).unwrap();
|
||||
|
||||
let changed_state = Object {
|
||||
description: Some("changed".into()),
|
||||
validator: Some(vec![4]),
|
||||
..first.clone()
|
||||
};
|
||||
first.validate_consistency_with(&changed_state).unwrap();
|
||||
|
||||
let inconsistent = Object {
|
||||
description: Some("different representation".into()),
|
||||
..first.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
first
|
||||
.validate_consistency_with(&inconsistent)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InconsistentObjectObservation {
|
||||
reference: "opaque-object-ref".into()
|
||||
}
|
||||
);
|
||||
|
||||
let validator_free = Object {
|
||||
validator: None,
|
||||
..first.clone()
|
||||
};
|
||||
let validator_free_change = Object {
|
||||
description: Some("latest observation".into()),
|
||||
validator: None,
|
||||
..first.clone()
|
||||
};
|
||||
validator_free
|
||||
.validate_consistency_with(&validator_free_change)
|
||||
.unwrap();
|
||||
|
||||
let unrelated = Object {
|
||||
r#ref: Some("another-ref".into()),
|
||||
..inconsistent
|
||||
};
|
||||
first.validate_consistency_with(&unrelated).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_supports_every_canonical_type_expression() {
|
||||
let descriptor = descriptor();
|
||||
descriptor.validate().unwrap();
|
||||
|
||||
let all = [
|
||||
TypeExpr::Unit,
|
||||
TypeExpr::Boolean,
|
||||
TypeExpr::Integer,
|
||||
TypeExpr::Number,
|
||||
TypeExpr::String,
|
||||
TypeExpr::Bytes,
|
||||
TypeExpr::Json,
|
||||
TypeExpr::Entry,
|
||||
TypeExpr::Named {
|
||||
name: "Payload".into(),
|
||||
},
|
||||
TypeExpr::Record {
|
||||
fields: vec![field("ok", TypeExpr::Boolean, true)],
|
||||
},
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::String),
|
||||
},
|
||||
TypeExpr::Enum {
|
||||
cases: vec![EnumCase {
|
||||
name: "yes".into(),
|
||||
documentation: None,
|
||||
}],
|
||||
},
|
||||
TypeExpr::Union {
|
||||
cases: vec![UnionCase {
|
||||
name: "some".into(),
|
||||
documentation: None,
|
||||
payload: Some(TypeExpr::Integer),
|
||||
}],
|
||||
},
|
||||
];
|
||||
assert_eq!(all.len(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_rejects_duplicate_names_missing_references_and_cycles() {
|
||||
let mut duplicate = descriptor();
|
||||
duplicate.types.push(duplicate.types[0].clone());
|
||||
assert_eq!(
|
||||
duplicate.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::TypeDeclaration,
|
||||
name: "Color".into(),
|
||||
}
|
||||
);
|
||||
|
||||
let mut missing = descriptor();
|
||||
missing.types[2].definition = TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Named {
|
||||
name: "Absent".into(),
|
||||
}),
|
||||
};
|
||||
let error = missing.validate().unwrap_err();
|
||||
assert_eq!(
|
||||
error.kind,
|
||||
ValidationErrorKind::UnknownType {
|
||||
name: "Absent".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
error.path,
|
||||
vec![
|
||||
PathSegment::Descriptor,
|
||||
PathSegment::Declaration("Payload".into())
|
||||
]
|
||||
);
|
||||
|
||||
let cyclic = InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(),
|
||||
documentation: None,
|
||||
types: vec![
|
||||
TypeDeclaration {
|
||||
name: "A".into(),
|
||||
documentation: None,
|
||||
definition: TypeExpr::Record {
|
||||
fields: vec![field("b", TypeExpr::Named { name: "B".into() }, true)],
|
||||
},
|
||||
},
|
||||
TypeDeclaration {
|
||||
name: "B".into(),
|
||||
documentation: None,
|
||||
definition: TypeExpr::Union {
|
||||
cases: vec![UnionCase {
|
||||
name: "a".into(),
|
||||
documentation: None,
|
||||
payload: Some(TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Named { name: "A".into() }),
|
||||
}),
|
||||
}],
|
||||
},
|
||||
},
|
||||
],
|
||||
operations: vec![],
|
||||
};
|
||||
assert_eq!(
|
||||
cyclic.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::RecursiveType {
|
||||
cycle: vec!["A".into(), "B".into(), "A".into()]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_record_enum_union_and_operation_names_are_unique() {
|
||||
let mut duplicate_field = descriptor();
|
||||
let TypeExpr::Record { fields } = &mut duplicate_field.types[2].definition else {
|
||||
unreachable!()
|
||||
};
|
||||
fields.push(field("title", TypeExpr::Integer, false));
|
||||
assert!(matches!(
|
||||
duplicate_field.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Field,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let mut duplicate_enum_case = descriptor();
|
||||
let TypeExpr::Enum { cases } = &mut duplicate_enum_case.types[0].definition else {
|
||||
unreachable!()
|
||||
};
|
||||
cases.push(cases[0].clone());
|
||||
assert!(matches!(
|
||||
duplicate_enum_case.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::EnumCase,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let mut duplicate_operation = descriptor();
|
||||
let duplicate = duplicate_operation.operations[0].clone();
|
||||
duplicate_operation.operations.push(duplicate);
|
||||
assert!(matches!(
|
||||
duplicate_operation.validate().unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::Operation,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_primitives_records_and_lists_validate_without_field_order_semantics() {
|
||||
let descriptor = descriptor();
|
||||
for (r#type, value) in [
|
||||
(TypeExpr::Unit, Value::Unit),
|
||||
(TypeExpr::Boolean, Value::Boolean(true)),
|
||||
(TypeExpr::Integer, Value::Integer(MAX_SAFE_INTEGER)),
|
||||
(TypeExpr::Number, Value::Number(1.5)),
|
||||
(TypeExpr::String, Value::String("hello".into())),
|
||||
(TypeExpr::Bytes, Value::Bytes(vec![0, 255])),
|
||||
(
|
||||
TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Boolean),
|
||||
},
|
||||
Value::List(vec![Value::Boolean(false), Value::Boolean(true)]),
|
||||
),
|
||||
] {
|
||||
descriptor.validate_value(&r#type, &value).unwrap();
|
||||
}
|
||||
|
||||
let schema = TypeExpr::Record {
|
||||
fields: vec![
|
||||
field("first", TypeExpr::String, true),
|
||||
field("second", TypeExpr::Integer, true),
|
||||
],
|
||||
};
|
||||
let first_order = record([
|
||||
("first", Value::String("x".into())),
|
||||
("second", Value::Integer(2)),
|
||||
]);
|
||||
let reverse_order = Value::Record(BTreeMap::from([
|
||||
("second".into(), Value::Integer(2)),
|
||||
("first".into(), Value::String("x".into())),
|
||||
]));
|
||||
descriptor.validate_value(&schema, &first_order).unwrap();
|
||||
descriptor.validate_value(&schema, &reverse_order).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_numeric_record_and_list_failures_are_rejected() {
|
||||
let descriptor = descriptor();
|
||||
assert_eq!(
|
||||
descriptor
|
||||
.validate_value(&TypeExpr::Integer, &Value::Integer(MAX_SAFE_INTEGER + 1))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::IntegerOutOfRange {
|
||||
value: MAX_SAFE_INTEGER + 1
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
descriptor
|
||||
.validate_value(&TypeExpr::Number, &Value::Number(f64::NAN))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::NonFiniteNumber
|
||||
);
|
||||
assert_eq!(
|
||||
descriptor
|
||||
.validate_value(
|
||||
&TypeExpr::List {
|
||||
items: Box::new(TypeExpr::Boolean)
|
||||
},
|
||||
&Value::List(vec![Value::Integer(1)])
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::TypeMismatch {
|
||||
expected: ValueKind::Boolean,
|
||||
actual: ValueKind::Integer,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_enum_and_union_are_descriptor_interpretations_of_raw_values() {
|
||||
let descriptor = descriptor();
|
||||
descriptor
|
||||
.validate_value(&TypeExpr::Entry, &Value::String("/articles/one".into()))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
descriptor
|
||||
.validate_value(&TypeExpr::Entry, &Value::String("articles//one".into()))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InvalidPath { .. }
|
||||
));
|
||||
|
||||
descriptor
|
||||
.validate_value(
|
||||
&TypeExpr::Named {
|
||||
name: "Color".into(),
|
||||
},
|
||||
&Value::String("red".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
descriptor
|
||||
.validate_value(
|
||||
&TypeExpr::Named {
|
||||
name: "Color".into()
|
||||
},
|
||||
&Value::String("green".into())
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::UnknownCase { .. }
|
||||
));
|
||||
|
||||
let selection = TypeExpr::Named {
|
||||
name: "Selection".into(),
|
||||
};
|
||||
descriptor
|
||||
.validate_value(
|
||||
&selection,
|
||||
&record([("$case", Value::String("all".into()))]),
|
||||
)
|
||||
.unwrap();
|
||||
descriptor
|
||||
.validate_value(
|
||||
&selection,
|
||||
&record([
|
||||
("$case", Value::String("one".into())),
|
||||
("value", Value::String("/items/1".into())),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
descriptor
|
||||
.validate_value(
|
||||
&selection,
|
||||
&record([
|
||||
("$case", Value::String("all".into())),
|
||||
("value", Value::Unit)
|
||||
])
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::UnexpectedUnionPayload
|
||||
);
|
||||
assert_eq!(
|
||||
descriptor
|
||||
.validate_value(
|
||||
&selection,
|
||||
&record([("$case", Value::String("one".into()))])
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::MissingUnionPayload
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_uses_the_normal_value_tree_and_rejects_bytes() {
|
||||
let descriptor = descriptor();
|
||||
let json = record([
|
||||
("null", Value::Unit),
|
||||
("boolean", Value::Boolean(true)),
|
||||
("integer", Value::Integer(42)),
|
||||
("number", Value::Number(2.5)),
|
||||
("string", Value::String("text".into())),
|
||||
(
|
||||
"array",
|
||||
Value::List(vec![Value::Unit, record([("nested", Value::Unit)])]),
|
||||
),
|
||||
]);
|
||||
descriptor.validate_value(&TypeExpr::Json, &json).unwrap();
|
||||
|
||||
let error = descriptor
|
||||
.validate_value(
|
||||
&TypeExpr::Json,
|
||||
&record([("nested", Value::List(vec![Value::Bytes(vec![1])]))]),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ValidationErrorKind::BytesInJson);
|
||||
assert_eq!(
|
||||
error.path,
|
||||
vec![
|
||||
PathSegment::Descriptor,
|
||||
PathSegment::Field("nested".into()),
|
||||
PathSegment::Index(0),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_validate_canonical_paths_named_arguments_and_unit_results() {
|
||||
let descriptor = descriptor();
|
||||
let payload = record([("title", Value::String("hello".into()))]);
|
||||
let request = CallOperationRequest {
|
||||
target: Target {
|
||||
path: "/articles/one".into(),
|
||||
validator: Some(vec![1]),
|
||||
},
|
||||
interface: InterfaceTarget {
|
||||
scope_ref: None,
|
||||
reference: reference("/", "catalog-v1"),
|
||||
validator: Some(vec![2]),
|
||||
},
|
||||
operation: "publish".into(),
|
||||
arguments: BTreeMap::from([("payload".into(), payload)]),
|
||||
};
|
||||
request.validate_with(&descriptor).unwrap();
|
||||
|
||||
CallOperationResponse {
|
||||
result: Value::Boolean(true),
|
||||
validator: Some(vec![3]),
|
||||
}
|
||||
.validate_for(&descriptor, "publish")
|
||||
.unwrap();
|
||||
descriptor.validate_result("refresh", &Value::Unit).unwrap();
|
||||
|
||||
let mut missing = request.clone();
|
||||
missing.arguments.clear();
|
||||
assert_eq!(
|
||||
missing.validate_with(&descriptor).unwrap_err().kind,
|
||||
ValidationErrorKind::MissingParameter {
|
||||
name: "payload".into()
|
||||
}
|
||||
);
|
||||
|
||||
let mut unknown = request.clone();
|
||||
unknown.arguments.insert("extra".into(), Value::Unit);
|
||||
assert_eq!(
|
||||
unknown.validate_with(&descriptor).unwrap_err().kind,
|
||||
ValidationErrorKind::UnknownParameter {
|
||||
name: "extra".into()
|
||||
}
|
||||
);
|
||||
|
||||
let mut bad_path = request;
|
||||
bad_path.target.path = "relative".into();
|
||||
assert!(matches!(
|
||||
bad_path.validate_with(&descriptor).unwrap_err().kind,
|
||||
ValidationErrorKind::InvalidPath { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_and_fetch_interface_dtos_validate_request_response_correspondence() {
|
||||
let observe = ObserveRequest {
|
||||
path: "/articles/one".into(),
|
||||
depth: 0,
|
||||
};
|
||||
observe.validate().unwrap();
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("one"),
|
||||
children: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("two"),
|
||||
children: None,
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
|
||||
for invalid in [
|
||||
"",
|
||||
"articles",
|
||||
"//articles",
|
||||
"/articles/",
|
||||
"/./articles",
|
||||
"/a/../b",
|
||||
] {
|
||||
assert!(matches!(
|
||||
ObserveRequest {
|
||||
path: invalid.into(),
|
||||
depth: 0,
|
||||
}
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InvalidPath { .. }
|
||||
));
|
||||
}
|
||||
|
||||
let request = FetchInterfaceRequest {
|
||||
interface: reference("/", "catalog-v1"),
|
||||
};
|
||||
let response = FetchInterfaceResponse {
|
||||
scope_ref: None,
|
||||
interface: reference("/", "catalog-v1"),
|
||||
descriptor: descriptor(),
|
||||
validator: Some(vec![9]),
|
||||
};
|
||||
response.validate_for(&request).unwrap();
|
||||
assert!(matches!(
|
||||
FetchInterfaceResponse {
|
||||
interface: reference("/", "other"),
|
||||
..response
|
||||
}
|
||||
.validate_for(&request)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::InterfaceResponseMismatch { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observe_response_validates_complete_children_and_depth_boundary() {
|
||||
let request = ObserveRequest {
|
||||
path: "/articles".into(),
|
||||
depth: 1,
|
||||
};
|
||||
let leaf = |name: &str| ObjectObservation {
|
||||
object: object(name),
|
||||
children: None,
|
||||
};
|
||||
let response = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![leaf("one"), leaf("two")]),
|
||||
};
|
||||
request.validate_response(&response).unwrap();
|
||||
|
||||
let empty = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![]),
|
||||
};
|
||||
request.validate_response(&empty).unwrap();
|
||||
|
||||
let missing = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
request.validate_response(&missing).unwrap_err().kind,
|
||||
ValidationErrorKind::ChildrenMissingBeforeDepth { depth: 0 }
|
||||
));
|
||||
|
||||
let boundary = ObserveRequest {
|
||||
depth: 0,
|
||||
..request.clone()
|
||||
};
|
||||
assert!(matches!(
|
||||
boundary.validate_response(&response).unwrap_err().kind,
|
||||
ValidationErrorKind::ChildrenAtDepthBoundary { depth: 0 }
|
||||
));
|
||||
|
||||
let duplicate = ObjectObservation {
|
||||
object: object("articles"),
|
||||
children: Some(vec![leaf("one"), leaf("one")]),
|
||||
};
|
||||
assert!(matches!(
|
||||
request.validate_response(&duplicate).unwrap_err().kind,
|
||||
ValidationErrorKind::DuplicateName {
|
||||
namespace: NameNamespace::ChildObject,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_result_exposes_the_exact_canonical_wire_error_codes() {
|
||||
assert_eq!(
|
||||
ProtocolErrorCode::ALL,
|
||||
[
|
||||
ProtocolErrorCode::InvalidRequest,
|
||||
ProtocolErrorCode::NotFound,
|
||||
ProtocolErrorCode::InterfaceNotFound,
|
||||
ProtocolErrorCode::InterfaceMismatch,
|
||||
ProtocolErrorCode::OperationNotFound,
|
||||
ProtocolErrorCode::InvalidArguments,
|
||||
ProtocolErrorCode::ValidatorRequired,
|
||||
ProtocolErrorCode::ValidatorMismatch,
|
||||
ProtocolErrorCode::InterfaceValidatorRequired,
|
||||
ProtocolErrorCode::InterfaceValidatorMismatch,
|
||||
ProtocolErrorCode::PermissionDenied,
|
||||
ProtocolErrorCode::ResourceLimitExceeded,
|
||||
ProtocolErrorCode::Internal,
|
||||
ProtocolErrorCode::OperationOutcomeUnknown,
|
||||
]
|
||||
);
|
||||
|
||||
let failure: ProtocolResult<()> = ProtocolResult::Failure(ProtocolError {
|
||||
code: ProtocolErrorCode::InvalidArguments,
|
||||
message: "payload.title is required".into(),
|
||||
});
|
||||
assert!(matches!(failure, ProtocolResult::Failure(_)));
|
||||
assert_eq!(
|
||||
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 observe_error_codes_are_exhaustive() {
|
||||
assert_allowed_codes(
|
||||
ProtocolInteraction::Observe,
|
||||
&[
|
||||
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 observe = ObserveRequest {
|
||||
path: "/articles/one".into(),
|
||||
depth: 0,
|
||||
};
|
||||
assert!(matches!(
|
||||
observe
|
||||
.validate_response(&ObjectObservation {
|
||||
object: object("other"),
|
||||
children: None,
|
||||
})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ValidationErrorKind::ObjectNameMismatch { .. }
|
||||
));
|
||||
|
||||
let interface_request = FetchInterfaceRequest {
|
||||
interface: reference("/", "catalog-v1"),
|
||||
};
|
||||
let mut invalid_descriptor = descriptor();
|
||||
invalid_descriptor
|
||||
.operations
|
||||
.push(invalid_descriptor.operations[0].clone());
|
||||
assert!(matches!(
|
||||
FetchInterfaceResponse {
|
||||
interface: interface_request.interface.clone(),
|
||||
scope_ref: None,
|
||||
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 @@
|
||||
{"files":{"Cargo.toml":"f7bf41f620fa218c3dbab3202a6c92f62e3f5f7d581e664dcb48dc70a5226c08","README.md":"8ab0580ca2e03dcd71357cefef5bdbb7911ed3a1638d9883a5958f01e229c2c3","src/lib.rs":"a5fbd621ee1f882fe9cacfb46cd1bf95e39707a2a7cde3931753bf3eec996415","src/limits.rs":"24fd5e0f6ec82d8c5a9c12eafa2c18bf1880e86cc3b6131433ad8a56aa6ddff5","src/render.rs":"f298c05842eace4c62fbad28984200ce349e7592117e240f220274de6cfc6cfb","src/token.rs":"24666bf2a054d9beaf08f20bef09912575e360bfb7866d23190093814bc55ed4","tests/golden/identifiers.txt":"270af3ba1b2bdedcf68839c1be3951fff84cac6d041d305b0786cdcdaa8f08ab","tests/golden/issue-read.txt":"fc4cc8171464bca0069b5580c0c371f188b79cba24b751f391dc150edd4d57eb","tests/golden/nested.txt":"e83c3f617f3de7add5abc791659b93156bdb8203b388103dc445c1827f8ab8d9","tests/golden/object.txt":"adcdeb198fbbf799bbede9b0b99a13f9ffd2f7d47a86ed404e81e0b4fbd2c159","tests/golden/union-return.txt":"dfaef0f545aa87012d43090a834ec53f05b0f26d4c7554b80f298f657d6222c5","tests/signatures.rs":"d3d52cea30c9dd0a9659e5b96c2f2ca2d76f04da8bc37f6196c0b025a93cb245"},"package":null}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "wip-text-view"
|
||||
version = "0.1.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Standalone Object and Interface Text View signatures for WIP"
|
||||
documentation = "https://docs.rs/wip-text-view"
|
||||
readme = "README.md"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://gitea.hareworks.net/Hare/wip-rs"
|
||||
|
||||
[lib]
|
||||
name = "wip_text_view"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "signatures"
|
||||
path = "tests/signatures.rs"
|
||||
|
||||
[dependencies.wip-protocol]
|
||||
version = "0.1.0"
|
||||
path = "../wip-protocol"
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
# wip-text-view
|
||||
|
||||
Standalone Object and Interface signature rendering for WIP Text View, following
|
||||
`4.2-text-view.md` at reference revision `6086f3c` and the Protocol semantics in
|
||||
`3-protocol.md`. Only `wip-protocol` and the Rust standard library are dependencies.
|
||||
No Client, Host, HTTP I/O, cache, UI framework or retrieval service is required.
|
||||
|
||||
## Single-entity API
|
||||
|
||||
```rust
|
||||
use wip_protocol::{Object, InterfaceReference, InterfaceDescriptor, INTERFACE_FORMAT_V1};
|
||||
use wip_text_view::{Interface, render_object, render_interface};
|
||||
|
||||
let reference = InterfaceReference { scope: "/".into(), name: "example".into() };
|
||||
let object = Object {
|
||||
name: "item".into(), description: None, interfaces: vec![reference.clone()],
|
||||
r#ref: None, validator: None,
|
||||
};
|
||||
let object_signature = render_object(&object)?;
|
||||
assert_eq!(object_signature,
|
||||
"object {\n name: \"item\";\n interfaces: [\"/::example\"];\n}\n");
|
||||
|
||||
let descriptor = InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(), documentation: None,
|
||||
types: vec![], operations: vec![],
|
||||
};
|
||||
let interface = Interface { reference: &reference, descriptor: &descriptor };
|
||||
let interface_signature = render_interface(&interface)?;
|
||||
assert_eq!(interface_signature, "interface \"/::example\" {\n}\n");
|
||||
# Ok::<(), wip_text_view::RenderError>(())
|
||||
```
|
||||
|
||||
`Interface<'a>` is one borrowed SDK input entity containing a complete structured
|
||||
reference and its corresponding descriptor, not a wire schema extension. The
|
||||
caller pairs them from a coherent observation or publication. The descriptor has
|
||||
no identity, so a renderer cannot prove the pairing's provenance or freshness.
|
||||
For example, a caller with a validated `FetchInterfaceResponse` can borrow its
|
||||
`interface` and `descriptor`; it does not pass `scope_ref` or validators.
|
||||
|
||||
An Object has no placement path. This API always emits `object { ... }`, never
|
||||
requests a path and never infers one from name or ref. It requires no descriptor.
|
||||
An Interface needs no Object, separate name/scope/context arguments or lookup.
|
||||
There is no document aggregator, configuration or details selector.
|
||||
|
||||
## Typed display tokens
|
||||
|
||||
```rust
|
||||
use wip_protocol::{Object, InterfaceReference, InterfaceDescriptor, INTERFACE_FORMAT_V1};
|
||||
use wip_text_view::{
|
||||
Interface, TokenKind, tokenize_object, tokenize_interface, to_plain_text,
|
||||
render_object, render_interface,
|
||||
};
|
||||
|
||||
let reference = InterfaceReference { scope: "/".into(), name: "example".into() };
|
||||
let object = Object {
|
||||
name: "item".into(), description: None, interfaces: vec![reference.clone()],
|
||||
r#ref: None, validator: None,
|
||||
};
|
||||
let object_tokens = tokenize_object(&object)?;
|
||||
assert_eq!(object_tokens[0].kind(), TokenKind::Keyword);
|
||||
assert_eq!(object_tokens[0].text(), "object");
|
||||
assert_eq!(to_plain_text(&object_tokens), render_object(&object)?);
|
||||
|
||||
let descriptor = InterfaceDescriptor {
|
||||
format: INTERFACE_FORMAT_V1.into(), documentation: None,
|
||||
types: vec![], operations: vec![],
|
||||
};
|
||||
let input = Interface { reference: &reference, descriptor: &descriptor };
|
||||
let tokens = tokenize_interface(&input)?;
|
||||
for token in &tokens {
|
||||
// Custom renderers can select presentation by role without reparsing text.
|
||||
if token.kind() == TokenKind::Reference {
|
||||
assert_eq!(token.text(), "\"/::example\"");
|
||||
}
|
||||
}
|
||||
let joined: String = tokens.iter().map(|token| token.text()).collect();
|
||||
assert_eq!(to_plain_text(&tokens), joined);
|
||||
assert_eq!(to_plain_text(&tokens), render_interface(&input)?);
|
||||
# Ok::<(), wip_text_view::RenderError>(())
|
||||
```
|
||||
|
||||
`tokenize_object` / `tokenize_interface` return `Result<Vec<Token>, RenderError>`.
|
||||
They generate **directly from the input structure**, not by lexing a completed
|
||||
Text View string. Each token owns its text (and can outlive the input) and exposes
|
||||
`kind()` / `text()`. Existing render APIs use the same token generation followed
|
||||
by `to_plain_text(&[Token])`; there is no second grammar/escape/layout engine.
|
||||
|
||||
### Kind and splitting contract
|
||||
|
||||
| Kind | One token contains |
|
||||
| --- | --- |
|
||||
| `Keyword` | One grammar keyword, Object property label, or primitive type keyword |
|
||||
| `TypeName` | One type declaration name or Named type reference |
|
||||
| `OperationName` | One Operation declaration name |
|
||||
| `ParameterName` / `FieldName` | One parameter / record field name |
|
||||
| `CaseName` | One enum or union case name |
|
||||
| `String` | One complete quoted Object name or description |
|
||||
| `Reference` | One complete quoted absolute Interface reference, with both quoting layers |
|
||||
| `Documentation` | Entire `/// "summary"` content, including marker and internal space, excluding indentation/LF |
|
||||
| `Symbol` | One punctuation mark, except the indivisible two-character `->` arrow |
|
||||
| `Whitespace` | One inter-token ASCII space |
|
||||
| `Newline` | One LF, including the final LF |
|
||||
| `Indentation` | All leading spaces of a non-root line, two spaces per depth level |
|
||||
|
||||
Quoted identifiers retain their semantic role even when named like keywords.
|
||||
Quotes, backticks and all WIP escapes are part of the data token, never separate
|
||||
symbols. Host spaces inside quoted data remain in that token. Adjacent symbols
|
||||
are separate; no empty tokens or zero-depth indentation tokens are emitted.
|
||||
`TokenKind` is non-exhaustive so consumers should handle future roles with a
|
||||
fallback. The API does not distinguish type declaration names from Named uses,
|
||||
or enum cases from union cases; both share the documented role.
|
||||
|
||||
All layout is included. Concatenate token text **without separators**, not with
|
||||
`join(" ")`. `to_plain_text` is only that concatenation: no interpretation,
|
||||
validation, quoting, escaping or layout completion. An empty slice yields `""`;
|
||||
a filtered/reordered slice is allowed but need not be a complete signature.
|
||||
|
||||
Token text is escaped for **WIP Text View**, not for HTML or other destinations.
|
||||
Custom renderers must escape for their destination and treat Host text as data,
|
||||
not markup or instructions. This crate supplies no HTML, ANSI, color or theme
|
||||
renderer/adapter and no external text lexer/parser or AST.
|
||||
|
||||
## Output and validation
|
||||
|
||||
- UTF-8 plain text with LF, two-space indentation and a final LF, without ANSI,
|
||||
Markdown fences, syntax highlighting or provider envelopes. Nonempty composites
|
||||
and parameter lists use multiple lines; layout is deterministic here, but not a
|
||||
byte-canonical protocol format.
|
||||
- All Object references remain in Host order. All types, then all operations,
|
||||
fields, parameters and cases remain in declaration order, without elision.
|
||||
- Missing vs empty description/documentation, optional vs unit, no payload vs
|
||||
unit payload, and empty record/enum/union/declaration sets remain distinct.
|
||||
- Full absolute references use component quoting **and** outer JSON-string quoting.
|
||||
Identifiers use keywords/backtick rules. All Host strings use standard JSON
|
||||
escapes plus DEL/C1, Unicode line/paragraph separator and bidi-control escapes.
|
||||
No normalization, case conversion, URL encoding or input mutation occurs.
|
||||
- Documentation summaries are displayed in their prescribed positions, including
|
||||
return documentation between `)` and `->`. Details are not displayed. Host text
|
||||
is data, not renderer instructions or markup; quoting alone is not a prompt
|
||||
injection defense. AI adapters must preserve the trust boundary.
|
||||
- Object ref/validator, children, domain data and Interface scope_ref/validator
|
||||
are not signature content. No annotations are inferred from operation names.
|
||||
|
||||
The render functions return `Result<String, RenderError>`; token generation
|
||||
returns `Result<Vec<Token>, RenderError>`. Neither returns partial signatures. Resource checks happen first, followed by existing Protocol validators:
|
||||
Object shape and reference uniqueness, or Interface reference shape plus descriptor
|
||||
structure, duplicate names, unknown Named references and cycles. Descriptor format
|
||||
is checked after semantics: valid but unsupported formats return
|
||||
`UnsupportedDescriptorFormat`, distinct from `InvalidDescriptor`. Supported format
|
||||
is exactly `wip-interface/1`. Other validation errors preserve the Protocol's typed
|
||||
`ValidationError` (also exposed as the error source).
|
||||
|
||||
Bounded input limits are **1 MiB** of total string/opaque byte data, **16,384**
|
||||
declarations/fields/parameters/cases/type expressions/references, **256** named type
|
||||
declarations, and **64** TypeExpr nesting levels. Details and Object runtime
|
||||
metadata count toward input bytes even though they are not rendered. A limit
|
||||
returns `RenderError::ResourceLimit`, never truncates or supplies `...`. Counts
|
||||
bound allocation and recursive validation before those validators run; these are
|
||||
library safety limits, not Protocol restrictions.
|
||||
|
||||
Without path/context, this library cannot attest Object scope ancestry, placement,
|
||||
observation consistency, identity, membership, authorization or currentness.
|
||||
Callers validate those at their observation boundary. Callers also own retrieval,
|
||||
resolution, cache, selection, multiple-signature arrangement and AI/UI adaptation.
|
||||
Text is display-only, not serialization, a digest, identity/cache key or call
|
||||
target. No parser or round-trip API is supplied.
|
||||
|
||||
## Validation
|
||||
|
||||
`tests/signatures.rs` is an external consumer of the public APIs. Goldens cover
|
||||
the spec's Object, issue.read, CloseResult, search/return documentation and
|
||||
identifier examples (with permitted multiline layout), plus nested documentation.
|
||||
The suite checks all TypeExpr variants/positions, ordering and empty distinctions,
|
||||
keyword and Unicode names, both reference quoting layers, all required control
|
||||
escapes, input immutability, metadata exclusion and typed rejection cases. Every
|
||||
existing case compares the render result (including exact errors) with token
|
||||
text concatenation and `to_plain_text`. Additional tests assert complete Object
|
||||
token splitting, all semantic roles, keyword collisions, atomic escaped data,
|
||||
all documentation positions, layout tokens and ownership beyond input lifetime.
|
||||
Input budgets bound token counts per node, indentation depth and escape expansion;
|
||||
token generation checks them before any rendering/validation traversal.
|
||||
|
||||
```console
|
||||
cargo test -p wip-text-view
|
||||
cargo clippy -p wip-text-view --all-targets -- -D warnings
|
||||
RUSTDOCFLAGS='-D warnings' cargo doc -p wip-text-view --no-deps
|
||||
```
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
//! Standalone, single-entity WIP Text View signatures.
|
||||
//!
|
||||
//! [`render_object`] accepts just an [`Object`], and [`render_interface`] accepts
|
||||
//! just an [`Interface`] (a reference paired with its corresponding descriptor).
|
||||
//! No Client, Host, HTTP, UI, retrieval, cache, path or display context is needed.
|
||||
//! The caller supplies a coherent observation; descriptor identity cannot be
|
||||
//! inferred from descriptor contents. No protocol wire fields are added.
|
||||
//!
|
||||
//! Output follows WIP `4.2-text-view.md` (reference revision `6086f3c`): UTF-8
|
||||
//! plain text, LF, two-space indentation, all declarations in original order,
|
||||
//! and documentation summaries only. There is no truncation or details setting.
|
||||
//! Object paths are neither requested nor guessed: output uses `object { ... }`.
|
||||
//! Runtime metadata is never rendered. Host documentation is untrusted data,
|
||||
//! not markup or instructions; quoting does not by itself prevent prompt injection.
|
||||
//!
|
||||
//! Each call checks resource limits, then Protocol shape/semantic validation.
|
||||
//! Interface rendering additionally requires [`wip_protocol::INTERFACE_FORMAT_V1`].
|
||||
//! Limits reject the entire input, never produce partial text: at most 1 MiB of
|
||||
//! input string/byte data, 16,384 declarations/fields/cases/type expressions or
|
||||
//! references, 256 named type declarations (bounding validator graph recursion),
|
||||
//! and 64 nested TypeExpr levels. These are implementation limits, not new
|
||||
//! Protocol semantics. An Object without placement context can only be checked
|
||||
//! for name/reference shape and duplicate references; the caller must validate
|
||||
//! scope ancestry and observation consistency at its observation boundary.
|
||||
//!
|
||||
//! Signatures are display-only: no parser, round-trip, identity comparison,
|
||||
//! cache key or call-target reconstruction is provided. The caller owns fetching,
|
||||
//! freshness, authorization, selection and arrangement of multiple signatures.
|
||||
//!
|
||||
//! ```
|
||||
//! use wip_protocol::{Object, InterfaceReference, InterfaceDescriptor, INTERFACE_FORMAT_V1};
|
||||
//! use wip_text_view::{Interface, render_object, render_interface};
|
||||
//! let reference = InterfaceReference { scope: "/".into(), name: "example".into() };
|
||||
//! let object = Object {
|
||||
//! name: "item".into(), description: None, interfaces: vec![reference.clone()],
|
||||
//! r#ref: Some("not a path".into()), validator: Some(vec![1]),
|
||||
//! };
|
||||
//! assert_eq!(render_object(&object)?,
|
||||
//! "object {\n name: \"item\";\n interfaces: [\"/::example\"];\n}\n");
|
||||
//! let descriptor = InterfaceDescriptor {
|
||||
//! format: INTERFACE_FORMAT_V1.into(), documentation: None,
|
||||
//! types: vec![], operations: vec![],
|
||||
//! };
|
||||
//! let interface = Interface { reference: &reference, descriptor: &descriptor };
|
||||
//! assert_eq!(render_interface(&interface)?, "interface \"/::example\" {\n}\n");
|
||||
//! # Ok::<(), wip_text_view::RenderError>(())
|
||||
//! ```
|
||||
//!
|
||||
//! # Typed display tokens
|
||||
//!
|
||||
//! [`tokenize_object`] and [`tokenize_interface`] traverse the input structure
|
||||
//! directly and return owned [`Token`] sequences, including all layout. Existing
|
||||
//! render APIs use this same generation path followed by [`to_plain_text`]. The
|
||||
//! input limits above also bound token allocation: tokens per node, indentation
|
||||
//! depth and escape expansion are bounded; no partial signature is returned.
|
||||
//! Token text is WIP-escaped, **not HTML-escaped** or escaped for other destinations.
|
||||
//! See [`Token`] for the semantic splitting contract; no renderer/theme is supplied.
|
||||
//!
|
||||
//! ```
|
||||
//! use wip_protocol::{InterfaceReference, InterfaceDescriptor, INTERFACE_FORMAT_V1};
|
||||
//! use wip_text_view::{Interface, TokenKind, tokenize_interface, to_plain_text, render_interface};
|
||||
//! let reference = InterfaceReference { scope: "/".into(), name: "example".into() };
|
||||
//! let descriptor = InterfaceDescriptor {
|
||||
//! format: INTERFACE_FORMAT_V1.into(), documentation: None,
|
||||
//! types: vec![], operations: vec![],
|
||||
//! };
|
||||
//! let input = Interface { reference: &reference, descriptor: &descriptor };
|
||||
//! let tokens = tokenize_interface(&input)?;
|
||||
//! assert_eq!(tokens[0].kind(), TokenKind::Keyword);
|
||||
//! assert_eq!(tokens[0].text(), "interface");
|
||||
//! let concatenated: String = tokens.iter().map(|token| token.text()).collect();
|
||||
//! assert_eq!(to_plain_text(&tokens), concatenated);
|
||||
//! assert_eq!(to_plain_text(&tokens), render_interface(&input)?);
|
||||
//! # Ok::<(), wip_text_view::RenderError>(())
|
||||
//! ```
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod limits;
|
||||
mod render;
|
||||
mod token;
|
||||
|
||||
pub use token::{Token, TokenKind, to_plain_text};
|
||||
|
||||
use std::{error::Error, fmt};
|
||||
use wip_protocol::{
|
||||
INTERFACE_FORMAT_V1, InterfaceDescriptor, InterfaceReference, Object, ValidationError,
|
||||
};
|
||||
|
||||
/// One Interface input entity, borrowing its identity and corresponding data.
|
||||
///
|
||||
/// The caller pairs values from the same observation/publication. The descriptor
|
||||
/// itself has no identity, so rendering cannot verify provenance or freshness.
|
||||
/// This is an SDK display input, not a replacement wire schema or a document.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Interface<'a> {
|
||||
/// Complete, absolute, Client-facing Interface reference.
|
||||
pub reference: &'a InterfaceReference,
|
||||
/// Descriptor corresponding to `reference`.
|
||||
pub descriptor: &'a InterfaceDescriptor,
|
||||
}
|
||||
|
||||
/// Failure to render a complete, validated signature. No partial text is returned.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RenderError {
|
||||
/// Object-independent Protocol validation failed.
|
||||
InvalidObject(ValidationError),
|
||||
/// The Interface's structured reference is malformed.
|
||||
InvalidReference(ValidationError),
|
||||
/// Descriptor structure or semantics failed Protocol validation.
|
||||
InvalidDescriptor(ValidationError),
|
||||
/// A semantically valid descriptor uses a format this renderer cannot interpret.
|
||||
UnsupportedDescriptorFormat {
|
||||
/// Exact unsupported format identifier.
|
||||
format: String,
|
||||
},
|
||||
/// Input exceeds an implementation safety limit, without truncation.
|
||||
ResourceLimit {
|
||||
/// Limit that was exceeded.
|
||||
limit: ResourceLimit,
|
||||
},
|
||||
}
|
||||
|
||||
/// Bounded input dimensions checked before recursive Protocol validation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResourceLimit {
|
||||
/// Total input string and opaque byte length exceeds 1 MiB.
|
||||
InputBytes,
|
||||
/// Total declarations, fields, parameters, cases, expressions or references exceeds 16,384.
|
||||
Nodes,
|
||||
/// More than 256 named type declarations.
|
||||
TypeDeclarations,
|
||||
/// More than 64 nested TypeExpr levels (outer expression is level one).
|
||||
TypeDepth,
|
||||
}
|
||||
|
||||
impl fmt::Display for RenderError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidObject(e) => write!(f, "invalid Object: {e}"),
|
||||
Self::InvalidReference(e) => write!(f, "invalid Interface reference: {e}"),
|
||||
Self::InvalidDescriptor(e) => write!(f, "invalid Interface descriptor: {e}"),
|
||||
Self::UnsupportedDescriptorFormat { format } => {
|
||||
write!(f, "unsupported descriptor format: {format:?}")
|
||||
}
|
||||
Self::ResourceLimit { limit } => write!(f, "Text View input exceeds {limit:?} limit"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RenderError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::InvalidObject(e) | Self::InvalidReference(e) | Self::InvalidDescriptor(e) => {
|
||||
Some(e)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders one complete Object signature, with no placement path or inferred data.
|
||||
///
|
||||
/// Validates shape and ordered-set uniqueness, but cannot validate ancestry or
|
||||
/// root/non-root placement without context. Missing and empty descriptions remain
|
||||
/// distinct; ref and validator bytes are ignored for display. Input is unmodified.
|
||||
/// See [crate documentation](crate) for limits and caller responsibilities.
|
||||
pub fn render_object(object: &Object) -> Result<String, RenderError> {
|
||||
tokenize_object(object).map(|tokens| to_plain_text(&tokens))
|
||||
}
|
||||
|
||||
/// Generates the complete owned display token sequence for one Object signature.
|
||||
///
|
||||
/// Uses the same validation, limits, metadata exclusion and caller responsibilities
|
||||
/// as [`render_object`]. No partial sequence is returned on error. Input is not
|
||||
/// modified. See [`Token`] and [`TokenKind`] for semantic roles and splitting.
|
||||
pub fn tokenize_object(object: &Object) -> Result<Vec<Token>, RenderError> {
|
||||
limits::object(object)?;
|
||||
object.validate().map_err(RenderError::InvalidObject)?;
|
||||
Ok(render::object(object))
|
||||
}
|
||||
|
||||
/// Renders one complete Interface signature from one paired input entity.
|
||||
///
|
||||
/// Validates reference shape and all descriptor declarations/named references,
|
||||
/// including cycles, before checking format support. No lookup or Object is
|
||||
/// needed. All types precede all operations, with original member order; only
|
||||
/// documentation summaries are shown, without interpreting Host text.
|
||||
/// Input is unmodified. See [crate documentation](crate) for safety limits.
|
||||
pub fn render_interface(interface: &Interface<'_>) -> Result<String, RenderError> {
|
||||
tokenize_interface(interface).map(|tokens| to_plain_text(&tokens))
|
||||
}
|
||||
|
||||
/// Generates the complete owned display token sequence for one Interface signature.
|
||||
///
|
||||
/// Uses the same validation, limits, format support and summary-only documentation
|
||||
/// as [`render_interface`]. No partial sequence is returned on error. Input is not
|
||||
/// modified. See [`Token`] and [`TokenKind`] for semantic roles and splitting.
|
||||
/// This traverses structured declarations directly, not a rendered-text lexer.
|
||||
pub fn tokenize_interface(interface: &Interface<'_>) -> Result<Vec<Token>, RenderError> {
|
||||
limits::interface(interface)?;
|
||||
interface
|
||||
.reference
|
||||
.validate()
|
||||
.map_err(RenderError::InvalidReference)?;
|
||||
interface
|
||||
.descriptor
|
||||
.validate()
|
||||
.map_err(RenderError::InvalidDescriptor)?;
|
||||
if interface.descriptor.format != INTERFACE_FORMAT_V1 {
|
||||
return Err(RenderError::UnsupportedDescriptorFormat {
|
||||
format: interface.descriptor.format.clone(),
|
||||
});
|
||||
}
|
||||
Ok(render::interface(interface))
|
||||
}
|
||||
|
||||
// Keep both README examples executable as external-consumer doctests.
|
||||
#[cfg(doctest)]
|
||||
#[doc = include_str!("../README.md")]
|
||||
mod readme {}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
use wip_protocol::{Documentation, InterfaceReference, Object, TypeExpr};
|
||||
|
||||
use crate::{Interface, RenderError, ResourceLimit};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Budget {
|
||||
bytes: usize,
|
||||
nodes: usize,
|
||||
}
|
||||
|
||||
fn check(value: usize, max: usize, limit: ResourceLimit) -> Result<(), RenderError> {
|
||||
if value > max {
|
||||
Err(RenderError::ResourceLimit { limit })
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn bytes(&mut self, len: usize) -> Result<(), RenderError> {
|
||||
self.bytes = self.bytes.saturating_add(len);
|
||||
check(self.bytes, 1024 * 1024, ResourceLimit::InputBytes)
|
||||
}
|
||||
|
||||
fn nodes(&mut self, len: usize) -> Result<(), RenderError> {
|
||||
self.nodes = self.nodes.saturating_add(len);
|
||||
check(self.nodes, 16_384, ResourceLimit::Nodes)
|
||||
}
|
||||
|
||||
fn reference(&mut self, reference: &InterfaceReference) -> Result<(), RenderError> {
|
||||
self.nodes(1)?;
|
||||
self.bytes(reference.scope.len())?;
|
||||
self.bytes(reference.name.len())
|
||||
}
|
||||
|
||||
fn doc(&mut self, doc: &Option<Documentation>) -> Result<(), RenderError> {
|
||||
if let Some(doc) = doc {
|
||||
self.bytes(doc.summary.len())?;
|
||||
self.bytes(doc.details.as_ref().map_or(0, String::len))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn declaration(&mut self, name: &str, doc: &Option<Documentation>) -> Result<(), RenderError> {
|
||||
self.nodes(1)?;
|
||||
self.bytes(name.len())?;
|
||||
self.doc(doc)
|
||||
}
|
||||
|
||||
fn expr(&mut self, expr: &TypeExpr, depth: usize) -> Result<(), RenderError> {
|
||||
check(depth, 64, ResourceLimit::TypeDepth)?;
|
||||
self.nodes(1)?;
|
||||
match expr {
|
||||
TypeExpr::Named { name } => self.bytes(name.len())?,
|
||||
TypeExpr::List { items } => self.expr(items, depth + 1)?,
|
||||
TypeExpr::Record { fields } => {
|
||||
self.nodes(fields.len())?;
|
||||
for field in fields {
|
||||
self.bytes(field.name.len())?;
|
||||
self.doc(&field.documentation)?;
|
||||
self.expr(&field.r#type, depth + 1)?;
|
||||
}
|
||||
}
|
||||
TypeExpr::Enum { cases } => {
|
||||
self.nodes(cases.len())?;
|
||||
for case in cases {
|
||||
self.bytes(case.name.len())?;
|
||||
self.doc(&case.documentation)?;
|
||||
}
|
||||
}
|
||||
TypeExpr::Union { cases } => {
|
||||
self.nodes(cases.len())?;
|
||||
for case in cases {
|
||||
self.bytes(case.name.len())?;
|
||||
self.doc(&case.documentation)?;
|
||||
if let Some(payload) = &case.payload {
|
||||
self.expr(payload, depth + 1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn object(object: &Object) -> Result<(), RenderError> {
|
||||
let mut budget = Budget::default();
|
||||
budget.bytes(object.name.len())?;
|
||||
budget.bytes(object.description.as_ref().map_or(0, String::len))?;
|
||||
budget.bytes(object.r#ref.as_ref().map_or(0, String::len))?;
|
||||
budget.bytes(object.validator.as_ref().map_or(0, Vec::len))?;
|
||||
check(object.interfaces.len(), 16_384, ResourceLimit::Nodes)?;
|
||||
for reference in &object.interfaces {
|
||||
budget.reference(reference)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn interface(interface: &Interface<'_>) -> Result<(), RenderError> {
|
||||
let mut budget = Budget::default();
|
||||
let descriptor = interface.descriptor;
|
||||
budget.reference(interface.reference)?;
|
||||
budget.bytes(descriptor.format.len())?;
|
||||
budget.doc(&descriptor.documentation)?;
|
||||
check(descriptor.types.len(), 256, ResourceLimit::TypeDeclarations)?;
|
||||
// Check collection counts before traversing even empty names/expressions.
|
||||
check(descriptor.operations.len(), 16_384, ResourceLimit::Nodes)?;
|
||||
for ty in &descriptor.types {
|
||||
budget.declaration(&ty.name, &ty.documentation)?;
|
||||
budget.expr(&ty.definition, 1)?;
|
||||
}
|
||||
for operation in &descriptor.operations {
|
||||
budget.declaration(&operation.name, &operation.documentation)?;
|
||||
check(operation.parameters.len(), 16_384, ResourceLimit::Nodes)?;
|
||||
for parameter in &operation.parameters {
|
||||
budget.declaration(¶meter.name, ¶meter.documentation)?;
|
||||
budget.expr(¶meter.r#type, 1)?;
|
||||
}
|
||||
budget.nodes(1)?; // Return declaration.
|
||||
budget.doc(&operation.returns.documentation)?;
|
||||
budget.expr(&operation.returns.r#type, 1)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
use std::fmt::Write as _;
|
||||
use wip_protocol::{Documentation, InterfaceReference, Object, OperationDeclaration, TypeExpr};
|
||||
|
||||
use crate::{Interface, Token, TokenKind};
|
||||
use TokenKind::{
|
||||
CaseName, FieldName, Indentation, Keyword, Newline, OperationName, ParameterName, Reference,
|
||||
Symbol, TypeName, Whitespace,
|
||||
};
|
||||
|
||||
// Quoting a component and quoting the complete reference are separate layers.
|
||||
fn reference(reference: &InterfaceReference) -> String {
|
||||
format!(
|
||||
"{}::{}",
|
||||
component(&reference.scope, true),
|
||||
component(&reference.name, false)
|
||||
)
|
||||
}
|
||||
|
||||
fn component(value: &str, scope: bool) -> String {
|
||||
if !value.is_empty()
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b) || (scope && b == b'/'))
|
||||
{
|
||||
value.into()
|
||||
} else {
|
||||
quote(value, '"')
|
||||
}
|
||||
}
|
||||
|
||||
fn identifier(value: &str) -> String {
|
||||
const KEYWORDS: &[&str] = &[
|
||||
"object",
|
||||
"at",
|
||||
"name",
|
||||
"description",
|
||||
"interfaces",
|
||||
"interface",
|
||||
"type",
|
||||
"operation",
|
||||
"enum",
|
||||
"union",
|
||||
"unit",
|
||||
"boolean",
|
||||
"integer",
|
||||
"number",
|
||||
"string",
|
||||
"bytes",
|
||||
"json",
|
||||
"entry",
|
||||
];
|
||||
if value
|
||||
.bytes()
|
||||
.next()
|
||||
.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
&& !KEYWORDS.contains(&value)
|
||||
{
|
||||
value.into()
|
||||
} else {
|
||||
quote(value, '`')
|
||||
}
|
||||
}
|
||||
|
||||
fn quote(value: &str, delimiter: char) -> String {
|
||||
let mut output = String::new();
|
||||
output.push(delimiter);
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'`' if delimiter == '`' => output.push_str("\\`"),
|
||||
'\\' => output.push_str("\\\\"),
|
||||
'"' => output.push_str("\\\""),
|
||||
'\u{08}' => output.push_str("\\b"),
|
||||
'\u{0c}' => output.push_str("\\f"),
|
||||
'\n' => output.push_str("\\n"),
|
||||
'\r' => output.push_str("\\r"),
|
||||
'\t' => output.push_str("\\t"),
|
||||
'\u{00}'..='\u{1f}'
|
||||
| '\u{7f}'..='\u{9f}'
|
||||
| '\u{2028}'
|
||||
| '\u{2029}'
|
||||
| '\u{061c}'
|
||||
| '\u{200e}'..='\u{200f}'
|
||||
| '\u{202a}'..='\u{202e}'
|
||||
| '\u{2066}'..='\u{2069}' => {
|
||||
write!(output, "\\u{:04x}", ch as u32).expect("String write");
|
||||
}
|
||||
_ => output.push(ch),
|
||||
}
|
||||
}
|
||||
output.push(delimiter);
|
||||
output
|
||||
}
|
||||
|
||||
pub(crate) fn object(object: &Object) -> Vec<Token> {
|
||||
let mut writer = Writer(Vec::new());
|
||||
writer.word(Keyword, "object");
|
||||
writer.space();
|
||||
writer.symbol("{");
|
||||
writer.newline();
|
||||
writer.indent(1);
|
||||
writer.word(Keyword, "name");
|
||||
writer.symbol(":");
|
||||
writer.space();
|
||||
writer.word(TokenKind::String, quote(&object.name, '"'));
|
||||
writer.symbol(";");
|
||||
writer.newline();
|
||||
if let Some(description) = &object.description {
|
||||
writer.indent(1);
|
||||
writer.word(Keyword, "description");
|
||||
writer.symbol(":");
|
||||
writer.space();
|
||||
writer.word(TokenKind::String, quote(description, '"'));
|
||||
writer.symbol(";");
|
||||
writer.newline();
|
||||
}
|
||||
writer.indent(1);
|
||||
writer.word(Keyword, "interfaces");
|
||||
writer.symbol(":");
|
||||
writer.space();
|
||||
writer.symbol("[");
|
||||
for (index, interface) in object.interfaces.iter().enumerate() {
|
||||
if index > 0 {
|
||||
writer.symbol(",");
|
||||
writer.space();
|
||||
}
|
||||
writer.word(Reference, quote(&reference(interface), '"'));
|
||||
}
|
||||
writer.symbol("]");
|
||||
writer.symbol(";");
|
||||
writer.newline();
|
||||
writer.symbol("}");
|
||||
writer.newline();
|
||||
writer.0
|
||||
}
|
||||
|
||||
pub(crate) fn interface(interface: &Interface<'_>) -> Vec<Token> {
|
||||
let mut writer = Writer(Vec::new());
|
||||
writer.doc(&interface.descriptor.documentation, 0);
|
||||
writer.word(Keyword, "interface");
|
||||
writer.space();
|
||||
writer.word(Reference, quote(&reference(interface.reference), '"'));
|
||||
writer.space();
|
||||
writer.symbol("{");
|
||||
writer.newline();
|
||||
for declaration in &interface.descriptor.types {
|
||||
writer.doc(&declaration.documentation, 1);
|
||||
writer.indent(1);
|
||||
writer.word(Keyword, "type");
|
||||
writer.space();
|
||||
writer.word(TypeName, identifier(&declaration.name));
|
||||
writer.space();
|
||||
writer.symbol("=");
|
||||
writer.space();
|
||||
writer.expr(&declaration.definition, 1);
|
||||
writer.symbol(";");
|
||||
writer.newline();
|
||||
}
|
||||
for operation in &interface.descriptor.operations {
|
||||
writer.operation(operation);
|
||||
}
|
||||
writer.symbol("}");
|
||||
writer.newline();
|
||||
writer.0
|
||||
}
|
||||
|
||||
struct Writer(Vec<Token>);
|
||||
|
||||
impl Writer {
|
||||
fn word(&mut self, kind: TokenKind, text: impl Into<String>) {
|
||||
self.0.push(Token {
|
||||
kind,
|
||||
text: text.into(),
|
||||
});
|
||||
}
|
||||
|
||||
fn symbol(&mut self, text: &str) {
|
||||
self.word(Symbol, text);
|
||||
}
|
||||
|
||||
fn space(&mut self) {
|
||||
self.word(Whitespace, " ");
|
||||
}
|
||||
|
||||
fn newline(&mut self) {
|
||||
self.word(Newline, "\n");
|
||||
}
|
||||
|
||||
fn indent(&mut self, depth: usize) {
|
||||
if depth > 0 {
|
||||
self.word(Indentation, " ".repeat(depth));
|
||||
}
|
||||
}
|
||||
|
||||
fn doc(&mut self, doc: &Option<Documentation>, depth: usize) {
|
||||
if let Some(doc) = doc {
|
||||
self.indent(depth);
|
||||
self.word(
|
||||
TokenKind::Documentation,
|
||||
format!("/// {}", quote(&doc.summary, '"')),
|
||||
);
|
||||
self.newline();
|
||||
}
|
||||
}
|
||||
|
||||
fn member(&mut self, kind: TokenKind, name: &str, required: bool, ty: &TypeExpr, depth: usize) {
|
||||
self.indent(depth);
|
||||
self.word(kind, identifier(name));
|
||||
if !required {
|
||||
self.symbol("?");
|
||||
}
|
||||
self.symbol(":");
|
||||
self.space();
|
||||
self.expr(ty, depth);
|
||||
self.symbol(",");
|
||||
self.newline();
|
||||
}
|
||||
|
||||
fn operation(&mut self, operation: &OperationDeclaration) {
|
||||
self.doc(&operation.documentation, 1);
|
||||
self.indent(1);
|
||||
self.word(Keyword, "operation");
|
||||
self.space();
|
||||
self.word(OperationName, identifier(&operation.name));
|
||||
self.symbol("(");
|
||||
if !operation.parameters.is_empty() {
|
||||
self.newline();
|
||||
for parameter in &operation.parameters {
|
||||
self.doc(¶meter.documentation, 2);
|
||||
self.member(
|
||||
ParameterName,
|
||||
¶meter.name,
|
||||
parameter.required,
|
||||
¶meter.r#type,
|
||||
2,
|
||||
);
|
||||
}
|
||||
self.indent(1);
|
||||
}
|
||||
self.symbol(")");
|
||||
if operation.returns.documentation.is_some() {
|
||||
self.newline();
|
||||
self.doc(&operation.returns.documentation, 1);
|
||||
self.indent(1);
|
||||
} else {
|
||||
self.space();
|
||||
}
|
||||
self.symbol("->");
|
||||
self.space();
|
||||
self.expr(&operation.returns.r#type, 1);
|
||||
self.symbol(";");
|
||||
self.newline();
|
||||
}
|
||||
|
||||
// Starts at the current cursor. Composite closing braces align with the
|
||||
// declaration/field/parameter containing this expression, not its width.
|
||||
fn expr(&mut self, expr: &TypeExpr, depth: usize) {
|
||||
match expr {
|
||||
TypeExpr::Unit => self.word(Keyword, "unit"),
|
||||
TypeExpr::Boolean => self.word(Keyword, "boolean"),
|
||||
TypeExpr::Integer => self.word(Keyword, "integer"),
|
||||
TypeExpr::Number => self.word(Keyword, "number"),
|
||||
TypeExpr::String => self.word(Keyword, "string"),
|
||||
TypeExpr::Bytes => self.word(Keyword, "bytes"),
|
||||
TypeExpr::Json => self.word(Keyword, "json"),
|
||||
TypeExpr::Entry => self.word(Keyword, "entry"),
|
||||
TypeExpr::Named { name } => self.word(TypeName, identifier(name)),
|
||||
TypeExpr::List { items } => {
|
||||
self.symbol("[");
|
||||
self.expr(items, depth);
|
||||
self.symbol("]");
|
||||
}
|
||||
TypeExpr::Record { fields } => {
|
||||
self.symbol("{");
|
||||
if !fields.is_empty() {
|
||||
self.newline();
|
||||
for field in fields {
|
||||
self.doc(&field.documentation, depth + 1);
|
||||
self.member(
|
||||
FieldName,
|
||||
&field.name,
|
||||
field.required,
|
||||
&field.r#type,
|
||||
depth + 1,
|
||||
);
|
||||
}
|
||||
self.indent(depth);
|
||||
}
|
||||
self.symbol("}");
|
||||
}
|
||||
TypeExpr::Enum { cases } => {
|
||||
self.word(Keyword, "enum");
|
||||
self.space();
|
||||
self.symbol("{");
|
||||
if !cases.is_empty() {
|
||||
self.newline();
|
||||
for case in cases {
|
||||
self.doc(&case.documentation, depth + 1);
|
||||
self.indent(depth + 1);
|
||||
self.word(CaseName, identifier(&case.name));
|
||||
self.symbol(",");
|
||||
self.newline();
|
||||
}
|
||||
self.indent(depth);
|
||||
}
|
||||
self.symbol("}");
|
||||
}
|
||||
TypeExpr::Union { cases } => {
|
||||
self.word(Keyword, "union");
|
||||
self.space();
|
||||
self.symbol("{");
|
||||
if !cases.is_empty() {
|
||||
self.newline();
|
||||
for case in cases {
|
||||
self.doc(&case.documentation, depth + 1);
|
||||
self.indent(depth + 1);
|
||||
self.word(CaseName, identifier(&case.name));
|
||||
if let Some(payload) = &case.payload {
|
||||
self.symbol("(");
|
||||
self.expr(payload, depth + 1);
|
||||
self.symbol(")");
|
||||
}
|
||||
self.symbol(",");
|
||||
self.newline();
|
||||
}
|
||||
self.indent(depth);
|
||||
}
|
||||
self.symbol("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
//! Owned display data, independent of the Protocol wire model.
|
||||
|
||||
/// Semantic display role assigned from the input structure, not from text parsing.
|
||||
///
|
||||
/// Identifiers retain their role even when quoted or identical to a keyword.
|
||||
/// Type declarations and Named expressions both use [`Self::TypeName`]. Enum and
|
||||
/// union cases both use [`Self::CaseName`]. See [`Token`] for splitting rules.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum TokenKind {
|
||||
/// Grammar keyword, including Object property labels and primitive types.
|
||||
Keyword,
|
||||
/// Named type declaration or reference within the same Interface.
|
||||
TypeName,
|
||||
/// Operation declaration name (not an invocation target).
|
||||
OperationName,
|
||||
/// Operation parameter name.
|
||||
ParameterName,
|
||||
/// Record field name.
|
||||
FieldName,
|
||||
/// Enum or union case name.
|
||||
CaseName,
|
||||
/// Quoted Object name or description.
|
||||
String,
|
||||
/// Entire quoted absolute Interface reference, including both quoting layers.
|
||||
Reference,
|
||||
/// Entire `/// "summary"` line content, excluding indentation and LF.
|
||||
Documentation,
|
||||
/// One punctuation mark, or the complete two-character return arrow `->`.
|
||||
Symbol,
|
||||
/// One inter-token ASCII space, never indentation or text inside quotes.
|
||||
Whitespace,
|
||||
/// One LF (`\n`), including the final signature LF.
|
||||
Newline,
|
||||
/// All leading spaces on a non-root line: two ASCII spaces per depth level.
|
||||
Indentation,
|
||||
}
|
||||
|
||||
/// One owned, already escaped fragment of a Text View signature.
|
||||
///
|
||||
/// Each keyword, identifier, quoted string and complete quoted reference is one
|
||||
/// token, including its delimiters and escapes. Documentation is one token for
|
||||
/// the `///` marker, space and quoted summary together. Symbols are individual
|
||||
/// punctuation marks except `->`, which is indivisible. Spaces between tokens,
|
||||
/// each LF, and each nonzero line indentation have separate tokens. No empty
|
||||
/// tokens are emitted; an empty value still has its quotes. Adjacent symbols are
|
||||
/// not merged. Host whitespace inside quoted data stays inside that data token.
|
||||
///
|
||||
/// The generation APIs emit all layout: concatenating [`Self::text`] in order,
|
||||
/// without separators, produces exactly the existing plain-text signature.
|
||||
/// Tokens own their text and can outlive the input; they are display data, not
|
||||
/// an AST, lexer output, Protocol serialization or identity/call-target data.
|
||||
///
|
||||
/// Text is escaped for **WIP Text View**, not for HTML or any other destination.
|
||||
/// Custom renderers must apply destination-specific escaping and must not treat
|
||||
/// Host documentation as markup or instructions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Token {
|
||||
pub(crate) kind: TokenKind,
|
||||
pub(crate) text: String,
|
||||
}
|
||||
|
||||
impl Token {
|
||||
/// Returns the semantic display role, without reparsing the output text.
|
||||
pub fn kind(&self) -> TokenKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// Returns the exact output fragment, with WIP quoting and escapes applied.
|
||||
pub fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
/// Concatenates token text in order, with no separators or further processing.
|
||||
///
|
||||
/// This performs no grammar interpretation, validation, quoting, escaping or
|
||||
/// layout completion. An empty slice yields an empty string. Filtering or
|
||||
/// reordering tokens is allowed, but need not produce a complete signature.
|
||||
/// Object/Interface generation limits are checked by [`crate::tokenize_object`]
|
||||
/// and [`crate::tokenize_interface`], not by this concatenation function.
|
||||
pub fn to_plain_text(tokens: &[Token]) -> String {
|
||||
tokens.iter().map(Token::text).collect()
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
interface "/::example" {
|
||||
type `string` = {
|
||||
`表示名`: string,
|
||||
};
|
||||
operation `find-item`(
|
||||
`search term`: string,
|
||||
) -> `string`;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/// "Issueの内容と関連項目を読む。"
|
||||
interface "/::issue.read" {
|
||||
type Relation = enum {
|
||||
parent,
|
||||
sibling,
|
||||
related,
|
||||
};
|
||||
type RelatedItems = {
|
||||
/// "同じWorldspace内の関連項目。"
|
||||
items: [entry],
|
||||
next_cursor?: string,
|
||||
};
|
||||
/// "本文を取得する。"
|
||||
operation read_body() -> {
|
||||
body: string,
|
||||
};
|
||||
/// "関係を指定して関連項目を取得する。"
|
||||
operation get_related_items(
|
||||
relation: Relation,
|
||||
limit?: integer,
|
||||
) -> RelatedItems;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
interface "/::example" {
|
||||
/// "type summary"
|
||||
type Z = {
|
||||
/// "field summary"
|
||||
z?: unit,
|
||||
a: [union {
|
||||
/// "case summary"
|
||||
z,
|
||||
/// ""
|
||||
a(unit),
|
||||
nested(enum {
|
||||
/// "enum summary"
|
||||
z,
|
||||
a,
|
||||
}),
|
||||
}],
|
||||
};
|
||||
operation z(
|
||||
z: unit,
|
||||
a?: unit,
|
||||
) -> unit;
|
||||
operation a()
|
||||
/// "no params result"
|
||||
-> unit;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
object {
|
||||
name: "123";
|
||||
description: "Issue 123の公開操作。本文はOperationで取得する。";
|
||||
interfaces: ["/::issue.read", "/::issue.lifecycle"];
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
interface "/::example" {
|
||||
type CloseResult = union {
|
||||
closed,
|
||||
blocked({
|
||||
dependencies: [entry],
|
||||
}),
|
||||
};
|
||||
operation refresh() -> unit;
|
||||
/// "対象を検索する。"
|
||||
operation search(
|
||||
/// "検索語。"
|
||||
query: string,
|
||||
)
|
||||
/// "条件に一致する項目。"
|
||||
-> {
|
||||
items: [entry],
|
||||
};
|
||||
}
|
||||
+1056
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user