use crate::ActionContract;
use crate::ActionParam;
use crate::action::{EncodedAction, ExecutionLocus, OperationKind};
use crate::context::ActionContext;
use crate::entry::Described;
use crate::executor::{ActionTransport, Dispatched, dispatch_by_with_context};
use crate::registry::ActionRegistry;
use crate::resource::{
ActionInput, ActionSpec, Collects, KEY_SEP, ResourceSpec, ResourceViewMountSpec,
ResourceViewRangeSpec,
};
use serde::{Deserialize, Serialize};
pub const NOT_READY: &str = "not_ready";
pub const NOT_READY_REASON: &str = "what this changes has not arrived from the workspace yet; ask \
again";
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ActionAddress {
pub resource: String,
pub action: String,
}
impl ActionAddress {
pub fn new(resource: impl Into<String>, action: impl Into<String>) -> Self {
Self {
resource: resource.into(),
action: action.into(),
}
}
#[must_use]
pub fn naming(resource: &ResourceSpec, action: &ActionSpec) -> Self {
Self::new(resource.id.as_str(), action.id.as_str())
}
#[must_use]
pub fn checked(resource: impl AsRef<str>, action: impl AsRef<str>) -> Option<Self> {
let (resource, action) = (resource.as_ref(), action.as_ref());
(!resource.is_empty()
&& !action.is_empty()
&& !resource.contains(KEY_SEP)
&& !action.contains(KEY_SEP))
.then(|| Self::new(resource, action))
}
pub fn encode(&self) -> String {
format!("{}{KEY_SEP}{}", self.resource, self.action)
}
pub fn parse(s: &str) -> Option<Self> {
let (resource, action) = s.split_once(KEY_SEP)?;
Self::checked(resource, action)
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum InputSpec {
None,
Text {
prompt: String,
placeholder: String,
collects: Collects,
},
}
impl ActionDescriptor {
#[must_use]
pub fn writes(&self) -> Option<String> {
if self.contract.effects.is_empty() {
return None;
}
let steps: Vec<String> = self
.contract
.effects
.iter()
.map(ToString::to_string)
.collect();
Some(format!("Writes: {}.", steps.join(", ")))
}
#[must_use]
pub fn changes_only_a_document(&self) -> bool {
self.kind == OperationKind::Document
|| self
.contract
.tags
.iter()
.any(|tag| tag == crate::ROUTED_CHANGE_TAG)
}
#[must_use]
pub fn prompt_param(&self) -> Option<&str> {
match self.input {
InputSpec::Text { .. } => self
.params
.iter()
.find(|param| param.entry)
.or_else(|| self.params.iter().find(|param| param.required))
.or_else(|| self.params.first())
.map(|param| param.name.as_ref()),
InputSpec::None => None,
}
}
#[must_use]
pub fn domain_resource(&self) -> &str {
match &self.semantic_identity {
Some(identity) if identity.is_valid() => identity.key.as_str(),
_ => self.address.resource.as_str(),
}
}
#[must_use]
pub fn entry_param(&self) -> Option<&str> {
self.params
.iter()
.find(|param| param.entry)
.map(|param| param.name.as_ref())
}
#[must_use]
pub fn bind_prompt_text(
&self,
mut arguments: serde_json::Map<String, serde_json::Value>,
) -> serde_json::Map<String, serde_json::Value> {
if arguments.len() == 1
&& let Some(name) = self.prompt_param()
&& name != crate::PROMPTED_PARAM
&& let Some(text) = arguments.remove(crate::PROMPTED_PARAM)
{
arguments.insert(name.to_owned(), text);
}
arguments
}
}
impl InputSpec {
fn of(input: ActionInput<'_>) -> Self {
match input {
ActionInput::Immediate(_) | ActionInput::Deferred { .. } => InputSpec::None,
ActionInput::Prompted {
prompt,
placeholder,
collects,
} => InputSpec::Text {
prompt: prompt.to_owned(),
placeholder: placeholder.to_owned(),
collects,
},
}
}
pub fn wants_text(&self) -> bool {
matches!(self, InputSpec::Text { .. })
}
pub fn wants_content(&self) -> bool {
matches!(
self,
InputSpec::Text {
collects: Collects::Content,
..
}
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ActionDescriptor {
pub address: ActionAddress,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub semantic_identity: Option<crate::ResourceSemanticIdentity>,
pub resource_kind: String,
pub resource_label: String,
pub action_label: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub did: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
pub state: crate::ActionState,
pub locus: ExecutionLocus,
pub kind: OperationKind,
pub contract: ActionContract,
pub input: InputSpec,
pub params: Vec<ActionParam>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<ResourceViewDescriptor>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ActionEffect {
pub app: String,
pub kind: String,
pub verb: String,
}
impl ActionEffect {
pub const UNDO: &'static str = "undo";
#[must_use]
pub fn undo(app: impl Into<String>) -> Self {
Self::new(app, "", Self::UNDO)
}
#[must_use]
pub fn undoes_in(&self, app: &str) -> bool {
self.app == app && self.kind.is_empty() && self.verb == Self::UNDO
}
#[must_use]
pub fn new(app: impl Into<String>, kind: impl Into<String>, verb: impl Into<String>) -> Self {
Self {
app: app.into(),
kind: kind.into(),
verb: verb.into(),
}
}
}
impl std::fmt::Display for ActionEffect {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.kind.is_empty() {
return write!(formatter, "{}#{}", self.app, self.verb);
}
write!(formatter, "{} {}#{}", self.app, self.kind, self.verb)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResourceViewDescriptor {
pub id: String,
pub label: String,
pub description: Option<String>,
pub open_action: String,
pub primary: bool,
pub mount: Option<ResourceViewMountSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub range: Option<ResourceViewRangeSpec>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub desktop: bool,
}
impl ResourceViewDescriptor {
#[must_use]
pub fn declared_for(resource: &ResourceSpec, action_id: &str) -> Option<Self> {
resource
.views
.iter()
.find(|view| view.open_action == action_id)
.map(|view| Self {
id: view.id.clone(),
label: view.label.clone(),
description: view.description.clone(),
open_action: view.open_action.clone(),
primary: view.primary,
mount: view.mount.clone(),
range: view.range.clone(),
desktop: view.desktop,
})
}
}
pub const NOT_THE_ASKED_PERSON: &str = "question-not-yours";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ApiError {
Unknown(ActionAddress),
MissingArgument(ActionAddress),
UnexpectedArgument(ActionAddress),
InvalidArguments(String),
ArgumentOutOfRange {
param: String,
violation: crate::params::ArgViolation,
},
Unavailable { code: String, reason: String },
ConfirmationRequired,
UnregisteredType(String),
Refused { code: String, reason: String },
Failed(String),
}
impl ApiError {
pub fn decoding(error: crate::action::ActionError) -> Self {
match error {
crate::action::ActionError::UnknownType(type_id) => ApiError::UnregisteredType(type_id),
other => ApiError::refused(other),
}
}
pub fn refused(error: crate::action::ActionError) -> Self {
match error {
crate::action::ActionError::Unavailable { code, message } => ApiError::Refused {
code,
reason: message,
},
other => ApiError::Failed(other.to_string()),
}
}
pub fn code(&self) -> &str {
match self {
ApiError::Unknown(_) | ApiError::UnregisteredType(_) => "unknown_action",
ApiError::MissingArgument(_)
| ApiError::UnexpectedArgument(_)
| ApiError::InvalidArguments(_)
| ApiError::ArgumentOutOfRange { .. } => "invalid_arguments",
ApiError::Unavailable { .. } => "action_unavailable",
ApiError::Refused { code, .. } => code,
ApiError::ConfirmationRequired => "action_confirmation_required",
ApiError::Failed(_) => "action_failed",
}
}
#[must_use]
pub fn failure_details(&self) -> Option<serde_json::Value> {
match self {
ApiError::ArgumentOutOfRange { param, violation } => {
Some(serde_json::json!({ "param": param, "violation": violation }))
}
ApiError::Unavailable { code, reason } => {
Some(serde_json::json!({ "code": code, "reason": reason }))
}
_ => None,
}
}
}
impl From<crate::params::ArgError> for ApiError {
fn from(error: crate::params::ArgError) -> Self {
match error {
crate::params::ArgError::OutOfRange { name, violation } => {
ApiError::ArgumentOutOfRange {
param: name,
violation,
}
}
error => ApiError::InvalidArguments(error.to_string()),
}
}
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ApiError::Unknown(a) => {
write!(f, "no action addressed by ({}, {})", a.resource, a.action)
}
ApiError::MissingArgument(a) => write!(
f,
"action ({}, {}) needs a text argument and none was given",
a.resource, a.action
),
ApiError::UnexpectedArgument(a) => {
write!(f, "action ({}, {}) takes no argument", a.resource, a.action)
}
ApiError::InvalidArguments(why) | ApiError::Failed(why) => write!(f, "{why}"),
ApiError::Refused { reason, .. } => f.write_str(reason),
ApiError::ArgumentOutOfRange { param, violation } => {
write!(f, "argument `{param}` {violation}")
}
ApiError::Unavailable { code, reason } => write!(f, "{code}: {reason}"),
ApiError::ConfirmationRequired => {
f.write_str("this action requires explicit confirmation")
}
ApiError::UnregisteredType(t) => {
write!(f, "no decoder registered for action type `{t}`")
}
}
}
}
impl std::error::Error for ApiError {}
pub fn survey(resources: &[ResourceSpec]) -> Vec<ActionDescriptor> {
survey_placed(resources)
.into_iter()
.map(|row| row.action)
.collect()
}
#[must_use]
pub fn publishes_same(a: &[ResourceSpec], b: &[ResourceSpec]) -> bool {
a.len() == b.len()
&& a.iter().zip(b).all(|(a, b)| {
a.id == b.id
&& a.kind == b.kind
&& a.label == b.label
&& a.presentation == b.presentation
&& a.semantic_identity == b.semantic_identity
&& a.app_id == b.app_id
&& a.views == b.views
&& a.personal == b.personal
&& a.workspace == b.workspace
&& a.resource_type == b.resource_type
&& a.actions.len() == b.actions.len()
&& a.actions
.iter()
.zip(&b.actions)
.all(|(x, y)| x.bound() == y.bound() && describe(a, x) == describe(b, y))
&& publishes_same(&a.children, &b.children)
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlacedAction {
pub parent: String,
pub has_children: bool,
pub action: ActionDescriptor,
}
#[must_use]
pub fn survey_placed(resources: &[ResourceSpec]) -> Vec<PlacedAction> {
let mut out = Vec::new();
let _ = survey_placed_each(resources, &mut |placed| {
out.push(placed);
true
});
out
}
pub fn survey_placed_each(
resources: &[ResourceSpec],
visit: &mut dyn FnMut(PlacedAction) -> bool,
) -> bool {
resources
.iter()
.all(|resource| placed_each(resource, "", visit))
}
pub fn survey_placed_level(
children: &[ResourceSpec],
parent: &str,
visit: &mut dyn FnMut(PlacedAction) -> bool,
) -> bool {
survey_placed_level_items(children, parent, &mut |_, placed| visit(placed))
}
pub fn survey_placed_level_items(
children: &[ResourceSpec],
parent: &str,
visit: &mut dyn FnMut(usize, PlacedAction) -> bool,
) -> bool {
children.iter().enumerate().all(|(at, child)| {
let has_children = !child.children.is_empty();
child.actions.iter().all(|action| {
visit(
at,
PlacedAction {
parent: parent.to_owned(),
has_children,
action: describe(child, action),
},
)
})
})
}
pub fn survey_placed_under(
resource: &ResourceSpec,
parent: &str,
visit: &mut dyn FnMut(PlacedAction) -> bool,
) -> bool {
placed_each(resource, parent, visit)
}
fn placed_each(
resource: &ResourceSpec,
parent: &str,
visit: &mut dyn FnMut(PlacedAction) -> bool,
) -> bool {
let has_children = !resource.children.is_empty();
for action in &resource.actions {
let go_on = visit(PlacedAction {
parent: parent.to_owned(),
has_children,
action: describe(resource, action),
});
if !go_on {
return false;
}
}
for child in &resource.children {
if !placed_each(child, resource.id.as_str(), visit) {
return false;
}
}
true
}
#[must_use]
pub fn described(resources: &[ResourceSpec], address: &ActionAddress) -> Option<ActionDescriptor> {
locate(resources, address).map(|(resource, action)| describe(resource, action))
}
fn describe(resource: &ResourceSpec, action: &ActionSpec) -> ActionDescriptor {
let view = ResourceViewDescriptor::declared_for(resource, &action.id);
ActionDescriptor {
address: ActionAddress::new(resource.id.as_str(), &action.id),
semantic_identity: resource.semantic_identity.clone(),
resource_kind: resource.kind.clone(),
resource_label: resource.label.clone(),
action_label: action.label.clone(),
keywords: action.keywords.clone(),
did: action.did.clone(),
icon: action.icon.clone(),
description: action.description.clone(),
state: action.state.clone(),
locus: action.locus,
kind: action.kind,
contract: action.contract.clone(),
input: InputSpec::of(action.input()),
params: action.params().to_vec(),
view,
}
}
pub fn resolve<'a>(
resources: &'a [ResourceSpec],
address: &ActionAddress,
) -> Option<&'a ActionSpec> {
locate(resources, address).map(|(_, spec)| spec)
}
pub fn locate<'a>(
resources: &'a [ResourceSpec],
address: &ActionAddress,
) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
fn walk<'a>(
r: &'a ResourceSpec,
address: &ActionAddress,
) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
if r.id.as_str() == address.resource
&& let Some(spec) = r.actions.iter().find(|a| a.id == address.action)
{
return Some((r, spec));
}
r.children.iter().find_map(|c| walk(c, address))
}
resources.iter().find_map(|r| walk(r, address))
}
pub fn published(
resources: &[ResourceSpec],
resource: &str,
action: &str,
) -> Option<ActionAddress> {
fn walk(r: &ResourceSpec, resource: &str, action: &str) -> Option<ActionAddress> {
if r.id.as_str() == resource
&& let Some(address) = r.action_address(action)
{
return Some(address);
}
r.children.iter().find_map(|c| walk(c, resource, action))
}
resources.iter().find_map(|r| walk(r, resource, action))
}
pub fn spec_of<'a>(
resources: &'a [ResourceSpec],
resource: &str,
action: &str,
) -> Option<&'a ActionSpec> {
published(resources, resource, action).and_then(|address| resolve(resources, &address))
}
pub fn encode(
resources: &[ResourceSpec],
address: &ActionAddress,
argument: Option<&str>,
) -> Result<EncodedAction, ApiError> {
let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
ensure_available(spec)?;
spec.validate_deferred_shape()
.map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
match (spec.input(), argument) {
(ActionInput::Deferred { type_id }, None) => {
let Some(encoded) = spec.build_deferred() else {
return Err(ApiError::Unknown(address.clone()));
};
if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
return Err(ApiError::InvalidArguments(
String::from_utf8_lossy(&encoded.payload).into_owned(),
));
}
if encoded.type_id != *type_id {
return Err(ApiError::InvalidArguments(format!(
"builder returned `{}` but declared `{type_id}`",
encoded.type_id
)));
}
Ok(encoded)
}
(ActionInput::Deferred { .. }, Some(_)) => {
Err(ApiError::UnexpectedArgument(address.clone()))
}
(ActionInput::Immediate(_), None) => spec
.encode_immediate()
.map(std::sync::Arc::unwrap_or_clone)
.ok_or_else(|| ApiError::Unknown(address.clone())),
(ActionInput::Immediate(_), Some(_)) => Err(ApiError::UnexpectedArgument(address.clone())),
(ActionInput::Prompted { .. }, Some(text)) => {
let Some(encoded) = spec.build_text(text) else {
return Err(ApiError::Unknown(address.clone()));
};
if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
return Err(ApiError::InvalidArguments(
String::from_utf8_lossy(&encoded.payload).into_owned(),
));
}
Ok(encoded)
}
(ActionInput::Prompted { .. }, None)
if !spec.params().is_empty() && spec.params().iter().all(|param| !param.required) =>
{
let encoded = spec
.build_json(&serde_json::Map::new())
.map_err(ApiError::from)?;
if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
return Err(ApiError::InvalidArguments(
String::from_utf8_lossy(&encoded.payload).into_owned(),
));
}
Ok(encoded)
}
(ActionInput::Prompted { .. }, None) => Err(ApiError::MissingArgument(address.clone())),
}
}
pub fn encode_json(
resources: &[ResourceSpec],
address: &ActionAddress,
arguments: &serde_json::Map<String, serde_json::Value>,
) -> Result<EncodedAction, ApiError> {
let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
ensure_available(spec)?;
let encoded = spec.build_json(arguments).map_err(ApiError::from)?;
if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
return Err(ApiError::InvalidArguments(
String::from_utf8_lossy(&encoded.payload).into_owned(),
));
}
Ok(encoded)
}
pub fn admit(
resources: &[ResourceSpec],
address: &ActionAddress,
arguments: &serde_json::Map<String, serde_json::Value>,
confirmation: Option<&crate::remote::Confirmation>,
) -> Result<EncodedAction, ApiError> {
let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
ensure_available(spec)?;
if !spec.confirmation_for_json(arguments).met_by(confirmation) {
return Err(ApiError::ConfirmationRequired);
}
encode_json(resources, address, arguments)
}
fn ensure_available(spec: &ActionSpec) -> Result<(), ApiError> {
match &spec.contract.availability {
crate::Availability::Available => Ok(()),
crate::Availability::Unavailable { code, reason } => Err(ApiError::Unavailable {
code: code.clone(),
reason: reason.clone(),
}),
}
}
#[derive(Clone, Copy, Debug)]
pub struct InvocationProvenance<'a> {
pub actor: &'a [u8],
pub ambient: Option<&'a ActionContext>,
}
impl<'a> InvocationProvenance<'a> {
#[must_use]
pub const fn caller(actor: &'a [u8]) -> Self {
Self {
actor,
ambient: None,
}
}
#[must_use]
pub const fn within(self, ambient: &'a ActionContext) -> Self {
Self {
actor: self.actor,
ambient: Some(ambient),
}
}
}
pub fn invoke(
doc: &mut crate::action::Doc,
resources: &[ResourceSpec],
address: &ActionAddress,
argument: Option<&str>,
(provenance, confirmed): (InvocationProvenance<'_>, bool),
registry: &ActionRegistry,
transport: &mut dyn ActionTransport,
) -> Result<Dispatched, ApiError> {
ensure_confirmation(resources, address, confirmed, |spec| {
spec.confirmation_for_argument(argument)
})?;
ensure_deferred_local_owner(resources, address, registry)?;
let encoded = encode(resources, address, argument)?;
dispatch_encoded_with_context(
doc, resources, address, encoded, provenance, registry, transport,
)
}
pub fn invoke_json(
doc: &mut crate::action::Doc,
resources: &[ResourceSpec],
address: &ActionAddress,
arguments: &serde_json::Map<String, serde_json::Value>,
(provenance, confirmed): (InvocationProvenance<'_>, bool),
registry: &ActionRegistry,
transport: &mut dyn ActionTransport,
) -> Result<Dispatched, ApiError> {
ensure_confirmation(resources, address, confirmed, |spec| {
spec.confirmation_for_json(arguments)
})?;
ensure_deferred_local_owner(resources, address, registry)?;
let encoded = encode_json(resources, address, arguments)?;
dispatch_encoded_with_context(
doc, resources, address, encoded, provenance, registry, transport,
)
}
fn ensure_confirmation(
resources: &[ResourceSpec],
address: &ActionAddress,
confirmed: bool,
policy: impl FnOnce(&ActionSpec) -> crate::ConfirmationPolicy,
) -> Result<(), ApiError> {
let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
if !matches!(policy(spec), crate::ConfirmationPolicy::None) && !confirmed {
return Err(ApiError::ConfirmationRequired);
}
Ok(())
}
fn ensure_deferred_local_owner(
resources: &[ResourceSpec],
address: &ActionAddress,
registry: &ActionRegistry,
) -> Result<(), ApiError> {
let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
if spec.deferred_invocation_type().is_some()
|| matches!(spec.input(), ActionInput::Deferred { .. })
{
spec.validate_deferred_shape()
.map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
if spec.kind != OperationKind::Document || spec.locus != ExecutionLocus::ClientLocal {
return Err(ApiError::Unavailable {
code: "deferred_owner_required".into(),
reason: "This creation must use the owning application's address-based action API"
.into(),
});
}
if let Some(type_id) = spec.deferred_invocation_type()
&& !registry.contains(type_id)
{
return Err(ApiError::UnregisteredType(type_id.into()));
}
}
Ok(())
}
fn dispatch_encoded_with_context(
doc: &mut crate::action::Doc,
resources: &[ResourceSpec],
address: &ActionAddress,
encoded: EncodedAction,
provenance: InvocationProvenance<'_>,
registry: &ActionRegistry,
transport: &mut dyn ActionTransport,
) -> Result<Dispatched, ApiError> {
let resource = find_resource(resources, &address.resource)
.ok_or_else(|| ApiError::Unknown(address.clone()))?;
let spec = resource
.actions
.iter()
.find(|candidate| candidate.id == address.action)
.ok_or_else(|| ApiError::Unknown(address.clone()))?;
if spec.kind != OperationKind::Document {
return Err(ApiError::Failed(format!(
"{} operation must be handled by the owning application",
spec.kind.as_str()
)));
}
let mut context = spec.history_context(resource.id.as_str(), &resource.kind, &resource.label);
if let Some(ambient) = provenance.ambient {
context = context.enriched_by(ambient);
}
if !spec.carries_actions()
&& let Some(described) = Described::of_published(
&encoded,
crate::ActionKey::new("", &resource.kind, &spec.id),
)
{
context = context.with_described(described);
}
let action = registry.decode(&encoded).map_err(ApiError::decoding)?;
if spec.deferred_invocation_type().is_some() && action.locus() != spec.locus {
return Err(ApiError::Failed(
"Deferred action locus differs from its declaration".into(),
));
}
dispatch_by_with_context(
doc,
action.as_ref(),
encoded,
transport,
Some(provenance.actor),
context,
)
.map_err(ApiError::refused)
}
#[must_use]
pub fn find_resource<'a>(resources: &'a [ResourceSpec], id: &str) -> Option<&'a ResourceSpec> {
fn walk<'a>(resource: &'a ResourceSpec, id: &str) -> Option<&'a ResourceSpec> {
if resource.id.as_str() == id {
return Some(resource);
}
resource.children.iter().find_map(|child| walk(child, id))
}
resources.iter().find_map(|resource| walk(resource, id))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::{Action, ActionError, Doc};
use crate::executor::{LocalTransport, replay};
use automerge::transaction::Transactable;
use automerge::{AutoCommit, ROOT, ReadDoc, ScalarValue};
use serde::{Deserialize, Serialize};
const NOTE_TYPE: &str = "test.note";
#[derive(Debug, Clone, Serialize, Deserialize)]
enum Note {
Star,
Retitle(String),
}
impl Action for Note {
fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
match self {
Note::Star => {
doc.put(&ROOT, "starred", ScalarValue::Boolean(true))?;
}
Note::Retitle(title) => {
doc.put(&ROOT, "title", ScalarValue::Str(title.as_str().into()))?;
}
}
Ok(())
}
}
fn registry() -> ActionRegistry {
let mut r = ActionRegistry::new();
r.register::<Note>(NOTE_TYPE);
r
}
fn encoded(action: &Note) -> EncodedAction {
EncodedAction::encode(NOTE_TYPE, action).unwrap()
}
fn note(star_does: &Note, retitle_does: fn(&str) -> Note) -> Vec<ResourceSpec> {
vec![
ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
.with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, star_does).unwrap())
.with_action(ActionSpec::prompted_param(
"retitle",
"Rename",
ActionParam::required("title", crate::ParamType::Text, "New title"),
"title",
ExecutionLocus::ClientLocal,
move |text| encoded(&retitle_does(text)),
)),
]
}
fn open() -> Vec<ResourceSpec> {
note(&Note::Star, |text| Note::Retitle(text.to_string()))
}
fn star() -> ActionAddress {
ActionAddress::new("notes.note:1", "star")
}
fn retitle() -> ActionAddress {
ActionAddress::new("notes.note:1", "retitle")
}
fn perform(
doc: &mut Doc,
tree: &[ResourceSpec],
address: &ActionAddress,
argument: Option<&str>,
) -> Result<Dispatched, ApiError> {
invoke(
doc,
tree,
address,
argument,
(InvocationProvenance::caller(b"caller-key"), false),
®istry(),
&mut LocalTransport::new(),
)
}
fn a_descriptor_carries_nothing_that_could_act() {
let honest = open();
let hijacked = note(&Note::Retitle("hijacked".into()), |_| Note::Star);
assert_eq!(
survey(&honest),
survey(&hijacked),
"descriptors that differ only in what they would run must not differ"
);
let mut a = AutoCommit::new();
perform(&mut a, &honest, &star(), None).unwrap();
let mut b = AutoCommit::new();
perform(&mut b, &hijacked, &star(), None).unwrap();
assert_eq!(
a.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
Some(true)
);
assert!(b.get(&ROOT, "starred").unwrap().is_none());
assert_eq!(
b.get(&ROOT, "title")
.unwrap()
.unwrap()
.0
.into_string()
.unwrap(),
"hijacked",
"the same descriptor performed a different operation — so it holds none of it"
);
let described = survey(&honest);
drop(honest);
assert_eq!(described.len(), 2);
}
tilo_test_env::scenario! {
fn a_survey_describes_without_acting;
phase surveying_through_the_api_describes_without_acting;
{
a_descriptor_carries_nothing_that_could_act();
survey_annotates_only_the_declared_view_open_action();
enumeration_leaves_the_document_untouched();
an_address_survives_its_string_form();
}
phase a_survey_names_the_row_each_action_stands_in;
{
let leaf = ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
.with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap());
let folder = ResourceSpec::new("notes.folder:a", "notes.folder", "Trips")
.with_action(
ActionSpec::immediate("archive", "Archive", NOTE_TYPE, &Note::Star).unwrap(),
)
.with_child(leaf);
let placed = survey_placed(std::slice::from_ref(&folder));
let at = |action: &str| {
placed
.iter()
.find(|placed| placed.action.address.action == action)
.expect("the action was surveyed")
};
let archived = at("archive");
assert_eq!(archived.parent, "", "the folder stands at the top level");
assert!(archived.has_children, "the folder holds the note below it");
let starred = at("star");
assert_eq!(starred.parent, "notes.folder:a", "the note is under it");
assert!(
!starred.has_children,
"nothing stands below the note: the listing ends here"
);
assert_eq!(
survey(std::slice::from_ref(&folder))
.iter()
.map(|descriptor| descriptor.address.action.clone())
.collect::<Vec<_>>(),
placed
.iter()
.map(|placed| placed.action.address.action.clone())
.collect::<Vec<_>>(),
);
}
}
fn survey_annotates_only_the_declared_view_open_action() {
let open =
ActionSpec::operation("open", "Open", OperationKind::View, "notes.open", &()).unwrap();
let select =
ActionSpec::operation("select", "Select", OperationKind::View, "notes.select", &())
.unwrap();
let resource = ResourceSpec::new("note:1", "notes.note", "Harbour")
.with_action(open)
.with_action(select)
.with_view(
crate::ResourceViewSpec::new("editor", "Editor", "open")
.with_description("Edit the note")
.with_primary(true),
);
let descriptors = survey(&[resource]);
let open = descriptors
.iter()
.find(|descriptor| descriptor.address.action == "open")
.unwrap();
assert_eq!(
open.view,
Some(ResourceViewDescriptor {
id: "editor".into(),
label: "Editor".into(),
description: Some("Edit the note".into()),
open_action: "open".into(),
primary: true,
range: None,
mount: None,
desktop: false,
})
);
assert!(
descriptors
.iter()
.find(|descriptor| descriptor.address.action == "select")
.unwrap()
.view
.is_none()
);
}
fn an_address_that_no_longer_resolves_is_refused_not_redirected() {
let address = survey(&open())[0].address.clone();
assert_eq!(address, star());
let now = vec![
ResourceSpec::new("notes.note:2", "notes.note", "Log").with_action(
ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
),
];
assert!(resolve(&now, &address).is_none());
let mut doc = AutoCommit::new();
let before = doc.get_heads();
let err = perform(&mut doc, &now, &address, None).unwrap_err();
assert_eq!(err, ApiError::Unknown(address));
assert_eq!(err.code(), "unknown_action");
assert_eq!(doc.get_heads(), before, "a refused address left no change");
assert!(doc.get(&ROOT, "starred").unwrap().is_none());
}
fn an_argument_that_does_not_match_the_declaration_is_refused() {
let tree = open();
let described = survey(&tree);
let spec = described.iter().find(|d| d.address == retitle()).unwrap();
assert!(spec.input.wants_text());
assert!(!spec.input.wants_content());
let mut doc = AutoCommit::new();
let before = doc.get_heads();
let err = perform(&mut doc, &tree, &retitle(), None).unwrap_err();
assert_eq!(err, ApiError::MissingArgument(retitle()));
assert_eq!(err.code(), "invalid_arguments");
let err = perform(&mut doc, &tree, &star(), Some("Log")).unwrap_err();
assert_eq!(err, ApiError::UnexpectedArgument(star()));
assert_eq!(err.code(), "invalid_arguments");
assert_eq!(doc.get_heads(), before, "a refused call left no change");
assert!(doc.get(&ROOT, "title").unwrap().is_none());
assert!(doc.get(&ROOT, "starred").unwrap().is_none());
}
fn an_unregistered_action_type_is_refused_rather_than_applied() {
let tree = open();
let mut doc = AutoCommit::new();
let before = doc.get_heads();
let err = invoke(
&mut doc,
&tree,
&star(),
None,
(InvocationProvenance::caller(b"caller-key"), false),
&ActionRegistry::new(),
&mut LocalTransport::new(),
)
.unwrap_err();
assert_eq!(err, ApiError::UnregisteredType(NOTE_TYPE.into()));
assert_eq!(doc.get_heads(), before);
assert!(doc.get(&ROOT, "starred").unwrap().is_none());
}
fn a_payload_its_decoder_cannot_read_is_not_called_unregistered() {
#[derive(Debug, Serialize, Deserialize)]
struct OtherShape {
#[serde(rename = "pinned")]
_pinned: bool,
}
impl Action for OtherShape {
fn apply(&self, _doc: &mut Doc) -> Result<(), ActionError> {
Ok(())
}
}
let tree = open();
let mut doc = AutoCommit::new();
let before = doc.get_heads();
let mut other = ActionRegistry::new();
other.register::<OtherShape>(NOTE_TYPE);
let err = invoke(
&mut doc,
&tree,
&star(),
None,
(InvocationProvenance::caller(b"caller-key"), false),
&other,
&mut LocalTransport::new(),
)
.unwrap_err();
let ApiError::Failed(why) = &err else {
panic!("a payload the decoder cannot read is its own failure: {err:?}");
};
assert!(why.contains(NOTE_TYPE), "{why}");
assert_eq!(doc.get_heads(), before);
}
fn notes(doc: &AutoCommit) -> Vec<ResourceSpec> {
let label = doc
.get(&ROOT, "title")
.ok()
.flatten()
.and_then(|(v, _)| v.into_string().ok())
.unwrap_or_else(|| "Untitled".into());
vec![
ResourceSpec::new("notes.note:1", "notes.note", label).with_action(
ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
),
]
}
fn enumeration_leaves_the_document_untouched() {
let mut doc = AutoCommit::new();
doc.put(&ROOT, "title", ScalarValue::Str("Harbour".into()))
.unwrap();
doc.commit();
let heads = doc.get_heads();
let saved = doc.save();
let first = survey(¬es(&doc));
let second = survey(¬es(&doc));
assert_eq!(first, second);
assert_eq!(
first.len(),
1,
"the survey found something to be side-effect free about"
);
assert_eq!(
first[0].resource_label, "Harbour",
"it really read the document"
);
assert_eq!(doc.get_heads(), heads);
assert_eq!(doc.save(), saved, "surveying rewrote the document");
}
fn a_change_through_the_api_is_attributed_to_the_caller() {
let mut doc = AutoCommit::new();
doc.put(&ROOT, "seed", ScalarValue::Str("s".into()))
.unwrap();
doc.commit();
let app_actor = doc.get_actor().clone();
let mut peer = AutoCommit::load(&doc.save()).unwrap();
let caller: &[u8] = b"maren-device-key";
let notes = ActionContext::default().with_app("org.tilo.Notes", "Notes");
let mut transport = LocalTransport::new();
let dispatched = invoke(
&mut doc,
&open(),
&star(),
None,
(InvocationProvenance::caller(caller).within(¬es), false),
®istry(),
&mut transport,
)
.unwrap();
assert!(dispatched.mutated_local());
let env = dispatched.envelope().clone();
assert_eq!(env.actor.as_deref(), Some(caller));
let context = env.context.as_ref().expect("the API supplies provenance");
assert_eq!(published_verb(context), "star");
assert_eq!(
context
.resource
.as_ref()
.map(|resource| resource.id.as_str()),
Some("notes.note:1")
);
let heads = doc.get_heads();
let change = doc.get_change_by_hash(&heads[0]).unwrap();
assert_eq!(change.actor_id().to_bytes(), caller);
assert_eq!(
change
.message()
.and_then(ActionContext::from_change_message),
env.context,
"semantic provenance survives as part of the durable change"
);
assert_ne!(change.actor_id(), &app_actor, "not the app's own actor");
assert_ne!(
change.actor_id().to_bytes(),
&env.id.actor_bytes()[..],
"not the action id's derived actor"
);
replay(&mut peer, &env, ®istry()).unwrap();
assert_eq!(
peer.get_heads(),
heads,
"attribution must not cost the identical replay"
);
assert_eq!(transport.replicated.len(), 1);
}
fn ambient_task_context_reaches_api_actions_without_overwriting_resource() {
let mut doc = AutoCommit::new();
let mut transport = LocalTransport::new();
let ambient = ActionContext::default()
.with_app("org.tilo.Notes", "Notes")
.with_purpose("Prepare launch")
.with_group("issue:42", "Launch", "issue");
let dispatched = invoke(
&mut doc,
&open(),
&star(),
None,
(
InvocationProvenance {
actor: b"agent:ada",
ambient: Some(&ambient),
},
false,
),
®istry(),
&mut transport,
)
.expect("the API answered");
let context = dispatched.envelope().context.as_ref().expect("context");
assert_eq!(published_verb(context), "star");
assert_eq!(context.purpose.as_deref(), Some("Prepare launch"));
assert_eq!(
context.group.as_ref().map(|group| group.id.as_str()),
Some("issue:42")
);
assert_eq!(
context
.resource
.as_ref()
.map(|resource| resource.id.as_str()),
Some("notes.note:1")
);
}
fn consequential_actions_cannot_cross_the_api_without_consent() {
let resources = vec![
ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
.unwrap()
.with_contract(ActionContract {
confirmation: crate::ConfirmationPolicy::Confirm,
..ActionContract::default()
}),
),
];
let mut doc = AutoCommit::new();
let mut transport = LocalTransport::new();
let refusal = invoke(
&mut doc,
&resources,
&star(),
None,
(InvocationProvenance::caller(b"caller-key"), false),
®istry(),
&mut transport,
)
.unwrap_err();
assert_eq!(refusal, ApiError::ConfirmationRequired);
assert!(doc.get(&ROOT, "starred").unwrap().is_none());
invoke(
&mut doc,
&resources,
&star(),
None,
(InvocationProvenance::caller(b"caller-key"), true),
®istry(),
&mut transport,
)
.expect("a policy check may explicitly attest confirmation");
assert_eq!(
doc.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
Some(true)
);
}
fn edit_by_value() -> Vec<ResourceSpec> {
vec![
ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
ActionSpec::typed(
"edit",
"Edit",
"title",
ExecutionLocus::ClientLocal,
vec![ActionParam::required(
"title",
crate::ParamType::Text,
"Title",
)],
|args| encoded(&Note::Retitle(args.text("title").unwrap_or("").to_owned())),
)
.for_audience(crate::Audience::Agents)
.with_risk(|args| {
if args.text("title").is_some_and(str::is_empty) {
crate::RiskLevel::Destructive
} else {
crate::RiskLevel::Low
}
}),
),
]
}
fn edit() -> ActionAddress {
ActionAddress::new("notes.note:1", "edit")
}
fn title(value: &str) -> serde_json::Map<String, serde_json::Value> {
serde_json::Map::from_iter([("title".to_owned(), serde_json::json!(value))])
}
fn stored_title(doc: &AutoCommit) -> Option<String> {
doc.get(&ROOT, "title")
.unwrap()
.and_then(|(value, _)| value.into_string().ok())
}
fn a_value_classified_as_destructive_needs_the_same_consent() {
let resources = edit_by_value();
let mut doc = AutoCommit::new();
let mut transport = LocalTransport::new();
let registry = registry();
let mut run = |doc: &mut AutoCommit, value: &str, confirmed: bool| {
invoke_json(
doc,
&resources,
&edit(),
&title(value),
(InvocationProvenance::caller(b"caller-key"), confirmed),
®istry,
&mut transport,
)
.map(|_| ())
};
run(&mut doc, "Harbour", false).expect("an ordinary value runs");
assert_eq!(
run(&mut doc, "", false).unwrap_err(),
ApiError::ConfirmationRequired
);
assert_eq!(
stored_title(&doc).as_deref(),
Some("Harbour"),
"the refused value changed nothing"
);
run(&mut doc, "", true).expect("a confirmed destructive value runs");
assert_eq!(stored_title(&doc).as_deref(), Some(""));
let mut transport = LocalTransport::new();
assert_eq!(
invoke(
&mut doc,
&resources,
&edit(),
Some(""),
(InvocationProvenance::caller(b"caller-key"), false),
®istry,
&mut transport,
)
.unwrap_err(),
ApiError::ConfirmationRequired
);
}
fn agent_session() -> ActionContext {
ActionContext::default()
.with_app("org.tilo.Agent", "Agent")
.with_purpose("Remove the draft marks")
.with_group("agent-session:7", "Remove the draft marks", "agent-session")
}
fn published_verb(context: &ActionContext) -> &str {
let Some(crate::Did::Verb(verb)) = &context.what else {
panic!("a verb: {context:?}");
};
assert_eq!(verb.action.kind, "notes.note");
assert!(!verb.action.app.is_empty(), "the app is filled in");
&verb.action.action
}
fn assert_recorded_within_run(doc: &mut AutoCommit, action: &str) {
let heads = doc.get_heads();
let change = doc
.get_change_by_hash(&heads[0])
.expect("the API committed");
assert_eq!(change.actor_id().to_bytes(), b"agent:ada");
let context = change
.message()
.and_then(ActionContext::from_change_message)
.expect("the change carries its semantic provenance");
assert_eq!(published_verb(&context), action);
assert_eq!(
context
.resource
.as_ref()
.map(|resource| resource.id.as_str()),
Some("notes.note:1"),
"the resource stays authoritative"
);
let group = context.group.as_ref().expect("the run's group is recorded");
assert_eq!(group.id, "agent-session:7");
assert_eq!(group.kind, "agent-session");
assert_eq!(context.purpose.as_deref(), Some("Remove the draft marks"));
}
tilo_test_env::scenario! {
fn an_invocation_through_the_api_is_checked_and_recorded;
phase invoking_through_the_api_refuses_mismatches_and_attributes_the_caller;
{
an_address_that_no_longer_resolves_is_refused_not_redirected();
an_argument_that_does_not_match_the_declaration_is_refused();
an_unregistered_action_type_is_refused_rather_than_applied();
a_payload_its_decoder_cannot_read_is_not_called_unregistered();
a_change_through_the_api_is_attributed_to_the_caller();
ambient_task_context_reaches_api_actions_without_overwriting_resource();
}
phase an_optional_only_prompt_runs_without_its_argument;
{
let tree = vec![
ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
ActionSpec::prompted_param(
"retitle",
"Rename",
ActionParam::optional("title", crate::ParamType::Text, "New title"),
"title",
ExecutionLocus::ClientLocal,
|text| encoded(&Note::Retitle(format!("[{text}]"))),
),
),
];
let mut doc = AutoCommit::new();
perform(&mut doc, &tree, &retitle(), None).unwrap();
assert_eq!(
doc.get(&ROOT, "title")
.unwrap()
.unwrap()
.0
.into_string()
.unwrap(),
"[]",
"the omitted optional text binds as nothing typed"
);
let mut doc = AutoCommit::new();
let err = perform(&mut doc, &open(), &retitle(), None).unwrap_err();
assert_eq!(err, ApiError::MissingArgument(retitle()));
}
phase a_wire_text_argument_goes_under_the_actions_own_prompt_parameter;
{
let tree = open();
let described = survey(&tree);
let retitle_spec = described.iter().find(|d| d.address == retitle()).unwrap();
assert_eq!(retitle_spec.prompt_param(), Some("title"));
let lone = serde_json::json!({ crate::PROMPTED_PARAM: "Log" })
.as_object()
.unwrap()
.clone();
assert_eq!(
retitle_spec.bind_prompt_text(lone.clone()),
serde_json::json!({"title": "Log"})
.as_object()
.unwrap()
.clone()
);
let named = serde_json::json!({"title": "Log"})
.as_object()
.unwrap()
.clone();
assert_eq!(retitle_spec.bind_prompt_text(named.clone()), named);
let star_spec = described.iter().find(|d| d.address == star()).unwrap();
assert_eq!(star_spec.prompt_param(), None);
assert_eq!(star_spec.bind_prompt_text(lone.clone()), lone);
}
phase consequential_api_actions_need_consent_whatever_form_the_argument_takes;
{
consequential_actions_cannot_cross_the_api_without_consent();
a_value_classified_as_destructive_needs_the_same_consent();
effective_confirmation_reads_every_argument_form();
}
phase a_confirmed_invocation_inside_a_run_is_recorded_with_its_group;
{
let resources = vec![
ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
.unwrap()
.destructive(),
),
];
let run = agent_session();
let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
let mut doc = AutoCommit::new();
let mut transport = LocalTransport::new();
assert_eq!(
invoke(
&mut doc,
&resources,
&star(),
None,
(provenance, false),
®istry(),
&mut transport,
)
.unwrap_err(),
ApiError::ConfirmationRequired
);
let dispatched = invoke(
&mut doc,
&resources,
&star(),
None,
(provenance, true),
®istry(),
&mut transport,
)
.expect("a confirmed destructive action runs");
assert_eq!(
dispatched
.envelope()
.context
.as_ref()
.and_then(|context| context.group.as_ref())
.map(|group| group.id.as_str()),
Some("agent-session:7"),
"the replicated envelope carries the run too"
);
assert_recorded_within_run(&mut doc, "star");
}
phase typed_invocations_inside_a_run_are_recorded_with_its_group;
{
let resources = edit_by_value();
let run = agent_session();
let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
let mut doc = AutoCommit::new();
let mut transport = LocalTransport::new();
invoke_json(
&mut doc,
&resources,
&edit(),
&title("Harbour"),
(provenance, false),
®istry(),
&mut transport,
)
.expect("an ordinary value runs");
assert_recorded_within_run(&mut doc, "edit");
invoke_json(
&mut doc,
&resources,
&edit(),
&title(""),
(provenance, true),
®istry(),
&mut transport,
)
.expect("a confirmed destructive value runs");
assert_eq!(stored_title(&doc).as_deref(), Some(""));
assert_recorded_within_run(&mut doc, "edit");
}
}
fn effective_confirmation_reads_every_argument_form() {
let resources = edit_by_value();
let spec = resolve(&resources, &edit()).unwrap();
let none = crate::ConfirmationPolicy::None;
let confirm = crate::ConfirmationPolicy::Confirm;
assert_eq!(spec.confirmation_for_json(&title("x")), none);
assert_eq!(spec.confirmation_for_json(&title("")), confirm);
assert_eq!(spec.confirmation_for_argument(Some("x")), none);
assert_eq!(spec.confirmation_for_argument(Some("")), confirm);
let typed = format!("{}{{\"title\":\"\"}}", crate::ARGUMENTS_JSON_PREFIX);
assert_eq!(spec.confirmation_for_argument(Some(&typed)), confirm);
assert_eq!(spec.confirmation_for_json(&serde_json::Map::new()), none);
assert!(!spec.reaches_people() && !spec.contract.reaches_people());
assert!(spec.contract.confirmation_depends_on_arguments());
assert_eq!(spec.contract.confirmation, none);
assert_eq!(spec.contract.advertised_confirmation(), confirm);
assert!(spec.contract.validate_declaration().is_empty());
let declared = spec.clone().destructive();
assert_eq!(declared.confirmation_for_json(&title("x")), confirm);
}
fn an_address_survives_its_string_form() {
let address = star();
assert_eq!(ActionAddress::parse(&address.encode()), Some(address));
let one = ActionAddress::new("notes.note:1", "edit");
assert_eq!(ActionAddress::parse(&one.encode()), Some(one));
assert_eq!(ActionAddress::parse("notes.note:1"), None);
assert_eq!(ActionAddress::parse(&format!("{KEY_SEP}star")), None);
assert_eq!(
ActionAddress::parse(&format!("notes{KEY_SEP}{KEY_SEP}edit")),
None
);
assert_eq!(
ActionAddress::parse(&format!("notes.note{KEY_SEP}notes.note:1{KEY_SEP}edit")),
None
);
assert_eq!(
ActionAddress::checked("notes.note:1", "edit"),
Some(ActionAddress::new("notes.note:1", "edit"))
);
assert_eq!(ActionAddress::checked("", "edit"), None);
assert_eq!(ActionAddress::checked("notes.note:1", ""), None);
assert_eq!(
ActionAddress::checked(format!("notes{KEY_SEP}note"), "edit"),
None
);
assert_eq!(
ActionAddress::checked("notes.note:1", format!("edit{KEY_SEP}title")),
None
);
}
const OP: &str = "test.operation";
fn published_tree() -> Vec<ResourceSpec> {
use crate::{ActionContract, ConfirmationPolicy, ParamType, RiskLevel};
let encode =
|value: serde_json::Value| EncodedAction::encode_operation(OP, &value).unwrap();
vec![
ResourceSpec::new("session", "test.session", "Session")
.with_action(ActionSpec::typed_operation(
"rename",
"Rename",
"name",
OperationKind::Effect,
OP,
vec![crate::ActionParam::required(
"name",
ParamType::Text,
"New name",
)],
move |args| encode(serde_json::json!({"rename": args.text("name")})),
))
.with_action(
ActionSpec::operation("reset", "Reset", OperationKind::Effect, OP, &"reset")
.unwrap()
.unavailable("not_now", "Finish the current step first"),
)
.with_child(
ResourceSpec::new("disk:/dev/vdb", "test.disk", "vdb").with_action(
ActionSpec::operation(
"erase",
"Erase",
OperationKind::Effect,
OP,
&"erase",
)
.unwrap()
.destructive()
.with_contract(ActionContract {
risk: RiskLevel::Destructive,
confirmation: ConfirmationPolicy::Phrase {
phrase: "/dev/vdb".into(),
},
..ActionContract::default()
}),
),
)
.with_child(
ResourceSpec::new("power", "test.power", "Power").with_action(
ActionSpec::operation(
"off",
"Power off",
OperationKind::Effect,
OP,
&"off",
)
.unwrap()
.privileged(),
),
),
]
}
#[test]
fn a_published_tree_is_listed_and_admits_only_exact_confirmed_bindings() {
use crate::remote::{CataloguePage, CatalogueQuery, Confirmation};
let tree = published_tree();
let page = CataloguePage::published("test", &tree, &CatalogueQuery::default());
assert_eq!(page.rows.len(), 2);
assert!(page.rows.iter().all(|row| row.provider == "test"));
let held = CatalogueQuery {
parent_resource: Some("session".into()),
..CatalogueQuery::default()
};
let held = CataloguePage::published("test", &tree, &held);
assert_eq!(held.rows.len(), 2);
let erase = held
.rows
.iter()
.find_map(|row| row.action.as_ref().filter(|a| a.address.action == "erase"))
.unwrap();
assert_eq!(erase.address.resource, "disk:/dev/vdb");
let narrowed = CatalogueQuery {
needle: "power".into(),
parent_resource: Some("session".into()),
..CatalogueQuery::default()
};
assert_eq!(
CataloguePage::published("test", &tree, &narrowed)
.rows
.len(),
1
);
let args = |value: serde_json::Value| value.as_object().unwrap().clone();
let admitted = |resource: &str, action: &str, value, confirmation: Option<Confirmation>| {
admit(
&tree,
&ActionAddress::new(resource, action),
&args(value),
confirmation.as_ref(),
)
};
assert_eq!(
admitted("session", "rename", serde_json::json!({"name": "x"}), None)
.unwrap()
.type_id,
OP
);
for (resource, action, value, refusal) in [
("session", "nope", serde_json::json!({}), "unknown"),
("session", "rename", serde_json::json!({}), "argument"),
(
"session",
"rename",
serde_json::json!({"name": 3}),
"argument",
),
(
"session",
"rename",
serde_json::json!({"name": "x", "extra": 1}),
"argument",
),
("session", "reset", serde_json::json!({}), "unavailable"),
] {
let error = admitted(resource, action, value, None).unwrap_err();
let kind = match error {
ApiError::Unknown(_) => "unknown",
ApiError::Unavailable { .. } => "unavailable",
ApiError::MissingArgument(_)
| ApiError::UnexpectedArgument(_)
| ApiError::InvalidArguments(_) => "argument",
other => panic!("{other:?}"),
};
assert_eq!(kind, refusal, "{action}");
}
let erase = |confirmation| {
admitted(
"disk:/dev/vdb",
"erase",
serde_json::json!({}),
confirmation,
)
};
for wrong in [
None,
Some(Confirmation::Phrase("/dev/vda".into())),
Some(Confirmation::Operated),
] {
assert!(matches!(erase(wrong), Err(ApiError::ConfirmationRequired)));
}
assert!(erase(Some(Confirmation::Phrase("/dev/vdb".into()))).is_ok());
let off = |confirmation| admitted("power", "off", serde_json::json!({}), confirmation);
for claimed in [
None,
Some(Confirmation::Operated),
Some(Confirmation::Phrase("off".into())),
] {
assert!(matches!(off(claimed), Err(ApiError::ConfirmationRequired)));
}
}
}