use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::action::{Action, ActionError, EncodedAction, ExecutionLocus, OperationKind};
use crate::api::ActionAddress;
use crate::contract::{
ActionContract, ActionKind, ActionNeed, Availability, ConfirmationPolicy, ExecutionMode,
ResultSpec, RiskLevel,
};
use crate::params::{ActionArgs, ActionParam, ArgError, ArgValue, ParamType};
pub type ArgsBuilder = Arc<dyn Fn(&Target, &ActionArgs) -> EncodedAction + Send + Sync>;
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum ActionBindingError {
#[error("action `{action}` is not exported by resource `{resource}`")]
ActionNotExported { resource: String, action: String },
#[error(transparent)]
InvalidArguments(#[from] ArgError),
#[error("{0}")]
Unbindable(String),
}
type Arguments<I> =
Arc<dyn Fn(I) -> Result<serde_json::Map<String, serde_json::Value>, String> + Send + Sync>;
pub trait Exports {
fn exported(&self) -> &ResourceSpec;
}
impl Exports for ResourceSpec {
fn exported(&self) -> &ResourceSpec {
self
}
}
impl<T: Exports + ?Sized> Exports for &T {
fn exported(&self) -> &ResourceSpec {
(**self).exported()
}
}
impl<T: Exports + ?Sized> Exports for Box<T> {
fn exported(&self) -> &ResourceSpec {
(**self).exported()
}
}
impl<T: Exports + ?Sized> Exports for std::rc::Rc<T> {
fn exported(&self) -> &ResourceSpec {
(**self).exported()
}
}
impl<T: Exports + ?Sized> Exports for Arc<T> {
fn exported(&self) -> &ResourceSpec {
(**self).exported()
}
}
impl<T: Exports> Exports for std::sync::LazyLock<T> {
fn exported(&self) -> &ResourceSpec {
std::sync::LazyLock::force(self).exported()
}
}
#[derive(Clone)]
pub struct ActionBinding<I> {
address: ActionAddress,
kind: String,
shared_by: Option<String>,
spec: ActionSpec,
arguments: Arguments<I>,
}
impl<I> ActionBinding<I> {
pub fn new(
resource: &(impl Exports + ?Sized),
spec: &ActionSpec,
arguments: impl Fn(I) -> serde_json::Map<String, serde_json::Value> + Send + Sync + 'static,
) -> Result<Self, ActionBindingError> {
Self::fallible(resource, spec, move |input| Ok(arguments(input)))
}
pub fn fallible(
resource: &(impl Exports + ?Sized),
spec: &ActionSpec,
arguments: impl Fn(I) -> Result<serde_json::Map<String, serde_json::Value>, String>
+ Send
+ Sync
+ 'static,
) -> Result<Self, ActionBindingError> {
let resource = resource.exported();
let exported = resource
.actions
.iter()
.find(|candidate| candidate.id == spec.id)
.ok_or_else(|| ActionBindingError::ActionNotExported {
resource: resource.id.0.clone(),
action: spec.id.clone(),
})?;
Ok(Self {
address: ActionAddress::new(resource.id.0.clone(), spec.id.clone()),
kind: resource.kind.clone(),
shared_by: (!resource.personal).then(|| resource.app_id.clone().unwrap_or_default()),
spec: exported.clone(),
arguments: Arc::new(arguments),
})
}
pub fn invoke(&self, input: I) -> Result<ControlInvocation, ActionBindingError> {
let arguments = (self.arguments)(input).map_err(ActionBindingError::Unbindable)?;
self.spec.validate_json(&arguments)?;
Ok(ControlInvocation {
address: self.address.clone(),
arguments,
})
}
pub fn address(&self) -> &ActionAddress {
&self.address
}
#[must_use]
pub fn shared_resource(&self) -> Option<(&str, &str, &str)> {
let app = self.shared_by.as_deref()?;
(self.spec.kind == OperationKind::Document).then_some((
app,
self.address.resource.as_str(),
self.kind.as_str(),
))
}
#[must_use]
pub fn identity(&self) -> ActionAddress {
self.address.clone()
}
#[must_use]
pub fn map_input<J>(self, map: impl Fn(J) -> I + Send + Sync + 'static) -> ActionBinding<J>
where
I: 'static,
{
let arguments = self.arguments;
ActionBinding {
address: self.address,
kind: self.kind,
shared_by: self.shared_by,
spec: self.spec,
arguments: Arc::new(move |input| arguments(map(input))),
}
}
}
impl ActionBinding<()> {
pub fn declared(
resource: impl Into<String>,
spec: ActionSpec,
) -> Result<Self, ActionBindingError> {
let binding = Self {
address: ActionAddress::new(resource, spec.id.clone()),
kind: String::new(),
shared_by: None,
spec,
arguments: std::sync::Arc::new(|()| Ok(serde_json::Map::new())),
};
binding.spec.validate_json(&serde_json::Map::new())?;
Ok(binding)
}
pub fn unit(
resource: &(impl Exports + ?Sized),
spec: &ActionSpec,
) -> Result<Self, ActionBindingError> {
let binding = Self::new(resource, spec, |()| serde_json::Map::new())?;
binding.spec.validate_json(&serde_json::Map::new())?;
Ok(binding)
}
pub fn unit_for(
resource: &(impl Exports + ?Sized),
action_id: &str,
) -> Result<Self, ActionBindingError> {
let spec = resource
.exported()
.actions
.iter()
.find(|spec| spec.id == action_id)
.ok_or_else(|| ActionBindingError::ActionNotExported {
resource: resource.exported().id.0.clone(),
action: action_id.to_string(),
})?;
Self::unit(resource, spec)
}
pub fn static_json(
resource: &(impl Exports + ?Sized),
spec: &ActionSpec,
arguments: serde_json::Map<String, serde_json::Value>,
) -> Result<Self, ActionBindingError> {
let binding = Self::new(resource, spec, move |()| arguments.clone())?;
binding
.spec
.validate_json(&(binding.arguments)(()).map_err(ActionBindingError::Unbindable)?)?;
Ok(binding)
}
pub fn static_json_for(
resource: &(impl Exports + ?Sized),
action_id: &str,
arguments: serde_json::Map<String, serde_json::Value>,
) -> Result<Self, ActionBindingError> {
let spec = resource
.exported()
.actions
.iter()
.find(|spec| spec.id == action_id)
.ok_or_else(|| ActionBindingError::ActionNotExported {
resource: resource.exported().id.0.clone(),
action: action_id.to_string(),
})?;
Self::static_json(resource, spec, arguments)
}
}
pub const PROMPTED_PARAM: &str = "value";
fn unnamed_kind(contract: ActionContract) -> ActionContract {
ActionContract {
kind: ActionKind::Outside,
..contract
}
}
pub fn sole_text_argument(arguments: &serde_json::Map<String, serde_json::Value>) -> Option<&str> {
let mut values = arguments.values();
match (values.next(), values.next()) {
(Some(serde_json::Value::String(text)), None) => Some(text),
_ => None,
}
}
pub const INVALID_ARGUMENTS_TYPE: &str = "tilo.invalid_arguments";
pub const SEMANTIC_OPERATION_TYPE: &str = "tilo.ui.semantic-action";
pub use tilo_action_types::ResourceId;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ActionState {
#[serde(skip_serializing_if = "Option::is_none")]
pub badge: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub toggles: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub shortcut: Option<String>,
}
impl ActionState {
pub const MAX_BADGE_BYTES: usize = ResourcePresentation::MAX_BADGE_BYTES;
#[must_use]
pub fn is_empty(&self) -> bool {
self == &Self::default()
}
#[must_use]
pub fn badge(badge: impl Into<String>) -> Self {
Self {
badge: Some(badge.into()),
..Self::default()
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ResourcePresentation {
pub detail: Option<String>,
pub badge: Option<String>,
pub preview: Option<String>,
}
impl ResourcePresentation {
pub const MAX_DETAIL_BYTES: usize = 160;
pub const MAX_BADGE_BYTES: usize = 32;
pub const MAX_PREVIEW_BYTES: usize = 512;
#[must_use]
pub fn is_valid(&self) -> bool {
self.detail
.as_ref()
.is_none_or(|value| value.len() <= Self::MAX_DETAIL_BYTES && !value.contains('\n'))
&& self
.badge
.as_ref()
.is_none_or(|value| value.len() <= Self::MAX_BADGE_BYTES && !value.contains('\n'))
&& self.preview.as_ref().is_none_or(|value| {
value.len() <= Self::MAX_PREVIEW_BYTES
&& !value
.chars()
.any(|character| matches!(character, '\r' | '\0'))
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResourceViewMountSpec {
pub action: String,
pub capability_param: String,
pub view_param: String,
}
impl ResourceViewMountSpec {
pub fn new(
action: impl Into<String>,
capability_param: impl Into<String>,
view_param: impl Into<String>,
) -> Self {
Self {
action: action.into(),
capability_param: capability_param.into(),
view_param: view_param.into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResourceViewRangeSpec {
pub action: String,
pub start_param: String,
pub end_param: String,
pub unit_param: String,
}
impl ResourceViewRangeSpec {
pub fn new(action: impl Into<String>) -> Self {
Self {
action: action.into(),
start_param: "start".into(),
end_param: "end".into(),
unit_param: "unit".into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResourceViewSpec {
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,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub place: bool,
}
impl ResourceViewSpec {
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
open_action: impl Into<String>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
description: None,
open_action: open_action.into(),
primary: false,
mount: None,
range: None,
desktop: false,
place: false,
}
}
#[must_use]
pub fn on_desktop(mut self) -> Self {
self.desktop = true;
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_primary(mut self, primary: bool) -> Self {
self.primary = primary;
self
}
#[must_use]
pub fn with_place(mut self, place: bool) -> Self {
self.place = place;
self
}
#[must_use]
pub fn with_mount(mut self, mount: ResourceViewMountSpec) -> Self {
self.mount = Some(mount);
self
}
#[must_use]
pub fn with_range(mut self, range: ResourceViewRangeSpec) -> Self {
self.range = Some(range);
self
}
pub fn validate(&self, resource: &ResourceSpec) -> Vec<String> {
let mut errors = Vec::new();
if self.id.is_empty() || self.id.contains(KEY_SEP) {
errors.push("view id is empty or contains the separator".into());
}
if self.label.trim().is_empty() {
errors.push("view label must be non-empty".into());
}
validate_view_action(resource, &self.open_action, "open", &mut errors);
if let Some(mount) = &self.mount {
validate_view_action(resource, &mount.action, "mount", &mut errors);
if mount.capability_param == mount.view_param {
errors.push("mount capability and view parameters must be distinct".into());
}
if let Some(action) = resource
.actions
.iter()
.find(|action| action.id == mount.action)
{
for (role, name) in [
("capability", &mount.capability_param),
("view", &mount.view_param),
] {
if name.trim().is_empty() {
errors.push(format!("mount {role} parameter must be non-empty"));
} else if !action.params().iter().any(|parameter| {
parameter.name.as_ref() == name
&& parameter.ty == ParamType::Text
&& !parameter.required
}) {
errors.push(format!(
"mount {role} parameter `{name}` must name an optional text parameter"
));
}
}
}
}
if let Some(range) = &self.range {
let names = [&range.start_param, &range.end_param, &range.unit_param];
if names.iter().any(|name| name.trim().is_empty())
|| names[0] == names[1]
|| names[0] == names[2]
|| names[1] == names[2]
{
errors.push("range parameter names must be non-empty and distinct".into());
}
if let Some(action) = resource.actions.iter().find(|a| a.id == range.action) {
if action.kind != OperationKind::View
|| action.contract.confirmation != ConfirmationPolicy::None
{
errors.push("range action must be a view without confirmation".into());
}
for (name, ty) in [
(&range.start_param, ParamType::Integer),
(&range.end_param, ParamType::Integer),
(&range.unit_param, ParamType::Text),
] {
if !action
.params()
.iter()
.any(|p| p.name.as_ref() == name && p.ty == ty)
{
errors.push(format!(
"range parameter `{name}` has the wrong type or is missing"
));
}
}
if action
.params()
.iter()
.any(|p| p.required && !names.iter().any(|n| p.name.as_ref() == *n))
{
errors.push("range action requires unrelated input".into());
}
} else {
errors.push("range action is not exported".into());
}
}
errors
}
}
fn validate_view_action(
resource: &ResourceSpec,
action_id: &str,
role: &str,
errors: &mut Vec<String>,
) {
let Some(action) = resource
.actions
.iter()
.find(|action| action.id == action_id)
else {
errors.push(format!("{role} action `{action_id}` is not exported"));
return;
};
if action.kind != OperationKind::View {
errors.push(format!(
"{role} action `{action_id}` must be a view operation"
));
}
if action.contract.confirmation != ConfirmationPolicy::None {
errors.push(format!(
"{role} action `{action_id}` must not require confirmation"
));
}
if action.params().iter().any(|parameter| parameter.required) {
errors.push(format!(
"{role} action `{action_id}` must not require caller parameters"
));
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ResourceSemanticIdentity {
pub kind: String,
pub key: String,
}
impl ResourceSemanticIdentity {
pub const MAX_KIND_BYTES: usize = 128;
pub const MAX_KEY_BYTES: usize = 4096;
#[must_use]
pub fn new(kind: impl Into<String>, key: impl Into<String>) -> Option<Self> {
let identity = Self {
kind: kind.into(),
key: key.into(),
};
identity.is_valid().then_some(identity)
}
#[must_use]
pub fn is_valid(&self) -> bool {
!self.kind.is_empty()
&& self.kind.len() <= Self::MAX_KIND_BYTES
&& self
.kind
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
&& !self.key.is_empty()
&& self.key.len() <= Self::MAX_KEY_BYTES
&& !self.key.chars().any(char::is_control)
}
}
pub use crate::noun::{Noun, ResourceType, action_label, app_label, in_words, plural, singular};
#[must_use]
pub fn kind_mirrors_a_control(kind: &str) -> bool {
kind == "tilo.control"
|| kind == "tl.host"
|| ["tilo.control.", "tilo.ui.", "tilo.host."]
.iter()
.any(|prefix| kind.starts_with(prefix))
}
#[must_use]
pub fn kind_is_a_drawn_control(kind: &str) -> bool {
kind == "tilo.control"
|| ["tilo.control.", "tilo.ui."]
.iter()
.any(|prefix| kind.starts_with(prefix))
}
#[must_use]
pub fn listed_for_people(kind: &str, label: &str) -> bool {
!label.trim().is_empty() && !kind_mirrors_a_control(kind)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Collects {
#[default]
Words,
Content,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ActionInput<'a> {
Immediate(Option<&'a Arc<EncodedAction>>),
Deferred { type_id: &'a str },
Prompted {
prompt: &'a str,
placeholder: &'a str,
collects: Collects,
},
}
#[derive(Clone)]
enum InputMode {
Immediate(Option<Arc<EncodedAction>>),
Deferred {
type_id: String,
},
Prompted {
prompt: String,
placeholder: String,
collects: Collects,
},
}
#[derive(Clone, Default)]
pub struct Target(Option<Arc<dyn std::any::Any + Send + Sync>>);
impl Target {
#[must_use]
pub const fn none() -> Self {
Self(None)
}
#[must_use]
pub fn new<T: std::any::Any + Send + Sync>(value: T) -> Self {
Self(Some(Arc::new(value)))
}
#[must_use]
pub fn get<T: std::any::Any>(&self) -> Option<&T> {
self.0.as_deref()?.downcast_ref()
}
#[must_use]
pub fn same(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
}
}
}
type TargetTextBuilder = Arc<dyn Fn(&Target, &str) -> EncodedAction + Send + Sync>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContinuationKey {
namespace: String,
parts: Vec<Vec<u8>>,
}
impl ContinuationKey {
pub fn new(
namespace: impl Into<String>,
parts: impl IntoIterator<Item = impl Into<Vec<u8>>>,
) -> Self {
Self {
namespace: namespace.into(),
parts: parts.into_iter().map(Into::into).collect(),
}
}
}
pub enum ContinuationArguments<'a> {
Immediate,
Text(&'a str),
Json(&'a serde_json::Map<String, serde_json::Value>),
}
pub enum ContinuationQuery<'a> {
Exact(ContinuationArguments<'a>),
Draft,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContinuationEvidence {
Exact {
target: ContinuationKey,
handler: ContinuationKey,
},
Draft {
resolution_domain: ContinuationKey,
handler: ContinuationKey,
},
}
impl ContinuationEvidence {
pub fn write_canonical_identity(&self, sink: &mut impl std::io::Write) -> std::io::Result<()> {
fn length(sink: &mut impl std::io::Write, value: usize) -> std::io::Result<()> {
let value = u64::try_from(value).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "identity length overflow")
})?;
sink.write_all(&value.to_le_bytes())
}
fn bytes(sink: &mut impl std::io::Write, value: &[u8]) -> std::io::Result<()> {
length(sink, value.len())?;
sink.write_all(value)
}
fn key(sink: &mut impl std::io::Write, value: &ContinuationKey) -> std::io::Result<()> {
bytes(sink, value.namespace.as_bytes())?;
length(sink, value.parts.len())?;
for part in &value.parts {
bytes(sink, part)?;
}
Ok(())
}
sink.write_all(b"tilo.continuation-identity\0v1")?;
match self {
Self::Exact { target, handler } => {
sink.write_all(&[0])?;
key(sink, target)?;
key(sink, handler)
}
Self::Draft {
resolution_domain,
handler,
} => {
sink.write_all(&[1])?;
key(sink, resolution_domain)?;
key(sink, handler)
}
}
}
}
type ContinuationResolver =
Arc<dyn for<'a> Fn(ContinuationQuery<'a>) -> Option<ContinuationEvidence> + Send + Sync>;
#[derive(Clone)]
enum InvocationBuilder {
Fixed(Arc<EncodedAction>),
Dynamic {
build: ArgsBuilder,
deferred_type: Option<String>,
},
Text(TargetTextBuilder),
}
pub const NESTED_RESOURCE_FACET: &str = "part";
#[derive(Clone)]
pub struct ActionType {
pub id: String,
pub declared: String,
pub label: String,
pub keywords: Vec<String>,
pub did: Option<String>,
pub icon: Option<String>,
pub description: Option<String>,
pub state: ActionState,
pub locus: ExecutionLocus,
pub kind: OperationKind,
pub operation_type: Option<String>,
pub contract: ActionContract,
input: InputMode,
pub(crate) params: Vec<ActionParam>,
build: InvocationBuilder,
risk_of: Option<RiskClassifier>,
undo_of: Option<UndoClassifier>,
need_of: Option<NeedClassifier>,
continuation_resolver: Option<ContinuationResolver>,
carrier: bool,
applied_as: Option<(String, String)>,
provider: Option<Arc<RunBy>>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RunBy {
pub provider: String,
pub resource: Option<String>,
pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
}
impl ActionType {
#[must_use]
pub fn bind(self: &Arc<Self>, target: Target) -> ActionSpec {
ActionSpec {
ty: Arc::clone(self),
target,
bound: None,
}
}
fn encode(&self, target: &Target, args: &ActionArgs) -> EncodedAction {
match &self.build {
InvocationBuilder::Fixed(encoded) => encoded.as_ref().clone(),
InvocationBuilder::Dynamic { build, .. } => build(target, args),
InvocationBuilder::Text(build) => {
let text = primary_param(&self.params)
.and_then(|param| args.text(¶m.name))
.unwrap_or("");
build(target, text)
}
}
}
}
#[derive(Clone)]
pub struct ActionSpec {
ty: Arc<ActionType>,
target: Target,
bound: Option<Arc<[(String, serde_json::Value)]>>,
}
impl std::ops::Deref for ActionSpec {
type Target = ActionType;
fn deref(&self) -> &ActionType {
&self.ty
}
}
pub type RiskClassifier = Arc<dyn Fn(&Target, &ActionArgs) -> RiskLevel + Send + Sync>;
pub type UndoClassifier = Arc<dyn Fn(&ActionArgs) -> bool + Send + Sync>;
pub type NeedClassifier = Arc<dyn Fn(&Target, &ActionArgs) -> ActionNeed + Send + Sync>;
struct TypedActionSeed {
id: String,
label: String,
placeholder: String,
locus: ExecutionLocus,
kind: OperationKind,
operation_type: Option<String>,
params: Vec<ActionParam>,
}
struct Declared {
id: String,
label: String,
locus: ExecutionLocus,
kind: OperationKind,
operation_type: Option<String>,
params: Vec<ActionParam>,
}
impl Declared {
fn new(id: String, label: String, locus: ExecutionLocus, kind: OperationKind) -> Self {
Self {
id,
label,
locus,
kind,
operation_type: None,
params: Vec::new(),
}
}
}
impl ActionSpec {
fn of(ty: ActionType) -> Self {
Self {
ty: Arc::new(ty),
target: Target::none(),
bound: None,
}
}
#[must_use]
pub fn action_type(&self) -> &Arc<ActionType> {
&self.ty
}
#[must_use]
pub fn target(&self) -> &Target {
&self.target
}
pub fn type_mut(&mut self) -> &mut ActionType {
Arc::make_mut(&mut self.ty)
}
#[must_use]
pub fn input(&self) -> ActionInput<'_> {
match &self.input {
InputMode::Immediate(encoded) => ActionInput::Immediate(encoded.as_ref()),
InputMode::Deferred { type_id } => ActionInput::Deferred { type_id },
InputMode::Prompted {
prompt,
placeholder,
collects,
} => ActionInput::Prompted {
prompt,
placeholder,
collects: *collects,
},
}
}
#[must_use]
pub fn encode_immediate(&self) -> Option<Arc<EncodedAction>> {
match &self.input {
InputMode::Immediate(Some(encoded)) => Some(Arc::clone(encoded)),
InputMode::Immediate(None) => {
Some(Arc::new(self.ty.encode(&self.target, &ActionArgs::none())))
}
InputMode::Deferred { .. } | InputMode::Prompted { .. } => None,
}
}
#[must_use]
pub fn published_encoding(&self) -> Option<&Arc<EncodedAction>> {
match &self.input {
InputMode::Immediate(encoded) => encoded.as_ref(),
InputMode::Deferred { .. } | InputMode::Prompted { .. } => None,
}
}
#[must_use]
pub fn build_deferred(&self) -> Option<EncodedAction> {
match &self.input {
InputMode::Deferred { .. } => Some(self.ty.encode(&self.target, &ActionArgs::none())),
InputMode::Immediate(_) | InputMode::Prompted { .. } => None,
}
}
#[must_use]
pub fn run_by(self, provider: impl Into<String>) -> Self {
self.run_as(RunBy {
provider: provider.into(),
resource: None,
invokes: None,
})
}
#[must_use]
pub fn run_as(mut self, run: RunBy) -> Self {
self.type_mut().provider = Some(Arc::new(run));
self
}
#[must_use]
pub fn run_by_provider(&self) -> Option<&RunBy> {
self.provider.as_deref()
}
#[must_use]
pub fn provider(&self) -> Option<&str> {
self.provider.as_deref().map(|run| run.provider.as_str())
}
#[must_use]
pub fn applied_as(mut self, kind: impl Into<String>, label: impl Into<String>) -> Self {
if self.kind == OperationKind::Document {
self.type_mut().applied_as = Some((kind.into(), label.into()));
}
self
}
#[must_use]
pub fn history_context(&self, id: &str, kind: &str, label: &str) -> crate::ActionContext {
match &self.applied_as {
Some((owner_kind, owner_label)) => {
let mut context = crate::ActionContext::for_resource(id, owner_kind, owner_label);
context
.facets
.push(crate::ActionFacet::new(NESTED_RESOURCE_FACET, label));
context
}
None => crate::ActionContext::for_resource(id, kind, label),
}
}
pub fn fixed_invocation_encoding(&self) -> Option<&EncodedAction> {
match &self.build {
InvocationBuilder::Fixed(encoded) => Some(encoded),
InvocationBuilder::Dynamic { .. } | InvocationBuilder::Text(_) => None,
}
}
pub fn has_continuation_identity(&self) -> bool {
self.continuation_resolver.is_some()
}
pub fn deferred_invocation_type(&self) -> Option<&str> {
match &self.build {
InvocationBuilder::Dynamic { deferred_type, .. } => deferred_type.as_deref(),
InvocationBuilder::Fixed(_) | InvocationBuilder::Text(_) => None,
}
}
pub(crate) fn validate_deferred_shape(&self) -> Result<(), ArgError> {
match (&self.input, self.deferred_invocation_type()) {
(InputMode::Deferred { type_id }, Some(expected))
if !type_id.is_empty()
&& type_id == expected
&& self.params.is_empty()
&& match self.kind {
OperationKind::Document => self.operation_type.is_none(),
OperationKind::Effect | OperationKind::View => {
self.operation_type.as_deref() == Some(expected)
}
} =>
{
Ok(())
}
(InputMode::Deferred { .. }, _) | (_, Some(_)) => Err(ArgError::Constraint {
name: "deferred".into(),
reason: "deferred input and retained declaration disagree".into(),
}),
(_, None) => Ok(()),
}
}
fn validate_built(&self, encoded: EncodedAction) -> Result<EncodedAction, ArgError> {
if let Some(expected) = self.deferred_invocation_type()
&& encoded.type_id != expected
&& encoded.type_id != INVALID_ARGUMENTS_TYPE
{
return Err(ArgError::Constraint {
name: "deferred".into(),
reason: format!(
"builder returned `{}` but declared `{expected}`",
encoded.type_id
),
});
}
Ok(encoded)
}
pub fn validate_json(
&self,
supplied: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), ArgError> {
self.validate_deferred_shape()?;
ActionArgs::bind_json(&self.params, self.without_bound(supplied)?.as_ref()).map(|_| ())
}
#[must_use]
pub fn bound(&self) -> &[(String, serde_json::Value)] {
self.bound.as_deref().unwrap_or_default()
}
#[must_use]
pub fn with_bound(mut self, values: Vec<(String, serde_json::Value)>) -> Self {
self.bound = (!values.is_empty()).then(|| values.into());
self
}
#[must_use]
pub fn stating_bound(mut self, name: &str, description: &str) -> Self {
let Some((_, value)) = self.bound().iter().find(|(bound, _)| bound == name) else {
return self;
};
let value = match value {
serde_json::Value::String(text) => text.clone(),
other => other.to_string(),
};
let ty = Arc::make_mut(&mut self.ty);
let stated = crate::ActionParam {
name: name.to_owned().into(),
ty: crate::ParamType::Text,
required: false,
entry: false,
description: description.to_owned().into(),
choices: vec![value.into()],
schema: None,
nullable: false,
};
match ty.params.iter_mut().find(|param| param.name == name) {
Some(param) => *param = stated,
None => ty.params.push(stated),
}
self
}
fn without_bound<'a>(
&self,
supplied: &'a serde_json::Map<String, serde_json::Value>,
) -> Result<std::borrow::Cow<'a, serde_json::Map<String, serde_json::Value>>, ArgError> {
let repeated: Vec<&(String, serde_json::Value)> = self
.bound()
.iter()
.filter(|(name, _)| supplied.contains_key(name))
.collect();
if repeated.is_empty() {
return Ok(std::borrow::Cow::Borrowed(supplied));
}
let mut kept = supplied.clone();
for (name, value) in repeated {
let given = kept.remove(name).unwrap_or_default();
check_bound(name, value, &given)?;
}
Ok(std::borrow::Cow::Owned(kept))
}
fn pairs_without_bound(
&self,
supplied: impl IntoIterator<Item = (String, ArgValue)>,
) -> Result<Vec<(String, ArgValue)>, ArgError> {
let mut kept = Vec::new();
for (name, given) in supplied {
match self.bound().iter().find(|(bound, _)| *bound == name) {
Some((_, value)) => check_bound(&name, value, &given.to_json())?,
None => kept.push((name, given)),
}
}
Ok(kept)
}
fn declared(
seed: Declared,
contract: ActionContract,
input: InputMode,
build: InvocationBuilder,
) -> Self {
Self::of(ActionType {
id: seed.id,
declared: String::new(),
label: seed.label,
keywords: Vec::new(),
did: None,
icon: None,
description: None,
state: ActionState::default(),
locus: seed.locus,
kind: seed.kind,
operation_type: seed.operation_type,
contract,
input,
params: seed.params,
build,
risk_of: None,
undo_of: None,
need_of: None,
continuation_resolver: None,
carrier: false,
applied_as: None,
provider: None,
})
}
pub fn deferred(
id: impl Into<String>,
label: impl Into<String>,
locus: ExecutionLocus,
type_id: impl Into<String>,
build: impl Fn() -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::deferred_on(id, label, locus, type_id, move |_| build())
}
pub fn deferred_on(
id: impl Into<String>,
label: impl Into<String>,
locus: ExecutionLocus,
type_id: impl Into<String>,
build: impl Fn(&Target) -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::deferred_with_kind(
Declared::new(id.into(), label.into(), locus, OperationKind::Document),
type_id.into(),
build,
)
}
pub fn deferred_operation(
id: impl Into<String>,
label: impl Into<String>,
kind: OperationKind,
type_id: impl Into<String>,
build: impl Fn() -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::deferred_with_kind(
Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind),
type_id.into(),
move |_| build(),
)
}
fn deferred_with_kind(
mut seed: Declared,
type_id: String,
build: impl Fn(&Target) -> EncodedAction + Send + Sync + 'static,
) -> Self {
seed.operation_type = (seed.kind != OperationKind::Document).then(|| type_id.clone());
let contract = ActionContract::for_operation(seed.kind);
Self::declared(
seed,
contract,
InputMode::Deferred {
type_id: type_id.clone(),
},
InvocationBuilder::Dynamic {
build: Arc::new(move |target, _| build(target)),
deferred_type: Some(type_id),
},
)
}
fn fixed(seed: Declared, contract: ActionContract, encoded: EncodedAction) -> Self {
let encoded = Arc::new(encoded);
Self::declared(
seed,
contract,
InputMode::Immediate(Some(Arc::clone(&encoded))),
InvocationBuilder::Fixed(encoded),
)
}
pub fn immediate<A>(
id: impl Into<String>,
label: impl Into<String>,
type_id: impl Into<String>,
action: &A,
) -> Result<Self, ActionError>
where
A: Action + serde::Serialize,
{
let locus = action.locus();
let encoded = EncodedAction::encode(type_id, action)?;
Ok(Self::fixed(
Declared::new(id.into(), label.into(), locus, OperationKind::Document),
unnamed_kind(ActionContract::default()),
encoded,
))
}
pub fn immediate_encoded(
id: impl Into<String>,
label: impl Into<String>,
locus: ExecutionLocus,
encoded: EncodedAction,
) -> Self {
Self::fixed(
Declared::new(id.into(), label.into(), locus, OperationKind::Document),
unnamed_kind(ActionContract::default()),
encoded,
)
}
pub fn prompted_param(
id: impl Into<String>,
label: impl Into<String>,
param: ActionParam,
placeholder: impl Into<String>,
locus: ExecutionLocus,
build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::prompted_param_on(id, label, param, placeholder, locus, move |_, text| {
build(text)
})
}
pub fn prompted_param_on(
id: impl Into<String>,
label: impl Into<String>,
param: ActionParam,
placeholder: impl Into<String>,
locus: ExecutionLocus,
build: impl Fn(&Target, &str) -> EncodedAction + Send + Sync + 'static,
) -> Self {
let mut seed = Declared::new(id.into(), label.into(), locus, OperationKind::Document);
let prompt = param.description.to_string();
seed.params = vec![param];
Self::declared(
seed,
unnamed_kind(ActionContract::default()),
InputMode::Prompted {
prompt,
placeholder: placeholder.into(),
collects: Collects::Words,
},
InvocationBuilder::Text(Arc::new(build)),
)
}
pub fn prompt_param(&self) -> Option<&str> {
match self.input {
InputMode::Prompted { .. } => {
primary_param(self.params()).map(|param| param.name.as_ref())
}
_ => None,
}
}
#[must_use]
pub fn entry_param(&self) -> Option<&str> {
self.params()
.iter()
.find(|param| param.entry)
.map(|param| param.name.as_ref())
}
pub fn prompt_arguments(
&self,
text: &str,
) -> Option<serde_json::Map<String, serde_json::Value>> {
let name = self.prompt_param()?;
let mut arguments = serde_json::Map::new();
arguments.insert(name.to_owned(), serde_json::Value::String(text.to_owned()));
Some(arguments)
}
pub fn operation<T>(
id: impl Into<String>,
label: impl Into<String>,
kind: OperationKind,
type_id: impl Into<String>,
payload: &T,
) -> Result<Self, ActionError>
where
T: serde::Serialize,
{
debug_assert_ne!(kind, OperationKind::Document);
let type_id = type_id.into();
let encoded = EncodedAction::encode_operation(type_id.clone(), payload)?;
let mut seed = Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind);
seed.operation_type = Some(type_id);
Ok(Self::fixed(
seed,
ActionContract::for_operation(kind),
encoded,
))
}
pub fn prompted_operation(
id: impl Into<String>,
label: impl Into<String>,
prompt: impl Into<String>,
placeholder: impl Into<String>,
kind: OperationKind,
type_id: impl Into<String>,
build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
) -> Self {
debug_assert_ne!(kind, OperationKind::Document);
let prompt = prompt.into();
let type_id = type_id.into();
let expected = type_id.clone();
let mut seed = Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind);
seed.operation_type = Some(type_id);
seed.params = vec![ActionParam::required_owned(
PROMPTED_PARAM,
ParamType::Text,
prompt.clone(),
)];
Self::declared(
seed,
ActionContract::for_operation(kind),
InputMode::Prompted {
prompt,
placeholder: placeholder.into(),
collects: Collects::Words,
},
InvocationBuilder::Text(Arc::new(move |_, value| {
enforce_operation_type(build(value), &expected)
})),
)
}
#[doc(hidden)]
pub fn typed(
id: impl Into<String>,
label: impl Into<String>,
placeholder: impl Into<String>,
locus: ExecutionLocus,
params: Vec<ActionParam>,
build: impl Fn(&ActionArgs) -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::typed_with_kind(
TypedActionSeed {
id: id.into(),
label: label.into(),
placeholder: placeholder.into(),
locus,
kind: OperationKind::Document,
operation_type: None,
params,
},
Arc::new(move |_, args| build(args)),
true,
)
}
#[doc(hidden)]
pub fn typed_on(
id: impl Into<String>,
label: impl Into<String>,
placeholder: impl Into<String>,
locus: ExecutionLocus,
params: Vec<ActionParam>,
build: impl Fn(&Target, &ActionArgs) -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::typed_with_kind(
TypedActionSeed {
id: id.into(),
label: label.into(),
placeholder: placeholder.into(),
locus,
kind: OperationKind::Document,
operation_type: None,
params,
},
Arc::new(build),
false,
)
}
#[doc(hidden)]
pub fn typed_operation(
id: impl Into<String>,
label: impl Into<String>,
placeholder: impl Into<String>,
kind: OperationKind,
type_id: impl Into<String>,
params: Vec<ActionParam>,
build: impl Fn(&ActionArgs) -> EncodedAction + Send + Sync + 'static,
) -> Self {
debug_assert_ne!(kind, OperationKind::Document);
Self::typed_with_kind(
TypedActionSeed {
id: id.into(),
label: label.into(),
placeholder: placeholder.into(),
locus: ExecutionLocus::ClientLocal,
kind,
operation_type: Some(type_id.into()),
params,
},
Arc::new(move |_, args| build(args)),
true,
)
}
#[doc(hidden)]
pub fn typed_operation_on(
id: impl Into<String>,
label: impl Into<String>,
placeholder: impl Into<String>,
kind: OperationKind,
type_id: impl Into<String>,
params: Vec<ActionParam>,
build: ArgsBuilder,
) -> Self {
debug_assert_ne!(kind, OperationKind::Document);
Self::typed_with_kind(
TypedActionSeed {
id: id.into(),
label: label.into(),
placeholder: placeholder.into(),
locus: ExecutionLocus::ClientLocal,
kind,
operation_type: Some(type_id.into()),
params,
},
build,
false,
)
}
fn typed_with_kind(seed: TypedActionSeed, build: ArgsBuilder, eager: bool) -> Self {
let build: ArgsBuilder = if let Some(expected) = seed.operation_type.clone() {
Arc::new(move |target, args| enforce_operation_type(build(target, args), &expected))
} else {
build
};
let input = match primary_param(&seed.params) {
None => InputMode::Immediate(
eager.then(|| Arc::new(build(&Target::none(), &ActionArgs::none()))),
),
Some(primary) => InputMode::Prompted {
prompt: primary.description.to_string(),
placeholder: seed.placeholder,
collects: Collects::Words,
},
};
let contract = unnamed_kind(ActionContract::for_operation(seed.kind));
Self::declared(
Declared {
id: seed.id,
label: seed.label,
locus: seed.locus,
kind: seed.kind,
operation_type: seed.operation_type,
params: seed.params,
},
contract,
input,
InvocationBuilder::Dynamic {
build,
deferred_type: None,
},
)
}
#[must_use]
pub fn with_immediate(mut self, encoded: EncodedAction) -> Self {
self.type_mut().input = InputMode::Immediate(Some(Arc::new(encoded)));
self
}
#[must_use]
pub fn with_immediate_per_target(mut self) -> Self {
if self.params().iter().all(|param| !param.required) {
self.type_mut().input = InputMode::Immediate(None);
}
self
}
#[must_use]
pub fn with_continuation_identity(
mut self,
resolver: impl for<'a> Fn(ContinuationQuery<'a>) -> Option<ContinuationEvidence>
+ Send
+ Sync
+ 'static,
) -> Self {
self.type_mut().continuation_resolver = Some(Arc::new(resolver));
self
}
pub fn continuation_identity(
&self,
query: ContinuationQuery<'_>,
) -> Option<ContinuationEvidence> {
let exact = matches!(query, ContinuationQuery::Exact(_));
let evidence = self.continuation_resolver.as_ref()?(query)?;
match (exact, &evidence) {
(true, ContinuationEvidence::Exact { .. })
| (false, ContinuationEvidence::Draft { .. }) => Some(evidence),
_ => None,
}
}
pub fn prompted_content(
id: impl Into<String>,
label: impl Into<String>,
prompt: impl Into<String>,
placeholder: impl Into<String>,
locus: ExecutionLocus,
build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
) -> Self {
Self::prompted_content_on(id, label, prompt, placeholder, locus, move |_, hash| {
build(hash)
})
}
pub fn prompted_content_on(
id: impl Into<String>,
label: impl Into<String>,
prompt: impl Into<String>,
placeholder: impl Into<String>,
locus: ExecutionLocus,
build: impl Fn(&Target, &str) -> EncodedAction + Send + Sync + 'static,
) -> Self {
let mut spec = Self::prompted_param_on(
id,
label,
ActionParam::required_owned(PROMPTED_PARAM, ParamType::Text, prompt.into()),
placeholder,
locus,
build,
);
if let InputMode::Prompted { collects, .. } = &mut spec.type_mut().input {
*collects = Collects::Content;
}
spec
}
#[must_use]
pub fn with_keywords<S: Into<String>>(mut self, keywords: impl IntoIterator<Item = S>) -> Self {
self.type_mut().keywords = keywords.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_did(mut self, did: impl Into<String>) -> Self {
let did = did.into();
self.type_mut().did = Some(did).filter(|did| !did.trim().is_empty());
self
}
#[must_use]
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.type_mut().icon = Some(icon.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.type_mut().description = Some(description.into());
self
}
#[must_use]
pub fn with_state(mut self, state: ActionState) -> Self {
self.type_mut().state = state;
self
}
#[must_use]
pub fn with_contract(mut self, contract: ActionContract) -> Self {
self.type_mut().contract = contract;
self
}
#[must_use]
pub fn unavailable(mut self, code: impl Into<String>, reason: impl Into<String>) -> Self {
self.type_mut().contract.availability = Availability::Unavailable {
code: code.into(),
reason: reason.into(),
};
self
}
#[must_use]
pub fn destructive(mut self) -> Self {
let contract = &mut self.type_mut().contract;
contract.risk = RiskLevel::Destructive;
contract.kind = contract.deletion_kind();
contract.settle_confirmation();
self
}
#[must_use]
pub fn for_audience(mut self, audience: crate::Audience) -> Self {
self.type_mut().contract.set_audience(audience);
self
}
#[must_use]
pub fn reads_document(mut self) -> Self {
push_tag(
&mut self.type_mut().contract,
crate::contract::DOCUMENT_READ_TAG,
);
self
}
#[must_use]
pub fn reads_resource(mut self) -> Self {
push_tag(
&mut self.type_mut().contract,
crate::contract::RESOURCE_READ_TAG,
);
self
}
#[must_use]
pub fn opens_path(mut self, extensions: &[&str]) -> Self {
push_tag(
&mut self.type_mut().contract,
crate::contract::OPENS_PATH_TAG,
);
for extension in extensions {
push_tag(
&mut self.type_mut().contract,
&format!(
"{}{}",
crate::contract::OPENS_PATH_EXTENSION_PREFIX,
extension.to_ascii_lowercase()
),
);
}
self
}
pub fn audience(&self) -> crate::Audience {
self.contract.audience()
}
pub fn reaches_people(&self) -> bool {
self.contract.reaches_people()
}
pub fn reaches_agents(&self) -> bool {
self.contract.reaches_agents()
}
pub fn takes_a_row_answer(&self) -> bool {
let mut required = self.params.iter().filter(|param| param.required);
match (required.next(), required.next()) {
(None, _) => true,
(Some(param), None) => {
matches!(self.input(), ActionInput::Prompted { .. })
&& matches!(
param.ty,
ParamType::Text
| ParamType::Integer
| ParamType::Number
| ParamType::DateTime
| ParamType::Secret
)
}
(Some(_), Some(_)) => false,
}
}
#[must_use]
pub fn carrying(mut self) -> Self {
self.type_mut().carrier = true;
push_tag(&mut self.type_mut().contract, crate::contract::CARRIER_TAG);
self
}
pub fn carries_actions(&self) -> bool {
self.carrier
}
#[must_use]
pub fn with_risk(
self,
classify: impl Fn(&ActionArgs) -> RiskLevel + Send + Sync + 'static,
) -> Self {
self.with_risk_on(move |_, args| classify(args))
}
#[must_use]
pub fn with_risk_on(
mut self,
classify: impl Fn(&Target, &ActionArgs) -> RiskLevel + Send + Sync + 'static,
) -> Self {
push_tag(
&mut self.type_mut().contract,
crate::contract::ARGUMENT_RISK_TAG,
);
self.type_mut().risk_of = Some(Arc::new(classify));
self
}
#[must_use]
pub fn with_need_of(
mut self,
classify: impl Fn(&ActionArgs) -> ActionNeed + Send + Sync + 'static,
) -> Self {
self.type_mut().need_of = Some(Arc::new(move |_, args| classify(args)));
self
}
pub fn need_for_args(&self, args: &ActionArgs) -> ActionNeed {
let mut need = self.need_of.as_ref().map_or_else(
|| self.contract.need(),
|classify| self.contract.scoped(classify(&self.target, args)),
);
need.privileged |= self.risk_for(args) == RiskLevel::Privileged;
need
}
#[must_use]
pub fn need_for(
&self,
json: Option<&serde_json::Map<String, serde_json::Value>>,
argument: Option<&str>,
) -> ActionNeed {
if self.need_of.is_none() && self.risk_of.is_none() {
return self.contract.need();
}
if let Some(json) = json {
return self
.without_bound(json)
.and_then(|json| ActionArgs::bind_json(&self.params, &json))
.map_or_else(|_| self.contract.need(), |args| self.need_for_args(&args));
}
if let Some(json) =
argument.and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
{
return serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(json)
.map_or_else(
|_| self.contract.need(),
|arguments| self.need_for(Some(&arguments), None),
);
}
let supplied = argument.map_or_else(Vec::new, |text| primary_argument(&self.params, text));
ActionArgs::bind(&self.params, supplied)
.map_or_else(|_| self.contract.need(), |args| self.need_for_args(&args))
}
#[must_use]
pub fn with_undo_of(
mut self,
classify: impl Fn(&ActionArgs) -> bool + Send + Sync + 'static,
) -> Self {
self.type_mut().undo_of = Some(Arc::new(classify));
self
}
pub fn undoable_for(&self, args: &ActionArgs) -> bool {
self.undo_of
.as_ref()
.map_or_else(|| self.contract.can_be_undone(), |classify| classify(args))
}
pub fn risk_for(&self, args: &ActionArgs) -> RiskLevel {
self.risk_of
.as_ref()
.map_or(self.contract.risk, |classify| classify(&self.target, args))
}
pub fn confirmation_for_args(&self, args: &ActionArgs) -> ConfirmationPolicy {
if self.contract.confirmation != ConfirmationPolicy::None || self.risk_of.is_none() {
return self.contract.confirmation.clone();
}
if self
.risk_for(args)
.requires_confirmation_when(self.undoable_for(args))
{
ConfirmationPolicy::Confirm
} else {
ConfirmationPolicy::None
}
}
pub fn confirmation_for_json(
&self,
supplied: &serde_json::Map<String, serde_json::Value>,
) -> ConfirmationPolicy {
if self.risk_of.is_none() {
return self.contract.confirmation.clone();
}
self.without_bound(supplied)
.and_then(|supplied| ActionArgs::bind_json(&self.params, &supplied))
.map_or_else(
|_| self.contract.confirmation.clone(),
|args| self.confirmation_for_args(&args),
)
}
pub fn confirmation_for_argument(&self, argument: Option<&str>) -> ConfirmationPolicy {
if self.risk_of.is_none() {
return self.contract.confirmation.clone();
}
if let Some(json) =
argument.and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
{
return serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(json)
.map_or_else(
|_| self.contract.confirmation.clone(),
|arguments| self.confirmation_for_json(&arguments),
);
}
let supplied = argument.map_or_else(Vec::new, |text| primary_argument(&self.params, text));
ActionArgs::bind(&self.params, supplied).map_or_else(
|_| self.contract.confirmation.clone(),
|args| self.confirmation_for_args(&args),
)
}
#[must_use]
pub fn privileged(mut self) -> Self {
self.type_mut().contract.risk = RiskLevel::Privileged;
self.type_mut().contract.confirmation = ConfirmationPolicy::Confirm;
self
}
#[must_use]
pub fn of_kind(mut self, kind: ActionKind) -> Self {
self.type_mut().contract.kind = kind;
self
}
#[must_use]
pub fn with_need(mut self, need: ActionNeed) -> Self {
self.type_mut().contract.kind = need.kind;
self.type_mut().contract.field = need.field;
self
}
#[must_use]
pub fn below_field(mut self, field: impl Into<String>) -> Self {
self.type_mut().contract.field = Some(field.into());
self
}
#[must_use]
pub fn execution(mut self, execution: ExecutionMode) -> Self {
self.type_mut().contract.execution = execution;
self
}
#[must_use]
pub fn returns(mut self, result: ResultSpec) -> Self {
self.type_mut().contract.result = result;
self
}
#[must_use]
pub fn rewrapped(
mut self,
wrapped_type: &str,
wrap: impl Fn(EncodedAction) -> EncodedAction + Send + Sync + 'static,
) -> Self {
if self.kind != OperationKind::Document {
return self;
}
let wrap: Arc<dyn Fn(EncodedAction) -> EncodedAction + Send + Sync> =
Arc::new(move |encoded: EncodedAction| {
if encoded.type_id == INVALID_ARGUMENTS_TYPE {
encoded
} else {
wrap(encoded)
}
});
let ty = self.type_mut();
ty.build = match ty.build.clone() {
InvocationBuilder::Fixed(encoded) => {
InvocationBuilder::Fixed(Arc::new(wrap(encoded.as_ref().clone())))
}
InvocationBuilder::Dynamic {
build,
deferred_type,
} => {
let wrap = Arc::clone(&wrap);
InvocationBuilder::Dynamic {
build: Arc::new(move |target, args| wrap(build(target, args))),
deferred_type: deferred_type.map(|_| wrapped_type.to_owned()),
}
}
InvocationBuilder::Text(build) => {
let wrap = Arc::clone(&wrap);
InvocationBuilder::Text(Arc::new(move |target, text| wrap(build(target, text))))
}
};
match &mut ty.input {
InputMode::Immediate(Some(encoded)) => {
*encoded = Arc::new(wrap(encoded.as_ref().clone()));
}
InputMode::Deferred { type_id } => wrapped_type.clone_into(type_id),
InputMode::Immediate(None) | InputMode::Prompted { .. } => {}
}
self
}
#[must_use]
pub fn routed(
self,
operation_type: &str,
wrap: impl Fn(EncodedAction) -> EncodedAction + Send + Sync + 'static,
) -> Self {
if self.kind != OperationKind::Document {
return self;
}
let mut spec = self.rewrapped(operation_type, wrap);
let ty = spec.type_mut();
ty.kind = OperationKind::Effect;
ty.operation_type = Some(operation_type.to_owned());
push_tag(&mut ty.contract, crate::ROUTED_CHANGE_TAG);
spec
}
pub fn params(&self) -> &[ActionParam] {
&self.params
}
pub fn narrow_param(&mut self, name: &str, narrow: impl FnOnce(&mut ActionParam)) {
if let Some(param) = Arc::make_mut(&mut self.ty)
.params
.iter_mut()
.find(|param| param.name == name)
{
narrow(param);
}
}
pub fn build_args(
&self,
supplied: impl IntoIterator<Item = (String, ArgValue)>,
) -> Result<EncodedAction, ArgError> {
self.validate_deferred_shape()?;
let bound = ActionArgs::bind(&self.params, self.pairs_without_bound(supplied)?)?;
self.validate_built(self.ty.encode(&self.target, &bound))
}
pub fn build_json(
&self,
supplied: &serde_json::Map<String, serde_json::Value>,
) -> Result<EncodedAction, ArgError> {
self.validate_deferred_shape()?;
let bound = ActionArgs::bind_json(&self.params, self.without_bound(supplied)?.as_ref())?;
self.validate_built(self.ty.encode(&self.target, &bound))
}
pub fn build_text(&self, text: &str) -> Option<EncodedAction> {
if !matches!(self.input, InputMode::Prompted { .. }) {
return None;
}
Some(match &self.build {
InvocationBuilder::Text(build) => build(&self.target, text),
InvocationBuilder::Fixed(_) | InvocationBuilder::Dynamic { .. } => {
match ActionArgs::bind(&self.params, primary_argument(&self.params, text)) {
Ok(bound) => self.ty.encode(&self.target, &bound),
Err(error) => EncodedAction {
type_id: INVALID_ARGUMENTS_TYPE.into(),
payload: error.to_string().into_bytes(),
},
}
}
})
}
}
fn check_bound(
name: &str,
value: &serde_json::Value,
given: &serde_json::Value,
) -> Result<(), ArgError> {
let same = given == value
|| match (value, given) {
(serde_json::Value::String(id), serde_json::Value::String(given)) => {
given.trim() == id
|| given
.rsplit(['/', ':'])
.next()
.is_some_and(|last| last == id && !id.is_empty())
}
_ => false,
};
if same {
return Ok(());
}
let shown = match value {
serde_json::Value::String(id) => id.clone(),
other => other.to_string(),
};
Err(ArgError::Constraint {
name: name.to_owned(),
reason: format!(
"is `{shown}` here: this action acts on that item only. Leave `{name}` out, or \
invoke the action on the item you mean"
),
})
}
fn enforce_operation_type(encoded: EncodedAction, expected: &str) -> EncodedAction {
if encoded.type_id == expected || encoded.type_id == INVALID_ARGUMENTS_TYPE {
encoded
} else {
EncodedAction {
type_id: INVALID_ARGUMENTS_TYPE.into(),
payload: format!(
"operation builder returned `{}` but declared `{expected}`",
encoded.type_id
)
.into_bytes(),
}
}
}
fn push_tag(contract: &mut ActionContract, tag: &str) {
if !contract.tags.iter().any(|existing| existing == tag) {
contract.tags.push(tag.to_owned());
}
}
fn primary_argument(params: &[ActionParam], text: &str) -> Vec<(String, ArgValue)> {
primary_param(params).map_or_else(Vec::new, |primary| {
parse_argument(&primary.name, primary.ty, text)
})
}
fn parse_argument(name: &str, ty: ParamType, text: &str) -> Vec<(String, ArgValue)> {
let parsed = match ty {
ParamType::Text => Some(ArgValue::Text(text.to_string())),
ParamType::Integer => text.trim().parse::<i128>().ok().map(ArgValue::Integer),
ParamType::Number => text.trim().parse::<f64>().ok().map(ArgValue::Number),
ParamType::Boolean => match text.trim() {
"true" | "yes" | "on" => Some(ArgValue::Boolean(true)),
"false" | "no" | "off" => Some(ArgValue::Boolean(false)),
_ => None,
},
ParamType::Object => {
serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(text)
.ok()
.map(ArgValue::Object)
}
ParamType::Array => serde_json::from_str::<Vec<serde_json::Value>>(text)
.ok()
.map(ArgValue::Array),
ParamType::Resource => Some(ArgValue::Resource(text.to_string())),
ParamType::DateTime => Some(ArgValue::DateTime(text.to_string())),
ParamType::Secret => Some(ArgValue::Secret(text.to_string())),
};
parsed
.map(|v| vec![(name.to_owned(), v)])
.unwrap_or_default()
}
fn primary_param(params: &[ActionParam]) -> Option<&ActionParam> {
params
.iter()
.find(|p| p.entry)
.or_else(|| params.iter().find(|p| p.required))
.or_else(|| params.first())
}
pub use tilo_action_types::KEY_SEP;
pub struct FlatAction<'a> {
pub key: String,
pub resource_id: ResourceId,
pub resource_kind: String,
pub resource_label: String,
pub resource_presentation: Option<ResourcePresentation>,
pub action: &'a ActionSpec,
pub depth: usize,
}
impl FlatAction<'_> {
#[must_use]
pub fn offered_to_a_person(&self) -> bool {
self.action.contract.a_person_can_take_now()
&& listed_for_people(&self.resource_kind, &self.resource_label)
&& !self
.action
.contract
.tags
.iter()
.any(|tag| tag == crate::OPENS_HIT_TAG)
}
#[must_use]
pub fn lists_a_row(&self) -> bool {
self.offered_to_a_person() && self.action.takes_a_row_answer()
}
#[must_use]
pub fn row(&self) -> ListedRow {
listed_row(
&self.action.label,
(self.depth > 0).then_some(self.resource_label.as_str()),
)
}
}
#[path = "resource/listed_row.rs"]
mod listed_row;
pub use listed_row::{ListedRow, listed_row, listed_row_problems};
mod reading_row;
pub use reading_row::ReadingRow;
pub fn flatten(resources: &[ResourceSpec]) -> Vec<FlatAction<'_>> {
let mut out = Vec::new();
for r in resources {
flatten_into(r, 0, &mut out);
}
out
}
fn flatten_into<'a>(resource: &'a ResourceSpec, depth: usize, out: &mut Vec<FlatAction<'a>>) {
for action in &resource.actions {
out.push(FlatAction {
key: format!("{}{}{}", resource.id.0, KEY_SEP, action.id),
resource_id: resource.id.clone(),
resource_kind: resource.kind.clone(),
resource_label: resource.label.clone(),
resource_presentation: resource.presentation.clone(),
action,
depth,
});
}
for child in &resource.children {
flatten_into(child, depth.saturating_add(1), out);
}
}
#[path = "resource/control.rs"]
mod control;
pub use control::ControlInvocation;
#[path = "resource/spec.rs"]
mod spec;
pub use spec::ResourceSpec;
#[path = "resource/choices.rs"]
mod choices;
#[path = "resource/carried.rs"]
mod carried;
#[cfg(test)]
#[path = "resource/tests.rs"]
mod tests;
#[cfg(test)]
#[path = "resource/history_tests.rs"]
mod history_tests;
#[cfg(test)]
#[path = "resource/effective_invocation_tests.rs"]
mod effective_invocation_tests;
#[cfg(test)]
#[path = "resource/deferred_tests.rs"]
mod deferred_tests;