Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions crates/session/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
134 changes: 134 additions & 0 deletions crates/session/src/extension.rs
Original file line number Diff line number Diff line change
@@ -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 `<PREFIX><METHOD>` **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` | `<PREFIX>READ` | `read_only` | `ReadData`, `ReadTimeline` |
//! | `write` | `<PREFIX>WRITE` | `mutating` | the caller's namespace, lanes and items |
//! | `structure` | `<PREFIX>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": "<session id>", "request": <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<String, String> {
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<String, String> {
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<Response, String> {
facet_json::from_str(json).map_err(|e| e.to_string())
}
50 changes: 17 additions & 33 deletions crates/session/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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.
///
Expand All @@ -108,10 +85,10 @@ pub fn extension_of(who: &Principal) -> Result<ExtensionId, SessionError> {
}
}

/// 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<RwLock<HashMap<String, SessionDoc>>>,
sessions: Sessions,
engine: Arc<dyn PermissionEngine>,
}

Expand All @@ -126,19 +103,26 @@ impl SessionHost {
#[must_use]
pub fn new(engine: Arc<dyn PermissionEngine>) -> 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<String>, 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
Expand All @@ -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`.
Expand Down
3 changes: 3 additions & 0 deletions crates/session/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions crates/session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//!
Expand All @@ -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")]
Expand Down
Loading
Loading