feat: add explicit protocol API and mutable playground host

This commit is contained in:
2026-10-19 18:21:21 +09:00
parent 1297d86140
commit b82c1d0a70
10 changed files with 1729 additions and 26 deletions
+2 -1
View File
@@ -14,6 +14,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
wip-client = { path = "../../../wip-rs/crates/wip-client", default-features = false }
wip-protocol = { path = "../../../wip-rs/crates/wip-protocol" }
wip-text-view = { path = "../../../wip-rs/crates/wip-text-view" }
wip-site-worldspace = { path = "../worldspace" }
serde_json = "1"
serde_json = { version = "1", features = ["float_roundtrip"] }
wasm-bindgen = "=0.2.121"
+7
View File
@@ -1,4 +1,6 @@
//! Browser-owned Client/Host session. JS conversion is outside the direct WIP exchange.
mod manual;
use std::collections::BTreeMap;
use serde_json::{Value as Json, json};
@@ -76,6 +78,11 @@ impl BrowserSession {
let mut paths = Vec::new();
let mut pending = vec!["/".to_owned()];
while let Some(path) = pending.pop() {
// Normal document navigation is manifest-only. Dynamic Protocol Objects
// do not implement document.read and have no display path or Web URL.
if !self.display_paths.contains_key(&path) {
continue;
}
if let Some(tree) = self.client.tree(&self.session, &path) {
pending.extend(tree.children.iter().rev().cloned());
}
+453
View File
@@ -0,0 +1,453 @@
//! Explicit protocol API. Only Client-accepted state is projected; no document map reads.
#[cfg(test)]
mod playground_tests;
#[cfg(test)]
mod tests;
use super::*;
use wip_client::{CallOutcome, ClientError, Completion, ObservationState};
use wip_protocol::{Documentation, InterfaceDescriptor, Object, ProtocolError, TypeExpr};
const MAX_TEXT_BYTES: usize = 4096;
const MAX_ARGUMENT_BYTES: usize = 64 * 1024;
const MAX_VALUE_NODES: usize = 4096;
const MAX_VALUE_DEPTH: usize = 32;
#[derive(Debug)]
struct ManualError {
kind: &'static str,
message: String,
code: Option<String>,
}
impl ManualError {
fn new(kind: &'static str, message: impl ToString) -> Self {
Self {
kind,
message: message.to_string(),
code: None,
}
}
fn input(message: impl ToString) -> Self {
Self::new("input", message)
}
fn client(error: ClientError) -> Self {
Self {
kind: "client",
message: error.to_string(),
code: Some(format!("{:?}", error.kind)),
}
}
fn protocol(error: ProtocolError) -> Self {
Self {
kind: "protocol",
message: error.message,
code: Some(format!("{:?}", error.code)),
}
}
fn js(self) -> JsValue {
let mut dto = json!({"kind": self.kind, "message": self.message});
if let Some(code) = self.code {
dto["code"] = json!(code);
}
JsValue::from_str(&dto.to_string())
}
}
type Result<T> = std::result::Result<T, ManualError>;
#[wasm_bindgen]
impl BrowserSession {
/// Explicit Observe only. `depth` must be an integer in 0..=32, not a JS-coerced u32.
/// The signature describes the root Object; children remain structured observation data.
pub fn observe(&mut self, path: &str, depth: f64) -> std::result::Result<String, JsValue> {
self.manual_observe(path, depth)
.map(|value| value.to_string())
.map_err(ManualError::js)
}
/// Explicit FetchInterface only, independent of any Object target.
pub fn fetch_interface(
&mut self,
scope: &str,
name: &str,
) -> std::result::Result<String, JsValue> {
self.manual_interface(scope, name)
.map(|value| value.to_string())
.map_err(ManualError::js)
}
/// Explicit call. Never observes, fetches, retries, or converts result data to a signature.
/// Arguments are a parameter-name map of tagged Values; `{}` means no arguments.
pub fn call_operation(
&mut self,
path: &str,
scope: &str,
name: &str,
operation: &str,
args_json: &str,
) -> std::result::Result<String, JsValue> {
self.manual_call(path, scope, name, operation, args_json)
.map(|value| value.to_string())
.map_err(ManualError::js)
}
}
impl BrowserSession {
fn manual_stats(&self) -> Json {
json!({"observes": self.observes, "interfaces": self.interfaces, "calls": self.calls})
}
// Same normal Host dispatch boundary as the existing composite APIs. Responses
// are correlated and validated before anything is exposed to JS.
fn manual_exchange(
&mut self,
request: wip_client::direct::PreparedRequest,
) -> Result<Completion> {
let id = request.id;
let response = match request.request {
Request::Observe(request) => {
self.observes += 1;
Response::Observe(self.world.observe(request))
}
Request::FetchInterface(request) => {
self.interfaces += 1;
Response::FetchInterface(self.world.fetch_interface(request))
}
Request::CallOperation(request) => {
self.client
.mark_dispatched(id)
.map_err(ManualError::client)?;
self.calls += 1;
Response::CallOperation(self.world.call_operation(request))
}
};
match self
.client
.complete(id, response)
.map_err(ManualError::client)?
{
Completion::ProtocolFailure(failure) => Err(ManualError::protocol(failure)),
completion => Ok(completion),
}
}
fn manual_observe(&mut self, path: &str, depth: f64) -> Result<Json> {
bounded_text(path)?;
if !depth.is_finite() || depth.fract() != 0.0 || !(0.0..=32.0).contains(&depth) {
return Err(ManualError::input("depth must be an integer in 0..=32"));
}
let depth = depth as u32;
// The current Client exposes explicit refresh, not public subtree
// invalidation. Playground Observe is a deliberate fresh retrieval,
// including retained NotFound/stale children after remove/recreate. No
// operation is retried, no result is used as observation data, and the
// immutable documents retain their existing ensure/cache behavior.
let playground = self.display_paths.contains_key("/playground")
&& (path == "/playground" || path.starts_with("/playground/"));
let prepared = if playground {
Some(
self.client
.refresh_observed(&self.session, path, depth)
.map_err(ManualError::client)?,
)
} else {
self.client
.ensure_observed(&self.session, path, depth)
.map_err(ManualError::client)?
};
let cached = prepared.is_none();
if let Some(request) = prepared {
self.manual_exchange(request)?;
}
// ensure_* can also return None for retained errors/capacity, not only hits.
// Reconstruct requested coverage from fresh Client state, never from Host data.
let observation = self.manual_observation(path, depth)?;
let object = self.fresh_object(path)?;
let text =
wip_text_view::render_object(&object).map_err(|e| ManualError::new("render", e))?;
Ok(
json!({"path": path, "observation": observation, "textView": text, "cached": cached, "stats": self.manual_stats()}),
)
}
fn fresh_object(&self, path: &str) -> Result<Object> {
let entry = self
.client
.object(&self.session, path)
.ok_or_else(missing_observation)?;
fresh(&entry.state)?;
entry.object.ok_or_else(missing_observation)
}
fn manual_observation(&self, path: &str, depth: u32) -> Result<Json> {
let object = self.fresh_object(path)?;
let children = if depth == 0 {
Json::Null
} else {
let tree = self
.client
.tree(&self.session, path)
.ok_or_else(missing_observation)?;
fresh(&tree.state)?;
Json::Array(
tree.children
.iter()
.map(|child| self.manual_observation(child, depth - 1))
.collect::<Result<Vec<_>>>()?,
)
};
Ok(json!({"object": object_json(&object), "children": children}))
}
fn manual_interface(&mut self, scope: &str, name: &str) -> Result<Json> {
bounded_text(scope)?;
bounded_text(name)?;
let reference = InterfaceReference {
scope: scope.into(),
name: name.into(),
};
let prepared = self
.client
.ensure_interface(&self.session, reference.clone())
.map_err(ManualError::client)?;
let cached = prepared.is_none();
if let Some(request) = prepared {
self.manual_exchange(request)?;
}
let observation = self
.client
.interface(&self.session, &reference)
.ok_or_else(missing_observation)?;
fresh(&observation.state)?;
let descriptor = observation
.descriptor
.as_ref()
.ok_or_else(missing_observation)?;
let text = wip_text_view::render_interface(&wip_text_view::Interface {
reference: &reference,
descriptor,
})
.map_err(|e| ManualError::new("render", e))?;
Ok(
json!({"reference": reference_json(&reference), "descriptor": descriptor_json(descriptor), "textView": text, "cached": cached, "stats": self.manual_stats()}),
)
}
fn manual_call(
&mut self,
path: &str,
scope: &str,
name: &str,
operation: &str,
args_json: &str,
) -> Result<Json> {
for text in [path, scope, name, operation] {
bounded_text(text)?;
}
let args = arguments(args_json)?;
let reference = InterfaceReference {
scope: scope.into(),
name: name.into(),
};
let prepared = self
.client
.prepare_call(&self.session, path, &reference, operation, args)
.map_err(ManualError::client)?;
let request_id = prepared.id;
let completion = self.manual_exchange(prepared)?;
let Completion::Call(record) = completion else {
return Err(missing_observation());
};
// Consume this exact completion, never the last unrelated history entry.
if record.request_id != request_id {
return Err(ManualError::new("client", "call correlation mismatch"));
}
match record.outcome {
CallOutcome::Success(response) => Ok(
json!({"path": path, "interface": reference_json(&reference), "operation": operation, "result": tagged_value(response.result), "stats": self.manual_stats()}),
),
CallOutcome::ProtocolFailure(failure) => Err(ManualError::protocol(failure)),
CallOutcome::NotDispatched(failure) => Err(ManualError::client(failure)),
CallOutcome::Unknown { reason, failure } => Err(ManualError {
kind: "client",
message: format!(
"operation outcome unknown ({reason:?}): {failure:?}; do not retry automatically"
),
code: Some("OperationOutcomeUnknown".into()),
}),
}
}
}
fn missing_observation() -> ManualError {
ManualError {
kind: "client",
message: "fresh observation or requested coverage unavailable".into(),
code: Some("MissingObservation".into()),
}
}
fn fresh(state: &ObservationState) -> Result<()> {
match state {
ObservationState::Fresh => Ok(()),
ObservationState::Error(error) => Err(ManualError::client(error.clone())),
_ => Err(missing_observation()),
}
}
fn bounded_text(text: &str) -> Result<()> {
if text.len() > MAX_TEXT_BYTES {
Err(ManualError::input(
"path, scope, name and operation are limited to 4096 UTF-8 bytes each",
))
} else {
Ok(())
}
}
fn reference_json(reference: &InterfaceReference) -> Json {
json!({"scope": reference.scope, "name": reference.name})
}
fn object_json(object: &Object) -> Json {
json!({"name": object.name, "description": object.description, "interfaces": object.interfaces.iter().map(reference_json).collect::<Vec<_>>(), "ref": object.r#ref, "validator": object.validator})
}
fn documentation_json(documentation: &Option<Documentation>) -> Json {
documentation
.as_ref()
.map(|d| json!({"summary": d.summary, "details": d.details}))
.unwrap_or(Json::Null)
}
fn descriptor_json(descriptor: &InterfaceDescriptor) -> Json {
json!({
"format": descriptor.format,
"documentation": documentation_json(&descriptor.documentation),
"types": descriptor.types.iter().map(|t| json!({"name": t.name, "documentation": documentation_json(&t.documentation), "definition": type_json(&t.definition)})).collect::<Vec<_>>(),
"operations": descriptor.operations.iter().map(|o| json!({"name": o.name, "documentation": documentation_json(&o.documentation), "parameters": o.parameters.iter().map(|p| json!({"name": p.name, "required": p.required, "documentation": documentation_json(&p.documentation), "type": type_json(&p.r#type)})).collect::<Vec<_>>(), "returns": {"documentation": documentation_json(&o.returns.documentation), "type": type_json(&o.returns.r#type)}})).collect::<Vec<_>>()
})
}
fn type_json(value: &TypeExpr) -> Json {
match value {
TypeExpr::Unit => json!({"kind": "unit"}),
TypeExpr::Boolean => json!({"kind": "boolean"}),
TypeExpr::Integer => json!({"kind": "integer"}),
TypeExpr::Number => json!({"kind": "number"}),
TypeExpr::String => json!({"kind": "string"}),
TypeExpr::Bytes => json!({"kind": "bytes"}),
TypeExpr::Json => json!({"kind": "json"}),
TypeExpr::Entry => json!({"kind": "entry"}),
TypeExpr::Named { name } => json!({"kind": "named", "name": name}),
TypeExpr::List { items } => json!({"kind": "list", "items": type_json(items)}),
TypeExpr::Record { fields } => {
json!({"kind": "record", "fields": fields.iter().map(|f| json!({"name": f.name, "required": f.required, "documentation": documentation_json(&f.documentation), "type": type_json(&f.r#type)})).collect::<Vec<_>>()})
}
TypeExpr::Enum { cases } => {
json!({"kind": "enum", "cases": cases.iter().map(|c| json!({"name": c.name, "documentation": documentation_json(&c.documentation)})).collect::<Vec<_>>()})
}
TypeExpr::Union { cases } => {
json!({"kind": "union", "cases": cases.iter().map(|c| json!({"name": c.name, "documentation": documentation_json(&c.documentation), "payload": c.payload.as_ref().map(type_json)})).collect::<Vec<_>>()})
}
}
}
fn tagged_value(value: Value) -> Json {
match value {
Value::Unit => json!({"kind": "unit"}),
Value::Boolean(value) => json!({"kind": "boolean", "value": value}),
Value::Integer(value) => json!({"kind": "integer", "value": value.to_string()}),
Value::Number(value) => json!({"kind": "number", "value": value}),
Value::String(value) => json!({"kind": "string", "value": value}),
Value::Bytes(value) => json!({"kind": "bytes", "value": value}),
Value::Record(value) => {
json!({"kind": "record", "value": value.into_iter().map(|(k,v)| (k,tagged_value(v))).collect::<serde_json::Map<_,_>>()})
}
Value::List(value) => {
json!({"kind": "list", "value": value.into_iter().map(tagged_value).collect::<Vec<_>>()})
}
}
}
fn arguments(input: &str) -> Result<BTreeMap<String, Value>> {
if input.len() > MAX_ARGUMENT_BYTES {
return Err(ManualError::input("arguments exceed 65536 UTF-8 bytes"));
}
// serde_json's recursion limit stays enabled, bounding parsing before our tighter Value limits.
let parsed: Json = serde_json::from_str(input).map_err(ManualError::input)?;
let map = parsed.as_object().ok_or_else(|| {
ManualError::input("arguments must be an object mapping parameter names to tagged Values")
})?;
let mut budget = MAX_VALUE_NODES;
map.iter()
.map(|(name, value)| Ok((name.clone(), parse_value(value, 1, &mut budget)?)))
.collect()
}
fn parse_value(input: &Json, depth: usize, budget: &mut usize) -> Result<Value> {
if depth > MAX_VALUE_DEPTH || *budget == 0 {
return Err(ManualError::input("Values exceed depth 32 or 4096 nodes"));
}
*budget -= 1;
let invalid = || {
ManualError::input(
"invalid tagged Value: expected kind and correctly typed value (unit has no value)",
)
};
let object = input.as_object().ok_or_else(invalid)?;
let kind = object
.get("kind")
.and_then(Json::as_str)
.ok_or_else(invalid)?;
if kind == "unit" {
return if object.len() == 1 {
Ok(Value::Unit)
} else {
Err(invalid())
};
}
if object.len() != 2 {
return Err(invalid());
}
let value = object.get("value").ok_or_else(invalid)?;
Ok(match kind {
"boolean" => Value::Boolean(value.as_bool().ok_or_else(invalid)?),
"integer" => {
let text = value.as_str().ok_or_else(invalid)?;
let integer: i64 = text.parse().map_err(|_| invalid())?;
if integer.to_string() != text {
return Err(ManualError::input(
"integer requires a canonical signed decimal string",
));
}
Value::Integer(integer)
}
"number" => Value::Number(
value
.as_f64()
.filter(|v| v.is_finite())
.ok_or_else(invalid)?,
),
"string" => Value::String(value.as_str().ok_or_else(invalid)?.to_owned()),
"bytes" => Value::Bytes(
value
.as_array()
.ok_or_else(invalid)?
.iter()
.map(|v| {
v.as_u64()
.and_then(|v| u8::try_from(v).ok())
.ok_or_else(invalid)
})
.collect::<Result<_>>()?,
),
"record" => Value::Record(
value
.as_object()
.ok_or_else(invalid)?
.iter()
.map(|(k, v)| Ok((k.clone(), parse_value(v, depth + 1, budget)?)))
.collect::<Result<_>>()?,
),
"list" => Value::List(
value
.as_array()
.ok_or_else(invalid)?
.iter()
.map(|v| parse_value(v, depth + 1, budget))
.collect::<Result<_>>()?,
),
_ => return Err(invalid()),
})
}
+243
View File
@@ -0,0 +1,243 @@
use super::*;
fn manifest() -> String {
json!({"nodes":[
{"path":"/","name":"","displayPath":"/","title":"Root","href":"/","html":"<p>root</p>"},
{"path":"/book","name":"book","parent":"/","displayPath":"/book","title":"Book","href":"/book/","html":"<p>book</p>"},
{"path":"/playground","name":"playground","parent":"/","displayPath":"/playground","title":"Playground","href":"/playground/","html":"<p>playground</p>"}
]}).to_string()
}
fn session() -> BrowserSession {
BrowserSession::new(&manifest()).unwrap()
}
fn increment(s: &mut BrowserSession, amount: i64) -> Result<Json> {
s.manual_call(
"/playground/apple",
"/",
"counter",
"increment",
&json!({"amount":{"kind":"integer","value":amount.to_string()}}).to_string(),
)
}
fn collection(s: &mut BrowserSession, operation: &str, name: &str) -> Result<Json> {
s.manual_call(
"/playground",
"/",
"collection",
operation,
&json!({"name":{"kind":"string","value":name}}).to_string(),
)
}
fn names(observed: &Json) -> Vec<&str> {
observed["observation"]["children"]
.as_array()
.unwrap()
.iter()
.map(|child| child["object"]["name"].as_str().unwrap())
.collect()
}
#[test]
fn explicit_observe_refreshes_counter_and_parent_but_does_not_retry_or_fill_interfaces() {
let mut s = session();
s.manual_observe("/book", 1.0).unwrap();
let initial = s.manual_observe("/playground", 1.0).unwrap();
assert_eq!(names(&initial), ["apple", "orange"]);
assert_eq!(
initial["observation"]["children"][0]["object"]["description"],
"3"
);
assert!(
increment(&mut s, 4).is_err(),
"descriptor fetch remains explicit"
);
assert_eq!(s.calls, 0);
s.manual_interface("/", "counter").unwrap();
let stats = s.manual_stats();
let result = increment(&mut s, 4).unwrap();
assert_eq!(result["result"], json!({"kind":"integer","value":"7"}));
assert!(result.get("observation").is_none());
assert!(result.get("textView").is_none());
assert_eq!(s.observes, stats["observes"].as_u64().unwrap() as u32);
assert_eq!(s.interfaces, stats["interfaces"].as_u64().unwrap() as u32);
// A result did not silently fabricate a refreshed Client Object.
assert_eq!(
s.client
.object(&s.session, "/playground/apple")
.unwrap()
.object
.unwrap()
.description
.as_deref(),
Some("3")
);
let parent = s.manual_observe("/playground", 1.0).unwrap();
assert_eq!(parent["cached"], false);
assert_eq!(
parent["observation"]["children"][0]["object"]["name"],
"apple"
);
assert_eq!(
parent["observation"]["children"][0]["object"]["description"],
"7"
);
let selected = s.manual_observe("/playground/apple", 1.0).unwrap();
assert_eq!(selected["cached"], false);
assert_eq!(selected["observation"]["object"]["description"], "7");
assert_eq!(
selected["textView"],
wip_text_view::render_object(&s.fresh_object("/playground/apple").unwrap()).unwrap()
);
assert_eq!(s.manual_observe("/book", 1.0).unwrap()["cached"], true);
assert_eq!(s.manual_interface("/", "counter").unwrap()["cached"], true);
assert_eq!(s.calls, 1);
}
#[test]
fn collection_refresh_removes_stale_children_and_recovers_from_retained_not_found() {
let mut s = session();
s.manual_observe("/playground", 2.0).unwrap();
s.manual_interface("/", "collection").unwrap();
s.manual_interface("/", "counter").unwrap();
assert_eq!(
collection(&mut s, "create", "pear").unwrap()["result"],
json!({"kind":"unit"})
);
assert_eq!(
names(&s.manual_observe("/playground", 1.0).unwrap()),
["apple", "orange", "pear"]
);
collection(&mut s, "remove", "apple").unwrap();
assert_eq!(
names(&s.manual_observe("/playground", 1.0).unwrap()),
["orange", "pear"]
);
assert_eq!(
s.manual_observe("/playground/apple", 1.0)
.unwrap_err()
.code
.as_deref(),
Some("NotFound")
);
collection(&mut s, "create", "apple").unwrap();
// Explicit fresh refresh recovers even from a retained Client NotFound.
let selected = s.manual_observe("/playground/apple", 1.0).unwrap();
assert_eq!(selected["observation"]["object"]["description"], "0");
assert_eq!(
names(&s.manual_observe("/playground", 1.0).unwrap()),
["apple", "orange", "pear"]
);
assert_eq!(increment(&mut s, 2).unwrap()["result"]["value"], "2");
s.manual_observe("/playground", 1.0).unwrap();
s.manual_call("/playground/apple", "/", "counter", "reset", "{}")
.unwrap();
assert_eq!(
s.manual_observe("/playground", 1.0).unwrap()["observation"]["children"][0]["object"]["description"],
"0"
);
}
#[test]
fn failures_are_atomic_and_each_explicit_call_dispatches_at_most_once() {
let mut s = session();
s.manual_observe("/playground", 2.0).unwrap();
s.manual_interface("/", "counter").unwrap();
s.manual_interface("/", "collection").unwrap();
increment(&mut s, wip_protocol::MAX_SAFE_INTEGER - 3).unwrap();
let maximum = s.manual_observe("/playground/apple", 1.0).unwrap();
let calls = s.calls;
let failure = increment(&mut s, 1).unwrap_err();
assert_eq!(failure.kind, "protocol");
assert_eq!(failure.code.as_deref(), Some("Internal"));
assert_eq!(s.calls, calls + 1);
assert_eq!(
s.manual_observe("/playground/apple", 1.0).unwrap()["observation"],
maximum["observation"]
);
for name in ["apple", "bad/name", "<img>", ""] {
let before = s.manual_observe("/playground", 1.0).unwrap();
let calls = s.calls;
assert!(collection(&mut s, "create", name).is_err());
assert_eq!(s.calls, calls + 1);
assert_eq!(
s.manual_observe("/playground", 1.0).unwrap()["observation"],
before["observation"]
);
}
let calls = s.calls;
assert!(increment(&mut s, i64::MAX).is_err());
assert_eq!(
s.calls, calls,
"out-of-range typed arguments rejected before Host dispatch"
);
}
#[test]
fn normal_tree_and_document_reads_ignore_dynamic_children_and_reload_resets_state() {
let mut s = session();
let tree = s.tree().unwrap();
let rows: Json = serde_json::from_str(&tree).unwrap();
assert_eq!(
rows.as_array()
.unwrap()
.iter()
.map(|row| row["path"].as_str().unwrap())
.collect::<Vec<_>>(),
["/", "/book", "/playground"]
);
let document = s.read("/playground").unwrap();
let book = s.read("/book").unwrap();
s.manual_interface("/", "counter").unwrap();
s.manual_interface("/", "collection").unwrap();
increment(&mut s, 10).unwrap();
collection(&mut s, "create", "pear").unwrap();
collection(&mut s, "remove", "orange").unwrap();
s.manual_observe("/playground", 1.0).unwrap();
assert_eq!(s.tree().unwrap(), tree);
assert_eq!(s.read("/playground").unwrap(), document);
assert_eq!(s.read("/book").unwrap(), book);
assert_eq!(
s.manual_observe("/playground/apple", 1.0).unwrap()["observation"]["object"]["description"],
"13",
"navigation does not reset state"
);
let mut reloaded = session();
let initial = reloaded.manual_observe("/playground", 1.0).unwrap();
assert_eq!(names(&initial), ["apple", "orange"]);
assert_eq!(
initial["observation"]["children"][0]["object"]["description"],
"3"
);
assert_eq!(
initial["observation"]["children"][1]["object"]["description"],
"0"
);
}
#[test]
fn old_manifests_do_not_enable_playground_or_change_cached_observation_behavior() {
let mut data: Json = serde_json::from_str(&manifest()).unwrap();
data["nodes"].as_array_mut().unwrap().pop();
let mut s = BrowserSession::new(&data.to_string()).unwrap();
assert_eq!(
s.manual_observe("/playground", 1.0)
.unwrap_err()
.code
.as_deref(),
Some("NotFound")
);
let stats = s.manual_stats();
assert_eq!(
s.manual_observe("/playground", 1.0).unwrap_err().kind,
"client"
);
assert_eq!(s.manual_stats(), stats);
for name in ["collection", "counter"] {
assert_eq!(
s.manual_interface("/", name).unwrap_err().code.as_deref(),
Some("InterfaceNotFound")
);
}
s.manual_observe("/", 1.0).unwrap();
assert_eq!(s.manual_observe("/", 1.0).unwrap()["cached"], true);
}
+326
View File
@@ -0,0 +1,326 @@
use super::*;
fn manifest() -> String {
json!({"nodes": [
{"path":"/", "name":"", "displayPath":"/", "title":"Root", "href":"/", "html":"<p>root body</p>"},
{"path":"/quoted", "name":"quoted", "displayPath":"/quoted", "parent":"/", "title":" 引用 \"quote\" \\ space\nnext\tline ", "href":"/quoted/", "html":"<script>not executed</script>"}
]}).to_string()
}
fn session() -> BrowserSession {
BrowserSession::new(&manifest()).unwrap()
}
#[test]
fn manual_exchanges_do_not_read_until_explicit_call_and_cache_only_fresh_state() {
let mut s = session();
let observed = s.manual_observe("/", 1.0).unwrap();
assert_eq!(
observed["stats"],
json!({"observes":1,"interfaces":0,"calls":0})
);
assert_eq!(observed["cached"], false);
assert_eq!(
observed["observation"]["children"][0]["children"],
Json::Null
);
assert!(!observed.to_string().contains("root body"));
let cached = s.manual_observe("/", 1.0).unwrap();
assert_eq!(cached["observation"], observed["observation"]);
assert_eq!(cached["cached"], true);
assert_eq!(cached["stats"], observed["stats"]);
let deeper = s.manual_observe("/", 2.0).unwrap();
assert_eq!(deeper["cached"], false);
assert_eq!(deeper["observation"]["children"][0]["children"], json!([]));
let fetched = s.manual_interface("/", "document").unwrap();
assert_eq!(
fetched["stats"],
json!({"observes":2,"interfaces":1,"calls":0})
);
assert_eq!(fetched["cached"], false);
assert!(!fetched.to_string().contains("root body"));
assert_eq!(s.manual_interface("/", "document").unwrap()["cached"], true);
let result = s
.manual_call("/quoted", "/", "document", "read", "{}")
.unwrap();
assert_eq!(
result["stats"],
json!({"observes":2,"interfaces":1,"calls":1})
);
assert_eq!(result["path"], "/quoted");
assert_eq!(result["interface"], json!({"scope":"/", "name":"document"}));
assert_eq!(result["result"]["kind"], "record");
assert_eq!(
result["result"]["value"]["path"],
json!({"kind":"string","value":"/quoted"})
);
assert_eq!(
result["result"]["value"]["html"],
json!({"kind":"string","value":"<script>not executed</script>"})
);
assert!(result.get("textView").is_none());
s.manual_call("/quoted", "/", "document", "read", "{}")
.unwrap();
assert_eq!(s.calls, 2);
}
#[test]
fn calls_do_not_fill_preconditions_or_retry_failures() {
let mut s = session();
let error = s
.manual_call("/", "/", "document", "read", "{}")
.unwrap_err();
assert_eq!(error.kind, "client");
assert_eq!(error.code.as_deref(), Some("MissingObservation"));
assert_eq!(
s.manual_stats(),
json!({"observes":0,"interfaces":0,"calls":0})
);
s.manual_observe("/", 0.0).unwrap();
assert_eq!(
s.manual_call("/", "/", "document", "read", "{}")
.unwrap_err()
.code
.as_deref(),
Some("MissingObservation")
);
assert_eq!(s.interfaces, 0);
s.manual_interface("/", "document").unwrap();
for (name, operation, args) in [
("document", "missing", "{}"),
("other", "read", "{}"),
(
"document",
"read",
r#"{"extra":{"kind":"string","value":"x"}}"#,
),
] {
assert_eq!(
s.manual_call("/", "/", name, operation, args)
.unwrap_err()
.kind,
"client"
);
}
assert_eq!(s.calls, 0);
assert_eq!(
s.manual_observe("/absent", 0.0)
.unwrap_err()
.code
.as_deref(),
Some("NotFound")
);
assert_eq!(
s.manual_interface("/", "absent")
.unwrap_err()
.code
.as_deref(),
Some("InterfaceNotFound")
);
let stats = s.manual_stats();
assert_eq!(s.manual_observe("/absent", 0.0).unwrap_err().kind, "client");
assert_eq!(
s.manual_interface("/", "absent").unwrap_err().kind,
"client"
);
assert_eq!(
s.manual_stats(),
stats,
"retained failures are not cache successes or retries"
);
}
#[test]
fn fetch_is_independent_and_sessions_do_not_share_observations() {
let mut normal = session();
normal.tree().unwrap();
let mut manual = session();
let fetch = manual.manual_interface("/", "document").unwrap();
assert_eq!(
fetch["stats"],
json!({"observes":0,"interfaces":1,"calls":0})
);
assert_eq!(
manual
.manual_call("/", "/", "document", "read", "{}")
.unwrap_err()
.code
.as_deref(),
Some("MissingObservation")
);
assert_eq!(manual.calls, 0);
manual.manual_observe("/", 0.0).unwrap();
assert_eq!(
manual
.manual_call("/", "/", "document", "read", "{}")
.unwrap()["result"]["value"]["path"]["value"],
"/"
);
}
#[test]
fn signatures_are_real_renderer_output_and_exclude_metadata() {
let mut s = session();
let observed = s.manual_observe("/quoted", 0.0).unwrap();
let mut object = s.fresh_object("/quoted").unwrap();
assert_eq!(
observed["textView"],
wip_text_view::render_object(&object).unwrap()
);
let text = observed["textView"].as_str().unwrap();
assert!(text.contains("引用 \\\"quote\\\" \\\\ space\\nnext\\tline "));
assert!(text.ends_with("}\n"));
object.r#ref = Some("secret metadata".into());
object.validator = Some(vec![1, 2, 3]);
assert_eq!(
observed["textView"],
wip_text_view::render_object(&object).unwrap()
);
let fetched = s.manual_interface("/", "document").unwrap();
let reference = Worldspace::document_interface();
let observation = s.client.interface(&s.session, &reference).unwrap();
let descriptor = observation.descriptor.as_ref().unwrap();
assert_eq!(
fetched["textView"],
wip_text_view::render_interface(&wip_text_view::Interface {
reference: &reference,
descriptor
})
.unwrap()
);
assert_eq!(fetched["descriptor"]["operations"][0]["name"], "read");
assert_eq!(
fetched["descriptor"]["operations"][0]["parameters"],
json!([])
);
}
#[test]
fn all_tagged_values_round_trip_without_integer_or_bytes_coercion() {
let values = vec![
Value::Unit,
Value::Boolean(true),
Value::Integer(i64::MIN),
Value::Integer(i64::MAX),
Value::Number(-0.0),
Value::Number(1.25),
Value::String("引用\n\t\"".into()),
Value::Bytes(vec![0, 255]),
Value::Record(BTreeMap::from([("__proto__".into(), Value::Integer(1))])),
Value::List(vec![Value::Unit, Value::String("x".into())]),
];
for value in values {
let dto = tagged_value(value.clone());
let encoded = json!({"arg": dto}).to_string();
let parsed = arguments(&encoded).unwrap();
assert_eq!(parsed["arg"], value);
if let Value::Number(n) = value {
let Value::Number(actual) = parsed["arg"] else {
panic!()
};
assert_eq!(n.to_bits(), actual.to_bits());
}
}
assert_eq!(arguments("{}").unwrap(), BTreeMap::new());
for input in [
"null",
"[]",
"{",
r#"{"x":1}"#,
r#"{"x":{"kind":"integer","value":9007199254740993}}"#,
r#"{"x":{"kind":"integer","value":"01"}}"#,
r#"{"x":{"kind":"bytes","value":[256]}}"#,
r#"{"x":{"kind":"unit","value":null}}"#,
r#"{"x":{"kind":"number","value":1e400}}"#,
r#"{"x":{"kind":"unknown"}}"#,
] {
assert_eq!(arguments(input).unwrap_err().kind, "input", "{input}");
}
// DTO conversion can represent all i64, but Protocol Integer remains JS-safe.
let descriptor = Worldspace::new(serde_json::from_str(&manifest()).unwrap())
.unwrap()
.fetch_interface(wip_protocol::FetchInterfaceRequest {
interface: Worldspace::document_interface(),
})
.unwrap()
.descriptor;
assert!(
descriptor
.validate_value(&TypeExpr::Integer, &Value::Integer(i64::MAX))
.is_err()
);
}
#[test]
fn bounds_fail_before_dispatch_and_render_failures_are_distinct() {
let mut s = session();
for depth in [-1.0, 0.5, 33.0, f64::NAN, f64::INFINITY, 4294967296.0] {
assert_eq!(s.manual_observe("/", depth).unwrap_err().kind, "input");
}
assert_eq!(
s.manual_observe(&"/".repeat(MAX_TEXT_BYTES + 1), 0.0)
.unwrap_err()
.kind,
"input"
);
assert_eq!(
s.manual_observe("relative", 0.0).unwrap_err().kind,
"client"
);
assert_eq!(
arguments(&" ".repeat(MAX_ARGUMENT_BYTES + 1))
.unwrap_err()
.kind,
"input"
);
let mut nested = json!({"kind":"unit"});
for _ in 0..MAX_VALUE_DEPTH {
nested = json!({"kind":"list", "value":[nested]});
}
assert_eq!(
arguments(&json!({"arg":nested}).to_string())
.unwrap_err()
.kind,
"input"
);
let mut budget = 1;
assert_eq!(
parse_value(
&json!({"kind":"list","value":[{"kind":"unit"}]}),
1,
&mut budget
)
.unwrap_err()
.kind,
"input"
);
assert_eq!(
s.manual_stats(),
json!({"observes":0,"interfaces":0,"calls":0})
);
let mut data: Json = serde_json::from_str(&manifest()).unwrap();
data["nodes"][0]["title"] = json!("x".repeat(1024 * 1024 + 1));
let mut large = BrowserSession::new(&data.to_string()).unwrap();
assert_eq!(large.manual_observe("/", 0.0).unwrap_err().kind, "render");
assert_eq!(
large.manual_stats(),
json!({"observes":1,"interfaces":0,"calls":0})
);
}
#[test]
fn host_call_failure_is_typed_and_counted_once() {
let mut s = session();
s.manual_observe("/quoted", 0.0).unwrap();
s.manual_interface("/", "document").unwrap();
// Simulate a publication disappearing after observation: real Host dispatch,
// not a fabricated Client response or a document-map shortcut.
let mut data: WorldspaceData = serde_json::from_str(&manifest()).unwrap();
data.nodes.pop();
s.world = Worldspace::new(data).unwrap();
let error = s
.manual_call("/quoted", "/", "document", "read", "{}")
.unwrap_err();
assert_eq!(error.kind, "protocol");
assert_eq!(error.code.as_deref(), Some("NotFound"));
assert_eq!(s.calls, 1);
}