From b36a447e828349d1e143978e6f25e00689ef4a6b Mon Sep 17 00:00:00 2001 From: "fts-forge[bot]" <345159799+fts-forge[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:05:24 -0800 Subject: [PATCH 1/2] feat(session): `fts.session` as an Architect extension service Inside an Architect app, one extension asks another through the host: `services.call("fts.session", method, args)`, run as the provider's action `` as the caller, with the caller's id in the action's context (`cx.caller`, from the call's principal). `session::extension::answer` (feature `extension`) is what that action does, with no Architect crate: JSON in (`Call { doc, request }`), JSON out (a `Response`), for `cx.caller`'s namespace. One method per action a request needs (`read`, `write`, `structure`), and `answer` refuses a request sent through another, so the effect each method's action declares (read_only, mutating) is what Architect's own check holds a caller to: a read-only share link's guest extension reads, and its edits are refused before the provider runs. `service::action_for`, `READ`/`WRITE`/`STRUCTURE` and the `Sessions` registry move to `service`, shared by the vox face (`host` re-exports its old paths) and this one. CI clippy covers `extension` and `vox`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 +- Cargo.lock | 1 + Cargo.toml | 1 + crates/session/Cargo.toml | 4 + crates/session/src/extension.rs | 134 ++++++++++++++++++++++ crates/session/src/host.rs | 50 +++----- crates/session/src/lib.rs | 4 + crates/session/src/service.rs | 82 ++++++++++++- crates/session/tests/session/extension.rs | 127 ++++++++++++++++++++ crates/session/tests/session/main.rs | 2 + 10 files changed, 372 insertions(+), 35 deletions(-) create mode 100644 crates/session/src/extension.rs create mode 100644 crates/session/tests/session/extension.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 223062a5..f83de772 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,7 +48,7 @@ jobs: - name: clippy run: | timeout 30m cargo clippy --workspace --all-features --all-targets -- -D warnings - for f in sync architect service; do + for f in sync architect service extension vox; do timeout 15m cargo clippy -p session --no-default-features --features "$f" --all-targets -- -D warnings done timeout 15m cargo clippy -p session --no-default-features --all-targets -- -D warnings diff --git a/Cargo.lock b/Cargo.lock index 7a7373ca..578c63cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1949,6 +1949,7 @@ dependencies = [ "architect-permissions", "crdt", "facet", + "facet-json", "loro", "thiserror 2.0.21", "tokio", diff --git a/Cargo.toml b/Cargo.toml index dc5f41f5..0b0c8da2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ rust-version = "1.99" # holds both resolves each to one source. [workspace.dependencies] facet = { version = "0.50.0-rc.5" } +facet-json = { version = "0.50.0-rc.7" } # `std::time::Instant` panics in a browser; `web-time`'s is the same API # over `performance.now()`. web-time = "1" diff --git a/crates/session/Cargo.toml b/crates/session/Cargo.toml index d94e4d6b..35a0f17b 100644 --- a/crates/session/Cargo.toml +++ b/crates/session/Cargo.toml @@ -25,10 +25,14 @@ service = ["architect"] # call's principal, what it may do from the permission engine. Named `vox` # because `#[architect::rpc]` emits `cfg(feature = "vox")` into the crate # that uses it. +# `fts.session` as an Architect extension service: the provider's actions +# hand `session::extension::answer` their JSON and the caller's id. +extension = ["service", "dep:facet-json"] vox = ["service", "dep:architect", "architect/vox", "dep:architect-permissions", "dep:thiserror", "dep:vox"] [dependencies] facet = { workspace = true } +facet-json = { workspace = true, optional = true } loro = { workspace = true, optional = true } crdt = { workspace = true, optional = true } architect = { workspace = true, optional = true } diff --git a/crates/session/src/extension.rs b/crates/session/src/extension.rs new file mode 100644 index 00000000..a8298249 --- /dev/null +++ b/crates/session/src/extension.rs @@ -0,0 +1,134 @@ +//! `fts.session` as an Architect extension service (feature `extension`). +//! +//! Inside an Architect app, one extension asks another through the host: +//! the caller declares `[requires] "fts.session"`, calls +//! `services.call("fts.session", method, args)` (`HostRequest::Service`), +//! and the host runs the provider's action `` **as the +//! caller**, with the caller's id in the action's context (`cx.caller`, +//! from the call's principal: the host's word, never the arguments). +//! [`answer`] is what that action does. It needs no Architect crate: the +//! provider registers three actions that hand it their JSON. +//! +//! **Methods.** One per action a request needs ([`crate::service::action_for`]), +//! so Architect's own effect check holds them: +//! +//! | method | action | effect | requests | +//! |-------------|-------------------------|-------------|----------| +//! | `read` | `READ` | `read_only` | `ReadData`, `ReadTimeline` | +//! | `write` | `WRITE` | `mutating` | the caller's namespace, lanes and items | +//! | `structure` | `STRUCTURE` | `mutating` | tempo, markers, regions | +//! +//! A share link's guest runs its extensions `read_only`, and the host +//! refuses a service call above the caller's effect before the provider +//! runs: a read-only link's chart view reads, and its edits never arrive. +//! That is Architect's permission, not a path here. [`answer`] refuses a +//! request sent through the wrong method, so the effect a method declares +//! is the effect it has. Who may change the song's structure is who the +//! host lets run `structure`. +//! +//! **The provider's manifest** (its prefix is its own, here `SESSION_`): +//! +//! ```toml +//! [provides] +//! "fts.session" = "0.1.0" +//! +//! [[actions]] +//! id = "SESSION_READ" +//! effect = "read_only" +//! +//! [[actions]] +//! id = "SESSION_WRITE" +//! effect = "mutating" +//! +//! [[actions]] +//! id = "SESSION_STRUCTURE" +//! effect = "mutating" +//! ``` +//! +//! and its code, for each: `.action_in("SESSION_READ", |args, cx| async +//! move { answer(&sessions, READ, &args.to_string(), cx["caller"].as_str()) })`, +//! parsing the reply back to JSON. +//! +//! **Arguments:** `{"doc": "", "request": }`; the +//! reply is a [`Response`]. Both are this crate's types in `facet-json`'s +//! encoding (an enum externally tagged: `{"TextSplice": {...}}`). + +use crate::id::ExtensionId; +use crate::service::{ + Grants, Request, Response, STRUCTURE, ServiceError, Sessions, action_for, handle, +}; + +/// The service's name. +pub const SERVICE: &str = "fts.session"; + +/// A call's arguments. +#[derive(Debug, Clone, PartialEq, facet::Facet)] +pub struct Call { + /// The session's document id. + pub doc: String, + pub request: Request, +} + +/// Answers one call to the service, as the provider's action does. +/// +/// `method` is `read`, `write` or `structure`; `args` a [`Call`] as JSON; +/// `caller` the extension in the action context's `caller`. It answers +/// against the sessions open in `sessions`, with a [`Response`] as JSON. +/// +/// # Errors +/// +/// A message when there is no caller (only an extension asks), the +/// arguments do not parse, the request does not belong to the method, +/// the session is not open, or [`handle`] refused or failed. +pub fn answer( + sessions: &Sessions, + method: &str, + args: &str, + caller: Option<&str>, +) -> Result { + let caller = caller + .filter(|c| !c.is_empty()) + .ok_or("only an extension asks the session (no caller in the context)")?; + let call: Call = facet_json::from_str(args).map_err(|e| format!("arguments: {e}"))?; + let needs = action_for(&call.request); + if needs != method { + return Err(format!( + "this request is a `{needs}`, not a `{method}`: call method `{needs}`" + )); + } + let session = sessions + .get(&call.doc) + .ok_or_else(|| format!("no session {} is open here", call.doc))?; + let grants = Grants { + structure: method == STRUCTURE, + }; + let response = handle(&session, &ExtensionId::from(caller), grants, call.request).map_err( + |e| match e { + ServiceError::Refused(why) => format!("refused: {why}"), + ServiceError::Failed(e) => format!("failed: {e}"), + }, + )?; + facet_json::to_string(&response).map_err(|e| format!("reply: {e}")) +} + +/// A call's arguments as JSON: what a caller passes `services.call`. +/// +/// # Errors +/// +/// The request could not be encoded. +pub fn call_json(doc: &str, request: Request) -> Result { + facet_json::to_string(&Call { + doc: doc.to_owned(), + request, + }) + .map_err(|e| e.to_string()) +} + +/// A reply as a [`Response`]. +/// +/// # Errors +/// +/// The JSON is not a response. +pub fn response_of(json: &str) -> Result { + facet_json::from_str(json).map_err(|e| e.to_string()) +} diff --git a/crates/session/src/host.rs b/crates/session/src/host.rs index 41087e0e..951593fa 100644 --- a/crates/session/src/host.rs +++ b/crates/session/src/host.rs @@ -21,14 +21,13 @@ //! - The gate checks `read` on `doc/{doc}` before the handler runs //! ([`PERMITS`]); the handler checks the exact action. -use std::collections::HashMap; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use architect_permissions::{Action, Decision, PermissionEngine, Principal, Resource}; use crate::doc::SessionDoc; use crate::id::ExtensionId; -use crate::service::{Grants, Request, Response, ServiceError, handle}; +use crate::service::{Grants, Request, Response, ServiceError, Sessions, handle}; /// Why a call was not answered. #[architect::error] @@ -69,29 +68,7 @@ pub const PERMITS: architect_permissions::ServicePermits = architect_permissions )], }; -/// The action a request needs on the document. -#[must_use] -pub const fn action_for(request: &Request) -> &'static str { - match request { - Request::ReadData | Request::ReadTimeline => Action::READ, - Request::SetTempo { .. } - | Request::PutMarker { .. } - | Request::PutRegion { .. } - | Request::RemoveMark { .. } => STRUCTURE, - Request::Set { .. } - | Request::MapSet { .. } - | Request::MapRemove { .. } - | Request::TextSplice { .. } - | Request::Remove { .. } - | Request::PutLane { .. } - | Request::RemoveLane { .. } - | Request::PutItem { .. } - | Request::RemoveItem { .. } => Action::WRITE, - } -} - -/// The action that writes the song's structure (tempo, markers, regions). -pub const STRUCTURE: &str = "structure"; +pub use crate::service::{STRUCTURE, action_for}; /// The namespace a principal's call writes: the extension's id. /// @@ -108,10 +85,10 @@ pub fn extension_of(who: &Principal) -> Result { } } -/// The sessions a host serves, by document id. +/// The sessions a host serves, by document id, and the engine it asks. #[derive(Clone)] pub struct SessionHost { - sessions: Arc>>, + sessions: Sessions, engine: Arc, } @@ -126,19 +103,26 @@ impl SessionHost { #[must_use] pub fn new(engine: Arc) -> Self { Self { - sessions: Arc::new(RwLock::new(HashMap::new())), + sessions: Sessions::default(), engine, } } /// Serves `session` under its document id. pub fn open(&self, doc: impl Into, session: SessionDoc) { - architect::write(&self.sessions).insert(doc.into(), session); + self.sessions.open(doc, session); } /// Stops serving `doc`. pub fn close(&self, doc: &str) { - architect::write(&self.sessions).remove(doc); + self.sessions.close(doc); + } + + /// The sessions it serves, shared (an extension's provider can answer + /// from the same ones: [`crate::extension`]). + #[must_use] + pub const fn sessions(&self) -> &Sessions { + &self.sessions } /// [`SessionService::ask`] for `who`: what the handler does once it @@ -165,9 +149,9 @@ impl SessionHost { who.describe() ))); } - let session = architect::read(&self.sessions) + let session = self + .sessions .get(doc) - .cloned() .ok_or_else(|| SessionError::NotFound(doc.to_owned()))?; // The structure action was checked above for the requests that // need it; the grant only says so to `handle`. diff --git a/crates/session/src/lib.rs b/crates/session/src/lib.rs index 28751c25..4839a14f 100644 --- a/crates/session/src/lib.rs +++ b/crates/session/src/lib.rs @@ -11,6 +11,8 @@ //! document. //! - [`service`] (feature `service`): what a runtime extension may do to //! the session, answered the same way by every host. +//! - [`extension`] (feature `extension`): that, as an Architect extension +//! service, for the provider's actions. //! - [`host`] (feature `vox`): that, served as `fts.session` over vox, the //! caller taken from the call's principal. //! @@ -26,6 +28,8 @@ pub mod value; #[cfg(feature = "architect")] pub mod doc; +#[cfg(feature = "extension")] +pub mod extension; #[cfg(feature = "vox")] pub mod host; #[cfg(feature = "service")] diff --git a/crates/session/src/service.rs b/crates/session/src/service.rs index 11463d72..9b4ec18f 100644 --- a/crates/session/src/service.rs +++ b/crates/session/src/service.rs @@ -31,7 +31,8 @@ //! `crdt::History::transact` to make it one named undo step, made as the //! extension. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, PoisonError, RwLock}; use crate::doc::{DocError, SessionDoc}; use crate::ext::ExtensionData; @@ -166,6 +167,85 @@ impl From for ServiceError { } } +/// The action a request needs on the session. +/// +/// [`READ`] for the two reads, [`STRUCTURE`] for the tempo map, markers and +/// regions, [`WRITE`] for every other edit. A host asks its permission +/// engine for it (the vox face, `crate::host`), or answers it with a +/// method of that name whose effect Architect checks (the extension face, +/// `crate::extension`). +#[must_use] +pub const fn action_for(request: &Request) -> &'static str { + match request { + Request::ReadData | Request::ReadTimeline => READ, + Request::SetTempo { .. } + | Request::PutMarker { .. } + | Request::PutRegion { .. } + | Request::RemoveMark { .. } => STRUCTURE, + Request::Set { .. } + | Request::MapSet { .. } + | Request::MapRemove { .. } + | Request::TextSplice { .. } + | Request::Remove { .. } + | Request::PutLane { .. } + | Request::RemoveLane { .. } + | Request::PutItem { .. } + | Request::RemoveItem { .. } => WRITE, + } +} + +/// Reads. +pub const READ: &str = "read"; +/// Edits to the caller's namespace, lanes and items. +pub const WRITE: &str = "write"; +/// Edits to the song's structure (tempo, markers, regions). +pub const STRUCTURE: &str = "structure"; + +/// The sessions a host has open, by document id. Cloning shares them. +#[derive(Clone, Default)] +pub struct Sessions(Arc>>); + +impl std::fmt::Debug for Sessions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let ids: Vec = self + .0 + .read() + .unwrap_or_else(PoisonError::into_inner) + .keys() + .cloned() + .collect(); + f.debug_tuple("Sessions").field(&ids).finish() + } +} + +impl Sessions { + /// Serves `session` under its document id. + pub fn open(&self, doc: impl Into, session: SessionDoc) { + self.0 + .write() + .unwrap_or_else(PoisonError::into_inner) + .insert(doc.into(), session); + } + + /// Stops serving `doc`. + pub fn close(&self, doc: &str) { + self.0 + .write() + .unwrap_or_else(PoisonError::into_inner) + .remove(doc); + } + + /// Session `doc`, if open. + #[must_use] + pub fn get(&self, doc: &str) -> Option { + self.0 + .read() + .unwrap_or_else(PoisonError::into_inner) + .get(doc) + .cloned() + } +} + fn refuse(why: impl Into) -> Result { Err(ServiceError::Refused(why.into())) } diff --git a/crates/session/tests/session/extension.rs b/crates/session/tests/session/extension.rs new file mode 100644 index 00000000..2e921cbe --- /dev/null +++ b/crates/session/tests/session/extension.rs @@ -0,0 +1,127 @@ +//! `fts.session` as an extension service: the provider's actions answer +//! for `cx.caller`, and each method takes only its own kind of request. + +use session::doc::SessionDoc; +use session::extension::{answer, call_json, response_of}; +use session::service::{READ, Request, Response, STRUCTURE, Sessions, WRITE}; +use session::{MarkId, Region, Time, Value}; + +fn sessions() -> Sessions { + let s = Sessions::default(); + s.open("song-1", SessionDoc::new()); + s +} + +fn splice(text: &str) -> String { + call_json( + "song-1", + Request::TextSplice { + name: "chart".into(), + at: 0, + delete: 0, + insert: text.into(), + }, + ) + .unwrap() +} + +#[test] +fn the_caller_in_the_context_is_the_namespace() { + let s = sessions(); + answer(&s, WRITE, &splice("Verse: C G\n"), Some("keyflow")).unwrap(); + let read = call_json("song-1", Request::ReadData).unwrap(); + let Response::Data(k) = + response_of(&answer(&s, READ, &read, Some("keyflow")).unwrap()).unwrap() + else { + panic!("not data") + }; + assert_eq!(k.text("chart"), Some("Verse: C G\n")); + let Response::Data(i) = + response_of(&answer(&s, READ, &read, Some("ignition")).unwrap()).unwrap() + else { + panic!("not data") + }; + assert_eq!(i.text("chart"), None); +} + +#[test] +fn a_method_takes_only_its_own_kind_of_request() { + let s = sessions(); + // An edit sent as a read (the read_only action a guest may run) is + // refused, and nothing is written. + let e = answer(&s, READ, &splice("vandal "), Some("keyflow")).unwrap_err(); + assert!(e.contains("is a `write`, not a `read`"), "{e}"); + let region = call_json( + "song-1", + Request::PutRegion { + id: MarkId::from("verse"), + region: Region { + start: Time::QuarterNotes(0.0), + end: Time::QuarterNotes(16.0), + name: "Verse".into(), + color: None, + ruler: None, + }, + }, + ) + .unwrap(); + assert!(answer(&s, WRITE, ®ion, Some("keyflow")).is_err()); + answer(&s, STRUCTURE, ®ion, Some("keyflow")).unwrap(); + assert_eq!(s.get("song-1").unwrap().read().regions.len(), 1); + let chart = s.get("song-1").unwrap().read_ext(&"keyflow".into()); + assert_eq!(chart.text("chart"), None); +} + +#[test] +fn only_an_extension_asks_and_only_open_sessions_answer() { + let s = sessions(); + let read = call_json("song-1", Request::ReadData).unwrap(); + assert!( + answer(&s, READ, &read, None) + .unwrap_err() + .contains("only an extension") + ); + assert!(answer(&s, READ, &read, Some("")).is_err()); + let other = call_json("song-9", Request::ReadData).unwrap(); + assert!( + answer(&s, READ, &other, Some("keyflow")) + .unwrap_err() + .contains("no session song-9") + ); + assert!( + answer(&s, READ, "{not json", Some("keyflow")) + .unwrap_err() + .starts_with("arguments") + ); +} + +#[test] +fn payloads_cross_json_whole() { + let s = sessions(); + let set = call_json( + "song-1", + Request::Set { + name: "meta".into(), + value: Value::map([ + ("key", Value::from("D")), + ("capo", Value::Int(2)), + ("swing", Value::Float(0.6)), + ( + "tags", + Value::List(vec![Value::from("ballad"), Value::Bool(true)]), + ), + ]), + }, + ) + .unwrap(); + answer(&s, WRITE, &set, Some("keyflow")).unwrap(); + let read = call_json("song-1", Request::ReadData).unwrap(); + let Response::Data(k) = + response_of(&answer(&s, READ, &read, Some("keyflow")).unwrap()).unwrap() + else { + panic!("not data") + }; + let meta = k.register("meta").unwrap(); + assert_eq!(meta.get("capo"), Some(&Value::Int(2))); + assert_eq!(meta.get("swing"), Some(&Value::Float(0.6))); +} diff --git a/crates/session/tests/session/main.rs b/crates/session/tests/session/main.rs index 2eb1edc6..20199fb2 100644 --- a/crates/session/tests/session/main.rs +++ b/crates/session/tests/session/main.rs @@ -17,6 +17,8 @@ mod time; #[cfg(feature = "architect")] mod doc; +#[cfg(feature = "extension")] +mod extension; #[cfg(feature = "sync")] mod follow; #[cfg(feature = "vox")] From 9e2a85cfa77ab62013e1d6486743219e98987b2a Mon Sep 17 00:00:00 2001 From: "fts-forge[bot]" <345159799+fts-forge[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:35:13 -0800 Subject: [PATCH 2/2] fix(session): ids are transparent on the wire, so a timeline crosses JSON A `Response::Timeline` did not survive `facet-json`: its maps are keyed by `LaneId` and `ItemId`, which it wrote as strings and could not read back as ids ("expected LaneId, but got String"). Ignition's cue lists, the first caller to read the timeline through the extension face, hit it. The id newtypes are now `#[facet(transparent)]`: on every wire (JSON, vox) an id is the string it wraps, a map key included. New test: a lane and an item put and read back over JSON, keyed by their ids. Co-Authored-By: Claude Opus 5.5 --- crates/session/src/id.rs | 3 ++ crates/session/tests/session/extension.rs | 58 +++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/crates/session/src/id.rs b/crates/session/src/id.rs index aefa4b1e..b8ceb633 100644 --- a/crates/session/src/id.rs +++ b/crates/session/src/id.rs @@ -11,7 +11,10 @@ use std::fmt; macro_rules! id { ($(#[$doc:meta])* $name:ident) => { $(#[$doc])* + // Transparent: on every wire (JSON, vox) an id is the string it + // wraps, so it works as a map key too. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, facet::Facet)] + #[facet(transparent)] pub struct $name(pub String); impl $name { diff --git a/crates/session/tests/session/extension.rs b/crates/session/tests/session/extension.rs index 2e921cbe..b51c5021 100644 --- a/crates/session/tests/session/extension.rs +++ b/crates/session/tests/session/extension.rs @@ -125,3 +125,61 @@ fn payloads_cross_json_whole() { assert_eq!(meta.get("capo"), Some(&Value::Int(2))); assert_eq!(meta.get("swing"), Some(&Value::Float(0.6))); } + +/// Every response crosses JSON: the timeline's maps are keyed by ids. +#[test] +fn the_timeline_crosses_json_keyed_by_ids() { + use session::{ExtensionId, Item, ItemId, Lane, LaneId}; + let s = sessions(); + let lane = LaneId::from("cues"); + let put = call_json( + "song-1", + Request::PutLane { + id: lane.clone(), + lane: Lane { + owner: ExtensionId::from("ignition"), + kind: "ignition.cues".into(), + name: "Main".into(), + order: 0.0, + parent: None, + }, + }, + ) + .unwrap(); + answer(&s, WRITE, &put, Some("ignition")).unwrap(); + let item = call_json( + "song-1", + Request::PutItem { + id: ItemId::from("cues/1"), + item: Item { + owner: ExtensionId::from("ignition"), + lane: lane.clone(), + kind: "ignition.cue".into(), + at: Time::QuarterNotes(4.0), + end: None, + payload: Value::map([("look", Value::from("Warm"))]), + }, + }, + ) + .unwrap(); + answer(&s, WRITE, &item, Some("ignition")).unwrap(); + let read = call_json("song-1", Request::ReadTimeline).unwrap(); + let Response::Timeline { lanes, items } = + response_of(&answer(&s, READ, &read, Some("ignition")).unwrap()).unwrap() + else { + panic!("not the timeline") + }; + assert_eq!(lanes[&lane].name, "Main"); + assert_eq!(items[&ItemId::from("cues/1")].at, Time::QuarterNotes(4.0)); + // An id is the string it wraps on the wire. + assert!( + call_json( + "cues", + Request::RemoveItem { + id: ItemId::from("cues/1") + } + ) + .unwrap() + .contains("\"cues/1\"") + ); +}