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
+35 -1
View File
@@ -1,6 +1,7 @@
# Public-document Worldspace
`wip-site-worldspace` is the site's immutable in-memory Host provider. It uses
`wip-site-worldspace` is the site's in-memory Host provider: immutable documents
plus an opt-in session-local playground. It uses
`wip-host`, `wip-interface` and `wip-protocol`; it does not depend on the filesystem
server, HTTP, a browser, or a network runtime. The native and WASM callers use the
same `Worldspace` instance API.
@@ -94,6 +95,39 @@ validates the assembled response against the request. At the requested depth,
Construction allows at most `MAX_NODES = 4096`, with hierarchy depth at most 32.
`from_json` also caps input at 16 MiB. Together these bounds cap traversal work.
## Playground
A manifest document at `/playground` opts into mutable state. Manifests without
that node retain document-only behavior. Manifest descendants of `/playground`
are rejected, so mutable counters cannot shadow or delete document content.
- `/playground` keeps `/::document.read()` and also exposes `/::collection`:
`create(name: String) -> Unit` creates a zero-valued counter;
`remove(name: String) -> Unit` removes an existing counter.
- Children start as `apple = 3` and `orange = 0`, ordered lexically. Each exposes
only `/::counter`: `get() -> Integer`, `increment(amount: Integer) -> Integer`,
and `reset() -> Integer`. Increment returns the new value; reset returns zero.
- Names match `[A-Za-z0-9_-]{1,32}` and are case-sensitive. At most 32 counters
exist. Duplicate creation, missing removal, invalid names, and checked sums
outside Protocol Integer's range `[-9007199254740991, 9007199254740991]` fail
without mutation. Capacity errors are `ResourceLimitExceeded`; domain
rejections are `Internal` with an explicit not-committed Host guarantee.
Invalid typed arguments are rejected by standard Client/Host validation.
- Every counter lookup publishes a fresh Object snapshot whose `description`
is the current decimal integer and whose `name` remains the slug. All
generated interfaces bind to the same actual root ScopeObservation.
- State belongs to one Worldspace/BrowserSession. Navigation retains it; a new
session restores initial state. Documents are never mutated.
The browser's normal `tree()` includes only manifest display paths and therefore
never calls `document.read` on dynamic counters. Manual playground `observe`
uses the real Client's `refresh_observed` on every explicit retrieval (including
recovery from retained missing/stale observations); other documents retain
`ensure_observed` caching. This Client version has no public subtree-invalidation
API. A call does not observe, fetch, retry, or convert its result into an Object.
The UI explicitly observes `/playground` at depth 1, then the selected Object at
depth 1 after calls, and observes `/playground` on entry to Protocol mode.
## Validation
From the site directory, with the configured Rust toolchain and dependencies:
+136 -24
View File
@@ -1,15 +1,19 @@
//! Immutable, site-specific Worldspace. All three interactions use the ordinary
//! Host publication boundary; only bounded recursive observation is site logic.
//! Site documents and an opt-in, session-local playground. All interactions use
//! the ordinary typed Host publication boundary.
mod playground;
pub use playground::{Collection, Counter, MAX_COUNTERS, PLAYGROUND_PATH};
use playground::{CollectionDefinition, CounterDefinition, Playground};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::rc::Rc;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use wip_host::{
ExecutionContext, InterfaceRegistry, ObjectProvider, ProviderResult, PublishedObject, Scope,
ScopeObservation, WipObject,
ExecutionContext, InterfaceRegistry, ObjectProvider, ProviderResult, PublishedObject,
RegisteredInterface, Scope, ScopeObservation, WipObject,
};
use wip_interface::{OperationResult, WipType, interface};
pub use wip_protocol;
@@ -62,25 +66,44 @@ pub trait Document {
}
/// Host-private implementation; no body lookup bypass is exposed to clients.
pub struct SiteObject(Arc<DocumentNode>);
pub enum SiteObject {
Document(Arc<DocumentNode>, Option<Rc<Playground>>),
Counter {
name: String,
description: String,
state: Rc<Playground>,
},
}
impl WipObject for SiteObject {
fn name(&self) -> &str {
&self.0.name
match self {
Self::Document(node, _) => &node.name,
Self::Counter { name, .. } => name,
}
}
fn description(&self) -> Option<&str> {
Some(&self.0.title)
Some(match self {
Self::Document(node, _) => &node.title,
Self::Counter { description, .. } => description,
})
}
}
impl Document for SiteObject {
fn read(&self) -> OperationResult<DocumentContent> {
let Self::Document(node, _) = self else {
return Err(wip_interface::HostError::internal(
"not a document",
wip_interface::EffectGuarantee::NotCommitted,
));
};
Ok(DocumentContent {
path: self.0.path.clone(),
title: self.0.title.clone(),
href: self.0.href.clone(),
html: self.0.html.clone(),
path: node.path.clone(),
title: node.title.clone(),
href: node.href.clone(),
html: node.html.clone(),
})
}
}
@@ -106,12 +129,15 @@ fn protocol_error(code: ProtocolErrorCode, message: impl Into<String>) -> Protoc
}
}
/// An immutable publication snapshot, shared by native and WASM callers.
/// Construction is the only mutation boundary; later interactions require only `&self`.
/// Immutable documents and isolated mutable playground state. This synchronous,
/// single-threaded provider publishes a fresh counter snapshot on every lookup.
pub struct Worldspace {
registry: InterfaceRegistry,
objects: BTreeMap<String, PublishedObject<SiteObject>>,
children: BTreeMap<String, Vec<String>>,
playground: Option<Rc<Playground>>,
counter: Option<RegisteredInterface<CounterDefinition>>,
current_scope: ScopeObservation,
}
impl Worldspace {
@@ -130,6 +156,37 @@ impl Worldspace {
let document = registry
.register(&scope, DOCUMENT_INTERFACE, DocumentDefinition, None)
.map_err(|error| invalid(error.to_string()))?;
let playground = data
.nodes
.iter()
.any(|node| node.path == PLAYGROUND_PATH)
.then(|| Rc::new(Playground::new()));
let (collection, counter) = if playground.is_some() {
// The mutable namespace cannot shadow or delete manifest documents.
if data
.nodes
.iter()
.any(|node| node.path.starts_with("/playground/"))
{
return Err(invalid(
"playground children are reserved for session counters",
));
}
(
Some(
registry
.register(&scope, "collection", CollectionDefinition, None)
.map_err(|error| invalid(error.to_string()))?,
),
Some(
registry
.register(&scope, "counter", CounterDefinition, None)
.map_err(|error| invalid(error.to_string()))?,
),
)
} else {
(None, None)
};
// Every publication attests the same actual, immutable root Object.
// Both fetch and calls need this association; a registry token alone is insufficient.
let root = Arc::new(
@@ -139,7 +196,8 @@ impl Worldspace {
.unwrap()
.clone(),
);
let current_scope = ScopeObservation::new(&scope, &SiteObject(Arc::clone(&root)));
let current_scope =
ScopeObservation::new(&scope, &SiteObject::Document(Arc::clone(&root), None));
let mut objects = BTreeMap::new();
let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
for node in data.nodes {
@@ -150,21 +208,36 @@ impl Worldspace {
.or_default()
.push(path.clone());
}
let object = SiteObject(if path == "/" {
Arc::clone(&root)
} else {
Arc::new(node)
});
let publication = PublishedObject::new(object)
let object = SiteObject::Document(
if path == "/" {
Arc::clone(&root)
} else {
Arc::new(node)
},
if path == PLAYGROUND_PATH {
playground.clone()
} else {
None
},
);
let mut publication = PublishedObject::new(object)
.bind_scope(current_scope.clone())
.expose(&document)
.map_err(|error| invalid(error.to_string()))?;
if path == PLAYGROUND_PATH {
publication = publication
.expose(collection.as_ref().unwrap())
.map_err(|error| invalid(error.to_string()))?;
}
objects.insert(path, publication);
}
Ok(Self {
registry,
objects,
children,
playground,
counter,
current_scope,
})
}
@@ -194,10 +267,8 @@ impl Worldspace {
None
} else {
Some(
self.children
.get(path)
.into_iter()
.flatten()
self.child_paths(path)
.iter()
.map(|child| self.observe_at(child, depth - 1))
.collect::<Result<Vec<_>, _>>()?,
)
@@ -205,6 +276,20 @@ impl Worldspace {
Ok(ObjectObservation { object, children })
}
fn child_paths(&self, path: &str) -> Vec<String> {
if path == PLAYGROUND_PATH
&& let Some(state) = &self.playground
{
return state
.counters
.borrow()
.keys()
.map(|name| format!("{PLAYGROUND_PATH}/{name}"))
.collect();
}
self.children.get(path).cloned().unwrap_or_default()
}
pub fn fetch_interface(
&self,
request: FetchInterfaceRequest,
@@ -237,6 +322,33 @@ impl ObjectProvider for Worldspace {
path: &str,
operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
) -> ProviderResult<R> {
if let (Some(state), Some(counter), Some(name)) = (
&self.playground,
&self.counter,
path.strip_prefix("/playground/"),
) {
let value = state.counters.borrow().get(name).copied();
let Some(value) = value else {
return ProviderResult::NotFound;
};
// No shared mutable description: each callback receives its own current
// snapshot. Rc/RefCell makes the synchronous lookup/dispatch boundary
// single-threaded, with no external writer between resolution and call.
let publication = PublishedObject::new(SiteObject::Counter {
name: name.into(),
description: value.to_string(),
state: Rc::clone(state),
})
.bind_scope(self.current_scope.clone())
.expose(counter);
return match publication {
Ok(publication) => ProviderResult::Found(operation(&publication)),
Err(error) => ProviderResult::Failure(wip_interface::HostError::internal(
error.to_string(),
wip_interface::EffectGuarantee::NotCommitted,
)),
};
}
match self.objects.get(path) {
Some(publication) => ProviderResult::Found(operation(publication)),
None => ProviderResult::NotFound,
+136
View File
@@ -0,0 +1,136 @@
//! Bounded in-memory state behind generated, typed Interface dispatch.
use std::cell::RefCell;
use std::collections::BTreeMap;
use wip_interface::{EffectGuarantee, HostError, OperationResult, interface};
use wip_protocol::{MAX_SAFE_INTEGER, MIN_SAFE_INTEGER};
use crate::SiteObject;
pub const PLAYGROUND_PATH: &str = "/playground";
pub const MAX_COUNTERS: usize = 32;
#[interface]
pub trait Collection {
/// Creates a zero-valued counter with a unique ASCII slug (1..=32 characters).
fn create(&self, name: String) -> OperationResult<()>;
/// Removes an existing counter.
fn remove(&self, name: String) -> OperationResult<()>;
}
#[interface]
pub trait Counter {
/// Returns the current counter value.
fn get(&self) -> OperationResult<i64>;
/// Adds a signed amount, failing without mutation outside Protocol Integer range.
fn increment(&self, amount: i64) -> OperationResult<i64>;
/// Resets the counter to zero and returns zero.
fn reset(&self) -> OperationResult<i64>;
}
pub struct Playground {
pub(crate) counters: RefCell<BTreeMap<String, i64>>,
}
impl Playground {
pub fn new() -> Self {
Self {
counters: RefCell::new(BTreeMap::from([("apple".into(), 3), ("orange".into(), 0)])),
}
}
}
fn rejected(message: &str) -> HostError {
HostError::internal(message, EffectGuarantee::NotCommitted)
}
fn validate_name(name: &str) -> OperationResult<()> {
if !(1..=32).contains(&name.len())
|| !name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
{
return Err(rejected(
"counter names must be ASCII slugs of length 1..=32",
));
}
Ok(())
}
impl Collection for SiteObject {
fn create(&self, name: String) -> OperationResult<()> {
validate_name(&name)?;
let Self::Document(_, Some(state)) = self else {
return Err(rejected("not a collection"));
};
let mut counters = state.counters.borrow_mut();
if counters.contains_key(&name) {
return Err(rejected("counter already exists"));
}
if counters.len() >= MAX_COUNTERS {
return Err(HostError::resource_limit(
"counter limit reached",
EffectGuarantee::NotCommitted,
));
}
counters.insert(name, 0);
Ok(())
}
fn remove(&self, name: String) -> OperationResult<()> {
validate_name(&name)?;
let Self::Document(_, Some(state)) = self else {
return Err(rejected("not a collection"));
};
let mut counters = state.counters.borrow_mut();
if !counters.contains_key(&name) {
return Err(rejected("counter does not exist"));
}
counters.remove(&name);
Ok(())
}
}
impl Counter for SiteObject {
fn get(&self) -> OperationResult<i64> {
let Self::Counter { name, state, .. } = self else {
return Err(rejected("not a counter"));
};
state
.counters
.borrow()
.get(name)
.copied()
.ok_or_else(|| rejected("counter does not exist"))
}
fn increment(&self, amount: i64) -> OperationResult<i64> {
let Self::Counter { name, state, .. } = self else {
return Err(rejected("not a counter"));
};
let mut counters = state.counters.borrow_mut();
let value = counters
.get_mut(name)
.ok_or_else(|| rejected("counter does not exist"))?;
// Validate before commit, including the generated codec's result range.
// Otherwise dispatch could fail to encode a result after changing state.
let next = value
.checked_add(amount)
.filter(|next| (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(next))
.ok_or_else(|| rejected("counter exceeds Protocol Integer range"))?;
*value = next;
Ok(next)
}
fn reset(&self) -> OperationResult<i64> {
let Self::Counter { name, state, .. } = self else {
return Err(rejected("not a counter"));
};
let mut counters = state.counters.borrow_mut();
let value = counters
.get_mut(name)
.ok_or_else(|| rejected("counter does not exist"))?;
*value = 0;
Ok(0)
}
}
+383
View File
@@ -0,0 +1,383 @@
use std::collections::BTreeMap;
use wip_site_worldspace::wip_protocol::{
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, InterfaceReference,
InterfaceTarget, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, ObjectObservation, ObserveRequest,
ProtocolError, ProtocolErrorCode, Target, TypeExpr, Value,
};
use wip_site_worldspace::{MAX_COUNTERS, Worldspace};
fn world() -> Worldspace {
Worldspace::from_json(r#"{"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>"}
]}"#).unwrap()
}
fn reference(name: &str) -> InterfaceReference {
InterfaceReference {
scope: "/".into(),
name: name.into(),
}
}
fn call(
world: &Worldspace,
path: &str,
interface: &str,
operation: &str,
arguments: BTreeMap<String, Value>,
) -> Result<CallOperationResponse, ProtocolError> {
world.call_operation(CallOperationRequest {
target: Target {
path: path.into(),
validator: None,
},
interface: InterfaceTarget {
reference: reference(interface),
scope_ref: None,
validator: None,
},
operation: operation.into(),
arguments,
})
}
fn collection(
world: &Worldspace,
operation: &str,
name: &str,
) -> Result<CallOperationResponse, ProtocolError> {
call(
world,
"/playground",
"collection",
operation,
BTreeMap::from([("name".into(), Value::String(name.into()))]),
)
}
fn increment(world: &Worldspace, amount: i64) -> Result<CallOperationResponse, ProtocolError> {
call(
world,
"/playground/apple",
"counter",
"increment",
BTreeMap::from([("amount".into(), Value::Integer(amount))]),
)
}
fn observe(world: &Worldspace, path: &str, depth: u32) -> ObjectObservation {
world
.observe(ObserveRequest {
path: path.into(),
depth,
})
.unwrap()
}
#[test]
fn typed_descriptors_root_scope_and_initial_snapshots() {
let world = world();
let collection = world
.fetch_interface(FetchInterfaceRequest {
interface: reference("collection"),
})
.unwrap();
let counter = world
.fetch_interface(FetchInterfaceRequest {
interface: reference("counter"),
})
.unwrap();
assert_eq!(
collection
.descriptor
.operations
.iter()
.map(|op| op.name.as_str())
.collect::<Vec<_>>(),
["create", "remove"]
);
for op in &collection.descriptor.operations {
assert_eq!(op.parameters.len(), 1);
assert_eq!(op.parameters[0].name, "name");
assert_eq!(op.parameters[0].r#type, TypeExpr::String);
assert_eq!(op.returns.r#type, TypeExpr::Unit);
}
assert_eq!(
counter
.descriptor
.operations
.iter()
.map(|op| op.name.as_str())
.collect::<Vec<_>>(),
["get", "increment", "reset"]
);
assert_eq!(
counter.descriptor.operations[1].parameters[0].name,
"amount"
);
assert_eq!(
counter.descriptor.operations[1].parameters[0].r#type,
TypeExpr::Integer
);
assert!(
counter
.descriptor
.operations
.iter()
.all(|op| op.returns.r#type == TypeExpr::Integer)
);
let initial = observe(&world, "/playground", 2);
assert_eq!(
initial.object.interfaces,
[reference("document"), reference("collection")]
);
let children = initial.children.unwrap();
assert_eq!(
children
.iter()
.map(|c| (c.object.name.as_str(), c.object.description.as_deref()))
.collect::<Vec<_>>(),
[("apple", Some("3")), ("orange", Some("0"))]
);
assert!(
children
.iter()
.all(|c| c.object.interfaces == [reference("counter")] && c.children == Some(vec![]))
);
assert_eq!(
call(
&world,
"/playground/apple",
"counter",
"get",
BTreeMap::new()
)
.unwrap()
.result,
Value::Integer(3)
);
assert_eq!(
call(
&world,
"/playground/apple",
"document",
"read",
BTreeMap::new()
)
.unwrap_err()
.code,
ProtocolErrorCode::InterfaceMismatch
);
assert_eq!(
call(&world, "/book", "collection", "create", BTreeMap::new())
.unwrap_err()
.code,
ProtocolErrorCode::InterfaceMismatch
);
}
#[test]
fn mutations_publish_new_values_and_children_without_mutating_documents() {
let world = world();
let before = observe(&world, "/playground/apple", 1);
let documents: Vec<_> = ["/", "/book", "/playground"]
.into_iter()
.map(|path| {
(
path,
call(&world, path, "document", "read", BTreeMap::new())
.unwrap()
.result,
)
})
.collect();
assert_eq!(increment(&world, 7).unwrap().result, Value::Integer(10));
assert_eq!(
observe(&world, "/playground/apple", 1)
.object
.description
.as_deref(),
Some("10")
);
assert_eq!(
before.object.description.as_deref(),
Some("3"),
"old snapshots stay immutable"
);
assert_eq!(increment(&world, -12).unwrap().result, Value::Integer(-2));
assert_eq!(
call(
&world,
"/playground/apple",
"counter",
"reset",
BTreeMap::new()
)
.unwrap()
.result,
Value::Integer(0)
);
assert_eq!(observe(&world, "/playground/apple", 1).object.name, "apple");
assert_eq!(
collection(&world, "create", "New_counter-2")
.unwrap()
.result,
Value::Unit
);
assert_eq!(
observe(&world, "/playground/New_counter-2", 1)
.object
.description
.as_deref(),
Some("0")
);
collection(&world, "remove", "apple").unwrap();
assert_eq!(
call(
&world,
"/playground/apple",
"counter",
"get",
BTreeMap::new()
)
.unwrap_err()
.code,
ProtocolErrorCode::NotFound
);
assert!(
!observe(&world, "/playground", 1)
.children
.unwrap()
.iter()
.any(|child| child.object.name == "apple")
);
collection(&world, "create", "apple").unwrap();
assert_eq!(
observe(&world, "/playground/apple", 1)
.object
.description
.as_deref(),
Some("0")
);
for (path, expected) in documents {
assert_eq!(
call(&world, path, "document", "read", BTreeMap::new())
.unwrap()
.result,
expected
);
}
}
#[test]
fn invalid_names_duplicates_missing_and_capacity_fail_without_mutation() {
let world = world();
let before = observe(&world, "/", 3);
for name in [
"",
".",
"..",
"a/b",
"a b",
"a\nb",
"<script>",
"é",
"a.b",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
] {
for operation in ["create", "remove"] {
assert!(
collection(&world, operation, name).is_err(),
"{operation} {name:?}"
);
assert_eq!(observe(&world, "/", 3), before);
}
}
assert!(collection(&world, "create", "apple").is_err());
assert!(collection(&world, "remove", "missing").is_err());
assert_eq!(observe(&world, "/", 3), before);
collection(&world, "create", &"a".repeat(32)).unwrap();
for index in 3..MAX_COUNTERS {
collection(&world, "create", &format!("counter-{index}")).unwrap();
}
let full = observe(&world, "/playground", 1);
assert_eq!(full.children.as_ref().unwrap().len(), MAX_COUNTERS);
assert_eq!(
collection(&world, "create", "over-limit").unwrap_err().code,
ProtocolErrorCode::ResourceLimitExceeded
);
assert_eq!(observe(&world, "/playground", 1), full);
collection(&world, "remove", "orange").unwrap();
collection(&world, "create", "over-limit").unwrap();
}
#[test]
fn integer_and_typed_argument_failures_are_atomic() {
let world = world();
assert_eq!(
increment(&world, MAX_SAFE_INTEGER - 3).unwrap().result,
Value::Integer(MAX_SAFE_INTEGER)
);
let maximum = observe(&world, "/playground/apple", 1);
for amount in [1, MAX_SAFE_INTEGER, i64::MAX, i64::MIN] {
assert!(increment(&world, amount).is_err());
assert_eq!(observe(&world, "/playground/apple", 1), maximum);
}
call(
&world,
"/playground/apple",
"counter",
"reset",
BTreeMap::new(),
)
.unwrap();
increment(&world, MIN_SAFE_INTEGER).unwrap();
let minimum = observe(&world, "/playground/apple", 1);
assert!(increment(&world, -1).is_err());
for args in [
BTreeMap::new(),
BTreeMap::from([("amount".into(), Value::String("1".into()))]),
BTreeMap::from([
("amount".into(), Value::Integer(1)),
("extra".into(), Value::Unit),
]),
] {
assert_eq!(
call(&world, "/playground/apple", "counter", "increment", args)
.unwrap_err()
.code,
ProtocolErrorCode::InvalidArguments
);
assert_eq!(observe(&world, "/playground/apple", 1), minimum);
}
}
#[test]
fn new_worldspace_resets_state_and_manifest_documents_cannot_be_shadowed() {
let first = world();
increment(&first, 12).unwrap();
collection(&first, "remove", "orange").unwrap();
collection(&first, "create", "pear").unwrap();
let fresh = world();
assert_eq!(
observe(&fresh, "/playground/apple", 1)
.object
.description
.as_deref(),
Some("3")
);
assert_eq!(
observe(&fresh, "/playground", 1)
.children
.unwrap()
.iter()
.map(|child| child.object.name.clone())
.collect::<Vec<_>>(),
["apple", "orange"]
);
assert!(Worldspace::from_json(r#"{"nodes":[
{"path":"/","name":"","displayPath":"/","title":"Root","href":"/","html":""},
{"path":"/playground","name":"playground","parent":"/","displayPath":"/playground","title":"Playground","href":"/playground/","html":""},
{"path":"/playground/apple","name":"apple","parent":"/playground","displayPath":"/playground/apple","title":"Document","href":"/apple/","html":""}
]}"#).is_err());
}