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 set_field(action: &Self::Action) -> Option<String> {
217 let _ = action;
218 None
219 }
220
221 fn field_of(action: &Self::Action) -> Option<&'static str> {
227 let _ = action;
228 None
229 }
230
231 fn least_need() -> ActionNeed {
238 least_need_declared(&vocabulary::<Self>().declarations())
239 }
240
241 fn declarations() -> Vec<ActionDecl<Self>> {
244 Vec::new()
245 }
246
247 fn action_schema() -> Option<serde_json::Value> {
256 None
257 }
258
259 fn children(_state: &Self::State) -> Vec<tilo_actions::ResourceSpec> {
264 Vec::new()
265 }
266
267 fn item_effects(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ActionSpec> {
271 Vec::new()
272 }
273
274 fn item_views(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ResourceViewSpec> {
279 Vec::new()
280 }
281
282 fn children_parts(state: &Self::State) -> crate::items::ChildrenParts {
290 crate::items::ChildrenParts {
291 others: Self::children(state),
292 kept: std::rc::Rc::default(),
293 items: Vec::new(),
294 item_actions: Vec::new(),
295 }
296 }
297
298 fn children_offer_bound(state: &Self::State) -> Vec<&'static str> {
309 offered_bound_ids(&Self::children(state), &vocabulary::<Self>().declarations())
310 }
311
312 fn child(_state: &Self::State, _id: &str) -> Option<tilo_actions::ResourceSpec> {
319 None
320 }
321
322 fn local_operations() -> Vec<tilo_actions::ActionSpec> {
330 Vec::new()
331 }
332
333 fn views(_state: &Self::State) -> Vec<tilo_actions::ResourceViewSpec> {
337 Vec::new()
338 }
339
340 fn search_scopes(_state: &Self::State) -> Vec<ScopeDecl> {
342 Vec::new()
343 }
344
345 fn search(_state: &Self::State) -> Vec<SearchEntry> {
346 Vec::new()
347 }
348
349 const READABLE: bool = false;
355
356 fn document_child(_state: &Self::State, _id: &str) -> bool {
362 false
363 }
364
365 fn read_content(
372 state: &Self::State,
373 doc: &Doc,
374 item: Option<&str>,
375 ) -> Result<serde_json::Value, String> {
376 let _ = (state, doc, item);
377 Err(format!("a {} does not answer reads", Self::LABEL))
378 }
379
380 const HAS_FACTS: bool = false;
384
385 const RESOURCE_TABLE: Option<&'static crate::table::ModelTable> = None;
391
392 fn facts(state: &Self::State, doc: &Doc) -> Result<serde_json::Value, String> {
400 let _ = (state, doc);
401 Err(format!("a {} states no facts", Self::LABEL))
402 }
403
404 const ANSWERS: bool = false;
409
410 fn answer(
416 _doc: &Doc,
417 _action: &str,
418 _changes: &[automerge::Patch],
419 ) -> Option<serde_json::Value> {
420 None
421 }
422
423 fn shape() -> Option<crate::Shape> {
428 None
429 }
430
431 fn state_json(state: &Self::State) -> Option<serde_json::Value> {
436 let _ = state;
437 None
438 }
439
440 const VERSION: u32 = 1;
444
445 const READERS: &'static str = "";
450
451 fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
455 let _ = doc;
456 Err(ModelError::invalid(format!(
457 "{} has no migration from storage version {from}",
458 Self::LABEL
459 )))
460 }
461
462 #[must_use]
465 fn surface() -> crate::surface::Surface {
466 crate::surface::surface_of::<Self>()
467 }
468
469 const EDITS: bool = false;
472
473 fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
476 let _ = edit;
477 None
478 }
479
480 fn stamp(action: &mut Self::Action, now_ms: i64) {
483 let _ = (action, now_ms);
484 }
485
486 fn op_schemas() -> Vec<(String, serde_json::Value)> {
490 Vec::new()
491 }
492
493 fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
496 let _ = (state, action);
497 tilo_actions::Availability::Available
498 }
499
500 fn seed() -> Option<Self::Action> {
503 None
504 }
505
506 fn kind_of(action: &Self::Action) -> ActionKind {
510 let _ = action;
511 ActionKind::Undoable
512 }
513
514 fn by_app(action: &Self::Action) -> bool {
521 let _ = action;
522 false
523 }
524
525 fn build_by_app(
530 id: &str,
531 arguments: &serde_json::Map<String, serde_json::Value>,
532 now_ms: i64,
533 ) -> Option<Result<Self::Action, String>> {
534 let _ = (id, arguments, now_ms);
535 None
536 }
537
538 fn action_item(action: &Self::Action) -> Option<crate::Id> {
543 let _ = action;
544 None
545 }
546
547 fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
552 let _ = action;
553 None
554 }
555
556 fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
560 let _ = (action, keep);
561 None
562 }
563
564 fn register(registry: &mut ActionRegistry) {
567 registry.register::<Self::Action>(Self::ACTION_TYPE);
568 }
569}
570
571pub trait NamesItem: Clone {
574 fn named_item(&self) -> Option<crate::Id>;
575}
576
577impl NamesItem for crate::Id {
578 fn named_item(&self) -> Option<crate::Id> {
579 Some(self.clone())
580 }
581}
582
583impl NamesItem for String {
584 fn named_item(&self) -> Option<crate::Id> {
585 Some(crate::Id::from_raw(self.clone()))
586 }
587}
588
589#[doc(hidden)]
591pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
592 entries.iter().map(NamesItem::named_item).collect()
593}
594
595#[doc(hidden)]
597#[must_use]
598pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
599 keep.iter()
600 .filter_map(|at| entries.get(*at).cloned())
601 .collect()
602}
603
604pub const APPLY: &str = "apply";
616pub const APPLY_PARAM: &str = "action";
618
619pub const FIELD_EDIT: &str = "field-edit";
622pub const EDIT_PARAM: &str = "edit";
624
625fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
627 let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
628 match (vocabulary.edit)(edit) {
629 Some(action) => Ok(action),
630 None => Err(format!("{} has no field edits", vocabulary.label)),
631 }
632}
633
634pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
640 let ops = (vocabulary.op_schemas)();
641 if let Some(shape) = (vocabulary.shape)()
642 && !shape.fields().is_empty()
643 {
644 let mut alternatives = Vec::new();
645 edit_paths(shape, &[], "", &ops, &mut alternatives);
646 if !alternatives.is_empty() {
647 return described_edit(&alternatives, &ops);
648 }
649 }
650 generic_edit_schema(&ops, |_| true)
651}
652
653fn described_edit(
658 alternatives: &[serde_json::Value],
659 ops: &[(String, serde_json::Value)],
660) -> serde_json::Value {
661 let taken: Vec<String> = alternatives
664 .iter()
665 .filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
666 .flatten()
667 .filter_map(serde_json::Value::as_str)
668 .map(str::to_owned)
669 .collect();
670 let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
671 let mut lines = vec![
672 "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(),
673 ];
674 let mut examples = Vec::new();
675 let mut shapes: Vec<Vec<String>> = Vec::new();
676 let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
679 let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
680 for (alternative, next) in alternatives.iter().zip(nexts) {
681 let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
682 let template = at("/properties/path/examples/0");
683 let ops: Vec<String> = at("/properties/op/enum")
684 .as_array()
685 .map(|ops| {
686 ops.iter()
687 .filter_map(serde_json::Value::as_str)
688 .map(str::to_owned)
689 .collect()
690 })
691 .unwrap_or_default();
692 let value = at("/properties/value");
693 let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
694 let title = text("/title");
695 let shape: Vec<String> = template
698 .as_array()
699 .map(|steps| {
700 steps
701 .iter()
702 .filter_map(|step| step.as_object()?.keys().next().cloned())
703 .collect()
704 })
705 .unwrap_or_default();
706 let leaf = next.is_none_or(|next| {
711 next.get("title")
712 .and_then(serde_json::Value::as_str)
713 .is_none_or(|next| !next.starts_with(&format!("{title}.")))
714 });
715 let in_resource = shape
716 .iter()
717 .rev()
718 .take(2)
719 .filter(|kind| *kind == "field")
720 .count()
721 == 2;
722 let record = title
723 .rsplit_once('.')
724 .and_then(|(parent, key)| {
725 listed
726 .iter_mut()
727 .find(|(path, ..)| path == parent)
728 .map(|(_, _, fields)| (fields, key))
729 })
730 .filter(|_| in_resource && leaf && ops == ["set"]);
731 if let Some((fields, key)) = record {
732 fields.push(format!("`{key}`"));
733 } else {
734 let kind = value_kind(&value);
735 let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
736 let line = format!(
737 "- `{title}`: {} — {}{}",
738 usage.join(", "),
739 text("/description"),
740 kind.map_or_else(String::new, |kind| format!(" ({kind})")),
741 );
742 listed.push((title.clone(), line, Vec::new()));
743 }
744 if shapes.contains(&shape) {
745 continue;
746 }
747 shapes.push(shape);
748 let mut example = serde_json::Map::new();
749 example.insert("path".into(), template);
750 if let Some(op) = ops.first() {
751 example.insert("op".into(), op.clone().into());
752 }
753 examples.push(serde_json::Value::Object(example));
754 }
755 lines.extend(listed.into_iter().map(|(_, line, fields)| {
756 if fields.is_empty() {
757 line
758 } else {
759 format!("{line}; set one field of it: {}", fields.join(", "))
760 }
761 }));
762 if let Some(object) = schema.as_object_mut() {
763 object.insert("description".into(), lines.join("\n").into());
764 object.insert("examples".into(), examples.into());
765 }
766 schema
767}
768
769fn value_kind(schema: &serde_json::Value) -> Option<String> {
774 if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
775 let options: Vec<String> = options
776 .iter()
777 .map(|option| {
778 option
779 .as_str()
780 .map_or_else(|| option.to_string(), str::to_owned)
781 })
782 .collect();
783 return Some(format!("one of {}", options.join(", ")));
784 }
785 match schema.get("type")? {
786 serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
787 serde_json::Value::Array(kinds) => Some(
788 kinds
789 .iter()
790 .filter_map(serde_json::Value::as_str)
791 .collect::<Vec<_>>()
792 .join(" or "),
793 ),
794 _ => None,
795 }
796}
797
798fn generic_edit_schema(
801 ops: &[(String, serde_json::Value)],
802 takes: impl Fn(&str) -> bool,
803) -> serde_json::Value {
804 let ops = ops.to_vec();
805 let mut schema = crate::path::edit_schema_taking(&takes);
806 if !ops.is_empty()
807 && takes("rich")
808 && let Some(properties) = schema
809 .get_mut("properties")
810 .and_then(serde_json::Value::as_object_mut)
811 {
812 let description = ops
818 .into_iter()
819 .map(|(path, schema)| {
820 format!(
821 "An edit of `{path}` in its own vocabulary, one of: {}",
822 crate::schema::summary(&schema)
823 )
824 })
825 .collect::<Vec<_>>()
826 .join("\n");
827 properties.insert(
828 "rich".into(),
829 crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
830 );
831 }
832 schema
833}
834
835fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
836 let mut properties = serde_json::Map::new();
837 properties.insert(kind.to_owned(), value);
838 serde_json::json!({
839 "type": "object",
840 "properties": properties,
841 "required": [kind],
842 })
843}
844
845fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
848 let ty = field.ty;
849 if ty.rsplit("::").next() == Some("Reactions") {
851 return vec!["react", "unreact"];
852 }
853 match field.shape {
854 crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
855 vec![
856 "upsert-item",
857 "insert-item",
858 "remove-item",
859 "move-to",
860 "set",
861 ]
862 }
863 _ if rich => vec!["replace", "rich"],
866 _ if ty.starts_with("Counter") => vec!["add", "set"],
867 _ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
868 _ if ty.starts_with("Grid<") => vec![
869 "set-cell",
870 "insert-row",
871 "insert-column",
872 "remove-row",
873 "remove-column",
874 ],
875 _ if ty.starts_with("Outbox") => vec!["settle", "forget"],
876 crate::Shape::Map(_) => vec!["set", "remove-key"],
877 _ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
878 _ => vec!["set"],
879 }
880}
881
882fn takes_own_verbs(field: &crate::FieldShape) -> bool {
886 let ops = field_ops(field, false);
887 ops.iter()
888 .any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
889}
890
891fn rich_schema_at<'a>(
894 rich: &'a [(String, serde_json::Value)],
895 at: &str,
896) -> Option<&'a serde_json::Value> {
897 rich.iter()
898 .find(|(path, _)| path == at)
899 .map(|(_, schema)| schema)
900}
901
902#[allow(
903 clippy::too_many_lines,
904 reason = "one walk over the stored shape, an alternative per kind of path"
905)]
906fn edit_paths(
907 shape: crate::Shape,
908 steps: &[serde_json::Value],
909 dotted: &str,
910 rich: &[(String, serde_json::Value)],
911 out: &mut Vec<serde_json::Value>,
912) {
913 let alternative = |steps: &[serde_json::Value],
914 open: bool,
915 ops: &[&str],
916 value: serde_json::Value,
917 rich: Option<&serde_json::Value>,
918 title: &str,
919 description: String| {
920 let template: Vec<serde_json::Value> = steps
922 .iter()
923 .map(|step| {
924 let properties = step.get("properties").and_then(serde_json::Value::as_object);
925 match properties.and_then(|properties| properties.iter().next()) {
926 Some((kind, value)) if kind == "field" => {
927 serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
928 }
929 Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
930 None => serde_json::Value::Null,
931 }
932 })
933 .collect();
934 let dotted: Vec<String> = template
935 .iter()
936 .map(
937 |step| match step.get("field").and_then(serde_json::Value::as_str) {
938 Some(field) => field.to_owned(),
939 None => "*".to_owned(),
940 },
941 )
942 .collect();
943 let mut path = serde_json::json!({
944 "type": "array",
945 "prefixItems": steps,
946 "minItems": steps.len(),
947 "examples": [template],
948 });
949 if let Some(path) = path.as_object_mut() {
950 if open {
951 path.insert("items".into(), serde_json::json!({ "type": "object" }));
953 } else {
954 path.insert("maxItems".into(), steps.len().into());
955 }
956 }
957 let mut properties = serde_json::Map::new();
958 properties.insert("path".into(), path);
959 properties.insert("op".into(), serde_json::json!({ "enum": ops }));
960 properties.insert("value".into(), value);
961 if ops.contains(&"upsert-item") {
962 properties.insert(
963 "match".into(),
964 serde_json::json!({
965 "type": "object",
966 "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"
967 }),
968 );
969 properties.insert(
970 "at".into(),
971 serde_json::json!({
972 "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
973 "anyOf": [
974 { "const": "end" },
975 { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
976 { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
977 { "type": "integer", "minimum": 0 }
978 ]
979 }),
980 );
981 }
982 if let Some(rich) = rich {
983 properties.insert("rich".into(), rich.clone());
984 }
985 serde_json::json!({
986 "title": dotted.join("."),
987 "description": if description.is_empty() {
988 title.to_owned()
989 } else {
990 format!("{title}; {description}")
991 },
992 "type": "object",
993 "properties": properties,
994 "required": ["path", "op"],
995 })
996 };
997 let item = step_schema("item", serde_json::json!({ "type": "string" }));
998 for field in shape
1002 .fields()
1003 .iter()
1004 .filter(|field| !field.readonly || takes_own_verbs(field))
1005 {
1006 let mut here = steps.to_vec();
1007 here.push(step_schema(
1008 "field",
1009 serde_json::json!({ "const": field.key }),
1010 ));
1011 let path = format!("{dotted}{}", field.key);
1012 let rich_schema = rich_schema_at(rich, &path);
1013 let ops = field_ops(field, rich_schema.is_some());
1014 let collection = matches!(
1015 field.shape,
1016 crate::Shape::Collection(_) | crate::Shape::Keyed(_)
1017 );
1018 let simple = ops.first() == Some(&"set") && !collection;
1021 let value = if simple {
1022 (field.schema)()
1023 } else {
1024 serde_json::json!({})
1025 };
1026 let mut flags = Vec::new();
1027 if field.unit {
1028 flags.push("its own storage unit".to_owned());
1029 }
1030 match field.trust {
1031 crate::Trust::Ordinary => {}
1032 crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
1033 crate::Trust::Weakens(_) => flags.push(
1034 "making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
1035 .to_owned(),
1036 ),
1037 crate::Trust::Weakening => flags.push(
1038 "changing it can weaken security: it asks for confirmation and needs the person's own grant"
1039 .to_owned(),
1040 ),
1041 }
1042 if collection {
1043 flags.push(if field.quiet_remove {
1046 "removing an item asks nothing".to_owned()
1047 } else {
1048 "removing an item asks nothing; Undo takes it back".to_owned()
1049 });
1050 }
1051 let description = flags.join("; ");
1052 out.push(alternative(
1053 &here,
1054 false,
1055 &ops,
1056 value,
1057 rich_schema,
1058 field.title,
1059 description,
1060 ));
1061 match field.shape {
1062 crate::Shape::Record(_) => {
1063 edit_paths(field.shape, &here, &format!("{path}."), rich, out);
1064 }
1065 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
1066 let mut items = here.clone();
1067 items.push(item.clone());
1068 let item_value = (field.schema)().get("items").map_or_else(
1069 || serde_json::json!({}),
1070 |items| {
1071 items
1073 .get("properties")
1074 .and_then(|properties| properties.get("value"))
1075 .cloned()
1076 .unwrap_or_else(|| items.clone())
1077 },
1078 );
1079 let item_ops: &[&str] = match *inner {
1082 crate::Shape::Value => &["set", "splice", "replace", "rich"],
1083 _ => &["set"],
1084 };
1085 out.push(alternative(
1086 &items,
1087 false,
1088 item_ops,
1089 item_value,
1090 None,
1091 field.title,
1092 "one item, by its id".to_owned(),
1093 ));
1094 edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
1095 }
1096 crate::Shape::Value if field.ty.starts_with("Grid<") => {
1097 let mut cells = here.clone();
1098 cells.push(step_schema(
1099 "cell",
1100 serde_json::json!({
1101 "type": "object",
1102 "properties": {
1103 "row": { "type": "string" },
1104 "column": { "type": "string" },
1105 },
1106 "required": ["row", "column"],
1107 }),
1108 ));
1109 out.push(alternative(
1110 &cells,
1111 true,
1112 &[
1113 "set", "splice", "replace", "add", "insert", "remove", "rich",
1114 ],
1115 serde_json::json!({}),
1116 None,
1117 field.title,
1118 "a cell, by its row and column ids, and what is inside it".to_owned(),
1119 ));
1120 }
1121 crate::Shape::Map(_) => {
1122 let mut entries = here.clone();
1123 entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
1124 let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
1126 let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
1127 if entry_rich.is_some() {
1128 ops.push("rich");
1129 }
1130 out.push(alternative(
1131 &entries,
1132 true,
1133 &ops,
1134 serde_json::json!({}),
1135 entry_rich,
1136 field.title,
1137 "an entry, by its key, and what is inside it".to_owned(),
1138 ));
1139 }
1140 crate::Shape::Value => {}
1141 }
1142 }
1143}
1144
1145mod field_edit;
1146use field_edit::rooted_edit_spec;
1147
1148pub(crate) fn field_edit_spec(
1151 vocabulary: &'static Vocabulary,
1152 now: Vec<(String, String)>,
1153) -> ActionSpec {
1154 let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
1157 Some(edit_schema(vocabulary))
1158 })
1159 .unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
1160 rooted_edit_spec(
1161 vocabulary,
1162 (vocabulary.shape)(),
1163 schema,
1164 format!("Edit a {} field", vocabulary.label),
1165 "The path of the field from the record's root, and the operation",
1166 now,
1167 )
1168}
1169
1170fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
1174 weakening_in(R::shape(), &|| R::state_json(state))
1175}
1176
1177#[inline(never)]
1181fn weakening_in(
1182 shape: Option<crate::Shape>,
1183 json: &dyn Fn() -> Option<serde_json::Value>,
1184) -> Vec<(String, String)> {
1185 let Some(shape) = shape else {
1186 return Vec::new();
1187 };
1188 let fields: Vec<String> = shape
1189 .guarded_fields()
1190 .into_iter()
1191 .filter(|(path, trust)| {
1192 matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
1193 })
1194 .map(|(path, _)| path)
1195 .collect();
1196 if fields.is_empty() {
1197 return Vec::new();
1198 }
1199 let Some(json) = json() else {
1200 return Vec::new();
1201 };
1202 fields
1203 .into_iter()
1204 .filter_map(|path| {
1205 let value = path
1206 .split('.')
1207 .try_fold(&json, |value, key| value.get(key))?
1208 .to_string();
1209 Some((path, value))
1210 })
1211 .collect()
1212}
1213
1214#[must_use]
1217pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
1218 item_field_edit_spec_of(vocabulary::<R>(), field, item)
1219}
1220
1221pub(crate) fn item_field_edit_spec_of(
1223 vocabulary: &'static Vocabulary,
1224 field: &str,
1225 item: &crate::Id,
1226) -> Option<ActionSpec> {
1227 field_edit_spec_at_of(
1228 vocabulary,
1229 vec![
1230 crate::Segment::Field(field.to_owned()),
1231 crate::Segment::Item(item.clone()),
1232 ],
1233 )
1234}
1235
1236#[must_use]
1240pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
1241 field_edit_spec_at_of(vocabulary::<R>(), prefix)
1242}
1243
1244pub(crate) fn field_edit_spec_at_of(
1246 vocabulary: &'static Vocabulary,
1247 prefix: Vec<crate::Segment>,
1248) -> Option<ActionSpec> {
1249 let mut shape = (vocabulary.shape)()?;
1250 let mut dotted = String::new();
1251 let mut readonly = false;
1252 for segment in &prefix {
1253 match (shape, segment) {
1254 (crate::Shape::Record(fields), crate::Segment::Field(key)) => {
1255 let field = fields.iter().find(|candidate| candidate.key == key)?;
1256 readonly |= field.readonly;
1257 shape = field.shape;
1258 dotted.push_str(key);
1259 dotted.push('.');
1260 }
1261 (
1262 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
1263 crate::Segment::Item(_),
1264 ) => {
1265 shape = *inner;
1266 dotted.push_str("*.");
1267 }
1268 _ => return None,
1269 }
1270 }
1271 if shape.fields().is_empty() || readonly {
1272 return None;
1273 }
1274 thread_local! {
1277 static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
1278 }
1279 let key = ((vocabulary.type_id)(), dotted.clone());
1280 crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
1281 .map(|ty| ty.bind(Target::new(prefix)))
1282}
1283
1284fn item_edit_type(
1287 vocabulary: &'static Vocabulary,
1288 shape: crate::Shape,
1289 dotted: &str,
1290) -> Option<Arc<ActionType>> {
1291 let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
1292 let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
1293 .into_iter()
1294 .filter_map(|(path, schema)| {
1295 path.strip_prefix(dotted)
1296 .map(|rest| (rest.to_owned(), schema))
1297 })
1298 .collect();
1299 let mut alternatives = Vec::new();
1300 edit_paths(shape, &[], "", &ops, &mut alternatives);
1301 (!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
1302 })?;
1303 let spec = rooted_edit_spec(
1304 vocabulary,
1305 Some(shape),
1306 schema,
1307 "Edit a field of this item".to_owned(),
1308 "The path of the field from the item, and the operation",
1309 Vec::new(),
1310 );
1311 Some(Arc::clone(spec.action_type()))
1312}
1313
1314#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
1320pub enum NoAction {}
1321
1322impl tilo_actions::Action for NoAction {
1323 fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
1325 Ok(())
1326 }
1327}
1328
1329#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1336#[serde(into = "tilo_actions::SelectionPlace")]
1337pub enum Place {
1338 Item(String),
1340 Caret { item: String, at: usize },
1342 Range {
1344 item: String,
1345 start: usize,
1346 end: usize,
1347 },
1348}
1349
1350impl Place {
1351 #[must_use]
1353 pub fn item(&self) -> &str {
1354 match self {
1355 Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
1356 }
1357 }
1358}
1359
1360impl<'de> serde::Deserialize<'de> for Place {
1368 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1369 let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
1370 match place_from_json(value) {
1371 Ok(place) => Ok(place),
1372 Err(error) => Err(serde::de::Error::custom(error)),
1373 }
1374 }
1375}
1376
1377fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
1379 match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
1380 Ok(wire) => Place::try_from(wire),
1381 Err(error) => Err(error.to_string()),
1382 }
1383}
1384
1385impl crate::JsonSchema for Place {
1386 fn json_schema() -> serde_json::Value {
1387 tilo_actions::place_schema()
1388 }
1389}
1390
1391impl From<Place> for tilo_actions::SelectionPlace {
1394 fn from(place: Place) -> Self {
1395 match place {
1396 Place::Item(item) => Self::item(item),
1397 Place::Caret { item, at } => Self::caret(item, at),
1398 Place::Range { item, start, end } => Self::range(item, start, end),
1399 }
1400 }
1401}
1402
1403impl TryFrom<tilo_actions::SelectionPlace> for Place {
1404 type Error = String;
1405
1406 fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
1407 match place.validated_span()? {
1408 tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
1409 tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
1410 item: place.item,
1411 at,
1412 }),
1413 tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
1414 item: place.item,
1415 start,
1416 end,
1417 }),
1418 }
1419 }
1420}
1421
1422pub type BuildAction<R> =
1426 Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;
1427
1428pub struct ActionDecl<R: Resource> {
1431 decl: Declaration,
1432 marker: std::marker::PhantomData<fn() -> R>,
1433}
1434
1435impl<R: Resource> Clone for ActionDecl<R> {
1436 fn clone(&self) -> Self {
1437 Self {
1438 decl: self.decl.clone(),
1439 marker: std::marker::PhantomData,
1440 }
1441 }
1442}
1443
1444impl<R: Resource> std::ops::Deref for ActionDecl<R> {
1445 type Target = Declaration;
1446
1447 fn deref(&self) -> &Declaration {
1448 &self.decl
1449 }
1450}
1451
1452impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
1453 fn as_ref(&self) -> &Declaration {
1454 &self.decl
1455 }
1456}
1457
1458impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
1459 fn deref_mut(&mut self) -> &mut Declaration {
1460 &mut self.decl
1461 }
1462}
1463
1464impl<R: Resource> ActionDecl<R> {
1465 pub fn edit_asking<V>(
1471 id: &'static str,
1472 label: impl Into<String>,
1473 param: &'static str,
1474 description: &'static str,
1475 make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
1476 ) -> Self
1477 where
1478 V: DeserializeOwned + crate::JsonSchema,
1479 {
1480 let schema = V::json_schema();
1481 let declared = ActionParam::required_owned(
1482 param,
1483 crate::__private::param_type_of(&schema),
1484 description,
1485 )
1486 .with_schema(schema);
1487 let vocabulary = vocabulary::<R>();
1488 let build: Builds = Arc::new(move |args, now_ms| {
1489 let value = taken_arg(args, param)?;
1490 let value: V = match serde_json::from_value(value) {
1491 Ok(value) => value,
1492 Err(error) => return Err(format!("`{param}`: {error}")),
1493 };
1494 stamped_edit(vocabulary, make(value).retyped(), now_ms)
1495 });
1496 Self::declared(Declaration::new(
1497 vocabulary,
1498 id,
1499 label.into(),
1500 vec![declared],
1501 build,
1502 ))
1503 }
1504
1505 pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
1509 where
1510 crate::Edit<R>: Send + Sync,
1511 {
1512 Self::declared(edit_declaration(
1513 vocabulary::<R>(),
1514 id,
1515 label.into(),
1516 edit.retyped(),
1517 ))
1518 }
1519
1520 pub fn new(
1521 id: &'static str,
1522 label: impl Into<String>,
1523 params: Vec<ActionParam>,
1524 build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
1525 ) -> Self {
1526 let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
1527 Ok(action) => Ok(Built::of::<R>(action)),
1528 Err(reason) => Err(reason),
1529 });
1530 Self::declared(Declaration::new(
1531 vocabulary::<R>(),
1532 id,
1533 label.into(),
1534 params,
1535 build,
1536 ))
1537 }
1538
1539 pub(crate) fn declared(decl: Declaration) -> Self {
1540 Self {
1541 decl,
1542 marker: std::marker::PhantomData,
1543 }
1544 }
1545
1546 #[must_use]
1549 pub fn with_arguments(
1550 &self,
1551 arguments: serde_json::Map<String, serde_json::Value>,
1552 ) -> crate::Invoke<R> {
1553 crate::Invoke::bound(self.decl.id, Ok(arguments))
1554 }
1555
1556 #[must_use]
1558 pub fn into_declaration(self) -> Declaration {
1559 self.decl
1560 }
1561
1562 pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
1564 typed::<R>(crate::content::invoking(|| {
1565 (self.decl.build)(args, now_ms)
1566 })?)
1567 }
1568
1569 #[must_use]
1572 pub fn refining(mut self) -> Self {
1573 self.decl.refines = true;
1574 self
1575 }
1576
1577 #[must_use]
1582 pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
1583 self.decl.tags.retain(|tag| {
1584 tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
1585 });
1586 if let Some(tag) = audience.tag() {
1587 self.decl.tags.push(tag.to_owned());
1588 }
1589 self
1590 }
1591
1592 #[must_use]
1595 pub fn tagged(mut self, tag: impl Into<String>) -> Self {
1596 self.decl.tag(tag.into());
1597 self
1598 }
1599
1600 #[must_use]
1601 pub fn describe(mut self, description: impl Into<String>) -> Self {
1602 self.decl.description = Some(description.into());
1603 self
1604 }
1605
1606 #[must_use]
1609 pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
1610 self.decl.result = Some(result);
1611 self
1612 }
1613
1614 #[must_use]
1616 pub fn of_kind(mut self, kind: ActionKind) -> Self {
1617 self.decl.kind = kind;
1618 self
1619 }
1620
1621 #[must_use]
1623 pub fn below_field(mut self, field: &'static str) -> Self {
1624 self.decl.field = Some(field);
1625 self
1626 }
1627
1628 #[must_use]
1629 pub fn destructive(mut self) -> Self {
1630 self.decl.destructive = true;
1631 self
1632 }
1633
1634 #[must_use]
1637 pub fn writing(mut self, units: Vec<String>) -> Self {
1638 self.decl.writes = units;
1639 self
1640 }
1641
1642 #[must_use]
1645 pub fn answering(mut self) -> Self {
1646 self.decl.answer();
1647 self
1648 }
1649}
1650
1651impl Declaration {
1652 fn tag(&mut self, tag: String) {
1653 if !self.tags.contains(&tag) {
1654 self.tags.push(tag);
1655 }
1656 }
1657
1658 fn answer(&mut self) {
1659 self.result = Some(tilo_actions::ResultSpec::Json {
1660 schema: serde_json::json!({"type": "object"}),
1661 });
1662 }
1663}
1664
1665fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
1667 built
1668 .into_action::<R>()
1669 .ok_or_else(|| format!("not an action of a {}", R::LABEL))
1670}
1671
1672fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
1674 match args.to_json().remove(param) {
1675 Some(value) => Ok(value),
1676 None => Err(format!("`{param}` is missing")),
1677 }
1678}
1679
1680pub(crate) fn stamped_edit(
1683 vocabulary: &Vocabulary,
1684 edit: Edit<()>,
1685 now_ms: i64,
1686) -> Result<Built, String> {
1687 let Some(mut action) = (vocabulary.edit)(edit) else {
1688 return Err(format!("{} has no field edits", vocabulary.label));
1689 };
1690 action.stamp(now_ms);
1691 Ok(action)
1692}
1693
1694fn edit_declaration(
1696 vocabulary: &'static Vocabulary,
1697 id: &'static str,
1698 label: String,
1699 edit: Edit<()>,
1700) -> Declaration {
1701 let destructive = (vocabulary.edit)(edit.clone())
1702 .is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
1703 let invokes = serde_json::to_value(&edit).ok().map(|edit| {
1704 (
1705 FIELD_EDIT.to_owned(),
1706 serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
1707 )
1708 });
1709 let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
1710 let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
1711 decl.destructive = destructive;
1712 decl.invokes = invokes;
1713 decl
1714}
1715
1716thread_local! {
1717 static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
1720}
1721
1722#[must_use]
1726pub fn origin_now_ms() -> i64 {
1727 ORIGIN_CLOCK
1728 .with(std::cell::Cell::get)
1729 .unwrap_or_else(tilo_clock::unix_now_ms_i64)
1730}
1731
1732pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
1737 struct Restore(Option<i64>);
1738 impl Drop for Restore {
1739 fn drop(&mut self) {
1740 ORIGIN_CLOCK.with(|clock| clock.set(self.0));
1741 }
1742 }
1743 let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
1744 f()
1745}
1746
1747pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
1752 EncodedAction::encode(R::ACTION_TYPE, action)
1753}
1754
1755pub(crate) fn encoded(action: &Built) -> EncodedAction {
1758 match action.encode() {
1759 Ok(encoded) => encoded,
1760 Err(error) => refused(&error.to_string()),
1761 }
1762}
1763
1764pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
1767 match built {
1768 Ok(action) => encoded(&action),
1769 Err(reason) => refused(&reason),
1770 }
1771}
1772
1773pub fn child_by_id<R: Resource>(
1777 state: &R::State,
1778 doc: &Doc,
1779 id: &str,
1780) -> Option<tilo_actions::ResourceSpec> {
1781 if let Some(child) = R::child(state, id) {
1782 return Some(child);
1783 }
1784 let mut fresh = R::read(doc).ok()?;
1785 R::load(&mut fresh, doc, &child_demand(id)).ok()?;
1786 R::child(&fresh, id)
1787}
1788
1789#[inline(never)]
1792fn child_demand(id: &str) -> Demand {
1793 let key = id.rsplit('/').next().unwrap_or(id);
1796 Demand::none().with_keys([id, key])
1797}
1798
1799pub(crate) fn refused(reason: &str) -> EncodedAction {
1802 EncodedAction {
1803 type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
1804 payload: reason.as_bytes().to_vec(),
1805 }
1806}
1807
1808fn offered_bound_ids(
1810 children: &[tilo_actions::ResourceSpec],
1811 declarations: &[Declaration],
1812) -> Vec<&'static str> {
1813 let mut ids = Vec::new();
1814 for decl in declarations {
1815 if crate::items::offered_bound(children, decl) {
1816 ids.push(decl.id);
1817 }
1818 }
1819 ids
1820}
1821
1822fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
1824 least_need_of(declarations.iter().map(|decl| decl.kind))
1825}
1826
1827#[must_use]
1838pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
1839 needs.into_iter().min().map_or_else(
1840 || tilo_actions::ActionContract::default().need(),
1841 |kind| ActionNeed {
1842 kind,
1843 field: None,
1844 privileged: false,
1845 },
1846 )
1847}
1848
1849#[must_use]
1857pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
1858 spec_of_declaration(decl.as_ref())
1859}
1860
1861fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
1863 let build = Arc::clone(&decl.build);
1864 spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
1865}
1866
1867pub(crate) fn spec_of_declaration_on(
1870 decl: &Declaration,
1871 build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
1872) -> ActionSpec {
1873 let build = Arc::new(build);
1874 let label = decl.shown_label();
1875 let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
1876 encode_built(crate::content::invoking(|| {
1877 build(target, args, origin_now_ms())
1878 }))
1879 };
1880 let spec = if let Some(prompt) = &decl.content {
1881 let param = ActionParam::required_owned(
1882 tilo_actions::PROMPTED_PARAM,
1883 ParamType::Text,
1884 prompt.clone(),
1885 );
1886 ActionSpec::prompted_content_on(
1887 decl.id,
1888 label,
1889 prompt.clone(),
1890 "content hash",
1891 ExecutionLocus::ClientLocal,
1892 move |target, hash| {
1893 let supplied = [(
1894 tilo_actions::PROMPTED_PARAM.to_owned(),
1895 tilo_actions::ArgValue::Text(hash.to_owned()),
1896 )];
1897 match ActionArgs::bind(std::slice::from_ref(¶m), supplied) {
1898 Ok(args) => encoded(target, &args),
1899 Err(error) => refused(&error.to_string()),
1900 }
1901 },
1902 )
1903 } else if decl.params.is_empty() {
1904 let domain = format!("{}#{}", decl.resource, decl.id);
1908 let action_type = decl.action_type;
1909 ActionSpec::deferred_on(
1910 decl.id,
1911 label,
1912 ExecutionLocus::ClientLocal,
1913 action_type,
1914 move |target| encoded(target, &tilo_actions::ActionArgs::none()),
1915 )
1916 .with_continuation_identity(move |query| match query {
1917 tilo_actions::ContinuationQuery::Draft => {
1918 Some(tilo_actions::ContinuationEvidence::Draft {
1919 resolution_domain: tilo_actions::ContinuationKey::new(
1920 "verb",
1921 [domain.as_bytes()],
1922 ),
1923 handler: tilo_actions::ContinuationKey::new(
1924 "action-type",
1925 [action_type.as_bytes()],
1926 ),
1927 })
1928 }
1929 tilo_actions::ContinuationQuery::Exact(_) => None,
1930 })
1931 } else {
1932 ActionSpec::typed_on(
1933 decl.id,
1934 label.clone(),
1935 label,
1936 ExecutionLocus::ClientLocal,
1937 decl.shown_params(),
1938 encoded,
1939 )
1940 };
1941 let mut spec = spec.of_kind(decl.kind);
1942 if decl.by_arguments {
1946 let classify = Arc::clone(&decl.build);
1947 spec = spec.with_need_of(move |args| match classify(args, 0) {
1948 Ok(action) => action.need(),
1949 Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
1950 });
1951 }
1952 if let Some(field) = decl.field {
1953 spec = spec.below_field(field);
1954 }
1955 if let Some(description) = &decl.description {
1956 spec = spec.with_description(description.clone());
1957 }
1958 if !decl.keywords.is_empty() {
1959 spec = spec.with_keywords(decl.keywords.iter().cloned());
1960 }
1961 spec = with_declared_words(spec, decl);
1962 if decl.destructive {
1963 spec = spec.destructive();
1964 }
1965 let contract = &mut spec.type_mut().contract;
1966 (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1967 if let Some(result) = &decl.result {
1968 contract.result = result.clone();
1969 }
1970 for tag in &decl.tags {
1971 if !contract.tags.contains(tag) {
1972 contract.tags.push(tag.clone());
1973 }
1974 }
1975 contract.settle_confirmation();
1978 spec
1979}
1980
1981pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
1984 spec.type_mut().icon.clone_from(&decl.icon);
1985 spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
1986 spec
1987}
1988
1989fn declared_args(
1991 declarations: &[Declaration],
1992) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
1993 let mut args = std::collections::BTreeMap::new();
1994 for decl in declarations {
1995 args.insert(decl.id, crate::schema::args_schema(&decl.params));
1996 }
1997 args
1998}
1999
2000pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
2004 let param = ActionParam::required_owned(
2005 APPLY_PARAM,
2006 ParamType::Object,
2007 format!("A {} action, as JSON", vocabulary.label),
2008 );
2009 let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
2010 let schema = (vocabulary.action_schema)()?;
2011 Some(crate::schema::fold_declared(
2012 &schema,
2013 &declared_args(&vocabulary.declarations()),
2014 ))
2015 });
2016 match schema {
2017 Some(schema) => param.with_shared_schema(schema),
2018 None => param,
2019 }
2020}
2021
2022#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2024enum TypeSchema {
2025 Apply,
2026 Group,
2027 Edit,
2030}
2031
2032#[derive(Default)]
2033struct CompiledSchemas {
2034 epoch: u64,
2035 entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
2036}
2037
2038static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();
2039
2040#[doc(hidden)]
2044pub fn reset_type_schemas() {
2045 if let Some(cache) = SCHEMAS.get() {
2046 let mut store = cache.lock_recover();
2047 store.epoch = store.epoch.wrapping_add(1);
2048 store.entries.clear();
2049 }
2050}
2051
2052pub(crate) fn type_epoch() -> u64 {
2055 SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
2056}
2057
2058pub(crate) fn words_epoch() -> u64 {
2062 type_epoch() ^ crate::label::revision().rotate_left(32)
2063}
2064
2065fn per_type(
2068 vocabulary: &Vocabulary,
2069 schema: TypeSchema,
2070 build: &dyn Fn() -> Option<serde_json::Value>,
2071) -> Option<Arc<serde_json::Value>> {
2072 per_type_at(vocabulary, schema, "", build)
2073}
2074
2075fn per_type_at(
2077 vocabulary: &Vocabulary,
2078 schema: TypeSchema,
2079 at: &str,
2080 build: &dyn Fn() -> Option<serde_json::Value>,
2081) -> Option<Arc<serde_json::Value>> {
2082 let cache = SCHEMAS.get_or_init(Mutex::default);
2083 cached_schema(
2084 cache,
2085 ((vocabulary.type_id)(), schema, at.to_owned()),
2086 build,
2087 )
2088}
2089
2090fn cached_schema(
2091 cache: &Mutex<CompiledSchemas>,
2092 key: (TypeId, TypeSchema, String),
2093 build: &dyn Fn() -> Option<serde_json::Value>,
2094) -> Option<Arc<serde_json::Value>> {
2095 let epoch = {
2096 let store = cache.lock_recover();
2097 if let Some(found) = store.entries.get(&key) {
2098 let _phase = crate::profiling::Phase::start("schema.cached_clone");
2099 return found.clone();
2100 }
2101 store.epoch
2102 };
2103 let value = build().map(Arc::new);
2105 let mut store = cache.lock_recover();
2106 if store.epoch == epoch {
2108 store.entries.insert(key, value.clone());
2109 }
2110 value
2111}
2112
2113#[must_use]
2116pub fn by_app_refusal(label: &str) -> String {
2117 format!("{label} keeps this itself: it is not an action to invoke")
2118}
2119
2120fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
2125 let declarations = vocabulary.declarations();
2126 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2127 for decl in declarations.iter() {
2128 ids.push(decl.id);
2129 }
2130 if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
2131 && let Some(decl) = declarations.iter().find(|decl| decl.id == id)
2132 && let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
2133 {
2134 return Err(format!("{id}: {error}"));
2135 }
2136 if let Some(schema) = apply_param(vocabulary).schema {
2140 tilo_actions::validate_json_schema(&value, &schema)?;
2141 }
2142 let action = (vocabulary.read)(value)?;
2143 if action.by_app() {
2144 return Err(by_app_refusal(vocabulary.label));
2145 }
2146 Ok(action)
2147}
2148
2149pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
2158 let schema = per_type(vocabulary, TypeSchema::Group, &|| {
2159 let declarations = vocabulary.declarations();
2160 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2161 for decl in declarations.iter() {
2162 ids.push(decl.id);
2163 }
2164 Some(group_schema(&ids, vocabulary.edits))
2165 })
2166 .unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
2167 ActionParam::required_owned(
2168 crate::GROUP_PARAM,
2169 ParamType::Array,
2170 format!(
2171 "{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
2172 A member names an item an earlier member of the same group makes by its place, \
2173 {{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
2174 of the ids it made, which the group fills in as it applies",
2175 vocabulary.label
2176 ),
2177 )
2178 .with_shared_schema(schema)
2179}
2180
2181pub const APPLY_MEMBER: &str =
2184 "One action value, as the `apply` action's `apply` parameter describes it";
2185
2186pub const FIELD_EDIT_MEMBER: &str =
2189 "A field edit, as the `field-edit` action's `edit` parameter describes it";
2190
2191fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
2194 use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
2195 let mut members = Vec::new();
2196 if !ids.is_empty() {
2197 members.push(describe(
2198 object(vec![
2199 ("action", string_enum(ids), true),
2200 (
2201 "args",
2202 nullable(serde_json::json!({"type": "object"})),
2203 false,
2204 ),
2205 ]),
2206 "A named action, args as it takes them",
2207 ));
2208 }
2209 let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
2210 if edits {
2211 members.push(describe(
2212 object(vec![
2213 ("action", constant(FIELD_EDIT), true),
2214 (
2215 "args",
2216 object(vec![(
2217 EDIT_PARAM,
2218 describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
2219 true,
2220 )]),
2221 true,
2222 ),
2223 ]),
2224 "A field edit",
2225 ));
2226 }
2227 members.push(object(vec![
2228 ("action", constant(APPLY), true),
2229 ("args", object(vec![(APPLY_PARAM, action, true)]), true),
2230 ]));
2231 array(one_of(members))
2232}
2233
2234fn object_arg(
2236 args: &tilo_actions::ActionArgs,
2237 param: &str,
2238) -> Option<serde_json::Map<String, serde_json::Value>> {
2239 match args.get(param) {
2240 Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
2241 _ => None,
2242 }
2243}
2244
2245pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2246 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2247 let _phase = crate::profiling::Phase::start("resource.apply_spec");
2248 let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
2249 Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
2250 None => Err("missing action".to_owned()),
2251 };
2252 ActionSpec::typed(
2253 APPLY,
2254 format!("Apply {} edit", vocabulary.label),
2255 "Action as JSON",
2256 ExecutionLocus::ClientLocal,
2257 vec![apply_param(vocabulary)],
2258 move |args| match crate::content::invoking(|| read(args)) {
2259 Ok(mut action) => {
2260 action.stamp(origin_now_ms());
2261 encoded(&action)
2262 }
2263 Err(reason) => refused(&reason),
2264 },
2265 )
2266 .with_description(
2267 "One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
2268 )
2269 .for_audience(tilo_actions::Audience::Agents)
2272 .carrying()
2274 .with_need((vocabulary.least_need)())
2277 .of_kind((vocabulary.least_need)().kind)
2278 .with_need_of(move |args| match read(args) {
2279 Ok(action) => action.need(),
2280 Err(_) => tilo_actions::ActionContract::default().need(),
2281 })
2282 .with_risk(move |args| {
2285 let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
2286 match value.map(vocabulary.read) {
2287 Some(Ok(action)) => action.risk(),
2288 _ => tilo_actions::RiskLevel::Low,
2289 }
2290 })
2291 .with_undo_of(move |args| {
2297 let Some(value) = object_arg(args, APPLY_PARAM) else {
2298 return false;
2299 };
2300 let value = serde_json::Value::Object(value);
2301 let declarations = vocabulary.declarations();
2302 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2303 for decl in declarations.iter() {
2304 ids.push(decl.id);
2305 }
2306 let carried = crate::schema::declared_invocation(&value, &ids)
2307 .and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
2308 tilo_actions::undo_takes_back(
2309 carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
2310 tilo_actions::ChangeKind::Content,
2311 carried.is_some_and(|decl| {
2312 decl.tags
2313 .iter()
2314 .any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
2315 }),
2316 )
2317 })
2318}
2319
2320#[must_use]
2325pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
2326 spec.contract.kind
2327}
2328
2329pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
2331 ActionNeed {
2332 kind: R::kind_of(action),
2333 field: R::field_of(action).map(str::to_owned),
2334 privileged: false,
2335 }
2336}
2337
2338pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
2342 let mut needs = needs.into_iter();
2343 let Some(mut group) = needs.next() else {
2344 return tilo_actions::ActionContract::default().need();
2345 };
2346 for need in needs {
2347 group = ActionNeed {
2348 kind: group.kind.max(need.kind),
2349 field: group
2350 .field
2351 .filter(|field| need.field.as_ref() == Some(field)),
2352 privileged: group.privileged || need.privileged,
2353 };
2354 }
2355 group
2356}
2357
2358pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
2365 if let [only] = members {
2366 return encoded(only);
2367 }
2368 let mut payload = Vec::with_capacity(128);
2369 payload.push(b'[');
2370 for (index, member) in members.iter().enumerate() {
2371 if index > 0 {
2372 payload.push(b',');
2373 }
2374 if let Err(error) = member.write_json(&mut payload) {
2375 return refused(&error.to_string());
2376 }
2377 }
2378 payload.push(b']');
2379 EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
2380}
2381
2382pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2383 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2384 let _phase = crate::profiling::Phase::start("resource.group_spec");
2385 let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
2386 crate::group::build_members(vocabulary, &args.to_json(), now_ms)
2387 };
2388 ActionSpec::typed(
2389 crate::GROUP,
2390 format!("Apply several {} edits as one", vocabulary.label),
2391 "Invocations as JSON",
2392 ExecutionLocus::ClientLocal,
2393 vec![group_param(vocabulary)],
2394 move |args| match build(args, origin_now_ms()) {
2395 Ok(members) => encode_group(vocabulary, &members),
2396 Err(reason) => refused(&reason),
2397 },
2398 )
2399 .with_description(
2400 "Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
2401 )
2402 .for_audience(tilo_actions::Audience::Agents)
2405 .carrying()
2407 .with_need((vocabulary.least_need)())
2409 .with_need_of(move |args| match build(args, 0) {
2410 Ok(members) => group_need(members.iter().map(Built::need)),
2411 Err(_) => tilo_actions::ActionContract::default().need(),
2412 })
2413 .with_risk(move |args| match build(args, 0) {
2415 Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
2416 Err(_) => tilo_actions::RiskLevel::Low,
2417 })
2418 .with_undo_of(move |args| match build(args, 0) {
2421 Ok(members) => members.iter().all(Built::undoable),
2422 Err(_) => false,
2423 })
2424}
2425
2426pub use crate::search_default::default_search;
2428
2429pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
2441 publish_parts::<R>(id, label, Some(state))
2442}
2443
2444#[must_use]
2448pub(crate) fn publish_actions<R: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
2449 publish_parts::<R>(id, label, None)
2450}
2451
2452pub fn state_from_reading<R: Resource>(
2468 reading: &serde_json::Value,
2469) -> Result<R::State, ModelError> {
2470 let table = R::RESOURCE_TABLE.ok_or_else(|| {
2471 ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
2472 })?;
2473 crate::table::Run(table).from_json(reading)
2474}
2475
2476pub(crate) fn publish_parts<R: Resource>(
2480 id: &str,
2481 label: &str,
2482 state: Option<&R::State>,
2483) -> tilo_actions::ResourceSpec {
2484 let vocabulary = vocabulary::<R>();
2485 let Some(state) = state else {
2486 let own = Own {
2487 availability: None,
2488 views: Vec::new(),
2489 local_operations: R::local_operations(),
2490 now: Vec::new(),
2491 };
2492 return publish_own(vocabulary, id, label, own, &|_| false);
2493 };
2494 let children = R::children(state);
2495 let own = Own {
2496 availability: Some(&|action| R::availability(state, action)),
2497 views: R::views(state),
2498 local_operations: R::local_operations(),
2499 now: weakening_now::<R>(state),
2500 };
2501 publish_own(vocabulary, id, label, own, &|decl| {
2502 crate::items::offered_bound(&children, decl)
2503 })
2504 .with_children(children)
2505}
2506
2507pub fn unreadable_parts<R: Resource>(
2515 id: &str,
2516 label: &str,
2517 reason: &str,
2518) -> tilo_actions::ResourceSpec {
2519 let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
2520 crate::unreadable::parts::<R>(id, &label, reason)
2521}
2522
2523struct Own<'a> {
2525 availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
2528 views: Vec<tilo_actions::ResourceViewSpec>,
2529 local_operations: Vec<ActionSpec>,
2530 now: Vec<(String, String)>,
2532}
2533
2534fn publish_own(
2538 vocabulary: &'static Vocabulary,
2539 id: &str,
2540 label: &str,
2541 own: Own<'_>,
2542 offered_bound: &dyn Fn(&Declaration) -> bool,
2543) -> tilo_actions::ResourceSpec {
2544 let _phase = crate::profiling::Phase::start("resource.published");
2545 let label = crate::label::published(
2548 vocabulary.kind,
2549 label,
2550 vocabulary.label,
2551 vocabulary.catalogue,
2552 );
2553 let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
2554 resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
2556 resource.app_id = Some(vocabulary.app.to_owned());
2559 resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
2565 let kept = own_specs(vocabulary);
2566 for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
2567 let _phase = crate::profiling::Phase::start("resource.declaration_spec");
2568 let mut spec = if decl.item.is_none() && offered_bound(decl) {
2572 declared.for_agents.clone()
2573 } else {
2574 declared.offered.clone()
2575 };
2576 if let Some(availability) = own.availability {
2579 let now = availability(decl.id);
2580 if spec.contract.availability != now {
2581 spec.type_mut().contract.availability = now;
2582 }
2583 }
2584 resource = resource.with_action(spec);
2585 }
2586 for view in own.views {
2587 resource = resource.with_view(view);
2588 }
2589 crate::share::offer(&mut resource);
2590 for spec in own.local_operations {
2591 if spec.kind == OperationKind::Document {
2592 continue;
2593 }
2594 resource = resource.with_action(spec);
2595 }
2596 resource = resource
2597 .with_action(kept.apply.clone())
2598 .with_action(kept.group.clone());
2599 if vocabulary.edits {
2600 resource = resource.with_action(field_edit_spec(vocabulary, own.now));
2601 }
2602 resource
2603}
2604
2605struct OwnSpecs {
2608 declared: Box<[DeclaredSpec]>,
2610 apply: ActionSpec,
2611 group: ActionSpec,
2612}
2613
2614struct DeclaredSpec {
2617 offered: ActionSpec,
2618 for_agents: ActionSpec,
2619}
2620
2621fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
2626 thread_local! {
2627 static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
2628 std::cell::RefCell::default();
2629 }
2630 crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
2631 let declared = vocabulary
2632 .declarations()
2633 .iter()
2634 .map(|decl| {
2635 let mut offered = spec_of_declaration(decl);
2636 if let Some(item) = decl.item {
2640 offered.type_mut().contract.item = Some(item.to_owned());
2641 }
2642 let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
2643 DeclaredSpec {
2644 offered,
2645 for_agents,
2646 }
2647 })
2648 .collect();
2649 std::rc::Rc::new(OwnSpecs {
2650 declared,
2651 apply: apply_spec(vocabulary),
2652 group: group_spec(vocabulary),
2653 })
2654 })
2655}
2656
2657pub fn build_action<R: Resource>(
2660 id: &str,
2661 arguments: &serde_json::Map<String, serde_json::Value>,
2662 now_ms: i64,
2663) -> Result<R::Action, String> {
2664 typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
2665}
2666
2667pub(crate) fn build_action_of(
2670 vocabulary: &Vocabulary,
2671 id: &str,
2672 arguments: &serde_json::Map<String, serde_json::Value>,
2673 now_ms: i64,
2674) -> Result<Built, String> {
2675 crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
2676}
2677
2678fn build_invoked(
2679 vocabulary: &Vocabulary,
2680 id: &str,
2681 arguments: &serde_json::Map<String, serde_json::Value>,
2682 now_ms: i64,
2683) -> Result<Built, String> {
2684 if id == crate::GROUP {
2685 return Err("a group is several actions; build it with `group::build_group`".into());
2686 }
2687 let read = if id == APPLY {
2688 Some((APPLY_PARAM, "missing action"))
2689 } else if id == FIELD_EDIT && vocabulary.edits {
2690 Some((EDIT_PARAM, "missing edit"))
2691 } else {
2692 None
2693 };
2694 if let Some((param, missing)) = read {
2695 let Some(value) = arguments.get(param).cloned() else {
2696 return Err(missing.to_owned());
2697 };
2698 let mut action = if id == APPLY {
2699 read_apply(vocabulary, value)?
2700 } else {
2701 read_edit(vocabulary, value)?
2702 };
2703 action.stamp(now_ms);
2704 return Ok(action);
2705 }
2706 let declarations = vocabulary.declarations();
2707 let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
2708 return Err(format!("{} has no action `{id}`", vocabulary.label));
2709 };
2710 let args = match ActionArgs::bind_json(&decl.params, arguments) {
2711 Ok(args) => args,
2712 Err(error) => return Err(error.to_string()),
2713 };
2714 (decl.build)(&args, now_ms)
2715}
2716
2717#[must_use]
2726pub fn bind_declaration(
2727 resource: tilo_actions::ResourceSpec,
2728 decl: &Declaration,
2729) -> tilo_actions::ResourceSpec {
2730 let spec = spec_of_declaration(decl);
2731 let mut resource = resource;
2732 match resource
2733 .actions
2734 .iter_mut()
2735 .find(|existing| existing.id == decl.id)
2736 {
2737 Some(declared) => {
2738 if decl.refines && same_shape(&spec, declared) {
2739 *declared = spec;
2740 }
2741 resource
2742 }
2743 None => resource.with_action(spec),
2744 }
2745}
2746
2747fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
2748 let shape = |spec: &ActionSpec| {
2749 spec.params()
2750 .iter()
2751 .map(|param| (param.name.to_string(), param.ty, param.required))
2752 .collect::<Vec<_>>()
2753 };
2754 bound.kind == declared.kind
2755 && shape(bound) == shape(declared)
2756 && bound.contract.kind == declared.contract.kind
2757 && bound.contract.field == declared.contract.field
2758 && bound.contract.risk == declared.contract.risk
2759}
2760
2761pub trait SharedResource: Resource {
2768 const OWNER: &'static str;
2771}
2772
2773#[derive(Clone, Debug, Default, PartialEq, Eq)]
2774pub struct SearchRow {
2775 pub subtitle: Option<String>,
2777 pub icon: Option<String>,
2780 pub shape: SearchRowShape,
2782}
2783
2784impl SearchRow {
2785 pub fn subtitle(subtitle: impl Into<String>) -> Self {
2787 Self {
2788 subtitle: Some(subtitle.into()),
2789 ..Self::default()
2790 }
2791 }
2792
2793 #[must_use]
2795 pub fn shaped(shape: SearchRowShape) -> Self {
2796 Self {
2797 shape,
2798 ..Self::default()
2799 }
2800 }
2801
2802 #[must_use]
2804 pub fn icon(mut self, name: impl Into<String>) -> Self {
2805 self.icon = Some(name.into());
2806 self
2807 }
2808}
2809
2810#[derive(Clone, Debug, Default, PartialEq, Eq)]
2811pub enum SearchRowShape {
2812 #[default]
2814 Plain,
2815 Message {
2817 sender: String,
2818 snippet: Option<String>,
2819 date: Option<String>,
2820 unread: bool,
2821 },
2822 Media {
2826 byline: Option<String>,
2827 duration: Option<String>,
2828 },
2829 FileHit {
2831 path: String,
2832 line: Option<u32>,
2833 snippet: String,
2834 },
2835}
2836
2837pub use tilo_actions::{ScopeDecl, scope_contains};
2838
2839#[cfg(test)]
2840mod schema_sharing_tests;
2841
2842#[cfg(test)]
2843mod selection_place_tests {
2844 use super::Place;
2845 use tilo_actions::SelectionPlace;
2846 use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;
2847
2848 #[test]
2849 fn a_selection_place_is_the_place_an_action_takes() {
2850 for (place, expected_json) in [
2851 (Place::Item("p1".into()), r#"{"item":"p1"}"#),
2852 (
2853 Place::Caret {
2854 item: "p1".into(),
2855 at: 3,
2856 },
2857 r#"{"item":"p1","at":3}"#,
2858 ),
2859 (
2860 Place::Range {
2861 item: "p1".into(),
2862 start: 2,
2863 end: 7,
2864 },
2865 r#"{"item":"p1","start":2,"end":7}"#,
2866 ),
2867 (
2868 Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
2869 &format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
2870 ),
2871 ] {
2872 let wire = serde_json::to_string(&place).unwrap();
2873 assert_eq!(wire, expected_json, "valid places serialise as before");
2874 let selection = SelectionPlace::from(place.clone());
2875 assert_eq!(
2876 serde_json::to_string(&selection).unwrap(),
2877 wire,
2878 "both travel in one wire form"
2879 );
2880 assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
2881 assert_eq!(Place::try_from(selection).unwrap(), place);
2882 }
2883
2884 let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
2885 let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
2886 assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);
2887
2888 for bad_item in [
2889 String::new(),
2890 overlong_ascii,
2891 overlong_utf8,
2892 "p\n1".to_owned(),
2893 "p\u{0}1".to_owned(),
2894 "p\x1b1".to_owned(),
2895 "p\t1".to_owned(),
2896 ] {
2897 for selection in [
2898 SelectionPlace::item(bad_item.clone()),
2899 SelectionPlace::caret(bad_item.clone(), 0),
2900 SelectionPlace::range(bad_item.clone(), 0, 1),
2901 ] {
2902 assert!(
2903 Place::try_from(selection.clone()).is_err(),
2904 "Place::try_from accepted invalid SelectionPlace: {selection:?}"
2905 );
2906 let json = serde_json::to_value(&selection).unwrap();
2907 assert!(
2908 serde_json::from_value::<Place>(json.clone()).is_err(),
2909 "Place::deserialize accepted invalid JSON: {json}"
2910 );
2911 }
2912 }
2913
2914 for malformed in [
2915 serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
2916 serde_json::json!({"item": "p1", "start": 2}),
2917 serde_json::json!({"item": "p1", "end": 2}),
2918 serde_json::json!({"item": "p1", "start": 5, "end": 2}),
2919 ] {
2920 let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
2921 let from_selection = Place::try_from(wire).unwrap_err();
2922 let from_json = serde_json::from_value::<Place>(malformed)
2923 .unwrap_err()
2924 .to_string();
2925 for error in [&from_selection, &from_json] {
2926 assert!(
2927 error.contains("at") && error.contains("start") && error.contains("end"),
2928 "malformed-shape error should name `at` and `start`/`end`: {error}"
2929 );
2930 }
2931 }
2932 assert!(
2933 serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
2934 .is_err()
2935 );
2936 }
2937}