use std::any::TypeId;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use serde::Serialize;
use serde::de::DeserializeOwned;
use tilo_actions::{
ActionArgs, ActionError, ActionNeed, ActionParam, ActionRegistry, ActionSpec, ActionType,
EncodedAction, ExecutionLocus, OperationKind, ParamType, Target,
};
use crate::action::ActionKind;
use crate::delta::Delta;
use crate::model::{Doc, ModelError};
use crate::path::Edit;
use crate::reader::Demand;
use crate::vocabulary::{Builds, Built, Declaration, Vocabulary, vocabulary};
use tilo_lock::MutexRecover as _;
mod head;
pub use head::{HeadInputs, head_inputs, publish_head, publish_head_of};
mod search_entry;
pub use search_entry::{SearchBody, SearchEntry, SearchPiece, SearchText, SearchWeight};
pub trait Resource: Sized + 'static {
const KIND: &'static str;
const LABEL: &'static str;
const CATALOGUE: Option<&'static crate::label::Catalogue> = None;
const APP_ID: &'static str = crate::kind::DEFAULT_APP;
const ACTION_TYPE: &'static str = Self::KIND;
fn label() -> String {
crate::label::localized(Self::KIND, Self::LABEL, Self::CATALOGUE)
}
type State: 'static;
type Action: tilo_actions::Action + Serialize + DeserializeOwned + Clone + 'static;
fn read(doc: &Doc) -> Result<Self::State, ModelError>;
fn refresh(state: &mut Self::State, doc: &Doc, delta: &Delta) -> Result<(), ModelError> {
if !delta.is_empty() {
*state = Self::read(doc)?;
}
Ok(())
}
fn copy_state(_state: &Self::State) -> Option<Self::State> {
None
}
fn publication_cache_epoch(_state: &Self::State) -> Option<String> {
None
}
fn locate(state: &Self::State, obj: &automerge::ObjId) -> Option<crate::delta::ObjPath> {
let _ = (state, obj);
None
}
fn load(state: &mut Self::State, doc: &Doc, demand: &Demand) -> Result<(), ModelError> {
let _ = (state, doc, demand);
Ok(())
}
fn initialize(_doc: &mut Doc) -> Result<(), ModelError> {
Ok(())
}
fn coalesces(previous: &Self::Action, next: &Self::Action) -> bool {
let _ = (previous, next);
false
}
fn continuable(action: &Self::Action) -> bool {
let _ = action;
true
}
fn lands(state: &Self::State, action: &Self::Action) -> Option<Place> {
let _ = (state, action);
None
}
fn lands_on_state(action: &Self::Action) -> bool {
let _ = action;
true
}
fn field_of(action: &Self::Action) -> Option<&'static str> {
let _ = action;
None
}
fn least_need() -> ActionNeed {
least_need_declared(&vocabulary::<Self>().declarations())
}
fn declarations() -> Vec<ActionDecl<Self>> {
Vec::new()
}
fn action_schema() -> Option<serde_json::Value> {
None
}
fn children(_state: &Self::State) -> Vec<tilo_actions::ResourceSpec> {
Vec::new()
}
fn item_effects(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ActionSpec> {
Vec::new()
}
fn item_views(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ResourceViewSpec> {
Vec::new()
}
fn children_parts(state: &Self::State) -> crate::items::ChildrenParts {
crate::items::ChildrenParts {
others: Self::children(state),
kept: std::rc::Rc::default(),
items: Vec::new(),
item_actions: Vec::new(),
}
}
fn children_offer_bound(state: &Self::State) -> Vec<&'static str> {
offered_bound_ids(&Self::children(state), &vocabulary::<Self>().declarations())
}
fn child(_state: &Self::State, _id: &str) -> Option<tilo_actions::ResourceSpec> {
None
}
fn local_operations() -> Vec<tilo_actions::ActionSpec> {
Vec::new()
}
fn views(_state: &Self::State) -> Vec<tilo_actions::ResourceViewSpec> {
Vec::new()
}
fn search_scopes(_state: &Self::State) -> Vec<ScopeDecl> {
Vec::new()
}
fn search(_state: &Self::State) -> Vec<SearchEntry> {
Vec::new()
}
const READABLE: bool = false;
fn document_child(_state: &Self::State, _id: &str) -> bool {
false
}
fn read_content(
state: &Self::State,
doc: &Doc,
item: Option<&str>,
) -> Result<serde_json::Value, String> {
let _ = (state, doc, item);
Err(format!("a {} does not answer reads", Self::LABEL))
}
const HAS_FACTS: bool = false;
const RESOURCE_TABLE: Option<&'static crate::table::ModelTable> = None;
fn facts(state: &Self::State, doc: &Doc) -> Result<serde_json::Value, String> {
let _ = (state, doc);
Err(format!("a {} states no facts", Self::LABEL))
}
const ANSWERS: bool = false;
fn answer(
_doc: &Doc,
_action: &str,
_changes: &[automerge::Patch],
) -> Option<serde_json::Value> {
None
}
fn shape() -> Option<crate::Shape> {
None
}
fn state_json(state: &Self::State) -> Option<serde_json::Value> {
let _ = state;
None
}
const VERSION: u32 = 1;
const READERS: &'static str = "";
fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
let _ = doc;
Err(ModelError::invalid(format!(
"{} has no migration from storage version {from}",
Self::LABEL
)))
}
#[must_use]
fn surface() -> crate::surface::Surface {
crate::surface::surface_of::<Self>()
}
const EDITS: bool = false;
fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
let _ = edit;
None
}
fn stamp(action: &mut Self::Action, now_ms: i64) {
let _ = (action, now_ms);
}
fn op_schemas() -> Vec<(String, serde_json::Value)> {
Vec::new()
}
fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
let _ = (state, action);
tilo_actions::Availability::Available
}
fn seed() -> Option<Self::Action> {
None
}
fn kind_of(action: &Self::Action) -> ActionKind {
let _ = action;
ActionKind::Undoable
}
fn by_app(action: &Self::Action) -> bool {
let _ = action;
false
}
fn build_by_app(
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
now_ms: i64,
) -> Option<Result<Self::Action, String>> {
let _ = (id, arguments, now_ms);
None
}
fn action_item(action: &Self::Action) -> Option<crate::Id> {
let _ = action;
None
}
fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
let _ = action;
None
}
fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
let _ = (action, keep);
None
}
fn register(registry: &mut ActionRegistry) {
registry.register::<Self::Action>(Self::ACTION_TYPE);
}
}
pub trait NamesItem: Clone {
fn named_item(&self) -> Option<crate::Id>;
}
impl NamesItem for crate::Id {
fn named_item(&self) -> Option<crate::Id> {
Some(self.clone())
}
}
impl NamesItem for String {
fn named_item(&self) -> Option<crate::Id> {
Some(crate::Id::from_raw(self.clone()))
}
}
#[doc(hidden)]
pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
entries.iter().map(NamesItem::named_item).collect()
}
#[doc(hidden)]
#[must_use]
pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
keep.iter()
.filter_map(|at| entries.get(*at).cloned())
.collect()
}
pub const APPLY: &str = "apply";
pub const APPLY_PARAM: &str = "action";
pub const FIELD_EDIT: &str = "field-edit";
pub const EDIT_PARAM: &str = "edit";
fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
match (vocabulary.edit)(edit) {
Some(action) => Ok(action),
None => Err(format!("{} has no field edits", vocabulary.label)),
}
}
pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
let ops = (vocabulary.op_schemas)();
if let Some(shape) = (vocabulary.shape)()
&& !shape.fields().is_empty()
{
let mut alternatives = Vec::new();
edit_paths(shape, &[], "", &ops, &mut alternatives);
if !alternatives.is_empty() {
return described_edit(&alternatives, &ops);
}
}
generic_edit_schema(&ops, |_| true)
}
fn described_edit(
alternatives: &[serde_json::Value],
ops: &[(String, serde_json::Value)],
) -> serde_json::Value {
let taken: Vec<String> = alternatives
.iter()
.filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
.flatten()
.filter_map(serde_json::Value::as_str)
.map(str::to_owned)
.collect();
let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
let mut lines = vec![
"A field edit: `path` from the record (fields by name, items by id, map entries by key) and `op` with its arguments. Editable paths:".to_owned(),
];
let mut examples = Vec::new();
let mut shapes: Vec<Vec<String>> = Vec::new();
let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
for (alternative, next) in alternatives.iter().zip(nexts) {
let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
let template = at("/properties/path/examples/0");
let ops: Vec<String> = at("/properties/op/enum")
.as_array()
.map(|ops| {
ops.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_owned)
.collect()
})
.unwrap_or_default();
let value = at("/properties/value");
let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
let title = text("/title");
let shape: Vec<String> = template
.as_array()
.map(|steps| {
steps
.iter()
.filter_map(|step| step.as_object()?.keys().next().cloned())
.collect()
})
.unwrap_or_default();
let leaf = next.is_none_or(|next| {
next.get("title")
.and_then(serde_json::Value::as_str)
.is_none_or(|next| !next.starts_with(&format!("{title}.")))
});
let in_resource = shape
.iter()
.rev()
.take(2)
.filter(|kind| *kind == "field")
.count()
== 2;
let record = title
.rsplit_once('.')
.and_then(|(parent, key)| {
listed
.iter_mut()
.find(|(path, ..)| path == parent)
.map(|(_, _, fields)| (fields, key))
})
.filter(|_| in_resource && leaf && ops == ["set"]);
if let Some((fields, key)) = record {
fields.push(format!("`{key}`"));
} else {
let kind = value_kind(&value);
let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
let line = format!(
"- `{title}`: {} — {}{}",
usage.join(", "),
text("/description"),
kind.map_or_else(String::new, |kind| format!(" ({kind})")),
);
listed.push((title.clone(), line, Vec::new()));
}
if shapes.contains(&shape) {
continue;
}
shapes.push(shape);
let mut example = serde_json::Map::new();
example.insert("path".into(), template);
if let Some(op) = ops.first() {
example.insert("op".into(), op.clone().into());
}
examples.push(serde_json::Value::Object(example));
}
lines.extend(listed.into_iter().map(|(_, line, fields)| {
if fields.is_empty() {
line
} else {
format!("{line}; set one field of it: {}", fields.join(", "))
}
}));
if let Some(object) = schema.as_object_mut() {
object.insert("description".into(), lines.join("\n").into());
object.insert("examples".into(), examples.into());
}
schema
}
fn value_kind(schema: &serde_json::Value) -> Option<String> {
if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
let options: Vec<String> = options
.iter()
.map(|option| {
option
.as_str()
.map_or_else(|| option.to_string(), str::to_owned)
})
.collect();
return Some(format!("one of {}", options.join(", ")));
}
match schema.get("type")? {
serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
serde_json::Value::Array(kinds) => Some(
kinds
.iter()
.filter_map(serde_json::Value::as_str)
.collect::<Vec<_>>()
.join(" or "),
),
_ => None,
}
}
fn generic_edit_schema(
ops: &[(String, serde_json::Value)],
takes: impl Fn(&str) -> bool,
) -> serde_json::Value {
let ops = ops.to_vec();
let mut schema = crate::path::edit_schema_taking(&takes);
if !ops.is_empty()
&& takes("rich")
&& let Some(properties) = schema
.get_mut("properties")
.and_then(serde_json::Value::as_object_mut)
{
let description = ops
.into_iter()
.map(|(path, schema)| {
format!(
"An edit of `{path}` in its own vocabulary, one of: {}",
crate::schema::summary(&schema)
)
})
.collect::<Vec<_>>()
.join("\n");
properties.insert(
"rich".into(),
crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
);
}
schema
}
fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
let mut properties = serde_json::Map::new();
properties.insert(kind.to_owned(), value);
serde_json::json!({
"type": "object",
"properties": properties,
"required": [kind],
})
}
fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
let ty = field.ty;
if ty.rsplit("::").next() == Some("Reactions") {
return vec!["react", "unreact"];
}
match field.shape {
crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
vec![
"upsert-item",
"insert-item",
"remove-item",
"move-to",
"set",
]
}
_ if rich => vec!["replace", "rich"],
_ if ty.starts_with("Counter") => vec!["add", "set"],
_ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
_ if ty.starts_with("Grid<") => vec![
"set-cell",
"insert-row",
"insert-column",
"remove-row",
"remove-column",
],
_ if ty.starts_with("Outbox") => vec!["settle", "forget"],
crate::Shape::Map(_) => vec!["set", "remove-key"],
_ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
_ => vec!["set"],
}
}
fn takes_own_verbs(field: &crate::FieldShape) -> bool {
let ops = field_ops(field, false);
ops.iter()
.any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
}
fn rich_schema_at<'a>(
rich: &'a [(String, serde_json::Value)],
at: &str,
) -> Option<&'a serde_json::Value> {
rich.iter()
.find(|(path, _)| path == at)
.map(|(_, schema)| schema)
}
#[allow(
clippy::too_many_lines,
reason = "one walk over the stored shape, an alternative per kind of path"
)]
fn edit_paths(
shape: crate::Shape,
steps: &[serde_json::Value],
dotted: &str,
rich: &[(String, serde_json::Value)],
out: &mut Vec<serde_json::Value>,
) {
let alternative = |steps: &[serde_json::Value],
open: bool,
ops: &[&str],
value: serde_json::Value,
rich: Option<&serde_json::Value>,
title: &str,
description: String| {
let template: Vec<serde_json::Value> = steps
.iter()
.map(|step| {
let properties = step.get("properties").and_then(serde_json::Value::as_object);
match properties.and_then(|properties| properties.iter().next()) {
Some((kind, value)) if kind == "field" => {
serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
}
Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
None => serde_json::Value::Null,
}
})
.collect();
let dotted: Vec<String> = template
.iter()
.map(
|step| match step.get("field").and_then(serde_json::Value::as_str) {
Some(field) => field.to_owned(),
None => "*".to_owned(),
},
)
.collect();
let mut path = serde_json::json!({
"type": "array",
"prefixItems": steps,
"minItems": steps.len(),
"examples": [template],
});
if let Some(path) = path.as_object_mut() {
if open {
path.insert("items".into(), serde_json::json!({ "type": "object" }));
} else {
path.insert("maxItems".into(), steps.len().into());
}
}
let mut properties = serde_json::Map::new();
properties.insert("path".into(), path);
properties.insert("op".into(), serde_json::json!({ "enum": ops }));
properties.insert("value".into(), value);
if ops.contains(&"upsert-item") {
properties.insert(
"match".into(),
serde_json::json!({
"type": "object",
"description": "upsert-item: the fields that identify the item, e.g. {\"name\": \"Ana\"}; it updates the one item holding them with `value`'s fields, else appends `value` as a new item"
}),
);
properties.insert(
"at".into(),
serde_json::json!({
"description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
"anyOf": [
{ "const": "end" },
{ "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
{ "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
{ "type": "integer", "minimum": 0 }
]
}),
);
}
if let Some(rich) = rich {
properties.insert("rich".into(), rich.clone());
}
serde_json::json!({
"title": dotted.join("."),
"description": if description.is_empty() {
title.to_owned()
} else {
format!("{title}; {description}")
},
"type": "object",
"properties": properties,
"required": ["path", "op"],
})
};
let item = step_schema("item", serde_json::json!({ "type": "string" }));
for field in shape
.fields()
.iter()
.filter(|field| !field.readonly || takes_own_verbs(field))
{
let mut here = steps.to_vec();
here.push(step_schema(
"field",
serde_json::json!({ "const": field.key }),
));
let path = format!("{dotted}{}", field.key);
let rich_schema = rich_schema_at(rich, &path);
let ops = field_ops(field, rich_schema.is_some());
let collection = matches!(
field.shape,
crate::Shape::Collection(_) | crate::Shape::Keyed(_)
);
let simple = ops.first() == Some(&"set") && !collection;
let value = if simple {
(field.schema)()
} else {
serde_json::json!({})
};
let mut flags = Vec::new();
if field.unit {
flags.push("its own storage unit".to_owned());
}
match field.trust {
crate::Trust::Ordinary => {}
crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
crate::Trust::Weakens(_) => flags.push(
"making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
.to_owned(),
),
crate::Trust::Weakening => flags.push(
"changing it can weaken security: it asks for confirmation and needs the person's own grant"
.to_owned(),
),
}
if collection {
flags.push(if field.quiet_remove {
"removing an item asks nothing".to_owned()
} else {
"removing an item asks nothing; Undo takes it back".to_owned()
});
}
let description = flags.join("; ");
out.push(alternative(
&here,
false,
&ops,
value,
rich_schema,
field.title,
description,
));
match field.shape {
crate::Shape::Record(_) => {
edit_paths(field.shape, &here, &format!("{path}."), rich, out);
}
crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
let mut items = here.clone();
items.push(item.clone());
let item_value = (field.schema)().get("items").map_or_else(
|| serde_json::json!({}),
|items| {
items
.get("properties")
.and_then(|properties| properties.get("value"))
.cloned()
.unwrap_or_else(|| items.clone())
},
);
let item_ops: &[&str] = match *inner {
crate::Shape::Value => &["set", "splice", "replace", "rich"],
_ => &["set"],
};
out.push(alternative(
&items,
false,
item_ops,
item_value,
None,
field.title,
"one item, by its id".to_owned(),
));
edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
}
crate::Shape::Value if field.ty.starts_with("Grid<") => {
let mut cells = here.clone();
cells.push(step_schema(
"cell",
serde_json::json!({
"type": "object",
"properties": {
"row": { "type": "string" },
"column": { "type": "string" },
},
"required": ["row", "column"],
}),
));
out.push(alternative(
&cells,
true,
&[
"set", "splice", "replace", "add", "insert", "remove", "rich",
],
serde_json::json!({}),
None,
field.title,
"a cell, by its row and column ids, and what is inside it".to_owned(),
));
}
crate::Shape::Map(_) => {
let mut entries = here.clone();
entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
if entry_rich.is_some() {
ops.push("rich");
}
out.push(alternative(
&entries,
true,
&ops,
serde_json::json!({}),
entry_rich,
field.title,
"an entry, by its key, and what is inside it".to_owned(),
));
}
crate::Shape::Value => {}
}
}
}
mod field_edit;
use field_edit::rooted_edit_spec;
pub(crate) fn field_edit_spec(
vocabulary: &'static Vocabulary,
now: Vec<(String, String)>,
) -> ActionSpec {
let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
Some(edit_schema(vocabulary))
})
.unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
rooted_edit_spec(
vocabulary,
(vocabulary.shape)(),
schema,
format!("Edit a {} field", vocabulary.label),
"The path of the field from the record's root, and the operation",
now,
)
}
fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
weakening_in(R::shape(), &|| R::state_json(state))
}
#[inline(never)]
fn weakening_in(
shape: Option<crate::Shape>,
json: &dyn Fn() -> Option<serde_json::Value>,
) -> Vec<(String, String)> {
let Some(shape) = shape else {
return Vec::new();
};
let fields: Vec<String> = shape
.guarded_fields()
.into_iter()
.filter(|(path, trust)| {
matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
})
.map(|(path, _)| path)
.collect();
if fields.is_empty() {
return Vec::new();
}
let Some(json) = json() else {
return Vec::new();
};
fields
.into_iter()
.filter_map(|path| {
let value = path
.split('.')
.try_fold(&json, |value, key| value.get(key))?
.to_string();
Some((path, value))
})
.collect()
}
#[must_use]
pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
item_field_edit_spec_of(vocabulary::<R>(), field, item)
}
pub(crate) fn item_field_edit_spec_of(
vocabulary: &'static Vocabulary,
field: &str,
item: &crate::Id,
) -> Option<ActionSpec> {
field_edit_spec_at_of(
vocabulary,
vec![
crate::Segment::Field(field.to_owned()),
crate::Segment::Item(item.clone()),
],
)
}
#[must_use]
pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
field_edit_spec_at_of(vocabulary::<R>(), prefix)
}
pub(crate) fn field_edit_spec_at_of(
vocabulary: &'static Vocabulary,
prefix: Vec<crate::Segment>,
) -> Option<ActionSpec> {
let mut shape = (vocabulary.shape)()?;
let mut dotted = String::new();
let mut readonly = false;
for segment in &prefix {
match (shape, segment) {
(crate::Shape::Record(fields), crate::Segment::Field(key)) => {
let field = fields.iter().find(|candidate| candidate.key == key)?;
readonly |= field.readonly;
shape = field.shape;
dotted.push_str(key);
dotted.push('.');
}
(
crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
crate::Segment::Item(_),
) => {
shape = *inner;
dotted.push_str("*.");
}
_ => return None,
}
}
if shape.fields().is_empty() || readonly {
return None;
}
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
}
let key = ((vocabulary.type_id)(), dotted.clone());
crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
.map(|ty| ty.bind(Target::new(prefix)))
}
fn item_edit_type(
vocabulary: &'static Vocabulary,
shape: crate::Shape,
dotted: &str,
) -> Option<Arc<ActionType>> {
let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
.into_iter()
.filter_map(|(path, schema)| {
path.strip_prefix(dotted)
.map(|rest| (rest.to_owned(), schema))
})
.collect();
let mut alternatives = Vec::new();
edit_paths(shape, &[], "", &ops, &mut alternatives);
(!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
})?;
let spec = rooted_edit_spec(
vocabulary,
Some(shape),
schema,
"Edit a field of this item".to_owned(),
"The path of the field from the item, and the operation",
Vec::new(),
);
Some(Arc::clone(spec.action_type()))
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum NoAction {}
impl tilo_actions::Action for NoAction {
fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(into = "tilo_actions::SelectionPlace")]
pub enum Place {
Item(String),
Caret { item: String, at: usize },
Range {
item: String,
start: usize,
end: usize,
},
}
impl Place {
#[must_use]
pub fn item(&self) -> &str {
match self {
Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
}
}
}
impl<'de> serde::Deserialize<'de> for Place {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
match place_from_json(value) {
Ok(place) => Ok(place),
Err(error) => Err(serde::de::Error::custom(error)),
}
}
}
fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
Ok(wire) => Place::try_from(wire),
Err(error) => Err(error.to_string()),
}
}
impl crate::JsonSchema for Place {
fn json_schema() -> serde_json::Value {
tilo_actions::place_schema()
}
}
impl From<Place> for tilo_actions::SelectionPlace {
fn from(place: Place) -> Self {
match place {
Place::Item(item) => Self::item(item),
Place::Caret { item, at } => Self::caret(item, at),
Place::Range { item, start, end } => Self::range(item, start, end),
}
}
}
impl TryFrom<tilo_actions::SelectionPlace> for Place {
type Error = String;
fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
match place.validated_span()? {
tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
item: place.item,
at,
}),
tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
item: place.item,
start,
end,
}),
}
}
}
pub type BuildAction<R> =
Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;
pub struct ActionDecl<R: Resource> {
decl: Declaration,
marker: std::marker::PhantomData<fn() -> R>,
}
impl<R: Resource> Clone for ActionDecl<R> {
fn clone(&self) -> Self {
Self {
decl: self.decl.clone(),
marker: std::marker::PhantomData,
}
}
}
impl<R: Resource> std::ops::Deref for ActionDecl<R> {
type Target = Declaration;
fn deref(&self) -> &Declaration {
&self.decl
}
}
impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
fn as_ref(&self) -> &Declaration {
&self.decl
}
}
impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
fn deref_mut(&mut self) -> &mut Declaration {
&mut self.decl
}
}
impl<R: Resource> ActionDecl<R> {
pub fn edit_asking<V>(
id: &'static str,
label: impl Into<String>,
param: &'static str,
description: &'static str,
make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
) -> Self
where
V: DeserializeOwned + crate::JsonSchema,
{
let schema = V::json_schema();
let declared = ActionParam::required_owned(
param,
crate::__private::param_type_of(&schema),
description,
)
.with_schema(schema);
let vocabulary = vocabulary::<R>();
let build: Builds = Arc::new(move |args, now_ms| {
let value = taken_arg(args, param)?;
let value: V = match serde_json::from_value(value) {
Ok(value) => value,
Err(error) => return Err(format!("`{param}`: {error}")),
};
stamped_edit(vocabulary, make(value).retyped(), now_ms)
});
Self::declared(Declaration::new(
vocabulary,
id,
label.into(),
vec![declared],
build,
))
}
pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
where
crate::Edit<R>: Send + Sync,
{
Self::declared(edit_declaration(
vocabulary::<R>(),
id,
label.into(),
edit.retyped(),
))
}
pub fn new(
id: &'static str,
label: impl Into<String>,
params: Vec<ActionParam>,
build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
) -> Self {
let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
Ok(action) => Ok(Built::of::<R>(action)),
Err(reason) => Err(reason),
});
Self::declared(Declaration::new(
vocabulary::<R>(),
id,
label.into(),
params,
build,
))
}
pub(crate) fn declared(decl: Declaration) -> Self {
Self {
decl,
marker: std::marker::PhantomData,
}
}
#[must_use]
pub fn with_arguments(
&self,
arguments: serde_json::Map<String, serde_json::Value>,
) -> crate::Invoke<R> {
crate::Invoke::bound(self.decl.id, Ok(arguments))
}
#[must_use]
pub fn into_declaration(self) -> Declaration {
self.decl
}
pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
typed::<R>(crate::content::invoking(|| {
(self.decl.build)(args, now_ms)
})?)
}
#[must_use]
pub fn refining(mut self) -> Self {
self.decl.refines = true;
self
}
#[must_use]
pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
self.decl.tags.retain(|tag| {
tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
});
if let Some(tag) = audience.tag() {
self.decl.tags.push(tag.to_owned());
}
self
}
#[must_use]
pub fn tagged(mut self, tag: impl Into<String>) -> Self {
self.decl.tag(tag.into());
self
}
#[must_use]
pub fn describe(mut self, description: impl Into<String>) -> Self {
self.decl.description = Some(description.into());
self
}
#[must_use]
pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
self.decl.result = Some(result);
self
}
#[must_use]
pub fn of_kind(mut self, kind: ActionKind) -> Self {
self.decl.kind = kind;
self
}
#[must_use]
pub fn below_field(mut self, field: &'static str) -> Self {
self.decl.field = Some(field);
self
}
#[must_use]
pub fn destructive(mut self) -> Self {
self.decl.destructive = true;
self
}
#[must_use]
pub fn writing(mut self, units: Vec<String>) -> Self {
self.decl.writes = units;
self
}
#[must_use]
pub fn answering(mut self) -> Self {
self.decl.answer();
self
}
}
impl Declaration {
fn tag(&mut self, tag: String) {
if !self.tags.contains(&tag) {
self.tags.push(tag);
}
}
fn answer(&mut self) {
self.result = Some(tilo_actions::ResultSpec::Json {
schema: serde_json::json!({"type": "object"}),
});
}
}
fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
built
.into_action::<R>()
.ok_or_else(|| format!("not an action of a {}", R::LABEL))
}
fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
match args.to_json().remove(param) {
Some(value) => Ok(value),
None => Err(format!("`{param}` is missing")),
}
}
pub(crate) fn stamped_edit(
vocabulary: &Vocabulary,
edit: Edit<()>,
now_ms: i64,
) -> Result<Built, String> {
let Some(mut action) = (vocabulary.edit)(edit) else {
return Err(format!("{} has no field edits", vocabulary.label));
};
action.stamp(now_ms);
Ok(action)
}
fn edit_declaration(
vocabulary: &'static Vocabulary,
id: &'static str,
label: String,
edit: Edit<()>,
) -> Declaration {
let destructive = (vocabulary.edit)(edit.clone())
.is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
let invokes = serde_json::to_value(&edit).ok().map(|edit| {
(
FIELD_EDIT.to_owned(),
serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
)
});
let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
decl.destructive = destructive;
decl.invokes = invokes;
decl
}
thread_local! {
static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
}
#[must_use]
pub fn origin_now_ms() -> i64 {
ORIGIN_CLOCK
.with(std::cell::Cell::get)
.unwrap_or_else(tilo_clock::unix_now_ms_i64)
}
pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
struct Restore(Option<i64>);
impl Drop for Restore {
fn drop(&mut self) {
ORIGIN_CLOCK.with(|clock| clock.set(self.0));
}
}
let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
f()
}
pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
EncodedAction::encode(R::ACTION_TYPE, action)
}
pub(crate) fn encoded(action: &Built) -> EncodedAction {
match action.encode() {
Ok(encoded) => encoded,
Err(error) => refused(&error.to_string()),
}
}
pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
match built {
Ok(action) => encoded(&action),
Err(reason) => refused(&reason),
}
}
pub fn child_by_id<R: Resource>(
state: &R::State,
doc: &Doc,
id: &str,
) -> Option<tilo_actions::ResourceSpec> {
if let Some(child) = R::child(state, id) {
return Some(child);
}
let mut fresh = R::read(doc).ok()?;
R::load(&mut fresh, doc, &child_demand(id)).ok()?;
R::child(&fresh, id)
}
#[inline(never)]
fn child_demand(id: &str) -> Demand {
let key = id.rsplit('/').next().unwrap_or(id);
Demand::none().with_keys([id, key])
}
pub(crate) fn refused(reason: &str) -> EncodedAction {
EncodedAction {
type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
payload: reason.as_bytes().to_vec(),
}
}
fn offered_bound_ids(
children: &[tilo_actions::ResourceSpec],
declarations: &[Declaration],
) -> Vec<&'static str> {
let mut ids = Vec::new();
for decl in declarations {
if crate::items::offered_bound(children, decl) {
ids.push(decl.id);
}
}
ids
}
fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
least_need_of(declarations.iter().map(|decl| decl.kind))
}
#[must_use]
pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
needs.into_iter().min().map_or_else(
|| tilo_actions::ActionContract::default().need(),
|kind| ActionNeed {
kind,
field: None,
privileged: false,
},
)
}
#[must_use]
pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
spec_of_declaration(decl.as_ref())
}
fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
let build = Arc::clone(&decl.build);
spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
}
pub(crate) fn spec_of_declaration_on(
decl: &Declaration,
build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
) -> ActionSpec {
let build = Arc::new(build);
let label = decl.shown_label();
let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
encode_built(crate::content::invoking(|| {
build(target, args, origin_now_ms())
}))
};
let spec = if let Some(prompt) = &decl.content {
let param = ActionParam::required_owned(
tilo_actions::PROMPTED_PARAM,
ParamType::Text,
prompt.clone(),
);
ActionSpec::prompted_content_on(
decl.id,
label,
prompt.clone(),
"content hash",
ExecutionLocus::ClientLocal,
move |target, hash| {
let supplied = [(
tilo_actions::PROMPTED_PARAM.to_owned(),
tilo_actions::ArgValue::Text(hash.to_owned()),
)];
match ActionArgs::bind(std::slice::from_ref(¶m), supplied) {
Ok(args) => encoded(target, &args),
Err(error) => refused(&error.to_string()),
}
},
)
} else if decl.params.is_empty() {
let domain = format!("{}#{}", decl.resource, decl.id);
let action_type = decl.action_type;
ActionSpec::deferred_on(
decl.id,
label,
ExecutionLocus::ClientLocal,
action_type,
move |target| encoded(target, &tilo_actions::ActionArgs::none()),
)
.with_continuation_identity(move |query| match query {
tilo_actions::ContinuationQuery::Draft => {
Some(tilo_actions::ContinuationEvidence::Draft {
resolution_domain: tilo_actions::ContinuationKey::new(
"verb",
[domain.as_bytes()],
),
handler: tilo_actions::ContinuationKey::new(
"action-type",
[action_type.as_bytes()],
),
})
}
tilo_actions::ContinuationQuery::Exact(_) => None,
})
} else {
ActionSpec::typed_on(
decl.id,
label.clone(),
label,
ExecutionLocus::ClientLocal,
decl.shown_params(),
encoded,
)
};
let mut spec = spec.of_kind(decl.kind);
if decl.by_arguments {
let classify = Arc::clone(&decl.build);
spec = spec.with_need_of(move |args| match classify(args, 0) {
Ok(action) => action.need(),
Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
});
}
if let Some(field) = decl.field {
spec = spec.below_field(field);
}
if let Some(description) = &decl.description {
spec = spec.with_description(description.clone());
}
if !decl.keywords.is_empty() {
spec = spec.with_keywords(decl.keywords.iter().cloned());
}
spec = with_declared_words(spec, decl);
if decl.destructive {
spec = spec.destructive();
}
let contract = &mut spec.type_mut().contract;
(contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
if let Some(result) = &decl.result {
contract.result = result.clone();
}
for tag in &decl.tags {
if !contract.tags.contains(tag) {
contract.tags.push(tag.clone());
}
}
contract.settle_confirmation();
spec
}
pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
spec.type_mut().icon.clone_from(&decl.icon);
spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
spec
}
fn declared_args(
declarations: &[Declaration],
) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
let mut args = std::collections::BTreeMap::new();
for decl in declarations {
args.insert(decl.id, crate::schema::args_schema(&decl.params));
}
args
}
pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
let param = ActionParam::required_owned(
APPLY_PARAM,
ParamType::Object,
format!("A {} action, as JSON", vocabulary.label),
);
let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
let schema = (vocabulary.action_schema)()?;
Some(crate::schema::fold_declared(
&schema,
&declared_args(&vocabulary.declarations()),
))
});
match schema {
Some(schema) => param.with_shared_schema(schema),
None => param,
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum TypeSchema {
Apply,
Group,
Edit,
}
#[derive(Default)]
struct CompiledSchemas {
epoch: u64,
entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
}
static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();
#[doc(hidden)]
pub fn reset_type_schemas() {
if let Some(cache) = SCHEMAS.get() {
let mut store = cache.lock_recover();
store.epoch = store.epoch.wrapping_add(1);
store.entries.clear();
}
}
pub(crate) fn type_epoch() -> u64 {
SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
}
pub(crate) fn words_epoch() -> u64 {
type_epoch() ^ crate::label::revision().rotate_left(32)
}
fn per_type(
vocabulary: &Vocabulary,
schema: TypeSchema,
build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
per_type_at(vocabulary, schema, "", build)
}
fn per_type_at(
vocabulary: &Vocabulary,
schema: TypeSchema,
at: &str,
build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
let cache = SCHEMAS.get_or_init(Mutex::default);
cached_schema(
cache,
((vocabulary.type_id)(), schema, at.to_owned()),
build,
)
}
fn cached_schema(
cache: &Mutex<CompiledSchemas>,
key: (TypeId, TypeSchema, String),
build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
let epoch = {
let store = cache.lock_recover();
if let Some(found) = store.entries.get(&key) {
let _phase = crate::profiling::Phase::start("schema.cached_clone");
return found.clone();
}
store.epoch
};
let value = build().map(Arc::new);
let mut store = cache.lock_recover();
if store.epoch == epoch {
store.entries.insert(key, value.clone());
}
value
}
#[must_use]
pub fn by_app_refusal(label: &str) -> String {
format!("{label} keeps this itself: it is not an action to invoke")
}
fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
let declarations = vocabulary.declarations();
let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
for decl in declarations.iter() {
ids.push(decl.id);
}
if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
&& let Some(decl) = declarations.iter().find(|decl| decl.id == id)
&& let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
{
return Err(format!("{id}: {error}"));
}
if let Some(schema) = apply_param(vocabulary).schema {
tilo_actions::validate_json_schema(&value, &schema)?;
}
let action = (vocabulary.read)(value)?;
if action.by_app() {
return Err(by_app_refusal(vocabulary.label));
}
Ok(action)
}
pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
let schema = per_type(vocabulary, TypeSchema::Group, &|| {
let declarations = vocabulary.declarations();
let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
for decl in declarations.iter() {
ids.push(decl.id);
}
Some(group_schema(&ids, vocabulary.edits))
})
.unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
ActionParam::required_owned(
crate::GROUP_PARAM,
ParamType::Array,
format!(
"{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
A member names an item an earlier member of the same group makes by its place, \
{{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
of the ids it made, which the group fills in as it applies",
vocabulary.label
),
)
.with_shared_schema(schema)
}
pub const APPLY_MEMBER: &str =
"One action value, as the `apply` action's `apply` parameter describes it";
pub const FIELD_EDIT_MEMBER: &str =
"A field edit, as the `field-edit` action's `edit` parameter describes it";
fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
let mut members = Vec::new();
if !ids.is_empty() {
members.push(describe(
object(vec![
("action", string_enum(ids), true),
(
"args",
nullable(serde_json::json!({"type": "object"})),
false,
),
]),
"A named action, args as it takes them",
));
}
let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
if edits {
members.push(describe(
object(vec![
("action", constant(FIELD_EDIT), true),
(
"args",
object(vec![(
EDIT_PARAM,
describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
true,
)]),
true,
),
]),
"A field edit",
));
}
members.push(object(vec![
("action", constant(APPLY), true),
("args", object(vec![(APPLY_PARAM, action, true)]), true),
]));
array(one_of(members))
}
fn object_arg(
args: &tilo_actions::ActionArgs,
param: &str,
) -> Option<serde_json::Map<String, serde_json::Value>> {
match args.get(param) {
Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
_ => None,
}
}
pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
let _phase = crate::profiling::Phase::start("resource.apply_spec");
let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
None => Err("missing action".to_owned()),
};
ActionSpec::typed(
APPLY,
format!("Apply {} edit", vocabulary.label),
"Action as JSON",
ExecutionLocus::ClientLocal,
vec![apply_param(vocabulary)],
move |args| match crate::content::invoking(|| read(args)) {
Ok(mut action) => {
action.stamp(origin_now_ms());
encoded(&action)
}
Err(reason) => refused(&reason),
},
)
.with_description(
"One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
)
.for_audience(tilo_actions::Audience::Agents)
.carrying()
.with_need((vocabulary.least_need)())
.of_kind((vocabulary.least_need)().kind)
.with_need_of(move |args| match read(args) {
Ok(action) => action.need(),
Err(_) => tilo_actions::ActionContract::default().need(),
})
.with_risk(move |args| {
let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
match value.map(vocabulary.read) {
Some(Ok(action)) => action.risk(),
_ => tilo_actions::RiskLevel::Low,
}
})
.with_undo_of(move |args| {
let Some(value) = object_arg(args, APPLY_PARAM) else {
return false;
};
let value = serde_json::Value::Object(value);
let declarations = vocabulary.declarations();
let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
for decl in declarations.iter() {
ids.push(decl.id);
}
let carried = crate::schema::declared_invocation(&value, &ids)
.and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
tilo_actions::undo_takes_back(
carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
tilo_actions::ChangeKind::Content,
carried.is_some_and(|decl| {
decl.tags
.iter()
.any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
}),
)
})
}
#[must_use]
pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
spec.contract.kind
}
pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
ActionNeed {
kind: R::kind_of(action),
field: R::field_of(action).map(str::to_owned),
privileged: false,
}
}
pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
let mut needs = needs.into_iter();
let Some(mut group) = needs.next() else {
return tilo_actions::ActionContract::default().need();
};
for need in needs {
group = ActionNeed {
kind: group.kind.max(need.kind),
field: group
.field
.filter(|field| need.field.as_ref() == Some(field)),
privileged: group.privileged || need.privileged,
};
}
group
}
pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
if let [only] = members {
return encoded(only);
}
let mut payload = Vec::with_capacity(128);
payload.push(b'[');
for (index, member) in members.iter().enumerate() {
if index > 0 {
payload.push(b',');
}
if let Err(error) = member.write_json(&mut payload) {
return refused(&error.to_string());
}
}
payload.push(b']');
EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
}
pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
let _phase = crate::profiling::Phase::start("resource.group_spec");
let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
crate::group::build_members(vocabulary, &args.to_json(), now_ms)
};
ActionSpec::typed(
crate::GROUP,
format!("Apply several {} edits as one", vocabulary.label),
"Invocations as JSON",
ExecutionLocus::ClientLocal,
vec![group_param(vocabulary)],
move |args| match build(args, origin_now_ms()) {
Ok(members) => encode_group(vocabulary, &members),
Err(reason) => refused(&reason),
},
)
.with_description(
"Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
)
.for_audience(tilo_actions::Audience::Agents)
.carrying()
.with_need((vocabulary.least_need)())
.with_need_of(move |args| match build(args, 0) {
Ok(members) => group_need(members.iter().map(Built::need)),
Err(_) => tilo_actions::ActionContract::default().need(),
})
.with_risk(move |args| match build(args, 0) {
Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
Err(_) => tilo_actions::RiskLevel::Low,
})
.with_undo_of(move |args| match build(args, 0) {
Ok(members) => members.iter().all(Built::undoable),
Err(_) => false,
})
}
pub use crate::search_default::default_search;
pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
publish_parts::<R>(id, label, Some(state))
}
#[must_use]
pub(crate) fn publish_actions<R: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
publish_parts::<R>(id, label, None)
}
pub fn state_from_reading<R: Resource>(
reading: &serde_json::Value,
) -> Result<R::State, ModelError> {
let table = R::RESOURCE_TABLE.ok_or_else(|| {
ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
})?;
crate::table::Run(table).from_json(reading)
}
pub(crate) fn publish_parts<R: Resource>(
id: &str,
label: &str,
state: Option<&R::State>,
) -> tilo_actions::ResourceSpec {
let vocabulary = vocabulary::<R>();
let Some(state) = state else {
let own = Own {
availability: None,
views: Vec::new(),
local_operations: R::local_operations(),
now: Vec::new(),
};
return publish_own(vocabulary, id, label, own, &|_| false);
};
let children = R::children(state);
let own = Own {
availability: Some(&|action| R::availability(state, action)),
views: R::views(state),
local_operations: R::local_operations(),
now: weakening_now::<R>(state),
};
publish_own(vocabulary, id, label, own, &|decl| {
crate::items::offered_bound(&children, decl)
})
.with_children(children)
}
pub fn unreadable_parts<R: Resource>(
id: &str,
label: &str,
reason: &str,
) -> tilo_actions::ResourceSpec {
let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
crate::unreadable::parts::<R>(id, &label, reason)
}
struct Own<'a> {
availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
views: Vec<tilo_actions::ResourceViewSpec>,
local_operations: Vec<ActionSpec>,
now: Vec<(String, String)>,
}
fn publish_own(
vocabulary: &'static Vocabulary,
id: &str,
label: &str,
own: Own<'_>,
offered_bound: &dyn Fn(&Declaration) -> bool,
) -> tilo_actions::ResourceSpec {
let _phase = crate::profiling::Phase::start("resource.published");
let label = crate::label::published(
vocabulary.kind,
label,
vocabulary.label,
vocabulary.catalogue,
);
let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
resource.app_id = Some(vocabulary.app.to_owned());
resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
let kept = own_specs(vocabulary);
for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
let _phase = crate::profiling::Phase::start("resource.declaration_spec");
let mut spec = if decl.item.is_none() && offered_bound(decl) {
declared.for_agents.clone()
} else {
declared.offered.clone()
};
if let Some(availability) = own.availability {
let now = availability(decl.id);
if spec.contract.availability != now {
spec.type_mut().contract.availability = now;
}
}
resource = resource.with_action(spec);
}
for view in own.views {
resource = resource.with_view(view);
}
crate::share::offer(&mut resource);
for spec in own.local_operations {
if spec.kind == OperationKind::Document {
continue;
}
resource = resource.with_action(spec);
}
resource = resource
.with_action(kept.apply.clone())
.with_action(kept.group.clone());
if vocabulary.edits {
resource = resource.with_action(field_edit_spec(vocabulary, own.now));
}
resource
}
struct OwnSpecs {
declared: Box<[DeclaredSpec]>,
apply: ActionSpec,
group: ActionSpec,
}
struct DeclaredSpec {
offered: ActionSpec,
for_agents: ActionSpec,
}
fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
std::cell::RefCell::default();
}
crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
let declared = vocabulary
.declarations()
.iter()
.map(|decl| {
let mut offered = spec_of_declaration(decl);
if let Some(item) = decl.item {
offered.type_mut().contract.item = Some(item.to_owned());
}
let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
DeclaredSpec {
offered,
for_agents,
}
})
.collect();
std::rc::Rc::new(OwnSpecs {
declared,
apply: apply_spec(vocabulary),
group: group_spec(vocabulary),
})
})
}
pub fn build_action<R: Resource>(
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
now_ms: i64,
) -> Result<R::Action, String> {
typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
}
pub(crate) fn build_action_of(
vocabulary: &Vocabulary,
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
now_ms: i64,
) -> Result<Built, String> {
crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
}
fn build_invoked(
vocabulary: &Vocabulary,
id: &str,
arguments: &serde_json::Map<String, serde_json::Value>,
now_ms: i64,
) -> Result<Built, String> {
if id == crate::GROUP {
return Err("a group is several actions; build it with `group::build_group`".into());
}
let read = if id == APPLY {
Some((APPLY_PARAM, "missing action"))
} else if id == FIELD_EDIT && vocabulary.edits {
Some((EDIT_PARAM, "missing edit"))
} else {
None
};
if let Some((param, missing)) = read {
let Some(value) = arguments.get(param).cloned() else {
return Err(missing.to_owned());
};
let mut action = if id == APPLY {
read_apply(vocabulary, value)?
} else {
read_edit(vocabulary, value)?
};
action.stamp(now_ms);
return Ok(action);
}
let declarations = vocabulary.declarations();
let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
return Err(format!("{} has no action `{id}`", vocabulary.label));
};
let args = match ActionArgs::bind_json(&decl.params, arguments) {
Ok(args) => args,
Err(error) => return Err(error.to_string()),
};
(decl.build)(&args, now_ms)
}
#[must_use]
pub fn bind_declaration(
resource: tilo_actions::ResourceSpec,
decl: &Declaration,
) -> tilo_actions::ResourceSpec {
let spec = spec_of_declaration(decl);
let mut resource = resource;
match resource
.actions
.iter_mut()
.find(|existing| existing.id == decl.id)
{
Some(declared) => {
if decl.refines && same_shape(&spec, declared) {
*declared = spec;
}
resource
}
None => resource.with_action(spec),
}
}
fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
let shape = |spec: &ActionSpec| {
spec.params()
.iter()
.map(|param| (param.name.to_string(), param.ty, param.required))
.collect::<Vec<_>>()
};
bound.kind == declared.kind
&& shape(bound) == shape(declared)
&& bound.contract.kind == declared.contract.kind
&& bound.contract.field == declared.contract.field
&& bound.contract.risk == declared.contract.risk
}
pub trait SharedResource: Resource {
const OWNER: &'static str;
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SearchRow {
pub subtitle: Option<String>,
pub icon: Option<String>,
pub shape: SearchRowShape,
}
impl SearchRow {
pub fn subtitle(subtitle: impl Into<String>) -> Self {
Self {
subtitle: Some(subtitle.into()),
..Self::default()
}
}
#[must_use]
pub fn shaped(shape: SearchRowShape) -> Self {
Self {
shape,
..Self::default()
}
}
#[must_use]
pub fn icon(mut self, name: impl Into<String>) -> Self {
self.icon = Some(name.into());
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum SearchRowShape {
#[default]
Plain,
Message {
sender: String,
snippet: Option<String>,
date: Option<String>,
unread: bool,
},
Media {
byline: Option<String>,
duration: Option<String>,
},
FileHit {
path: String,
line: Option<u32>,
snippet: String,
},
}
pub use tilo_actions::{ScopeDecl, scope_contains};
#[cfg(test)]
mod schema_sharing_tests;
#[cfg(test)]
mod selection_place_tests {
use super::Place;
use tilo_actions::SelectionPlace;
use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;
#[test]
fn a_selection_place_is_the_place_an_action_takes() {
for (place, expected_json) in [
(Place::Item("p1".into()), r#"{"item":"p1"}"#),
(
Place::Caret {
item: "p1".into(),
at: 3,
},
r#"{"item":"p1","at":3}"#,
),
(
Place::Range {
item: "p1".into(),
start: 2,
end: 7,
},
r#"{"item":"p1","start":2,"end":7}"#,
),
(
Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
&format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
),
] {
let wire = serde_json::to_string(&place).unwrap();
assert_eq!(wire, expected_json, "valid places serialise as before");
let selection = SelectionPlace::from(place.clone());
assert_eq!(
serde_json::to_string(&selection).unwrap(),
wire,
"both travel in one wire form"
);
assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
assert_eq!(Place::try_from(selection).unwrap(), place);
}
let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);
for bad_item in [
String::new(),
overlong_ascii,
overlong_utf8,
"p\n1".to_owned(),
"p\u{0}1".to_owned(),
"p\x1b1".to_owned(),
"p\t1".to_owned(),
] {
for selection in [
SelectionPlace::item(bad_item.clone()),
SelectionPlace::caret(bad_item.clone(), 0),
SelectionPlace::range(bad_item.clone(), 0, 1),
] {
assert!(
Place::try_from(selection.clone()).is_err(),
"Place::try_from accepted invalid SelectionPlace: {selection:?}"
);
let json = serde_json::to_value(&selection).unwrap();
assert!(
serde_json::from_value::<Place>(json.clone()).is_err(),
"Place::deserialize accepted invalid JSON: {json}"
);
}
}
for malformed in [
serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
serde_json::json!({"item": "p1", "start": 2}),
serde_json::json!({"item": "p1", "end": 2}),
serde_json::json!({"item": "p1", "start": 5, "end": 2}),
] {
let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
let from_selection = Place::try_from(wire).unwrap_err();
let from_json = serde_json::from_value::<Place>(malformed)
.unwrap_err()
.to_string();
for error in [&from_selection, &from_json] {
assert!(
error.contains("at") && error.contains("start") && error.contains("end"),
"malformed-shape error should name `at` and `start`/`end`: {error}"
);
}
}
assert!(
serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
.is_err()
);
}
}