use std::sync::Arc;
use tilo_actions::{
ActionAddress, ActionContract, ActionKind, ActionParam, ActionSpec, ActionType, ApiError,
ConfirmationPolicy, EncodedAction, ExecutionMode, OperationKind, ResourceSpec, ResultSpec,
RetryPolicy, RiskLevel, Target,
};
#[must_use]
pub fn offer<E: Effect>(mut resource: ResourceSpec) -> ResourceSpec {
resource.actions.extend(E::specs());
resource
}
pub fn decode<E: Effect>(
published: &[ResourceSpec],
resource: &str,
action: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
) -> Result<E, ApiError> {
let address = ActionAddress::new(resource, action);
let (_, spec) = tilo_actions::api::locate(published, &address)
.ok_or_else(|| ApiError::Unknown(address.clone()))?;
tilo_actions::api::encode_json(published, &address, arguments)?;
let mut all = arguments.clone();
for (name, value) in spec.bound() {
all.insert(name.clone(), value.clone());
}
E::decode(&spec.id, &all).map_err(|error| ApiError::InvalidArguments(error.to_string()))
}
#[derive(Debug, thiserror::Error)]
pub enum EffectDecodeError {
#[error("there is no effect `{0}`")]
Unknown(String),
#[error("the effect's payload does not decode: {0}")]
Payload(#[source] serde_json::Error),
#[error("the effect's `{name}` argument does not decode: {source}")]
Argument {
name: String,
#[source]
source: serde_json::Error,
},
#[error(
"the effect's `{name}` argument is `{value}`, which names no id: ids travel as decimal text"
)]
Identity { name: String, value: String },
}
pub trait Effect: Sized + 'static {
const OPERATION: &'static str;
const APP_ID: &'static str = crate::kind::DEFAULT_APP;
const LABEL: &'static str = Self::OPERATION;
fn declarations() -> Vec<EffectDecl>;
fn rows() -> Vec<EffectRow>;
fn declaration(id: &str) -> Option<EffectDecl> {
first_declaration(Self::declarations(), id)
}
fn id(&self) -> &'static str;
fn confirmation_phrase(&self) -> Option<String> {
None
}
fn kind() -> crate::kind::ResourceKind {
crate::kind::ResourceKind::of_effect::<Self>(Self::OPERATION, Self::LABEL, Self::APP_ID)
}
fn key(&self) -> tilo_actions::ActionKey {
tilo_actions::ActionKey::new(Self::APP_ID, Self::OPERATION, self.id())
}
fn spec(id: &str) -> Option<tilo_actions::ActionSpec> {
Self::declaration(id).map(|decl| decl.spec_checked(Self::OPERATION, check::<Self>))
}
fn arguments(&self) -> serde_json::Map<String, serde_json::Value>;
fn decode(
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
) -> Result<Self, EffectDecodeError>;
fn specs() -> Vec<ActionSpec> {
kept_specs(
check::<Self>,
std::any::TypeId::of::<Self>(),
Self::OPERATION,
Self::declarations,
)
}
fn bound(&self) -> ActionSpec {
let id = self.id();
let arguments = self.arguments();
let spec = kept_type((std::any::TypeId::of::<Self>(), id, None), || {
bound_type(check::<Self>, Self::OPERATION, id, Self::declaration(id))
})
.bind(Target::new(arguments.clone()))
.with_bound(arguments.into_iter().collect());
asking_phrase(spec, self.confirmation_phrase())
}
fn bound_asking(&self, asking: &[&str]) -> ActionSpec {
let params = Self::declaration(self.id())
.map(|decl| {
decl.params
.into_iter()
.filter(|param| asking.contains(&&*param.name))
.collect()
})
.unwrap_or_default();
self.bound_asking_params(params)
}
fn bound_asking_params(&self, params: Vec<ActionParam>) -> ActionSpec {
let id = self.id();
match Self::declaration(id) {
Some(decl) => asking_phrase(
asking_spec(
check::<Self>,
Self::OPERATION,
&decl,
params,
self.arguments(),
),
self.confirmation_phrase(),
),
None => self.bound(),
}
}
fn item_specs(field: &str, item: &crate::Id) -> Vec<ActionSpec> {
target_specs(
check::<Self>,
std::any::TypeId::of::<Self>(),
Self::OPERATION,
Self::declarations,
&|target| target.is_field(field),
item,
)
}
fn row_specs(kind: &'static str, row: &crate::Id) -> Vec<ActionSpec> {
target_specs(
check::<Self>,
std::any::TypeId::of::<Self>(),
Self::OPERATION,
Self::declarations,
&|target| target.is_row(kind),
row,
)
}
fn row_specs_with(
kind: &'static str,
_row: &crate::Id,
bindings: &crate::row::RowBindings,
) -> Vec<ActionSpec> {
target_specs_with(
check::<Self>,
std::any::TypeId::of::<Self>(),
Self::OPERATION,
Self::declarations,
&|target| target.is_row(kind),
bindings,
)
}
fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
tilo_actions::ActionAddress::new(resource, self.id())
}
fn from_payload(payload: &[u8]) -> Result<Self, EffectDecodeError> {
crate::content::invoking(|| {
let Payload { effect, args } = decode_payload(payload)?;
Self::decode(&effect, &args)
})
}
}
#[inline(never)]
fn asking_phrase(mut spec: ActionSpec, phrase: Option<String>) -> ActionSpec {
if let Some(phrase) = phrase {
spec.type_mut().contract.confirmation = ConfirmationPolicy::Phrase { phrase };
}
spec
}
#[derive(serde::Serialize, serde::Deserialize)]
struct Payload {
effect: String,
#[serde(default)]
args: serde_json::Map<String, serde_json::Value>,
}
#[inline(never)]
fn decode_payload(payload: &[u8]) -> Result<Payload, EffectDecodeError> {
tilo_actions::decode_json(payload).map_err(EffectDecodeError::Payload)
}
#[derive(Clone, Copy)]
enum Bound {
None,
Only,
UnderCaller,
OverCaller,
}
type BoundArguments = serde_json::Map<String, serde_json::Value>;
type Check = fn(&str, &BoundArguments) -> Option<String>;
fn check<E: Effect>(id: &str, arguments: &BoundArguments) -> Option<String> {
E::decode(id, arguments)
.err()
.map(|problem| problem.to_string())
}
fn encoder(
check: Check,
operation: &'static str,
effect: &'static str,
mode: Bound,
) -> impl Fn(&Target, &tilo_actions::ActionArgs) -> EncodedAction + Send + Sync + 'static {
move |target, args| {
let args = effect_arguments(mode, target, args);
if let Some(problem) = check(effect, &args) {
return EncodedAction {
type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
payload: problem.into_bytes(),
};
}
EncodedAction::encode_operation(
operation,
&Payload {
effect: effect.to_owned(),
args,
},
)
.unwrap_or_else(|_| EncodedAction {
type_id: operation.to_owned(),
payload: Vec::new(),
})
}
}
fn effect_arguments(
mode: Bound,
target: &Target,
args: &tilo_actions::ActionArgs,
) -> BoundArguments {
let empty = BoundArguments::new();
let bound = target.get::<BoundArguments>().unwrap_or(&empty);
match mode {
Bound::None => args.to_json(),
Bound::Only => bound.clone(),
Bound::UnderCaller => {
let mut merged = bound.clone();
merged.extend(args.to_json());
merged
}
Bound::OverCaller => {
let mut merged = args.to_json();
merged.extend(
bound
.iter()
.map(|(name, value)| (name.clone(), value.clone())),
);
merged
}
}
}
fn kept_specs(
check: Check,
key: std::any::TypeId,
operation: &'static str,
declarations: fn() -> Vec<EffectDecl>,
) -> Vec<ActionSpec> {
type Kept = (
u64,
std::collections::HashMap<std::any::TypeId, std::rc::Rc<[ActionSpec]>>,
);
thread_local! {
static KEPT: std::cell::RefCell<Kept> =
std::cell::RefCell::new((0, std::collections::HashMap::new()));
}
let epoch = crate::resource::words_epoch();
let found = KEPT.with(|kept| {
let kept = kept.borrow();
if kept.0 == epoch {
kept.1.get(&key).cloned()
} else {
None
}
});
let specs = found.unwrap_or_else(|| {
let built: std::rc::Rc<[ActionSpec]> =
offered_specs(check, declarations(), operation).into();
KEPT.with(|kept| {
let mut kept = kept.borrow_mut();
if kept.0 != epoch {
*kept = (epoch, std::collections::HashMap::new());
}
kept.1.insert(key, std::rc::Rc::clone(&built));
});
built
});
specs.to_vec()
}
#[inline(never)]
fn first_declaration(declarations: Vec<EffectDecl>, id: &str) -> Option<EffectDecl> {
declarations.into_iter().find(|decl| decl.id == id)
}
fn offered_specs(check: Check, decls: Vec<EffectDecl>, operation: &'static str) -> Vec<ActionSpec> {
decls
.into_iter()
.filter(|decl| !decl.row)
.map(|decl| {
let mut spec = decl.spec_checked(operation, check);
if let Some(target) = decl.items.first() {
spec.type_mut().contract.item = Some(target.key().to_owned());
}
spec
})
.collect()
}
fn bound_type(
check: Check,
operation: &'static str,
id: &'static str,
decl: Option<EffectDecl>,
) -> Arc<ActionType> {
let build = encoder(check, operation, id, Bound::Only);
let spec = match decl {
Some(decl) => decl.spec_with_boxed(operation, Vec::new(), Arc::new(build)),
None => ActionSpec::typed_operation_on(
id,
id,
id,
OperationKind::Effect,
operation,
Vec::new(),
Arc::new(build),
),
};
Arc::clone(spec.action_type())
}
fn asking_spec(
check: Check,
operation: &'static str,
decl: &EffectDecl,
params: Vec<ActionParam>,
args: BoundArguments,
) -> ActionSpec {
let fixed = args
.iter()
.filter(|(name, _)| !params.iter().any(|param| param.name == name.as_str()))
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
let build = encoder(check, operation, decl.id, Bound::UnderCaller);
decl.spec_with_boxed(operation, params, Arc::new(build))
.action_type()
.bind(Target::new(args))
.with_bound(fixed)
}
#[inline(never)]
fn params_from(params: &[ActionParam]) -> Vec<ActionParam> {
params.to_vec()
}
fn target_specs(
check: Check,
key: std::any::TypeId,
operation: &'static str,
declarations: fn() -> Vec<EffectDecl>,
matches: &dyn Fn(&EffectTarget) -> bool,
entity: &crate::Id,
) -> Vec<ActionSpec> {
declared(key, declarations)
.iter()
.filter_map(|decl| {
let target = *decl.items.iter().find(|target| matches(target))?;
let mut refused = None;
let bound = match decl.params.first() {
Some(first) => BoundArguments::from_iter([(
first.name.to_string(),
match (target, decl.row_id) {
(EffectTarget::Row(_), Some(parse)) => match parse(entity.as_str()) {
Ok(value) => value,
Err(reason) => {
refused = Some(reason);
serde_json::Value::String(entity.as_str().to_owned())
}
},
_ => serde_json::Value::String(entity.as_str().to_owned()),
},
)]),
None => BoundArguments::new(),
};
let ty = kept_type((key, decl.id, Some(target.key())), || {
let rest = params_from(decl.params.get(1..).unwrap_or_default());
let build = encoder(check, operation, decl.id, Bound::OverCaller);
Arc::clone(
decl.spec_with_boxed(operation, rest, Arc::new(build))
.action_type(),
)
});
let fixed: Vec<(String, serde_json::Value)> = bound.clone().into_iter().collect();
let arguments: serde_json::Map<String, serde_json::Value> =
fixed.iter().cloned().collect();
let mut spec = ty.bind(Target::new(bound)).with_bound(fixed);
if let Some(phrase) = decl.phrase {
spec = asking_phrase(spec, phrase(&arguments));
}
if let Some(reason) = refused {
spec.type_mut().contract.availability = tilo_actions::Availability::Unavailable {
code: "row_id".to_owned(),
reason,
};
}
Some(spec)
})
.collect()
}
fn target_specs_with(
check: Check,
key: std::any::TypeId,
operation: &'static str,
declarations: fn() -> Vec<EffectDecl>,
matches: &dyn Fn(&EffectTarget) -> bool,
bindings: &crate::row::RowBindings,
) -> Vec<ActionSpec> {
declared(key, declarations)
.iter()
.filter(|decl| decl.items.iter().any(matches))
.flat_map(|decl| {
bindings
.arguments(decl.id)
.unwrap_or_default()
.iter()
.map(|given| {
let asking = bindings.asks(decl.id);
let asks = |name: &str| asking.contains(&name);
let mut bound = BoundArguments::new();
let mut defaults: Vec<(&str, serde_json::Value)> = Vec::new();
let mut taken: Vec<&str> = Vec::new();
for (name, value) in given {
if !decl
.params
.iter()
.any(|param| param.name.as_ref() == name.as_str())
{
continue;
}
if asks(name.as_str()) {
defaults.push((name.as_str(), value.clone()));
continue;
}
taken.push(name.as_str());
if !value.is_null() {
bound.insert(name.clone(), value.clone());
}
}
let mut asked = decl
.params
.iter()
.filter(|param| !taken.contains(¶m.name.as_ref()))
.cloned()
.collect::<Vec<_>>();
for param in &mut asked {
if let Some((_, value)) = defaults
.iter()
.find(|(name, _)| *name == param.name.as_ref())
&& !value.is_null()
{
*param = param.clone().with_default(value.clone());
}
if let Some(choices) = bindings.chosen(decl.id, param.name.as_ref()) {
param.choices = choices.iter().cloned().map(Into::into).collect();
}
}
let asked = params_from(&asked);
let mode = if asking.is_empty() {
Bound::OverCaller
} else {
Bound::UnderCaller
};
let build = encoder(check, operation, decl.id, mode);
let fixed: Vec<(String, serde_json::Value)> =
bound.clone().into_iter().collect();
let mut target = bound.clone();
for (name, value) in &defaults {
target.insert((*name).to_owned(), value.clone());
}
let arguments: serde_json::Map<String, serde_json::Value> =
target.clone().into_iter().collect();
let mut spec = decl.spec_with_boxed(operation, asked, Arc::new(build));
if let Some(phrase) = decl.phrase {
spec = asking_phrase(spec, phrase(&arguments));
}
spec.action_type()
.bind(Target::new(target))
.with_bound(fixed)
})
.collect::<Vec<_>>()
})
.collect()
}
type TypeKey = (std::any::TypeId, &'static str, Option<&'static str>);
fn declared(
key: std::any::TypeId,
declarations: fn() -> Vec<EffectDecl>,
) -> std::rc::Rc<[EffectDecl]> {
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptTypes<std::any::TypeId, std::rc::Rc<[EffectDecl]>>> =
std::cell::RefCell::default();
}
crate::kept::kept_type(&KEPT, key, || declarations().into())
}
fn kept_type(key: TypeKey, build: impl FnOnce() -> Arc<ActionType>) -> Arc<ActionType> {
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeKey>> =
std::cell::RefCell::default();
}
crate::kept::kept_type(&KEPT, key, build)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EffectTarget {
Field(&'static str),
Row(&'static str),
}
impl EffectTarget {
fn key(self) -> &'static str {
match self {
Self::Field(field) | Self::Row(field) => field,
}
}
fn is_field(self, field: &str) -> bool {
matches!(self, Self::Field(named) if named == field)
}
fn is_row(self, kind: &str) -> bool {
matches!(self, Self::Row(named) if named == kind)
}
}
#[doc(hidden)]
#[derive(Clone)]
#[allow(
clippy::struct_excessive_bools,
reason = "each flag is an independent property a declaration states, as the derive's options do"
)]
pub struct EffectRow {
pub id: &'static str,
pub label: crate::label::Word,
pub keywords: &'static [&'static str],
pub icon: Option<&'static str>,
pub description: &'static str,
pub params: fn() -> Vec<ActionParam>,
pub param_types: fn() -> Vec<(&'static str, crate::surface::FieldTypeOf)>,
pub result: Option<EffectResult>,
pub kind: OperationKind,
pub prompted: bool,
pub row: bool,
pub answers: Answers,
pub risk: RiskLevel,
pub idempotent: bool,
pub action_kind: ActionKind,
pub own_device: bool,
pub attended: bool,
pub risk_of: Option<fn(&tilo_actions::ActionArgs) -> RiskLevel>,
pub audience: tilo_actions::Audience,
pub untrusted: bool,
pub opens: Option<&'static [&'static str]>,
pub presence: bool,
pub edits: bool,
pub member: bool,
pub items: &'static [EffectTarget],
pub row_id: Option<RowIdOf>,
pub phrase: Option<PhraseOf>,
pub offload: Option<EffectOffload>,
pub tags: &'static [&'static str],
pub outside_with: Option<&'static str>,
}
pub type PhraseOf = fn(&serde_json::Map<String, serde_json::Value>) -> Option<String>;
pub type RowIdOf = fn(&str) -> Result<serde_json::Value, String>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EffectOffload {
pub gpu: bool,
pub cpu_time_ms: u64,
pub memory_bytes: u64,
pub output_bytes: u64,
}
impl EffectOffload {
#[must_use]
pub fn contract(&self) -> tilo_actions::Offload {
tilo_actions::Offload {
gpu: self.gpu,
cpu_time_ms: self.cpu_time_ms,
memory_bytes: self.memory_bytes,
output_bytes: self.output_bytes,
}
}
}
#[doc(hidden)]
#[must_use]
pub fn no_params() -> Vec<ActionParam> {
Vec::new()
}
#[doc(hidden)]
#[must_use]
pub fn no_param_types() -> Vec<(&'static str, crate::surface::FieldTypeOf)> {
Vec::new()
}
#[derive(Clone, Copy, Debug)]
pub struct EffectResult {
pub schema: fn() -> serde_json::Value,
pub ty: Option<crate::surface::FieldTypeOf>,
}
#[derive(Clone, Debug)]
#[allow(
clippy::struct_excessive_bools,
reason = "each flag is an independent property a declaration states, as the derive's options do"
)]
pub struct EffectDecl {
pub id: &'static str,
pub label: crate::label::Word,
pub keywords: &'static [&'static str],
pub icon: Option<&'static str>,
pub description: &'static str,
pub params: Vec<ActionParam>,
pub param_types: Vec<(&'static str, crate::surface::FieldTypeOf)>,
pub result: Option<EffectResult>,
pub kind: OperationKind,
pub prompted: bool,
pub row: bool,
pub answers: Answers,
pub risk: RiskLevel,
pub idempotent: bool,
pub action_kind: ActionKind,
pub own_device: bool,
pub attended: bool,
pub risk_of: Option<fn(&tilo_actions::ActionArgs) -> RiskLevel>,
pub audience: tilo_actions::Audience,
pub untrusted: bool,
pub opens: Option<&'static [&'static str]>,
pub presence: bool,
pub edits: bool,
pub member: bool,
pub items: &'static [EffectTarget],
pub row_id: Option<RowIdOf>,
pub phrase: Option<PhraseOf>,
pub offload: Option<EffectOffload>,
pub tags: &'static [&'static str],
pub outside_with: Option<&'static str>,
}
pub const EDITS_TAG: &str = "submits-edits";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Answers {
Nothing,
Value,
Content,
Later {
cancellable: bool,
returns: bool,
},
}
impl EffectDecl {
pub fn spec<E: Effect>(&self, operation: &'static str) -> ActionSpec {
self.spec_checked(operation, check::<E>)
}
fn spec_checked(&self, operation: &'static str, check: Check) -> ActionSpec {
let build = encoder(check, operation, self.id, Bound::None);
let spec = self.spec_with_boxed(operation, params_from(&self.params), Arc::new(build));
let asks_words = matches!(
spec.input(),
tilo_actions::ActionInput::Prompted {
collects: tilo_actions::Collects::Words,
..
}
);
if asks_words && !self.prompted && !self.params.iter().any(|param| param.entry) {
spec.with_immediate_per_target()
} else {
spec
}
}
pub fn spec_of<E: Effect>(&self) -> ActionSpec {
self.spec::<E>(E::OPERATION)
}
#[doc(hidden)]
#[must_use]
pub fn of_rows(rows: &'static [EffectRow]) -> Vec<Self> {
rows.iter().map(Self::of_row).collect()
}
#[doc(hidden)]
#[must_use]
pub fn find_row(rows: &'static [EffectRow], id: &str) -> Option<Self> {
rows.iter().find(|row| row.id == id).map(Self::of_row)
}
pub fn of_row(row: &EffectRow) -> Self {
Self {
id: row.id,
label: row.label.clone(),
keywords: row.keywords,
icon: row.icon,
description: row.description,
params: (row.params)(),
param_types: (row.param_types)(),
result: row.result,
kind: row.kind,
prompted: row.prompted,
row: row.row,
answers: row.answers,
risk: row.risk,
idempotent: row.idempotent,
action_kind: row.action_kind,
own_device: row.own_device,
attended: row.attended,
risk_of: row.risk_of,
audience: row.audience,
untrusted: row.untrusted,
opens: row.opens,
presence: row.presence,
edits: row.edits,
member: row.member,
items: row.items,
row_id: row.row_id,
phrase: row.phrase,
offload: row.offload,
tags: row.tags,
outside_with: row.outside_with,
}
}
fn result_contract(&self) -> ResultSpec {
match self.answers {
Answers::Later { returns: false, .. } => ResultSpec::Job,
Answers::Value | Answers::Later { returns: true, .. } => ResultSpec::Json {
schema: self
.result
.map_or_else(|| serde_json::json!({}), |result| (result.schema)()),
},
Answers::Content => ResultSpec::Resource {
resource_kind: tilo_actions::CONTENT_RESOURCE_KIND.to_owned(),
},
Answers::Nothing => ResultSpec::None,
}
}
#[must_use]
pub fn action_kind(&self) -> crate::ActionKind {
if self.edits {
crate::ActionKind::Undoable
} else if self.kind == OperationKind::View {
crate::ActionKind::Read
} else {
crate::ActionKind::Outside
}
}
fn contract_tags(&self, base: &[String]) -> Vec<String> {
let mut tags = base.to_vec();
if self.own_device {
tags.push(tilo_actions::OWN_DEVICE_SCOPE.to_owned());
}
if self.attended {
tags.push(tilo_actions::ATTENDED_TAG.to_owned());
}
if let Some(tag) = self.audience.tag() {
tags.push(tag.to_owned());
}
if self.untrusted {
tags.push(tilo_actions::UNTRUSTED_CONTENT_TAG.to_owned());
}
if let Some(extensions) = self.opens {
tags.push(tilo_actions::OPENS_PATH_TAG.to_owned());
tags.extend(extensions.iter().map(|extension| {
format!("{}{extension}", tilo_actions::OPENS_PATH_EXTENSION_PREFIX)
}));
}
if self.presence {
tags.push(tilo_actions::PRESENCE_VIEW_TAG.to_owned());
}
if self.edits {
tags.push(EDITS_TAG.to_owned());
}
if self.member {
tags.push(tilo_actions::MEMBER_OWN_TAG.to_owned());
}
tags.extend(self.tags.iter().map(|tag| (*tag).to_owned()));
tags
}
fn spec_with_boxed(
&self,
operation: &'static str,
params: Vec<ActionParam>,
build: tilo_actions::resource::ArgsBuilder,
) -> ActionSpec {
let view = self.kind == OperationKind::View;
let label = self.label.read();
let params = crate::label::titled(&self.label, operation, params);
let mut spec = if self.kind == OperationKind::Document {
ActionSpec::typed_on(
self.id,
label.clone(),
label,
tilo_actions::ExecutionLocus::ClientLocal,
params,
move |target: &Target, args: &tilo_actions::ActionArgs| build(target, args),
)
} else {
ActionSpec::typed_operation_on(
self.id,
label.clone(),
label,
if view {
OperationKind::View
} else {
OperationKind::Effect
},
operation,
params,
build,
)
};
if !self.description.is_empty() {
spec = spec.with_description(self.description);
}
if !self.keywords.is_empty() {
spec = spec.with_keywords(self.keywords.iter().copied());
}
spec.type_mut().icon = self.icon.map(str::to_owned);
let base = match self.kind {
OperationKind::View => ActionContract::view(),
OperationKind::Document => ActionContract::for_operation(OperationKind::Document),
OperationKind::Effect => ActionContract::default(),
};
spec.type_mut().contract = ActionContract {
kind: self.action_kind,
risk: self.risk,
confirmation: if matches!(
self.risk,
RiskLevel::Destructive | RiskLevel::Privileged | RiskLevel::Sensitive
) {
ConfirmationPolicy::Confirm
} else {
ConfirmationPolicy::None
},
execution: match self.answers {
Answers::Later { cancellable, .. } => ExecutionMode::Background { cancellable },
Answers::Nothing | Answers::Value | Answers::Content => ExecutionMode::Immediate,
},
result: self.result_contract(),
retry: if view || self.idempotent {
RetryPolicy::Idempotent
} else {
base.retry
},
tags: self.contract_tags(&base.tags),
offload: self.offload.as_ref().map(EffectOffload::contract),
..base
};
let spec = match self.outside_with {
Some(param) => spec.with_need_of(outside_with(param, self.action_kind)),
None => spec,
};
match self.risk_of {
Some(classify) => spec.with_risk(classify),
None => spec,
}
}
pub fn is_job(&self) -> bool {
matches!(self.answers, Answers::Later { .. })
}
}
fn outside_with(
param: &'static str,
least: ActionKind,
) -> impl Fn(&tilo_actions::ActionArgs) -> tilo_actions::ActionNeed + Send + Sync + 'static {
move |args| {
let given = args
.to_json()
.get(param)
.is_some_and(|value| !value.is_null());
tilo_actions::ActionNeed::of(if given { ActionKind::Outside } else { least })
}
}
#[derive(Clone, Copy, Debug)]
pub enum NoEffect {}
impl Effect for NoEffect {
const OPERATION: &'static str = "tilo.no-effect";
fn declarations() -> Vec<EffectDecl> {
Vec::new()
}
fn rows() -> Vec<EffectRow> {
Vec::new()
}
fn id(&self) -> &'static str {
""
}
fn arguments(&self) -> serde_json::Map<String, serde_json::Value> {
serde_json::Map::new()
}
fn decode(
id: &str,
_: &serde_json::Map<String, serde_json::Value>,
) -> Result<Self, EffectDecodeError> {
Err(EffectDecodeError::Unknown(id.to_owned()))
}
}
#[doc(hidden)]
pub fn argument<T: serde::de::DeserializeOwned>(
arguments: &serde_json::Map<String, serde_json::Value>,
name: &str,
) -> Result<T, EffectDecodeError> {
T::deserialize(argument_value(arguments, name)).map_err(|error| EffectDecodeError::Argument {
name: name.to_owned(),
source: error,
})
}
#[doc(hidden)]
pub fn flattened_argument<T: serde::de::DeserializeOwned>(
arguments: &serde_json::Map<String, serde_json::Value>,
struct_name: &str,
) -> Result<T, EffectDecodeError> {
serde_path_to_error::deserialize(serde_json::Value::Object(arguments.clone())).map_err(
|error| {
let path = error.path().to_string();
EffectDecodeError::Argument {
name: if path.is_empty() {
struct_name.to_owned()
} else {
path
},
source: error.into_inner(),
}
},
)
}
pub fn identity_argument(
arguments: &serde_json::Map<String, serde_json::Value>,
name: &str,
) -> Result<String, EffectDecodeError> {
match argument_value(arguments, name) {
serde_json::Value::String(text) => identity(name, &text),
serde_json::Value::Null => Err(EffectDecodeError::Argument {
name: name.to_owned(),
source: serde::de::Error::custom("is required"),
}),
other => Err(not_an_identity(name, other.to_string())),
}
}
pub fn optional_identity_argument(
arguments: &serde_json::Map<String, serde_json::Value>,
name: &str,
) -> Result<Option<String>, EffectDecodeError> {
match argument_value(arguments, name) {
serde_json::Value::Null => Ok(None),
serde_json::Value::String(text) => identity(name, &text).map(Some),
other => Err(not_an_identity(name, other.to_string())),
}
}
fn identity(name: &str, text: &str) -> Result<String, EffectDecodeError> {
let canonical = text.parse::<u64>().is_ok_and(|id| id.to_string() == text);
if canonical {
return Ok(text.to_owned());
}
Err(not_an_identity(name, text.to_owned()))
}
fn not_an_identity(name: &str, value: String) -> EffectDecodeError {
EffectDecodeError::Identity {
name: name.to_owned(),
value,
}
}
#[inline(never)]
fn argument_value(
arguments: &serde_json::Map<String, serde_json::Value>,
name: &str,
) -> serde_json::Value {
arguments
.get(name)
.cloned()
.unwrap_or(serde_json::Value::Null)
}
#[doc(hidden)]
pub fn put<T: serde::Serialize>(
arguments: &mut serde_json::Map<String, serde_json::Value>,
name: &str,
value: &T,
) {
match crate::__private::json_via_bytes(value) {
Ok(serde_json::Value::Null) | Err(_) => {}
Ok(value) => {
arguments.insert(name.to_owned(), value);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Effect;
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.effects", catalogue = "tests/locales")]
enum Sample {
#[effect(kind = "outside")]
Reload,
#[effect(returns, kind = "read")]
RenameThing {
#[param("The thing")]
thing: String,
label: Option<String>,
},
#[effect(kind = "outside")]
#[effect(job, cancellable, destructive)]
Wipe { passes: u32 },
#[effect(privileged, kind = "read")]
CopyKey { thing: String },
#[effect(kind = "outside")]
Paint {
#[param("The colour", choices = ["red", "green"])]
colour: String,
#[param(choices = Self::SHADES)]
shade: Option<String>,
},
#[effect(kind = "outside")]
Widen {
#[param(decimal, "The column")]
column: String,
#[param(decimal, "The table")]
table: Option<String>,
#[param("The width")]
width: u32,
},
}
impl Sample {
const SHADES: [&str; 2] = ["light", "dark"];
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.transforms", catalogue = "tests/locales")]
enum Transforms {
#[effect(
content,
idempotent,
kind = "read",
offload(cpu_ms = 60000, memory_mb = 512, output_mb = 8)
)]
Shrink {
#[param(content, "The images")]
images: Vec<String>,
},
#[effect(content, kind = "read")]
Copy {
#[param(content, "The image")]
image: String,
},
}
tilo_test_env::scenario! {
fn an_effect_declares_publishes_and_binds_what_its_type_says;
phase an_offload_option_declares_a_valid_offloadable_contract;
{
let specs = Transforms::specs();
let shrink = &specs[0];
assert_eq!(
shrink.contract.offload,
Some(tilo_actions::Offload {
gpu: false,
cpu_time_ms: 60_000,
memory_bytes: 512 * 1024 * 1024,
output_bytes: 8 * 1024 * 1024,
})
);
assert_eq!(shrink.contract.kind, ActionKind::Read);
assert!(
shrink.contract.validate_declaration().is_empty(),
"{:?}",
shrink.contract.validate_declaration()
);
assert_eq!(specs[1].contract.offload, None, "only where declared");
assert!(shrink.params()[0].is_content_list());
assert!(specs[1].params()[0].is_content());
}
phase a_derived_vocabulary_publishes_each_variant_and_round_trips_through_its_spec;
{
let specs = Sample::specs();
let ids: Vec<&str> = specs.iter().map(|spec| spec.id.as_str()).collect();
assert_eq!(
ids,
[
"reload",
"rename-thing",
"wipe",
"copy-key",
"paint",
"widen"
]
);
let rename = &specs[1];
assert_eq!(rename.label, "Rename a thing");
assert_eq!(
rename.description.as_deref(),
Some("Rename a thing. It keeps its id.")
);
assert_eq!(rename.kind, OperationKind::Effect);
assert_eq!(rename.contract.kind, ActionKind::Read);
assert!(matches!(rename.contract.result, ResultSpec::Json { .. }));
assert_eq!(rename.contract.execution, ExecutionMode::Immediate);
let schema_type = |param: &tilo_actions::ActionParam| {
param
.schema
.as_deref()
.and_then(|schema| schema.get("type"))
.cloned()
};
assert_eq!(
schema_type(&rename.params()[0]),
Some(serde_json::json!("string"))
);
assert_eq!(
schema_type(&specs[2].params()[0]),
Some(serde_json::json!("integer"))
);
let paint = &specs[4];
assert_eq!(paint.params()[0].description, "The colour");
let choices = |index: usize| -> Vec<&str> {
paint.params()[index]
.choices
.iter()
.map(std::convert::AsRef::as_ref)
.collect()
};
assert_eq!(choices(0), ["red", "green"]);
assert_eq!(choices(1), ["light", "dark"]);
assert!(!paint.params()[1].required);
let wipe = &specs[2];
assert_eq!(wipe.label, "Wipe");
assert_eq!(wipe.contract.risk, RiskLevel::Destructive);
assert_eq!(wipe.contract.confirmation, ConfirmationPolicy::Confirm);
assert_eq!(
wipe.contract.execution,
ExecutionMode::Background { cancellable: true }
);
let value = Sample::RenameThing {
thing: "a".into(),
label: None,
};
let encoded = rename.build_json(&value.arguments()).unwrap();
assert_eq!(encoded.type_id, "test.effects");
assert_eq!(Sample::from_payload(&encoded.payload).unwrap(), value);
assert_eq!(
Sample::from_payload(
&specs[0]
.build_json(&serde_json::Map::new())
.unwrap()
.payload
)
.unwrap(),
Sample::Reload
);
assert!(Sample::decode("wipe", &serde_json::Map::new()).is_err());
let bound = Sample::Wipe { passes: 3 }.bound();
assert_eq!(bound.id, "wipe");
assert_eq!(bound.label, "Wipe");
assert!(bound.params().is_empty());
assert_eq!(bound.contract.confirmation, ConfirmationPolicy::Confirm);
let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
assert_eq!(
Sample::from_payload(&encoded.payload).unwrap(),
Sample::Wipe { passes: 3 }
);
assert!(Sample::decode("format", &serde_json::Map::new()).is_err());
let asking = Sample::RenameThing {
thing: "a".into(),
label: None,
}
.bound_asking(&["label"]);
assert_eq!(asking.id, "rename-thing");
let asked: Vec<&str> = asking.params().iter().map(|param| &*param.name).collect();
assert_eq!(asked, ["label"]);
let mut label = serde_json::Map::new();
label.insert("label".into(), "b".into());
let encoded = asking.build_json(&label).unwrap();
assert_eq!(
Sample::from_payload(&encoded.payload).unwrap(),
Sample::RenameThing {
thing: "a".into(),
label: Some("b".into()),
}
);
}
phase an_identity_argument_is_decimal_text_and_is_refused_otherwise;
{
let widen = Sample::spec("widen").unwrap();
let encoded = |arguments: serde_json::Value| -> Result<String, String> {
let arguments: serde_json::Map<String, serde_json::Value> =
serde_json::from_value(arguments).expect("a test's call is an object");
widen
.build_json(&arguments)
.map(|built| built.type_id)
.map_err(|error| error.to_string())
};
assert_eq!(
encoded(serde_json::json!({"column": "9007199254740993", "width": 80})),
Ok("test.effects".to_owned()),
"a salted id outgrows a JSON number, and travels as text"
);
for refused in [
serde_json::json!({"column": "left", "width": 80}),
serde_json::json!({"column": "07", "width": 80}),
serde_json::json!({"column": "1", "table": "wide", "width": 80}),
] {
assert_eq!(
encoded(refused.clone()),
Ok(tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned()),
"{refused}"
);
}
let not_text = encoded(serde_json::json!({"column": 7, "width": 80}));
assert!(
not_text.is_err(),
"an id is text, never a number: {not_text:?}"
);
}
phase views_publish_as_views_and_row_effects_only_bound_to_their_item;
{
let specs = Rows::specs();
let ids: Vec<&str> = specs.iter().map(|spec| spec.id.as_str()).collect();
assert_eq!(
ids,
["search"],
"a row effect is not offered on the resource"
);
let search = &specs[0];
assert_eq!(search.kind, OperationKind::View);
assert_eq!(search.contract.kind, ActionKind::Read);
assert_eq!(search.contract.risk, RiskLevel::None);
assert_eq!(search.contract.retry, RetryPolicy::Idempotent);
let open = Rows::Open { item: "a".into() };
let bound = open.bound();
assert_eq!(
(bound.id.as_str(), bound.kind),
("open", OperationKind::View)
);
assert!(bound.params().is_empty());
let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
assert_eq!(encoded.type_id, "test.rows");
assert_eq!(Rows::from_payload(&encoded.payload).unwrap(), open);
let connect = Rows::Connect { item: "b".into() }.bound();
assert_eq!(connect.kind, OperationKind::Effect);
assert_eq!(connect.contract.kind, ActionKind::Outside);
assert_eq!(connect.contract.retry, RetryPolicy::Idempotent);
assert_eq!(
connect.contract.execution,
ExecutionMode::Background { cancellable: false }
);
assert_eq!(
Sample::specs()[0].contract.retry,
RetryPolicy::AtMostOnce,
"an effect is not repeated unless it says it may be"
);
}
phase a_privileged_effect_asks_first_and_binds_to_the_entity_it_names;
{
let copy = Sample::CopyKey { thing: "a".into() };
let bound = copy.bound();
assert_eq!(bound.id, "copy-key");
assert_eq!(bound.label, "Copy a thing's key");
assert_eq!(bound.kind, OperationKind::Effect);
assert!(bound.params().is_empty(), "the row names the thing already");
assert_eq!(bound.contract.risk, RiskLevel::Privileged);
assert_eq!(bound.contract.confirmation, ConfirmationPolicy::Confirm);
assert_eq!(bound.contract.kind, ActionKind::Read);
let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
assert_eq!(encoded.type_id, "test.effects");
assert_eq!(Sample::from_payload(&encoded.payload).unwrap(), copy);
}
phase a_sensitive_effect_asks_first;
{
let spec = Exports::ExportBook.bound();
assert_eq!(spec.contract.risk, RiskLevel::Sensitive);
assert_eq!(spec.contract.confirmation, ConfirmationPolicy::Confirm);
}
phase a_secret_parameter_is_published_as_a_secret;
{
let specs = Pairing::specs();
let params = specs[0].params();
assert_eq!(params[0].ty, tilo_actions::ParamType::Secret);
assert_eq!(&*params[0].description, "The invite the other device shows");
assert_eq!(params[1].ty, tilo_actions::ParamType::Secret);
assert!(!params[1].required);
let value = Pairing::Pair {
invite: "grayjay://invite".into(),
pin: None,
};
let encoded = specs[0].build_json(&value.arguments()).unwrap();
assert_eq!(Pairing::from_payload(&encoded.payload).unwrap(), value);
}
phase a_path_parameter_refuses_a_relative_path;
{
let specs = Files::specs();
let params = specs[0].params();
assert_eq!(params[0].ty, tilo_actions::ParamType::Text);
assert!(params[0].required);
assert_eq!(params[1].ty, tilo_actions::ParamType::Text);
assert!(!params[1].required);
let arguments = |path: &str, folder: Option<&str>| {
let mut arguments = serde_json::Map::new();
arguments.insert("path".into(), path.into());
if let Some(folder) = folder {
arguments.insert("folder".into(), folder.into());
}
arguments
};
let error = Files::decode("save-copy", &arguments("copy.txt", None)).unwrap_err();
assert!(
matches!(
&error,
EffectDecodeError::Argument { name, source }
if name == "path" && source.to_string().contains("absolute")
),
"{error}"
);
assert!(Files::decode("save-copy", &arguments("/a/copy.txt", Some("b"))).is_err());
let value = Files::decode("save-copy", &arguments("/a/copy.txt", Some("/b"))).unwrap();
let encoded = specs[0].build_json(&value.arguments()).unwrap();
assert_eq!(Files::from_payload(&encoded.payload).unwrap(), value);
}
phase variant_refs_bind_controls_by_id;
{
assert_eq!(Sample::RENAME_THING.id, "rename-thing");
assert_eq!(
Sample::RENAME_THING
.arguments(&("b".to_owned(), Some("B".to_owned())))
.unwrap(),
Sample::RenameThing {
thing: "b".into(),
label: Some("B".into())
}
.arguments()
);
}
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.rows", catalogue = "tests/locales")]
enum Rows {
#[effect(view, row)]
Open { item: String },
#[effect(kind = "outside")]
#[effect(row, job, idempotent)]
Connect { item: String },
#[effect(view)]
Search,
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.exports", catalogue = "tests/locales")]
enum Exports {
#[effect(kind = "outside")]
#[effect(job, sensitive)]
ExportBook,
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.secrets", catalogue = "tests/locales")]
enum Pairing {
#[effect(kind = "outside")]
Pair {
#[param(secret, "The invite the other device shows")]
invite: String,
#[param(secret)]
pin: Option<String>,
},
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.files", catalogue = "tests/locales")]
enum Files {
#[effect(kind = "outside")]
SaveCopy {
#[param("Where to write it")]
path: crate::AbsolutePath,
folder: Option<crate::AbsolutePath>,
},
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.ids", catalogue = "tests/locales")]
enum Ids {
#[effect(kind = "undoable")]
Place {
#[param("The strip it stands in")]
strip: u64,
#[param("The place's own id; a new one when left out")]
place: Option<u64>,
#[param(resource = "", "The resource it shows")]
resource: String,
},
}
#[test]
fn an_effects_named_arguments_round_trip_through_its_spec() {
let spec = Ids::specs().remove(0);
let salted = 0xB3A1_0000_0000_0001_u64;
let arguments = serde_json::json!({
"strip": salted,
"place": salted,
"resource": "notes:1",
})
.as_object()
.expect("arguments")
.clone();
let encoded = spec.build_json(&arguments).expect("the place encodes");
assert_eq!(
encoded.type_id,
Ids::OPERATION,
"the place is encoded as its own operation, not a refusal: {:?}",
String::from_utf8_lossy(&encoded.payload)
);
assert_eq!(
Ids::from_payload(&encoded.payload).expect("the place decodes"),
Ids::Place {
strip: salted,
place: Some(salted),
resource: "notes:1".into(),
}
);
}
#[derive(Clone, Debug, PartialEq, Effect)]
#[effect(operation = "test.readers", catalogue = "tests/locales")]
enum Readers {
#[effect(kind = "read")]
Open {
#[param(content, "The documents")]
documents: Vec<crate::Bytes>,
},
}
#[test]
fn an_effects_content_argument_is_read_where_the_effect_runs() {
let window = tilo_wake::WakeScope::new();
let workspace = tilo_content::ContentStore::memory_in_workspace().sealing();
crate::content::register(&window.handle(), workspace.clone());
let _entered = window.enter();
let documents: Vec<Vec<u8>> = [7_u8, 8].into_iter().map(|byte| vec![byte; 4096]).collect();
let references: Vec<String> = documents
.iter()
.map(|bytes| workspace.put(bytes).expect("kept"))
.collect();
let arguments = serde_json::Map::from_iter([(
"documents".to_owned(),
serde_json::json!([
tilo_actions::content_resource(&references[0]).expect("an address"),
references[1].clone(),
]),
)]);
let spec = Readers::specs().remove(0);
assert!(spec.params()[0].is_content_list());
let encoded = crate::content::invoking(|| spec.build_json(&arguments).unwrap());
let Readers::Open { documents: read } =
Readers::from_payload(&encoded.payload).expect("read where it runs");
assert_eq!(read.len(), 2);
for (read, kept) in read.iter().zip(&references) {
assert_eq!(
read.reference().as_deref(),
Some(kept.as_str()),
"the reference that opens exactly those bytes"
);
assert!(read.read(&workspace).is_some(), "and the bytes themselves");
}
}
}