1use std::any::TypeId;
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex, OnceLock};
8
9use serde::Serialize;
10use serde::de::DeserializeOwned;
11use tilo_actions::{
12 ActionArgs, ActionError, ActionNeed, ActionParam, ActionRegistry, ActionSpec, ActionType,
13 EncodedAction, ExecutionLocus, OperationKind, ParamType, Target,
14};
15
16use crate::action::ActionKind;
17use crate::delta::Delta;
18use crate::model::{Doc, ModelError};
19use crate::path::Edit;
20use crate::reader::Demand;
21use crate::vocabulary::{Builds, Built, Declaration, Vocabulary, vocabulary};
22use tilo_lock::MutexRecover as _;
23
24mod head;
25pub use head::{HeadInputs, head_inputs, publish_head, publish_head_of};
26
27mod search_entry;
28pub use search_entry::{SearchBody, SearchEntry, SearchPiece, SearchText, SearchWeight};
29
30pub trait Resource: Sized + 'static {
54 const KIND: &'static str;
56 const LABEL: &'static str;
60 const CATALOGUE: Option<&'static crate::label::Catalogue> = None;
64 const APP_ID: &'static str = crate::kind::DEFAULT_APP;
70 const ACTION_TYPE: &'static str = Self::KIND;
72
73 fn label() -> String {
78 crate::label::localized(Self::KIND, Self::LABEL, Self::CATALOGUE)
79 }
80
81 type State: 'static;
83 type Action: tilo_actions::Action + Serialize + DeserializeOwned + Clone + 'static;
86
87 fn read(doc: &Doc) -> Result<Self::State, ModelError>;
92
93 fn refresh(state: &mut Self::State, doc: &Doc, delta: &Delta) -> Result<(), ModelError> {
101 if !delta.is_empty() {
102 *state = Self::read(doc)?;
103 }
104 Ok(())
105 }
106
107 fn copy_state(_state: &Self::State) -> Option<Self::State> {
113 None
114 }
115
116 fn publication_cache_epoch(_state: &Self::State) -> Option<String> {
124 None
125 }
126
127 fn locate(state: &Self::State, obj: &automerge::ObjId) -> Option<crate::delta::ObjPath> {
133 let _ = (state, obj);
134 None
135 }
136
137 fn load(state: &mut Self::State, doc: &Doc, demand: &Demand) -> Result<(), ModelError> {
148 let _ = (state, doc, demand);
149 Ok(())
150 }
151
152 fn initialize(_doc: &mut Doc) -> Result<(), ModelError> {
165 Ok(())
166 }
167
168 fn coalesces(previous: &Self::Action, next: &Self::Action) -> bool {
180 let _ = (previous, next);
181 false
182 }
183
184 fn continuable(action: &Self::Action) -> bool {
190 let _ = action;
191 true
192 }
193
194 fn lands(state: &Self::State, action: &Self::Action) -> Option<Place> {
200 let _ = (state, action);
201 None
202 }
203
204 fn lands_on_state(action: &Self::Action) -> bool {
209 let _ = action;
210 true
211 }
212
213 fn field_of(action: &Self::Action) -> Option<&'static str> {
219 let _ = action;
220 None
221 }
222
223 fn least_need() -> ActionNeed {
230 least_need_declared(&vocabulary::<Self>().declarations())
231 }
232
233 fn declarations() -> Vec<ActionDecl<Self>> {
236 Vec::new()
237 }
238
239 fn action_schema() -> Option<serde_json::Value> {
248 None
249 }
250
251 fn children(_state: &Self::State) -> Vec<tilo_actions::ResourceSpec> {
256 Vec::new()
257 }
258
259 fn item_effects(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ActionSpec> {
263 Vec::new()
264 }
265
266 fn item_views(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ResourceViewSpec> {
271 Vec::new()
272 }
273
274 fn children_parts(state: &Self::State) -> crate::items::ChildrenParts {
282 crate::items::ChildrenParts {
283 others: Self::children(state),
284 kept: std::rc::Rc::default(),
285 items: Vec::new(),
286 item_actions: Vec::new(),
287 }
288 }
289
290 fn children_offer_bound(state: &Self::State) -> Vec<&'static str> {
301 offered_bound_ids(&Self::children(state), &vocabulary::<Self>().declarations())
302 }
303
304 fn child(_state: &Self::State, _id: &str) -> Option<tilo_actions::ResourceSpec> {
311 None
312 }
313
314 fn local_operations() -> Vec<tilo_actions::ActionSpec> {
322 Vec::new()
323 }
324
325 fn views(_state: &Self::State) -> Vec<tilo_actions::ResourceViewSpec> {
329 Vec::new()
330 }
331
332 fn search_scopes(_state: &Self::State) -> Vec<ScopeDecl> {
334 Vec::new()
335 }
336
337 fn search(_state: &Self::State) -> Vec<SearchEntry> {
338 Vec::new()
339 }
340
341 const READABLE: bool = false;
347
348 fn document_child(_state: &Self::State, _id: &str) -> bool {
354 false
355 }
356
357 fn read_content(
364 state: &Self::State,
365 doc: &Doc,
366 item: Option<&str>,
367 ) -> Result<serde_json::Value, String> {
368 let _ = (state, doc, item);
369 Err(format!("a {} does not answer reads", Self::LABEL))
370 }
371
372 const HAS_FACTS: bool = false;
376
377 const RESOURCE_TABLE: Option<&'static crate::table::ModelTable> = None;
383
384 fn facts(state: &Self::State, doc: &Doc) -> Result<serde_json::Value, String> {
392 let _ = (state, doc);
393 Err(format!("a {} states no facts", Self::LABEL))
394 }
395
396 const ANSWERS: bool = false;
401
402 fn answer(
408 _doc: &Doc,
409 _action: &str,
410 _changes: &[automerge::Patch],
411 ) -> Option<serde_json::Value> {
412 None
413 }
414
415 fn shape() -> Option<crate::Shape> {
420 None
421 }
422
423 fn state_json(state: &Self::State) -> Option<serde_json::Value> {
428 let _ = state;
429 None
430 }
431
432 const VERSION: u32 = 1;
436
437 const READERS: &'static str = "";
442
443 fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
447 let _ = doc;
448 Err(ModelError::invalid(format!(
449 "{} has no migration from storage version {from}",
450 Self::LABEL
451 )))
452 }
453
454 #[must_use]
457 fn surface() -> crate::surface::Surface {
458 crate::surface::surface_of::<Self>()
459 }
460
461 const EDITS: bool = false;
464
465 fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
468 let _ = edit;
469 None
470 }
471
472 fn stamp(action: &mut Self::Action, now_ms: i64) {
475 let _ = (action, now_ms);
476 }
477
478 fn op_schemas() -> Vec<(String, serde_json::Value)> {
482 Vec::new()
483 }
484
485 fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
488 let _ = (state, action);
489 tilo_actions::Availability::Available
490 }
491
492 fn seed() -> Option<Self::Action> {
495 None
496 }
497
498 fn kind_of(action: &Self::Action) -> ActionKind {
502 let _ = action;
503 ActionKind::Undoable
504 }
505
506 fn by_app(action: &Self::Action) -> bool {
513 let _ = action;
514 false
515 }
516
517 fn build_by_app(
522 id: &str,
523 arguments: &serde_json::Map<String, serde_json::Value>,
524 now_ms: i64,
525 ) -> Option<Result<Self::Action, String>> {
526 let _ = (id, arguments, now_ms);
527 None
528 }
529
530 fn action_item(action: &Self::Action) -> Option<crate::Id> {
535 let _ = action;
536 None
537 }
538
539 fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
544 let _ = action;
545 None
546 }
547
548 fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
552 let _ = (action, keep);
553 None
554 }
555
556 fn register(registry: &mut ActionRegistry) {
559 registry.register::<Self::Action>(Self::ACTION_TYPE);
560 }
561}
562
563pub trait NamesItem: Clone {
566 fn named_item(&self) -> Option<crate::Id>;
567}
568
569impl NamesItem for crate::Id {
570 fn named_item(&self) -> Option<crate::Id> {
571 Some(self.clone())
572 }
573}
574
575impl NamesItem for String {
576 fn named_item(&self) -> Option<crate::Id> {
577 Some(crate::Id::from_raw(self.clone()))
578 }
579}
580
581#[doc(hidden)]
583pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
584 entries.iter().map(NamesItem::named_item).collect()
585}
586
587#[doc(hidden)]
589#[must_use]
590pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
591 keep.iter()
592 .filter_map(|at| entries.get(*at).cloned())
593 .collect()
594}
595
596pub const APPLY: &str = "apply";
608pub const APPLY_PARAM: &str = "action";
610
611pub const FIELD_EDIT: &str = "field-edit";
614pub const EDIT_PARAM: &str = "edit";
616
617fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
619 let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
620 match (vocabulary.edit)(edit) {
621 Some(action) => Ok(action),
622 None => Err(format!("{} has no field edits", vocabulary.label)),
623 }
624}
625
626pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
632 let ops = (vocabulary.op_schemas)();
633 if let Some(shape) = (vocabulary.shape)()
634 && !shape.fields().is_empty()
635 {
636 let mut alternatives = Vec::new();
637 edit_paths(shape, &[], "", &ops, &mut alternatives);
638 if !alternatives.is_empty() {
639 return described_edit(&alternatives, &ops);
640 }
641 }
642 generic_edit_schema(&ops, |_| true)
643}
644
645fn described_edit(
650 alternatives: &[serde_json::Value],
651 ops: &[(String, serde_json::Value)],
652) -> serde_json::Value {
653 let taken: Vec<String> = alternatives
656 .iter()
657 .filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
658 .flatten()
659 .filter_map(serde_json::Value::as_str)
660 .map(str::to_owned)
661 .collect();
662 let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
663 let mut lines = vec![
664 "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(),
665 ];
666 let mut examples = Vec::new();
667 let mut shapes: Vec<Vec<String>> = Vec::new();
668 let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
671 let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
672 for (alternative, next) in alternatives.iter().zip(nexts) {
673 let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
674 let template = at("/properties/path/examples/0");
675 let ops: Vec<String> = at("/properties/op/enum")
676 .as_array()
677 .map(|ops| {
678 ops.iter()
679 .filter_map(serde_json::Value::as_str)
680 .map(str::to_owned)
681 .collect()
682 })
683 .unwrap_or_default();
684 let value = at("/properties/value");
685 let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
686 let title = text("/title");
687 let shape: Vec<String> = template
690 .as_array()
691 .map(|steps| {
692 steps
693 .iter()
694 .filter_map(|step| step.as_object()?.keys().next().cloned())
695 .collect()
696 })
697 .unwrap_or_default();
698 let leaf = next.is_none_or(|next| {
703 next.get("title")
704 .and_then(serde_json::Value::as_str)
705 .is_none_or(|next| !next.starts_with(&format!("{title}.")))
706 });
707 let in_resource = shape
708 .iter()
709 .rev()
710 .take(2)
711 .filter(|kind| *kind == "field")
712 .count()
713 == 2;
714 let record = title
715 .rsplit_once('.')
716 .and_then(|(parent, key)| {
717 listed
718 .iter_mut()
719 .find(|(path, ..)| path == parent)
720 .map(|(_, _, fields)| (fields, key))
721 })
722 .filter(|_| in_resource && leaf && ops == ["set"]);
723 if let Some((fields, key)) = record {
724 fields.push(format!("`{key}`"));
725 } else {
726 let kind = value_kind(&value);
727 let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
728 let line = format!(
729 "- `{title}`: {} — {}{}",
730 usage.join(", "),
731 text("/description"),
732 kind.map_or_else(String::new, |kind| format!(" ({kind})")),
733 );
734 listed.push((title.clone(), line, Vec::new()));
735 }
736 if shapes.contains(&shape) {
737 continue;
738 }
739 shapes.push(shape);
740 let mut example = serde_json::Map::new();
741 example.insert("path".into(), template);
742 if let Some(op) = ops.first() {
743 example.insert("op".into(), op.clone().into());
744 }
745 examples.push(serde_json::Value::Object(example));
746 }
747 lines.extend(listed.into_iter().map(|(_, line, fields)| {
748 if fields.is_empty() {
749 line
750 } else {
751 format!("{line}; set one field of it: {}", fields.join(", "))
752 }
753 }));
754 if let Some(object) = schema.as_object_mut() {
755 object.insert("description".into(), lines.join("\n").into());
756 object.insert("examples".into(), examples.into());
757 }
758 schema
759}
760
761fn value_kind(schema: &serde_json::Value) -> Option<String> {
766 if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
767 let options: Vec<String> = options
768 .iter()
769 .map(|option| {
770 option
771 .as_str()
772 .map_or_else(|| option.to_string(), str::to_owned)
773 })
774 .collect();
775 return Some(format!("one of {}", options.join(", ")));
776 }
777 match schema.get("type")? {
778 serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
779 serde_json::Value::Array(kinds) => Some(
780 kinds
781 .iter()
782 .filter_map(serde_json::Value::as_str)
783 .collect::<Vec<_>>()
784 .join(" or "),
785 ),
786 _ => None,
787 }
788}
789
790fn generic_edit_schema(
793 ops: &[(String, serde_json::Value)],
794 takes: impl Fn(&str) -> bool,
795) -> serde_json::Value {
796 let ops = ops.to_vec();
797 let mut schema = crate::path::edit_schema_taking(&takes);
798 if !ops.is_empty()
799 && takes("rich")
800 && let Some(properties) = schema
801 .get_mut("properties")
802 .and_then(serde_json::Value::as_object_mut)
803 {
804 let description = ops
810 .into_iter()
811 .map(|(path, schema)| {
812 format!(
813 "An edit of `{path}` in its own vocabulary, one of: {}",
814 crate::schema::summary(&schema)
815 )
816 })
817 .collect::<Vec<_>>()
818 .join("\n");
819 properties.insert(
820 "rich".into(),
821 crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
822 );
823 }
824 schema
825}
826
827fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
828 let mut properties = serde_json::Map::new();
829 properties.insert(kind.to_owned(), value);
830 serde_json::json!({
831 "type": "object",
832 "properties": properties,
833 "required": [kind],
834 })
835}
836
837fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
840 let ty = field.ty;
841 if ty.rsplit("::").next() == Some("Reactions") {
843 return vec!["react", "unreact"];
844 }
845 match field.shape {
846 crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
847 vec![
848 "upsert-item",
849 "insert-item",
850 "remove-item",
851 "move-to",
852 "set",
853 ]
854 }
855 _ if rich => vec!["replace", "rich"],
858 _ if ty.starts_with("Counter") => vec!["add", "set"],
859 _ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
860 _ if ty.starts_with("Grid<") => vec![
861 "set-cell",
862 "insert-row",
863 "insert-column",
864 "remove-row",
865 "remove-column",
866 ],
867 _ if ty.starts_with("Outbox") => vec!["settle", "forget"],
868 crate::Shape::Map(_) => vec!["set", "remove-key"],
869 _ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
870 _ => vec!["set"],
871 }
872}
873
874fn takes_own_verbs(field: &crate::FieldShape) -> bool {
878 let ops = field_ops(field, false);
879 ops.iter()
880 .any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
881}
882
883fn rich_schema_at<'a>(
886 rich: &'a [(String, serde_json::Value)],
887 at: &str,
888) -> Option<&'a serde_json::Value> {
889 rich.iter()
890 .find(|(path, _)| path == at)
891 .map(|(_, schema)| schema)
892}
893
894#[allow(
895 clippy::too_many_lines,
896 reason = "one walk over the stored shape, an alternative per kind of path"
897)]
898fn edit_paths(
899 shape: crate::Shape,
900 steps: &[serde_json::Value],
901 dotted: &str,
902 rich: &[(String, serde_json::Value)],
903 out: &mut Vec<serde_json::Value>,
904) {
905 let alternative = |steps: &[serde_json::Value],
906 open: bool,
907 ops: &[&str],
908 value: serde_json::Value,
909 rich: Option<&serde_json::Value>,
910 title: &str,
911 description: String| {
912 let template: Vec<serde_json::Value> = steps
914 .iter()
915 .map(|step| {
916 let properties = step.get("properties").and_then(serde_json::Value::as_object);
917 match properties.and_then(|properties| properties.iter().next()) {
918 Some((kind, value)) if kind == "field" => {
919 serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
920 }
921 Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
922 None => serde_json::Value::Null,
923 }
924 })
925 .collect();
926 let dotted: Vec<String> = template
927 .iter()
928 .map(
929 |step| match step.get("field").and_then(serde_json::Value::as_str) {
930 Some(field) => field.to_owned(),
931 None => "*".to_owned(),
932 },
933 )
934 .collect();
935 let mut path = serde_json::json!({
936 "type": "array",
937 "prefixItems": steps,
938 "minItems": steps.len(),
939 "examples": [template],
940 });
941 if let Some(path) = path.as_object_mut() {
942 if open {
943 path.insert("items".into(), serde_json::json!({ "type": "object" }));
945 } else {
946 path.insert("maxItems".into(), steps.len().into());
947 }
948 }
949 let mut properties = serde_json::Map::new();
950 properties.insert("path".into(), path);
951 properties.insert("op".into(), serde_json::json!({ "enum": ops }));
952 properties.insert("value".into(), value);
953 if ops.contains(&"upsert-item") {
954 properties.insert(
955 "match".into(),
956 serde_json::json!({
957 "type": "object",
958 "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"
959 }),
960 );
961 properties.insert(
962 "at".into(),
963 serde_json::json!({
964 "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
965 "anyOf": [
966 { "const": "end" },
967 { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
968 { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
969 { "type": "integer", "minimum": 0 }
970 ]
971 }),
972 );
973 }
974 if let Some(rich) = rich {
975 properties.insert("rich".into(), rich.clone());
976 }
977 serde_json::json!({
978 "title": dotted.join("."),
979 "description": if description.is_empty() {
980 title.to_owned()
981 } else {
982 format!("{title}; {description}")
983 },
984 "type": "object",
985 "properties": properties,
986 "required": ["path", "op"],
987 })
988 };
989 let item = step_schema("item", serde_json::json!({ "type": "string" }));
990 for field in shape
994 .fields()
995 .iter()
996 .filter(|field| !field.readonly || takes_own_verbs(field))
997 {
998 let mut here = steps.to_vec();
999 here.push(step_schema(
1000 "field",
1001 serde_json::json!({ "const": field.key }),
1002 ));
1003 let path = format!("{dotted}{}", field.key);
1004 let rich_schema = rich_schema_at(rich, &path);
1005 let ops = field_ops(field, rich_schema.is_some());
1006 let collection = matches!(
1007 field.shape,
1008 crate::Shape::Collection(_) | crate::Shape::Keyed(_)
1009 );
1010 let simple = ops.first() == Some(&"set") && !collection;
1013 let value = if simple {
1014 (field.schema)()
1015 } else {
1016 serde_json::json!({})
1017 };
1018 let mut flags = Vec::new();
1019 if field.unit {
1020 flags.push("its own storage unit".to_owned());
1021 }
1022 match field.trust {
1023 crate::Trust::Ordinary => {}
1024 crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
1025 crate::Trust::Weakens(_) => flags.push(
1026 "making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
1027 .to_owned(),
1028 ),
1029 crate::Trust::Weakening => flags.push(
1030 "changing it can weaken security: it asks for confirmation and needs the person's own grant"
1031 .to_owned(),
1032 ),
1033 }
1034 if collection {
1035 flags.push(if field.quiet_remove {
1038 "removing an item asks nothing".to_owned()
1039 } else {
1040 "removing an item asks nothing; Undo takes it back".to_owned()
1041 });
1042 }
1043 let description = flags.join("; ");
1044 out.push(alternative(
1045 &here,
1046 false,
1047 &ops,
1048 value,
1049 rich_schema,
1050 field.title,
1051 description,
1052 ));
1053 match field.shape {
1054 crate::Shape::Record(_) => {
1055 edit_paths(field.shape, &here, &format!("{path}."), rich, out);
1056 }
1057 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
1058 let mut items = here.clone();
1059 items.push(item.clone());
1060 let item_value = (field.schema)().get("items").map_or_else(
1061 || serde_json::json!({}),
1062 |items| {
1063 items
1065 .get("properties")
1066 .and_then(|properties| properties.get("value"))
1067 .cloned()
1068 .unwrap_or_else(|| items.clone())
1069 },
1070 );
1071 let item_ops: &[&str] = match *inner {
1074 crate::Shape::Value => &["set", "splice", "replace", "rich"],
1075 _ => &["set"],
1076 };
1077 out.push(alternative(
1078 &items,
1079 false,
1080 item_ops,
1081 item_value,
1082 None,
1083 field.title,
1084 "one item, by its id".to_owned(),
1085 ));
1086 edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
1087 }
1088 crate::Shape::Value if field.ty.starts_with("Grid<") => {
1089 let mut cells = here.clone();
1090 cells.push(step_schema(
1091 "cell",
1092 serde_json::json!({
1093 "type": "object",
1094 "properties": {
1095 "row": { "type": "string" },
1096 "column": { "type": "string" },
1097 },
1098 "required": ["row", "column"],
1099 }),
1100 ));
1101 out.push(alternative(
1102 &cells,
1103 true,
1104 &[
1105 "set", "splice", "replace", "add", "insert", "remove", "rich",
1106 ],
1107 serde_json::json!({}),
1108 None,
1109 field.title,
1110 "a cell, by its row and column ids, and what is inside it".to_owned(),
1111 ));
1112 }
1113 crate::Shape::Map(_) => {
1114 let mut entries = here.clone();
1115 entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
1116 let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
1118 let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
1119 if entry_rich.is_some() {
1120 ops.push("rich");
1121 }
1122 out.push(alternative(
1123 &entries,
1124 true,
1125 &ops,
1126 serde_json::json!({}),
1127 entry_rich,
1128 field.title,
1129 "an entry, by its key, and what is inside it".to_owned(),
1130 ));
1131 }
1132 crate::Shape::Value => {}
1133 }
1134 }
1135}
1136
1137mod field_edit;
1138use field_edit::rooted_edit_spec;
1139
1140pub(crate) fn field_edit_spec(
1143 vocabulary: &'static Vocabulary,
1144 now: Vec<(String, String)>,
1145) -> ActionSpec {
1146 let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
1149 Some(edit_schema(vocabulary))
1150 })
1151 .unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
1152 rooted_edit_spec(
1153 vocabulary,
1154 (vocabulary.shape)(),
1155 schema,
1156 format!("Edit a {} field", vocabulary.label),
1157 "The path of the field from the record's root, and the operation",
1158 now,
1159 )
1160}
1161
1162fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
1166 weakening_in(R::shape(), &|| R::state_json(state))
1167}
1168
1169#[inline(never)]
1173fn weakening_in(
1174 shape: Option<crate::Shape>,
1175 json: &dyn Fn() -> Option<serde_json::Value>,
1176) -> Vec<(String, String)> {
1177 let Some(shape) = shape else {
1178 return Vec::new();
1179 };
1180 let fields: Vec<String> = shape
1181 .guarded_fields()
1182 .into_iter()
1183 .filter(|(path, trust)| {
1184 matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
1185 })
1186 .map(|(path, _)| path)
1187 .collect();
1188 if fields.is_empty() {
1189 return Vec::new();
1190 }
1191 let Some(json) = json() else {
1192 return Vec::new();
1193 };
1194 fields
1195 .into_iter()
1196 .filter_map(|path| {
1197 let value = path
1198 .split('.')
1199 .try_fold(&json, |value, key| value.get(key))?
1200 .to_string();
1201 Some((path, value))
1202 })
1203 .collect()
1204}
1205
1206#[must_use]
1209pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
1210 item_field_edit_spec_of(vocabulary::<R>(), field, item)
1211}
1212
1213pub(crate) fn item_field_edit_spec_of(
1215 vocabulary: &'static Vocabulary,
1216 field: &str,
1217 item: &crate::Id,
1218) -> Option<ActionSpec> {
1219 field_edit_spec_at_of(
1220 vocabulary,
1221 vec![
1222 crate::Segment::Field(field.to_owned()),
1223 crate::Segment::Item(item.clone()),
1224 ],
1225 )
1226}
1227
1228#[must_use]
1232pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
1233 field_edit_spec_at_of(vocabulary::<R>(), prefix)
1234}
1235
1236pub(crate) fn field_edit_spec_at_of(
1238 vocabulary: &'static Vocabulary,
1239 prefix: Vec<crate::Segment>,
1240) -> Option<ActionSpec> {
1241 let mut shape = (vocabulary.shape)()?;
1242 let mut dotted = String::new();
1243 let mut readonly = false;
1244 for segment in &prefix {
1245 match (shape, segment) {
1246 (crate::Shape::Record(fields), crate::Segment::Field(key)) => {
1247 let field = fields.iter().find(|candidate| candidate.key == key)?;
1248 readonly |= field.readonly;
1249 shape = field.shape;
1250 dotted.push_str(key);
1251 dotted.push('.');
1252 }
1253 (
1254 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
1255 crate::Segment::Item(_),
1256 ) => {
1257 shape = *inner;
1258 dotted.push_str("*.");
1259 }
1260 _ => return None,
1261 }
1262 }
1263 if shape.fields().is_empty() || readonly {
1264 return None;
1265 }
1266 thread_local! {
1269 static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
1270 }
1271 let key = ((vocabulary.type_id)(), dotted.clone());
1272 crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
1273 .map(|ty| ty.bind(Target::new(prefix)))
1274}
1275
1276fn item_edit_type(
1279 vocabulary: &'static Vocabulary,
1280 shape: crate::Shape,
1281 dotted: &str,
1282) -> Option<Arc<ActionType>> {
1283 let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
1284 let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
1285 .into_iter()
1286 .filter_map(|(path, schema)| {
1287 path.strip_prefix(dotted)
1288 .map(|rest| (rest.to_owned(), schema))
1289 })
1290 .collect();
1291 let mut alternatives = Vec::new();
1292 edit_paths(shape, &[], "", &ops, &mut alternatives);
1293 (!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
1294 })?;
1295 let spec = rooted_edit_spec(
1296 vocabulary,
1297 Some(shape),
1298 schema,
1299 "Edit a field of this item".to_owned(),
1300 "The path of the field from the item, and the operation",
1301 Vec::new(),
1302 );
1303 Some(Arc::clone(spec.action_type()))
1304}
1305
1306#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
1312pub enum NoAction {}
1313
1314impl tilo_actions::Action for NoAction {
1315 fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
1317 Ok(())
1318 }
1319}
1320
1321#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1328#[serde(into = "tilo_actions::SelectionPlace")]
1329pub enum Place {
1330 Item(String),
1332 Caret { item: String, at: usize },
1334 Range {
1336 item: String,
1337 start: usize,
1338 end: usize,
1339 },
1340}
1341
1342impl Place {
1343 #[must_use]
1345 pub fn item(&self) -> &str {
1346 match self {
1347 Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
1348 }
1349 }
1350}
1351
1352impl<'de> serde::Deserialize<'de> for Place {
1360 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1361 let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
1362 match place_from_json(value) {
1363 Ok(place) => Ok(place),
1364 Err(error) => Err(serde::de::Error::custom(error)),
1365 }
1366 }
1367}
1368
1369fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
1371 match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
1372 Ok(wire) => Place::try_from(wire),
1373 Err(error) => Err(error.to_string()),
1374 }
1375}
1376
1377impl crate::JsonSchema for Place {
1378 fn json_schema() -> serde_json::Value {
1379 tilo_actions::place_schema()
1380 }
1381}
1382
1383impl From<Place> for tilo_actions::SelectionPlace {
1386 fn from(place: Place) -> Self {
1387 match place {
1388 Place::Item(item) => Self::item(item),
1389 Place::Caret { item, at } => Self::caret(item, at),
1390 Place::Range { item, start, end } => Self::range(item, start, end),
1391 }
1392 }
1393}
1394
1395impl TryFrom<tilo_actions::SelectionPlace> for Place {
1396 type Error = String;
1397
1398 fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
1399 match place.validated_span()? {
1400 tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
1401 tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
1402 item: place.item,
1403 at,
1404 }),
1405 tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
1406 item: place.item,
1407 start,
1408 end,
1409 }),
1410 }
1411 }
1412}
1413
1414pub type BuildAction<R> =
1418 Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;
1419
1420pub struct ActionDecl<R: Resource> {
1423 decl: Declaration,
1424 marker: std::marker::PhantomData<fn() -> R>,
1425}
1426
1427impl<R: Resource> Clone for ActionDecl<R> {
1428 fn clone(&self) -> Self {
1429 Self {
1430 decl: self.decl.clone(),
1431 marker: std::marker::PhantomData,
1432 }
1433 }
1434}
1435
1436impl<R: Resource> std::ops::Deref for ActionDecl<R> {
1437 type Target = Declaration;
1438
1439 fn deref(&self) -> &Declaration {
1440 &self.decl
1441 }
1442}
1443
1444impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
1445 fn as_ref(&self) -> &Declaration {
1446 &self.decl
1447 }
1448}
1449
1450impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
1451 fn deref_mut(&mut self) -> &mut Declaration {
1452 &mut self.decl
1453 }
1454}
1455
1456impl<R: Resource> ActionDecl<R> {
1457 pub fn edit_asking<V>(
1463 id: &'static str,
1464 label: impl Into<String>,
1465 param: &'static str,
1466 description: &'static str,
1467 make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
1468 ) -> Self
1469 where
1470 V: DeserializeOwned + crate::JsonSchema,
1471 {
1472 let schema = V::json_schema();
1473 let declared = ActionParam::required_owned(
1474 param,
1475 crate::__private::param_type_of(&schema),
1476 description,
1477 )
1478 .with_schema(schema);
1479 let vocabulary = vocabulary::<R>();
1480 let build: Builds = Arc::new(move |args, now_ms| {
1481 let value = taken_arg(args, param)?;
1482 let value: V = match serde_json::from_value(value) {
1483 Ok(value) => value,
1484 Err(error) => return Err(format!("`{param}`: {error}")),
1485 };
1486 stamped_edit(vocabulary, make(value).retyped(), now_ms)
1487 });
1488 Self::declared(Declaration::new(
1489 vocabulary,
1490 id,
1491 label.into(),
1492 vec![declared],
1493 build,
1494 ))
1495 }
1496
1497 pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
1501 where
1502 crate::Edit<R>: Send + Sync,
1503 {
1504 Self::declared(edit_declaration(
1505 vocabulary::<R>(),
1506 id,
1507 label.into(),
1508 edit.retyped(),
1509 ))
1510 }
1511
1512 pub fn new(
1513 id: &'static str,
1514 label: impl Into<String>,
1515 params: Vec<ActionParam>,
1516 build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
1517 ) -> Self {
1518 let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
1519 Ok(action) => Ok(Built::of::<R>(action)),
1520 Err(reason) => Err(reason),
1521 });
1522 Self::declared(Declaration::new(
1523 vocabulary::<R>(),
1524 id,
1525 label.into(),
1526 params,
1527 build,
1528 ))
1529 }
1530
1531 pub(crate) fn declared(decl: Declaration) -> Self {
1532 Self {
1533 decl,
1534 marker: std::marker::PhantomData,
1535 }
1536 }
1537
1538 #[must_use]
1541 pub fn with_arguments(
1542 &self,
1543 arguments: serde_json::Map<String, serde_json::Value>,
1544 ) -> crate::Invoke<R> {
1545 crate::Invoke::bound(self.decl.id, Ok(arguments))
1546 }
1547
1548 #[must_use]
1550 pub fn into_declaration(self) -> Declaration {
1551 self.decl
1552 }
1553
1554 pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
1556 typed::<R>(crate::content::invoking(|| {
1557 (self.decl.build)(args, now_ms)
1558 })?)
1559 }
1560
1561 #[must_use]
1564 pub fn refining(mut self) -> Self {
1565 self.decl.refines = true;
1566 self
1567 }
1568
1569 #[must_use]
1574 pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
1575 self.decl.tags.retain(|tag| {
1576 tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
1577 });
1578 if let Some(tag) = audience.tag() {
1579 self.decl.tags.push(tag.to_owned());
1580 }
1581 self
1582 }
1583
1584 #[must_use]
1587 pub fn tagged(mut self, tag: impl Into<String>) -> Self {
1588 self.decl.tag(tag.into());
1589 self
1590 }
1591
1592 #[must_use]
1593 pub fn describe(mut self, description: impl Into<String>) -> Self {
1594 self.decl.description = Some(description.into());
1595 self
1596 }
1597
1598 #[must_use]
1601 pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
1602 self.decl.result = Some(result);
1603 self
1604 }
1605
1606 #[must_use]
1608 pub fn of_kind(mut self, kind: ActionKind) -> Self {
1609 self.decl.kind = kind;
1610 self
1611 }
1612
1613 #[must_use]
1615 pub fn below_field(mut self, field: &'static str) -> Self {
1616 self.decl.field = Some(field);
1617 self
1618 }
1619
1620 #[must_use]
1621 pub fn destructive(mut self) -> Self {
1622 self.decl.destructive = true;
1623 self
1624 }
1625
1626 #[must_use]
1629 pub fn writing(mut self, units: Vec<String>) -> Self {
1630 self.decl.writes = units;
1631 self
1632 }
1633
1634 #[must_use]
1637 pub fn answering(mut self) -> Self {
1638 self.decl.answer();
1639 self
1640 }
1641}
1642
1643impl Declaration {
1644 fn tag(&mut self, tag: String) {
1645 if !self.tags.contains(&tag) {
1646 self.tags.push(tag);
1647 }
1648 }
1649
1650 fn answer(&mut self) {
1651 self.result = Some(tilo_actions::ResultSpec::Json {
1652 schema: serde_json::json!({"type": "object"}),
1653 });
1654 }
1655}
1656
1657fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
1659 built
1660 .into_action::<R>()
1661 .ok_or_else(|| format!("not an action of a {}", R::LABEL))
1662}
1663
1664fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
1666 match args.to_json().remove(param) {
1667 Some(value) => Ok(value),
1668 None => Err(format!("`{param}` is missing")),
1669 }
1670}
1671
1672pub(crate) fn stamped_edit(
1675 vocabulary: &Vocabulary,
1676 edit: Edit<()>,
1677 now_ms: i64,
1678) -> Result<Built, String> {
1679 let Some(mut action) = (vocabulary.edit)(edit) else {
1680 return Err(format!("{} has no field edits", vocabulary.label));
1681 };
1682 action.stamp(now_ms);
1683 Ok(action)
1684}
1685
1686fn edit_declaration(
1688 vocabulary: &'static Vocabulary,
1689 id: &'static str,
1690 label: String,
1691 edit: Edit<()>,
1692) -> Declaration {
1693 let destructive = (vocabulary.edit)(edit.clone())
1694 .is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
1695 let invokes = serde_json::to_value(&edit).ok().map(|edit| {
1696 (
1697 FIELD_EDIT.to_owned(),
1698 serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
1699 )
1700 });
1701 let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
1702 let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
1703 decl.destructive = destructive;
1704 decl.invokes = invokes;
1705 decl
1706}
1707
1708thread_local! {
1709 static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
1712}
1713
1714#[must_use]
1718pub fn origin_now_ms() -> i64 {
1719 ORIGIN_CLOCK
1720 .with(std::cell::Cell::get)
1721 .unwrap_or_else(tilo_clock::unix_now_ms_i64)
1722}
1723
1724pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
1729 struct Restore(Option<i64>);
1730 impl Drop for Restore {
1731 fn drop(&mut self) {
1732 ORIGIN_CLOCK.with(|clock| clock.set(self.0));
1733 }
1734 }
1735 let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
1736 f()
1737}
1738
1739pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
1744 EncodedAction::encode(R::ACTION_TYPE, action)
1745}
1746
1747pub(crate) fn encoded(action: &Built) -> EncodedAction {
1750 match action.encode() {
1751 Ok(encoded) => encoded,
1752 Err(error) => refused(&error.to_string()),
1753 }
1754}
1755
1756pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
1759 match built {
1760 Ok(action) => encoded(&action),
1761 Err(reason) => refused(&reason),
1762 }
1763}
1764
1765pub fn child_by_id<R: Resource>(
1769 state: &R::State,
1770 doc: &Doc,
1771 id: &str,
1772) -> Option<tilo_actions::ResourceSpec> {
1773 if let Some(child) = R::child(state, id) {
1774 return Some(child);
1775 }
1776 let mut fresh = R::read(doc).ok()?;
1777 R::load(&mut fresh, doc, &child_demand(id)).ok()?;
1778 R::child(&fresh, id)
1779}
1780
1781#[inline(never)]
1784fn child_demand(id: &str) -> Demand {
1785 let key = id.rsplit('/').next().unwrap_or(id);
1788 Demand::none().with_keys([id, key])
1789}
1790
1791pub(crate) fn refused(reason: &str) -> EncodedAction {
1794 EncodedAction {
1795 type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
1796 payload: reason.as_bytes().to_vec(),
1797 }
1798}
1799
1800fn offered_bound_ids(
1802 children: &[tilo_actions::ResourceSpec],
1803 declarations: &[Declaration],
1804) -> Vec<&'static str> {
1805 let mut ids = Vec::new();
1806 for decl in declarations {
1807 if crate::items::offered_bound(children, decl) {
1808 ids.push(decl.id);
1809 }
1810 }
1811 ids
1812}
1813
1814fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
1816 least_need_of(declarations.iter().map(|decl| decl.kind))
1817}
1818
1819#[must_use]
1830pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
1831 needs.into_iter().min().map_or_else(
1832 || tilo_actions::ActionContract::default().need(),
1833 |kind| ActionNeed {
1834 kind,
1835 field: None,
1836 privileged: false,
1837 },
1838 )
1839}
1840
1841#[must_use]
1849pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
1850 spec_of_declaration(decl.as_ref())
1851}
1852
1853fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
1855 let build = Arc::clone(&decl.build);
1856 spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
1857}
1858
1859pub(crate) fn spec_of_declaration_on(
1862 decl: &Declaration,
1863 build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
1864) -> ActionSpec {
1865 let build = Arc::new(build);
1866 let label = decl.shown_label();
1867 let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
1868 encode_built(crate::content::invoking(|| {
1869 build(target, args, origin_now_ms())
1870 }))
1871 };
1872 let spec = if let Some(prompt) = &decl.content {
1873 let param = ActionParam::required_owned(
1874 tilo_actions::PROMPTED_PARAM,
1875 ParamType::Text,
1876 prompt.clone(),
1877 );
1878 ActionSpec::prompted_content_on(
1879 decl.id,
1880 label,
1881 prompt.clone(),
1882 "content hash",
1883 ExecutionLocus::ClientLocal,
1884 move |target, hash| {
1885 let supplied = [(
1886 tilo_actions::PROMPTED_PARAM.to_owned(),
1887 tilo_actions::ArgValue::Text(hash.to_owned()),
1888 )];
1889 match ActionArgs::bind(std::slice::from_ref(¶m), supplied) {
1890 Ok(args) => encoded(target, &args),
1891 Err(error) => refused(&error.to_string()),
1892 }
1893 },
1894 )
1895 } else if decl.params.is_empty() {
1896 let domain = format!("{}#{}", decl.resource, decl.id);
1900 let action_type = decl.action_type;
1901 ActionSpec::deferred_on(
1902 decl.id,
1903 label,
1904 ExecutionLocus::ClientLocal,
1905 action_type,
1906 move |target| encoded(target, &tilo_actions::ActionArgs::none()),
1907 )
1908 .with_continuation_identity(move |query| match query {
1909 tilo_actions::ContinuationQuery::Draft => {
1910 Some(tilo_actions::ContinuationEvidence::Draft {
1911 resolution_domain: tilo_actions::ContinuationKey::new(
1912 "verb",
1913 [domain.as_bytes()],
1914 ),
1915 handler: tilo_actions::ContinuationKey::new(
1916 "action-type",
1917 [action_type.as_bytes()],
1918 ),
1919 })
1920 }
1921 tilo_actions::ContinuationQuery::Exact(_) => None,
1922 })
1923 } else {
1924 ActionSpec::typed_on(
1925 decl.id,
1926 label.clone(),
1927 label,
1928 ExecutionLocus::ClientLocal,
1929 decl.shown_params(),
1930 encoded,
1931 )
1932 };
1933 let mut spec = spec.of_kind(decl.kind);
1934 if decl.by_arguments {
1938 let classify = Arc::clone(&decl.build);
1939 spec = spec.with_need_of(move |args| match classify(args, 0) {
1940 Ok(action) => action.need(),
1941 Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
1942 });
1943 }
1944 if let Some(field) = decl.field {
1945 spec = spec.below_field(field);
1946 }
1947 if let Some(description) = &decl.description {
1948 spec = spec.with_description(description.clone());
1949 }
1950 if !decl.keywords.is_empty() {
1951 spec = spec.with_keywords(decl.keywords.iter().cloned());
1952 }
1953 spec = with_declared_words(spec, decl);
1954 if decl.destructive {
1955 spec = spec.destructive();
1956 }
1957 let contract = &mut spec.type_mut().contract;
1958 (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1959 if let Some(result) = &decl.result {
1960 contract.result = result.clone();
1961 }
1962 for tag in &decl.tags {
1963 if !contract.tags.contains(tag) {
1964 contract.tags.push(tag.clone());
1965 }
1966 }
1967 contract.settle_confirmation();
1970 spec
1971}
1972
1973pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
1976 spec.type_mut().icon.clone_from(&decl.icon);
1977 spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
1978 spec
1979}
1980
1981fn declared_args(
1983 declarations: &[Declaration],
1984) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
1985 let mut args = std::collections::BTreeMap::new();
1986 for decl in declarations {
1987 args.insert(decl.id, crate::schema::args_schema(&decl.params));
1988 }
1989 args
1990}
1991
1992pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
1996 let param = ActionParam::required_owned(
1997 APPLY_PARAM,
1998 ParamType::Object,
1999 format!("A {} action, as JSON", vocabulary.label),
2000 );
2001 let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
2002 let schema = (vocabulary.action_schema)()?;
2003 Some(crate::schema::fold_declared(
2004 &schema,
2005 &declared_args(&vocabulary.declarations()),
2006 ))
2007 });
2008 match schema {
2009 Some(schema) => param.with_shared_schema(schema),
2010 None => param,
2011 }
2012}
2013
2014#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2016enum TypeSchema {
2017 Apply,
2018 Group,
2019 Edit,
2022}
2023
2024#[derive(Default)]
2025struct CompiledSchemas {
2026 epoch: u64,
2027 entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
2028}
2029
2030static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();
2031
2032#[doc(hidden)]
2036pub fn reset_type_schemas() {
2037 if let Some(cache) = SCHEMAS.get() {
2038 let mut store = cache.lock_recover();
2039 store.epoch = store.epoch.wrapping_add(1);
2040 store.entries.clear();
2041 }
2042}
2043
2044pub(crate) fn type_epoch() -> u64 {
2047 SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
2048}
2049
2050pub(crate) fn words_epoch() -> u64 {
2054 type_epoch() ^ crate::label::revision().rotate_left(32)
2055}
2056
2057fn per_type(
2060 vocabulary: &Vocabulary,
2061 schema: TypeSchema,
2062 build: &dyn Fn() -> Option<serde_json::Value>,
2063) -> Option<Arc<serde_json::Value>> {
2064 per_type_at(vocabulary, schema, "", build)
2065}
2066
2067fn per_type_at(
2069 vocabulary: &Vocabulary,
2070 schema: TypeSchema,
2071 at: &str,
2072 build: &dyn Fn() -> Option<serde_json::Value>,
2073) -> Option<Arc<serde_json::Value>> {
2074 let cache = SCHEMAS.get_or_init(Mutex::default);
2075 cached_schema(
2076 cache,
2077 ((vocabulary.type_id)(), schema, at.to_owned()),
2078 build,
2079 )
2080}
2081
2082fn cached_schema(
2083 cache: &Mutex<CompiledSchemas>,
2084 key: (TypeId, TypeSchema, String),
2085 build: &dyn Fn() -> Option<serde_json::Value>,
2086) -> Option<Arc<serde_json::Value>> {
2087 let epoch = {
2088 let store = cache.lock_recover();
2089 if let Some(found) = store.entries.get(&key) {
2090 let _phase = crate::profiling::Phase::start("schema.cached_clone");
2091 return found.clone();
2092 }
2093 store.epoch
2094 };
2095 let value = build().map(Arc::new);
2097 let mut store = cache.lock_recover();
2098 if store.epoch == epoch {
2100 store.entries.insert(key, value.clone());
2101 }
2102 value
2103}
2104
2105#[must_use]
2108pub fn by_app_refusal(label: &str) -> String {
2109 format!("{label} keeps this itself: it is not an action to invoke")
2110}
2111
2112fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
2117 let declarations = vocabulary.declarations();
2118 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2119 for decl in declarations.iter() {
2120 ids.push(decl.id);
2121 }
2122 if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
2123 && let Some(decl) = declarations.iter().find(|decl| decl.id == id)
2124 && let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
2125 {
2126 return Err(format!("{id}: {error}"));
2127 }
2128 if let Some(schema) = apply_param(vocabulary).schema {
2132 tilo_actions::validate_json_schema(&value, &schema)?;
2133 }
2134 let action = (vocabulary.read)(value)?;
2135 if action.by_app() {
2136 return Err(by_app_refusal(vocabulary.label));
2137 }
2138 Ok(action)
2139}
2140
2141pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
2150 let schema = per_type(vocabulary, TypeSchema::Group, &|| {
2151 let declarations = vocabulary.declarations();
2152 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2153 for decl in declarations.iter() {
2154 ids.push(decl.id);
2155 }
2156 Some(group_schema(&ids, vocabulary.edits))
2157 })
2158 .unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
2159 ActionParam::required_owned(
2160 crate::GROUP_PARAM,
2161 ParamType::Array,
2162 format!(
2163 "{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
2164 A member names an item an earlier member of the same group makes by its place, \
2165 {{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
2166 of the ids it made, which the group fills in as it applies",
2167 vocabulary.label
2168 ),
2169 )
2170 .with_shared_schema(schema)
2171}
2172
2173pub const APPLY_MEMBER: &str =
2176 "One action value, as the `apply` action's `apply` parameter describes it";
2177
2178pub const FIELD_EDIT_MEMBER: &str =
2181 "A field edit, as the `field-edit` action's `edit` parameter describes it";
2182
2183fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
2186 use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
2187 let mut members = Vec::new();
2188 if !ids.is_empty() {
2189 members.push(describe(
2190 object(vec![
2191 ("action", string_enum(ids), true),
2192 (
2193 "args",
2194 nullable(serde_json::json!({"type": "object"})),
2195 false,
2196 ),
2197 ]),
2198 "A named action, args as it takes them",
2199 ));
2200 }
2201 let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
2202 if edits {
2203 members.push(describe(
2204 object(vec![
2205 ("action", constant(FIELD_EDIT), true),
2206 (
2207 "args",
2208 object(vec![(
2209 EDIT_PARAM,
2210 describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
2211 true,
2212 )]),
2213 true,
2214 ),
2215 ]),
2216 "A field edit",
2217 ));
2218 }
2219 members.push(object(vec![
2220 ("action", constant(APPLY), true),
2221 ("args", object(vec![(APPLY_PARAM, action, true)]), true),
2222 ]));
2223 array(one_of(members))
2224}
2225
2226fn object_arg(
2228 args: &tilo_actions::ActionArgs,
2229 param: &str,
2230) -> Option<serde_json::Map<String, serde_json::Value>> {
2231 match args.get(param) {
2232 Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
2233 _ => None,
2234 }
2235}
2236
2237pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2238 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2239 let _phase = crate::profiling::Phase::start("resource.apply_spec");
2240 let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
2241 Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
2242 None => Err("missing action".to_owned()),
2243 };
2244 ActionSpec::typed(
2245 APPLY,
2246 format!("Apply {} edit", vocabulary.label),
2247 "Action as JSON",
2248 ExecutionLocus::ClientLocal,
2249 vec![apply_param(vocabulary)],
2250 move |args| match crate::content::invoking(|| read(args)) {
2251 Ok(mut action) => {
2252 action.stamp(origin_now_ms());
2253 encoded(&action)
2254 }
2255 Err(reason) => refused(&reason),
2256 },
2257 )
2258 .with_description(
2259 "One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
2260 )
2261 .for_audience(tilo_actions::Audience::Agents)
2264 .carrying()
2266 .with_need((vocabulary.least_need)())
2269 .of_kind((vocabulary.least_need)().kind)
2270 .with_need_of(move |args| match read(args) {
2271 Ok(action) => action.need(),
2272 Err(_) => tilo_actions::ActionContract::default().need(),
2273 })
2274 .with_risk(move |args| {
2277 let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
2278 match value.map(vocabulary.read) {
2279 Some(Ok(action)) => action.risk(),
2280 _ => tilo_actions::RiskLevel::Low,
2281 }
2282 })
2283 .with_undo_of(move |args| {
2289 let Some(value) = object_arg(args, APPLY_PARAM) else {
2290 return false;
2291 };
2292 let value = serde_json::Value::Object(value);
2293 let declarations = vocabulary.declarations();
2294 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2295 for decl in declarations.iter() {
2296 ids.push(decl.id);
2297 }
2298 let carried = crate::schema::declared_invocation(&value, &ids)
2299 .and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
2300 tilo_actions::undo_takes_back(
2301 carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
2302 tilo_actions::ChangeKind::Content,
2303 carried.is_some_and(|decl| {
2304 decl.tags
2305 .iter()
2306 .any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
2307 }),
2308 )
2309 })
2310}
2311
2312#[must_use]
2317pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
2318 spec.contract.kind
2319}
2320
2321pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
2323 ActionNeed {
2324 kind: R::kind_of(action),
2325 field: R::field_of(action).map(str::to_owned),
2326 privileged: false,
2327 }
2328}
2329
2330pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
2334 let mut needs = needs.into_iter();
2335 let Some(mut group) = needs.next() else {
2336 return tilo_actions::ActionContract::default().need();
2337 };
2338 for need in needs {
2339 group = ActionNeed {
2340 kind: group.kind.max(need.kind),
2341 field: group
2342 .field
2343 .filter(|field| need.field.as_ref() == Some(field)),
2344 privileged: group.privileged || need.privileged,
2345 };
2346 }
2347 group
2348}
2349
2350pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
2357 if let [only] = members {
2358 return encoded(only);
2359 }
2360 let mut payload = Vec::with_capacity(128);
2361 payload.push(b'[');
2362 for (index, member) in members.iter().enumerate() {
2363 if index > 0 {
2364 payload.push(b',');
2365 }
2366 if let Err(error) = member.write_json(&mut payload) {
2367 return refused(&error.to_string());
2368 }
2369 }
2370 payload.push(b']');
2371 EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
2372}
2373
2374pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2375 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2376 let _phase = crate::profiling::Phase::start("resource.group_spec");
2377 let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
2378 crate::group::build_members(vocabulary, &args.to_json(), now_ms)
2379 };
2380 ActionSpec::typed(
2381 crate::GROUP,
2382 format!("Apply several {} edits as one", vocabulary.label),
2383 "Invocations as JSON",
2384 ExecutionLocus::ClientLocal,
2385 vec![group_param(vocabulary)],
2386 move |args| match build(args, origin_now_ms()) {
2387 Ok(members) => encode_group(vocabulary, &members),
2388 Err(reason) => refused(&reason),
2389 },
2390 )
2391 .with_description(
2392 "Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
2393 )
2394 .for_audience(tilo_actions::Audience::Agents)
2397 .carrying()
2399 .with_need((vocabulary.least_need)())
2401 .with_need_of(move |args| match build(args, 0) {
2402 Ok(members) => group_need(members.iter().map(Built::need)),
2403 Err(_) => tilo_actions::ActionContract::default().need(),
2404 })
2405 .with_risk(move |args| match build(args, 0) {
2407 Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
2408 Err(_) => tilo_actions::RiskLevel::Low,
2409 })
2410 .with_undo_of(move |args| match build(args, 0) {
2413 Ok(members) => members.iter().all(Built::undoable),
2414 Err(_) => false,
2415 })
2416}
2417
2418pub use crate::search_default::default_search;
2420
2421pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
2433 publish_parts::<R>(id, label, Some(state))
2434}
2435
2436#[must_use]
2440pub(crate) fn publish_actions<R: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
2441 publish_parts::<R>(id, label, None)
2442}
2443
2444pub fn state_from_reading<R: Resource>(
2460 reading: &serde_json::Value,
2461) -> Result<R::State, ModelError> {
2462 let table = R::RESOURCE_TABLE.ok_or_else(|| {
2463 ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
2464 })?;
2465 crate::table::Run(table).from_json(reading)
2466}
2467
2468pub(crate) fn publish_parts<R: Resource>(
2472 id: &str,
2473 label: &str,
2474 state: Option<&R::State>,
2475) -> tilo_actions::ResourceSpec {
2476 let vocabulary = vocabulary::<R>();
2477 let Some(state) = state else {
2478 let own = Own {
2479 availability: None,
2480 views: Vec::new(),
2481 local_operations: R::local_operations(),
2482 now: Vec::new(),
2483 };
2484 return publish_own(vocabulary, id, label, own, &|_| false);
2485 };
2486 let children = R::children(state);
2487 let own = Own {
2488 availability: Some(&|action| R::availability(state, action)),
2489 views: R::views(state),
2490 local_operations: R::local_operations(),
2491 now: weakening_now::<R>(state),
2492 };
2493 publish_own(vocabulary, id, label, own, &|decl| {
2494 crate::items::offered_bound(&children, decl)
2495 })
2496 .with_children(children)
2497}
2498
2499pub fn unreadable_parts<R: Resource>(
2507 id: &str,
2508 label: &str,
2509 reason: &str,
2510) -> tilo_actions::ResourceSpec {
2511 let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
2512 crate::unreadable::parts::<R>(id, &label, reason)
2513}
2514
2515struct Own<'a> {
2517 availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
2520 views: Vec<tilo_actions::ResourceViewSpec>,
2521 local_operations: Vec<ActionSpec>,
2522 now: Vec<(String, String)>,
2524}
2525
2526fn publish_own(
2530 vocabulary: &'static Vocabulary,
2531 id: &str,
2532 label: &str,
2533 own: Own<'_>,
2534 offered_bound: &dyn Fn(&Declaration) -> bool,
2535) -> tilo_actions::ResourceSpec {
2536 let _phase = crate::profiling::Phase::start("resource.published");
2537 let label = crate::label::published(
2540 vocabulary.kind,
2541 label,
2542 vocabulary.label,
2543 vocabulary.catalogue,
2544 );
2545 let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
2546 resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
2548 resource.app_id = Some(vocabulary.app.to_owned());
2551 resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
2557 let kept = own_specs(vocabulary);
2558 for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
2559 let _phase = crate::profiling::Phase::start("resource.declaration_spec");
2560 let mut spec = if decl.item.is_none() && offered_bound(decl) {
2564 declared.for_agents.clone()
2565 } else {
2566 declared.offered.clone()
2567 };
2568 if let Some(availability) = own.availability {
2571 let now = availability(decl.id);
2572 if spec.contract.availability != now {
2573 spec.type_mut().contract.availability = now;
2574 }
2575 }
2576 resource = resource.with_action(spec);
2577 }
2578 for view in own.views {
2579 resource = resource.with_view(view);
2580 }
2581 crate::share::offer(&mut resource);
2582 for spec in own.local_operations {
2583 if spec.kind == OperationKind::Document {
2584 continue;
2585 }
2586 resource = resource.with_action(spec);
2587 }
2588 resource = resource
2589 .with_action(kept.apply.clone())
2590 .with_action(kept.group.clone());
2591 if vocabulary.edits {
2592 resource = resource.with_action(field_edit_spec(vocabulary, own.now));
2593 }
2594 resource
2595}
2596
2597struct OwnSpecs {
2600 declared: Box<[DeclaredSpec]>,
2602 apply: ActionSpec,
2603 group: ActionSpec,
2604}
2605
2606struct DeclaredSpec {
2609 offered: ActionSpec,
2610 for_agents: ActionSpec,
2611}
2612
2613fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
2618 thread_local! {
2619 static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
2620 std::cell::RefCell::default();
2621 }
2622 crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
2623 let declared = vocabulary
2624 .declarations()
2625 .iter()
2626 .map(|decl| {
2627 let mut offered = spec_of_declaration(decl);
2628 if let Some(item) = decl.item {
2632 offered.type_mut().contract.item = Some(item.to_owned());
2633 }
2634 let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
2635 DeclaredSpec {
2636 offered,
2637 for_agents,
2638 }
2639 })
2640 .collect();
2641 std::rc::Rc::new(OwnSpecs {
2642 declared,
2643 apply: apply_spec(vocabulary),
2644 group: group_spec(vocabulary),
2645 })
2646 })
2647}
2648
2649pub fn build_action<R: Resource>(
2652 id: &str,
2653 arguments: &serde_json::Map<String, serde_json::Value>,
2654 now_ms: i64,
2655) -> Result<R::Action, String> {
2656 typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
2657}
2658
2659pub(crate) fn build_action_of(
2662 vocabulary: &Vocabulary,
2663 id: &str,
2664 arguments: &serde_json::Map<String, serde_json::Value>,
2665 now_ms: i64,
2666) -> Result<Built, String> {
2667 crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
2668}
2669
2670fn build_invoked(
2671 vocabulary: &Vocabulary,
2672 id: &str,
2673 arguments: &serde_json::Map<String, serde_json::Value>,
2674 now_ms: i64,
2675) -> Result<Built, String> {
2676 if id == crate::GROUP {
2677 return Err("a group is several actions; build it with `group::build_group`".into());
2678 }
2679 let read = if id == APPLY {
2680 Some((APPLY_PARAM, "missing action"))
2681 } else if id == FIELD_EDIT && vocabulary.edits {
2682 Some((EDIT_PARAM, "missing edit"))
2683 } else {
2684 None
2685 };
2686 if let Some((param, missing)) = read {
2687 let Some(value) = arguments.get(param).cloned() else {
2688 return Err(missing.to_owned());
2689 };
2690 let mut action = if id == APPLY {
2691 read_apply(vocabulary, value)?
2692 } else {
2693 read_edit(vocabulary, value)?
2694 };
2695 action.stamp(now_ms);
2696 return Ok(action);
2697 }
2698 let declarations = vocabulary.declarations();
2699 let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
2700 return Err(format!("{} has no action `{id}`", vocabulary.label));
2701 };
2702 let args = match ActionArgs::bind_json(&decl.params, arguments) {
2703 Ok(args) => args,
2704 Err(error) => return Err(error.to_string()),
2705 };
2706 (decl.build)(&args, now_ms)
2707}
2708
2709#[must_use]
2718pub fn bind_declaration(
2719 resource: tilo_actions::ResourceSpec,
2720 decl: &Declaration,
2721) -> tilo_actions::ResourceSpec {
2722 let spec = spec_of_declaration(decl);
2723 let mut resource = resource;
2724 match resource
2725 .actions
2726 .iter_mut()
2727 .find(|existing| existing.id == decl.id)
2728 {
2729 Some(declared) => {
2730 if decl.refines && same_shape(&spec, declared) {
2731 *declared = spec;
2732 }
2733 resource
2734 }
2735 None => resource.with_action(spec),
2736 }
2737}
2738
2739fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
2740 let shape = |spec: &ActionSpec| {
2741 spec.params()
2742 .iter()
2743 .map(|param| (param.name.to_string(), param.ty, param.required))
2744 .collect::<Vec<_>>()
2745 };
2746 bound.kind == declared.kind
2747 && shape(bound) == shape(declared)
2748 && bound.contract.kind == declared.contract.kind
2749 && bound.contract.field == declared.contract.field
2750 && bound.contract.risk == declared.contract.risk
2751}
2752
2753pub trait SharedResource: Resource {
2760 const OWNER: &'static str;
2763}
2764
2765#[derive(Clone, Debug, Default, PartialEq, Eq)]
2766pub struct SearchRow {
2767 pub subtitle: Option<String>,
2769 pub icon: Option<String>,
2772 pub shape: SearchRowShape,
2774}
2775
2776impl SearchRow {
2777 pub fn subtitle(subtitle: impl Into<String>) -> Self {
2779 Self {
2780 subtitle: Some(subtitle.into()),
2781 ..Self::default()
2782 }
2783 }
2784
2785 #[must_use]
2787 pub fn shaped(shape: SearchRowShape) -> Self {
2788 Self {
2789 shape,
2790 ..Self::default()
2791 }
2792 }
2793
2794 #[must_use]
2796 pub fn icon(mut self, name: impl Into<String>) -> Self {
2797 self.icon = Some(name.into());
2798 self
2799 }
2800}
2801
2802#[derive(Clone, Debug, Default, PartialEq, Eq)]
2803pub enum SearchRowShape {
2804 #[default]
2806 Plain,
2807 Message {
2809 sender: String,
2810 snippet: Option<String>,
2811 date: Option<String>,
2812 unread: bool,
2813 },
2814 Media {
2818 byline: Option<String>,
2819 duration: Option<String>,
2820 },
2821 FileHit {
2823 path: String,
2824 line: Option<u32>,
2825 snippet: String,
2826 },
2827}
2828
2829pub use tilo_actions::{ScopeDecl, scope_contains};
2830
2831#[cfg(test)]
2832mod schema_sharing_tests;
2833
2834#[cfg(test)]
2835mod selection_place_tests {
2836 use super::Place;
2837 use tilo_actions::SelectionPlace;
2838 use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;
2839
2840 #[test]
2841 fn a_selection_place_is_the_place_an_action_takes() {
2842 for (place, expected_json) in [
2843 (Place::Item("p1".into()), r#"{"item":"p1"}"#),
2844 (
2845 Place::Caret {
2846 item: "p1".into(),
2847 at: 3,
2848 },
2849 r#"{"item":"p1","at":3}"#,
2850 ),
2851 (
2852 Place::Range {
2853 item: "p1".into(),
2854 start: 2,
2855 end: 7,
2856 },
2857 r#"{"item":"p1","start":2,"end":7}"#,
2858 ),
2859 (
2860 Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
2861 &format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
2862 ),
2863 ] {
2864 let wire = serde_json::to_string(&place).unwrap();
2865 assert_eq!(wire, expected_json, "valid places serialise as before");
2866 let selection = SelectionPlace::from(place.clone());
2867 assert_eq!(
2868 serde_json::to_string(&selection).unwrap(),
2869 wire,
2870 "both travel in one wire form"
2871 );
2872 assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
2873 assert_eq!(Place::try_from(selection).unwrap(), place);
2874 }
2875
2876 let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
2877 let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
2878 assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);
2879
2880 for bad_item in [
2881 String::new(),
2882 overlong_ascii,
2883 overlong_utf8,
2884 "p\n1".to_owned(),
2885 "p\u{0}1".to_owned(),
2886 "p\x1b1".to_owned(),
2887 "p\t1".to_owned(),
2888 ] {
2889 for selection in [
2890 SelectionPlace::item(bad_item.clone()),
2891 SelectionPlace::caret(bad_item.clone(), 0),
2892 SelectionPlace::range(bad_item.clone(), 0, 1),
2893 ] {
2894 assert!(
2895 Place::try_from(selection.clone()).is_err(),
2896 "Place::try_from accepted invalid SelectionPlace: {selection:?}"
2897 );
2898 let json = serde_json::to_value(&selection).unwrap();
2899 assert!(
2900 serde_json::from_value::<Place>(json.clone()).is_err(),
2901 "Place::deserialize accepted invalid JSON: {json}"
2902 );
2903 }
2904 }
2905
2906 for malformed in [
2907 serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
2908 serde_json::json!({"item": "p1", "start": 2}),
2909 serde_json::json!({"item": "p1", "end": 2}),
2910 serde_json::json!({"item": "p1", "start": 5, "end": 2}),
2911 ] {
2912 let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
2913 let from_selection = Place::try_from(wire).unwrap_err();
2914 let from_json = serde_json::from_value::<Place>(malformed)
2915 .unwrap_err()
2916 .to_string();
2917 for error in [&from_selection, &from_json] {
2918 assert!(
2919 error.contains("at") && error.contains("start") && error.contains("end"),
2920 "malformed-shape error should name `at` and `start`/`end`: {error}"
2921 );
2922 }
2923 }
2924 assert!(
2925 serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
2926 .is_err()
2927 );
2928 }
2929}