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 const MIGRATES: bool = false;
446
447 fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
451 let _ = doc;
452 Err(ModelError::invalid(format!(
453 "{} has no migration from storage version {from}",
454 Self::LABEL
455 )))
456 }
457
458 #[must_use]
461 fn surface() -> crate::surface::Surface {
462 crate::surface::surface_of::<Self>()
463 }
464
465 const EDITS: bool = false;
468
469 fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
472 let _ = edit;
473 None
474 }
475
476 fn stamp(action: &mut Self::Action, now_ms: i64) {
479 let _ = (action, now_ms);
480 }
481
482 fn op_schemas() -> Vec<(String, serde_json::Value)> {
486 Vec::new()
487 }
488
489 fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
492 let _ = (state, action);
493 tilo_actions::Availability::Available
494 }
495
496 fn seed() -> Option<Self::Action> {
499 None
500 }
501
502 fn kind_of(action: &Self::Action) -> ActionKind {
506 let _ = action;
507 ActionKind::Undoable
508 }
509
510 fn by_app(action: &Self::Action) -> bool {
517 let _ = action;
518 false
519 }
520
521 fn build_by_app(
526 id: &str,
527 arguments: &serde_json::Map<String, serde_json::Value>,
528 now_ms: i64,
529 ) -> Option<Result<Self::Action, String>> {
530 let _ = (id, arguments, now_ms);
531 None
532 }
533
534 fn action_item(action: &Self::Action) -> Option<crate::Id> {
539 let _ = action;
540 None
541 }
542
543 fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
548 let _ = action;
549 None
550 }
551
552 fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
556 let _ = (action, keep);
557 None
558 }
559
560 fn register(registry: &mut ActionRegistry) {
563 registry.register::<Self::Action>(Self::ACTION_TYPE);
564 }
565}
566
567pub trait NamesItem: Clone {
570 fn named_item(&self) -> Option<crate::Id>;
571}
572
573impl NamesItem for crate::Id {
574 fn named_item(&self) -> Option<crate::Id> {
575 Some(self.clone())
576 }
577}
578
579impl NamesItem for String {
580 fn named_item(&self) -> Option<crate::Id> {
581 Some(crate::Id::from_raw(self.clone()))
582 }
583}
584
585#[doc(hidden)]
587pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
588 entries.iter().map(NamesItem::named_item).collect()
589}
590
591#[doc(hidden)]
593#[must_use]
594pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
595 keep.iter()
596 .filter_map(|at| entries.get(*at).cloned())
597 .collect()
598}
599
600pub const APPLY: &str = "apply";
612pub const APPLY_PARAM: &str = "action";
614
615pub const FIELD_EDIT: &str = "field-edit";
618pub const EDIT_PARAM: &str = "edit";
620
621fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
623 let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
624 match (vocabulary.edit)(edit) {
625 Some(action) => Ok(action),
626 None => Err(format!("{} has no field edits", vocabulary.label)),
627 }
628}
629
630pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
636 let ops = (vocabulary.op_schemas)();
637 if let Some(shape) = (vocabulary.shape)()
638 && !shape.fields().is_empty()
639 {
640 let mut alternatives = Vec::new();
641 edit_paths(shape, &[], "", &ops, &mut alternatives);
642 if !alternatives.is_empty() {
643 return described_edit(&alternatives, &ops);
644 }
645 }
646 generic_edit_schema(&ops, |_| true)
647}
648
649fn described_edit(
654 alternatives: &[serde_json::Value],
655 ops: &[(String, serde_json::Value)],
656) -> serde_json::Value {
657 let taken: Vec<String> = alternatives
660 .iter()
661 .filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
662 .flatten()
663 .filter_map(serde_json::Value::as_str)
664 .map(str::to_owned)
665 .collect();
666 let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
667 let mut lines = vec![
668 "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(),
669 ];
670 let mut examples = Vec::new();
671 let mut shapes: Vec<Vec<String>> = Vec::new();
672 let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
675 let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
676 for (alternative, next) in alternatives.iter().zip(nexts) {
677 let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
678 let template = at("/properties/path/examples/0");
679 let ops: Vec<String> = at("/properties/op/enum")
680 .as_array()
681 .map(|ops| {
682 ops.iter()
683 .filter_map(serde_json::Value::as_str)
684 .map(str::to_owned)
685 .collect()
686 })
687 .unwrap_or_default();
688 let value = at("/properties/value");
689 let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
690 let title = text("/title");
691 let shape: Vec<String> = template
694 .as_array()
695 .map(|steps| {
696 steps
697 .iter()
698 .filter_map(|step| step.as_object()?.keys().next().cloned())
699 .collect()
700 })
701 .unwrap_or_default();
702 let leaf = next.is_none_or(|next| {
707 next.get("title")
708 .and_then(serde_json::Value::as_str)
709 .is_none_or(|next| !next.starts_with(&format!("{title}.")))
710 });
711 let in_resource = shape
712 .iter()
713 .rev()
714 .take(2)
715 .filter(|kind| *kind == "field")
716 .count()
717 == 2;
718 let record = title
719 .rsplit_once('.')
720 .and_then(|(parent, key)| {
721 listed
722 .iter_mut()
723 .find(|(path, ..)| path == parent)
724 .map(|(_, _, fields)| (fields, key))
725 })
726 .filter(|_| in_resource && leaf && ops == ["set"]);
727 if let Some((fields, key)) = record {
728 fields.push(format!("`{key}`"));
729 } else {
730 let kind = value_kind(&value);
731 let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
732 let line = format!(
733 "- `{title}`: {} — {}{}",
734 usage.join(", "),
735 text("/description"),
736 kind.map_or_else(String::new, |kind| format!(" ({kind})")),
737 );
738 listed.push((title.clone(), line, Vec::new()));
739 }
740 if shapes.contains(&shape) {
741 continue;
742 }
743 shapes.push(shape);
744 let mut example = serde_json::Map::new();
745 example.insert("path".into(), template);
746 if let Some(op) = ops.first() {
747 example.insert("op".into(), op.clone().into());
748 }
749 examples.push(serde_json::Value::Object(example));
750 }
751 lines.extend(listed.into_iter().map(|(_, line, fields)| {
752 if fields.is_empty() {
753 line
754 } else {
755 format!("{line}; set one field of it: {}", fields.join(", "))
756 }
757 }));
758 if let Some(object) = schema.as_object_mut() {
759 object.insert("description".into(), lines.join("\n").into());
760 object.insert("examples".into(), examples.into());
761 }
762 schema
763}
764
765fn value_kind(schema: &serde_json::Value) -> Option<String> {
770 if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
771 let options: Vec<String> = options
772 .iter()
773 .map(|option| {
774 option
775 .as_str()
776 .map_or_else(|| option.to_string(), str::to_owned)
777 })
778 .collect();
779 return Some(format!("one of {}", options.join(", ")));
780 }
781 match schema.get("type")? {
782 serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
783 serde_json::Value::Array(kinds) => Some(
784 kinds
785 .iter()
786 .filter_map(serde_json::Value::as_str)
787 .collect::<Vec<_>>()
788 .join(" or "),
789 ),
790 _ => None,
791 }
792}
793
794fn generic_edit_schema(
797 ops: &[(String, serde_json::Value)],
798 takes: impl Fn(&str) -> bool,
799) -> serde_json::Value {
800 let ops = ops.to_vec();
801 let mut schema = crate::path::edit_schema_taking(&takes);
802 if !ops.is_empty()
803 && takes("rich")
804 && let Some(properties) = schema
805 .get_mut("properties")
806 .and_then(serde_json::Value::as_object_mut)
807 {
808 let description = ops
814 .into_iter()
815 .map(|(path, schema)| {
816 format!(
817 "An edit of `{path}` in its own vocabulary, one of: {}",
818 crate::schema::summary(&schema)
819 )
820 })
821 .collect::<Vec<_>>()
822 .join("\n");
823 properties.insert(
824 "rich".into(),
825 crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
826 );
827 }
828 schema
829}
830
831fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
832 let mut properties = serde_json::Map::new();
833 properties.insert(kind.to_owned(), value);
834 serde_json::json!({
835 "type": "object",
836 "properties": properties,
837 "required": [kind],
838 })
839}
840
841fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
844 let ty = field.ty;
845 if ty.rsplit("::").next() == Some("Reactions") {
847 return vec!["react", "unreact"];
848 }
849 match field.shape {
850 crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
851 vec![
852 "upsert-item",
853 "insert-item",
854 "remove-item",
855 "move-to",
856 "set",
857 ]
858 }
859 _ if rich => vec!["replace", "rich"],
862 _ if ty.starts_with("Counter") => vec!["add", "set"],
863 _ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
864 _ if ty.starts_with("Grid<") => vec![
865 "set-cell",
866 "insert-row",
867 "insert-column",
868 "remove-row",
869 "remove-column",
870 ],
871 _ if ty.starts_with("Outbox") => vec!["settle", "forget"],
872 crate::Shape::Map(_) => vec!["set", "remove-key"],
873 _ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
874 _ => vec!["set"],
875 }
876}
877
878fn takes_own_verbs(field: &crate::FieldShape) -> bool {
882 let ops = field_ops(field, false);
883 ops.iter()
884 .any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
885}
886
887fn rich_schema_at<'a>(
890 rich: &'a [(String, serde_json::Value)],
891 at: &str,
892) -> Option<&'a serde_json::Value> {
893 rich.iter()
894 .find(|(path, _)| path == at)
895 .map(|(_, schema)| schema)
896}
897
898#[allow(
899 clippy::too_many_lines,
900 reason = "one walk over the stored shape, an alternative per kind of path"
901)]
902fn edit_paths(
903 shape: crate::Shape,
904 steps: &[serde_json::Value],
905 dotted: &str,
906 rich: &[(String, serde_json::Value)],
907 out: &mut Vec<serde_json::Value>,
908) {
909 let alternative = |steps: &[serde_json::Value],
910 open: bool,
911 ops: &[&str],
912 value: serde_json::Value,
913 rich: Option<&serde_json::Value>,
914 title: &str,
915 description: String| {
916 let template: Vec<serde_json::Value> = steps
918 .iter()
919 .map(|step| {
920 let properties = step.get("properties").and_then(serde_json::Value::as_object);
921 match properties.and_then(|properties| properties.iter().next()) {
922 Some((kind, value)) if kind == "field" => {
923 serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
924 }
925 Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
926 None => serde_json::Value::Null,
927 }
928 })
929 .collect();
930 let dotted: Vec<String> = template
931 .iter()
932 .map(
933 |step| match step.get("field").and_then(serde_json::Value::as_str) {
934 Some(field) => field.to_owned(),
935 None => "*".to_owned(),
936 },
937 )
938 .collect();
939 let mut path = serde_json::json!({
940 "type": "array",
941 "prefixItems": steps,
942 "minItems": steps.len(),
943 "examples": [template],
944 });
945 if let Some(path) = path.as_object_mut() {
946 if open {
947 path.insert("items".into(), serde_json::json!({ "type": "object" }));
949 } else {
950 path.insert("maxItems".into(), steps.len().into());
951 }
952 }
953 let mut properties = serde_json::Map::new();
954 properties.insert("path".into(), path);
955 properties.insert("op".into(), serde_json::json!({ "enum": ops }));
956 properties.insert("value".into(), value);
957 if ops.contains(&"upsert-item") {
958 properties.insert(
959 "match".into(),
960 serde_json::json!({
961 "type": "object",
962 "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"
963 }),
964 );
965 properties.insert(
966 "at".into(),
967 serde_json::json!({
968 "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
969 "anyOf": [
970 { "const": "end" },
971 { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
972 { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
973 { "type": "integer", "minimum": 0 }
974 ]
975 }),
976 );
977 }
978 if let Some(rich) = rich {
979 properties.insert("rich".into(), rich.clone());
980 }
981 serde_json::json!({
982 "title": dotted.join("."),
983 "description": if description.is_empty() {
984 title.to_owned()
985 } else {
986 format!("{title}; {description}")
987 },
988 "type": "object",
989 "properties": properties,
990 "required": ["path", "op"],
991 })
992 };
993 let item = step_schema("item", serde_json::json!({ "type": "string" }));
994 for field in shape
998 .fields()
999 .iter()
1000 .filter(|field| !field.readonly || takes_own_verbs(field))
1001 {
1002 let mut here = steps.to_vec();
1003 here.push(step_schema(
1004 "field",
1005 serde_json::json!({ "const": field.key }),
1006 ));
1007 let path = format!("{dotted}{}", field.key);
1008 let rich_schema = rich_schema_at(rich, &path);
1009 let ops = field_ops(field, rich_schema.is_some());
1010 let collection = matches!(
1011 field.shape,
1012 crate::Shape::Collection(_) | crate::Shape::Keyed(_)
1013 );
1014 let simple = ops.first() == Some(&"set") && !collection;
1017 let value = if simple {
1018 (field.schema)()
1019 } else {
1020 serde_json::json!({})
1021 };
1022 let mut flags = Vec::new();
1023 if field.unit {
1024 flags.push("its own storage unit".to_owned());
1025 }
1026 match field.trust {
1027 crate::Trust::Ordinary => {}
1028 crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
1029 crate::Trust::Weakens(_) => flags.push(
1030 "making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
1031 .to_owned(),
1032 ),
1033 crate::Trust::Weakening => flags.push(
1034 "changing it can weaken security: it asks for confirmation and needs the person's own grant"
1035 .to_owned(),
1036 ),
1037 }
1038 if collection {
1039 flags.push(if field.quiet_remove {
1042 "removing an item asks nothing".to_owned()
1043 } else {
1044 "removing an item asks nothing; Undo takes it back".to_owned()
1045 });
1046 }
1047 let description = flags.join("; ");
1048 out.push(alternative(
1049 &here,
1050 false,
1051 &ops,
1052 value,
1053 rich_schema,
1054 field.title,
1055 description,
1056 ));
1057 match field.shape {
1058 crate::Shape::Record(_) => {
1059 edit_paths(field.shape, &here, &format!("{path}."), rich, out);
1060 }
1061 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
1062 let mut items = here.clone();
1063 items.push(item.clone());
1064 let item_value = (field.schema)().get("items").map_or_else(
1065 || serde_json::json!({}),
1066 |items| {
1067 items
1069 .get("properties")
1070 .and_then(|properties| properties.get("value"))
1071 .cloned()
1072 .unwrap_or_else(|| items.clone())
1073 },
1074 );
1075 let item_ops: &[&str] = match *inner {
1078 crate::Shape::Value => &["set", "splice", "replace", "rich"],
1079 _ => &["set"],
1080 };
1081 out.push(alternative(
1082 &items,
1083 false,
1084 item_ops,
1085 item_value,
1086 None,
1087 field.title,
1088 "one item, by its id".to_owned(),
1089 ));
1090 edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
1091 }
1092 crate::Shape::Value if field.ty.starts_with("Grid<") => {
1093 let mut cells = here.clone();
1094 cells.push(step_schema(
1095 "cell",
1096 serde_json::json!({
1097 "type": "object",
1098 "properties": {
1099 "row": { "type": "string" },
1100 "column": { "type": "string" },
1101 },
1102 "required": ["row", "column"],
1103 }),
1104 ));
1105 out.push(alternative(
1106 &cells,
1107 true,
1108 &[
1109 "set", "splice", "replace", "add", "insert", "remove", "rich",
1110 ],
1111 serde_json::json!({}),
1112 None,
1113 field.title,
1114 "a cell, by its row and column ids, and what is inside it".to_owned(),
1115 ));
1116 }
1117 crate::Shape::Map(_) => {
1118 let mut entries = here.clone();
1119 entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
1120 let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
1122 let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
1123 if entry_rich.is_some() {
1124 ops.push("rich");
1125 }
1126 out.push(alternative(
1127 &entries,
1128 true,
1129 &ops,
1130 serde_json::json!({}),
1131 entry_rich,
1132 field.title,
1133 "an entry, by its key, and what is inside it".to_owned(),
1134 ));
1135 }
1136 crate::Shape::Value => {}
1137 }
1138 }
1139}
1140
1141mod field_edit;
1142use field_edit::rooted_edit_spec;
1143
1144pub(crate) fn field_edit_spec(
1147 vocabulary: &'static Vocabulary,
1148 now: Vec<(String, String)>,
1149) -> ActionSpec {
1150 let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
1153 Some(edit_schema(vocabulary))
1154 })
1155 .unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
1156 rooted_edit_spec(
1157 vocabulary,
1158 (vocabulary.shape)(),
1159 schema,
1160 format!("Edit a {} field", vocabulary.label),
1161 "The path of the field from the record's root, and the operation",
1162 now,
1163 )
1164}
1165
1166fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
1170 weakening_in(R::shape(), &|| R::state_json(state))
1171}
1172
1173#[inline(never)]
1177fn weakening_in(
1178 shape: Option<crate::Shape>,
1179 json: &dyn Fn() -> Option<serde_json::Value>,
1180) -> Vec<(String, String)> {
1181 let Some(shape) = shape else {
1182 return Vec::new();
1183 };
1184 let fields: Vec<String> = shape
1185 .guarded_fields()
1186 .into_iter()
1187 .filter(|(path, trust)| {
1188 matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
1189 })
1190 .map(|(path, _)| path)
1191 .collect();
1192 if fields.is_empty() {
1193 return Vec::new();
1194 }
1195 let Some(json) = json() else {
1196 return Vec::new();
1197 };
1198 fields
1199 .into_iter()
1200 .filter_map(|path| {
1201 let value = path
1202 .split('.')
1203 .try_fold(&json, |value, key| value.get(key))?
1204 .to_string();
1205 Some((path, value))
1206 })
1207 .collect()
1208}
1209
1210#[must_use]
1213pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
1214 item_field_edit_spec_of(vocabulary::<R>(), field, item)
1215}
1216
1217pub(crate) fn item_field_edit_spec_of(
1219 vocabulary: &'static Vocabulary,
1220 field: &str,
1221 item: &crate::Id,
1222) -> Option<ActionSpec> {
1223 field_edit_spec_at_of(
1224 vocabulary,
1225 vec![
1226 crate::Segment::Field(field.to_owned()),
1227 crate::Segment::Item(item.clone()),
1228 ],
1229 )
1230}
1231
1232#[must_use]
1236pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
1237 field_edit_spec_at_of(vocabulary::<R>(), prefix)
1238}
1239
1240pub(crate) fn field_edit_spec_at_of(
1242 vocabulary: &'static Vocabulary,
1243 prefix: Vec<crate::Segment>,
1244) -> Option<ActionSpec> {
1245 let mut shape = (vocabulary.shape)()?;
1246 let mut dotted = String::new();
1247 let mut readonly = false;
1248 for segment in &prefix {
1249 match (shape, segment) {
1250 (crate::Shape::Record(fields), crate::Segment::Field(key)) => {
1251 let field = fields.iter().find(|candidate| candidate.key == key)?;
1252 readonly |= field.readonly;
1253 shape = field.shape;
1254 dotted.push_str(key);
1255 dotted.push('.');
1256 }
1257 (
1258 crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
1259 crate::Segment::Item(_),
1260 ) => {
1261 shape = *inner;
1262 dotted.push_str("*.");
1263 }
1264 _ => return None,
1265 }
1266 }
1267 if shape.fields().is_empty() || readonly {
1268 return None;
1269 }
1270 thread_local! {
1273 static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
1274 }
1275 let key = ((vocabulary.type_id)(), dotted.clone());
1276 crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
1277 .map(|ty| ty.bind(Target::new(prefix)))
1278}
1279
1280fn item_edit_type(
1283 vocabulary: &'static Vocabulary,
1284 shape: crate::Shape,
1285 dotted: &str,
1286) -> Option<Arc<ActionType>> {
1287 let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
1288 let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
1289 .into_iter()
1290 .filter_map(|(path, schema)| {
1291 path.strip_prefix(dotted)
1292 .map(|rest| (rest.to_owned(), schema))
1293 })
1294 .collect();
1295 let mut alternatives = Vec::new();
1296 edit_paths(shape, &[], "", &ops, &mut alternatives);
1297 (!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
1298 })?;
1299 let spec = rooted_edit_spec(
1300 vocabulary,
1301 Some(shape),
1302 schema,
1303 "Edit a field of this item".to_owned(),
1304 "The path of the field from the item, and the operation",
1305 Vec::new(),
1306 );
1307 Some(Arc::clone(spec.action_type()))
1308}
1309
1310#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
1316pub enum NoAction {}
1317
1318impl tilo_actions::Action for NoAction {
1319 fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
1321 Ok(())
1322 }
1323}
1324
1325#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1332#[serde(into = "tilo_actions::SelectionPlace")]
1333pub enum Place {
1334 Item(String),
1336 Caret { item: String, at: usize },
1338 Range {
1340 item: String,
1341 start: usize,
1342 end: usize,
1343 },
1344}
1345
1346impl Place {
1347 #[must_use]
1349 pub fn item(&self) -> &str {
1350 match self {
1351 Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
1352 }
1353 }
1354}
1355
1356impl<'de> serde::Deserialize<'de> for Place {
1364 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1365 let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
1366 match place_from_json(value) {
1367 Ok(place) => Ok(place),
1368 Err(error) => Err(serde::de::Error::custom(error)),
1369 }
1370 }
1371}
1372
1373fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
1375 match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
1376 Ok(wire) => Place::try_from(wire),
1377 Err(error) => Err(error.to_string()),
1378 }
1379}
1380
1381impl crate::JsonSchema for Place {
1382 fn json_schema() -> serde_json::Value {
1383 tilo_actions::place_schema()
1384 }
1385}
1386
1387impl From<Place> for tilo_actions::SelectionPlace {
1390 fn from(place: Place) -> Self {
1391 match place {
1392 Place::Item(item) => Self::item(item),
1393 Place::Caret { item, at } => Self::caret(item, at),
1394 Place::Range { item, start, end } => Self::range(item, start, end),
1395 }
1396 }
1397}
1398
1399impl TryFrom<tilo_actions::SelectionPlace> for Place {
1400 type Error = String;
1401
1402 fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
1403 match place.validated_span()? {
1404 tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
1405 tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
1406 item: place.item,
1407 at,
1408 }),
1409 tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
1410 item: place.item,
1411 start,
1412 end,
1413 }),
1414 }
1415 }
1416}
1417
1418pub type BuildAction<R> =
1422 Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;
1423
1424pub struct ActionDecl<R: Resource> {
1427 decl: Declaration,
1428 marker: std::marker::PhantomData<fn() -> R>,
1429}
1430
1431impl<R: Resource> Clone for ActionDecl<R> {
1432 fn clone(&self) -> Self {
1433 Self {
1434 decl: self.decl.clone(),
1435 marker: std::marker::PhantomData,
1436 }
1437 }
1438}
1439
1440impl<R: Resource> std::ops::Deref for ActionDecl<R> {
1441 type Target = Declaration;
1442
1443 fn deref(&self) -> &Declaration {
1444 &self.decl
1445 }
1446}
1447
1448impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
1449 fn as_ref(&self) -> &Declaration {
1450 &self.decl
1451 }
1452}
1453
1454impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
1455 fn deref_mut(&mut self) -> &mut Declaration {
1456 &mut self.decl
1457 }
1458}
1459
1460impl<R: Resource> ActionDecl<R> {
1461 pub fn edit_asking<V>(
1467 id: &'static str,
1468 label: impl Into<String>,
1469 param: &'static str,
1470 description: &'static str,
1471 make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
1472 ) -> Self
1473 where
1474 V: DeserializeOwned + crate::JsonSchema,
1475 {
1476 let schema = V::json_schema();
1477 let declared = ActionParam::required_owned(
1478 param,
1479 crate::__private::param_type_of(&schema),
1480 description,
1481 )
1482 .with_schema(schema);
1483 let vocabulary = vocabulary::<R>();
1484 let build: Builds = Arc::new(move |args, now_ms| {
1485 let value = taken_arg(args, param)?;
1486 let value: V = match serde_json::from_value(value) {
1487 Ok(value) => value,
1488 Err(error) => return Err(format!("`{param}`: {error}")),
1489 };
1490 stamped_edit(vocabulary, make(value).retyped(), now_ms)
1491 });
1492 Self::declared(Declaration::new(
1493 vocabulary,
1494 id,
1495 label.into(),
1496 vec![declared],
1497 build,
1498 ))
1499 }
1500
1501 pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
1505 where
1506 crate::Edit<R>: Send + Sync,
1507 {
1508 Self::declared(edit_declaration(
1509 vocabulary::<R>(),
1510 id,
1511 label.into(),
1512 edit.retyped(),
1513 ))
1514 }
1515
1516 pub fn new(
1517 id: &'static str,
1518 label: impl Into<String>,
1519 params: Vec<ActionParam>,
1520 build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
1521 ) -> Self {
1522 let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
1523 Ok(action) => Ok(Built::of::<R>(action)),
1524 Err(reason) => Err(reason),
1525 });
1526 Self::declared(Declaration::new(
1527 vocabulary::<R>(),
1528 id,
1529 label.into(),
1530 params,
1531 build,
1532 ))
1533 }
1534
1535 pub(crate) fn declared(decl: Declaration) -> Self {
1536 Self {
1537 decl,
1538 marker: std::marker::PhantomData,
1539 }
1540 }
1541
1542 #[must_use]
1545 pub fn with_arguments(
1546 &self,
1547 arguments: serde_json::Map<String, serde_json::Value>,
1548 ) -> crate::Invoke<R> {
1549 crate::Invoke::bound(self.decl.id, Ok(arguments))
1550 }
1551
1552 #[must_use]
1554 pub fn into_declaration(self) -> Declaration {
1555 self.decl
1556 }
1557
1558 pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
1560 typed::<R>(crate::content::invoking(|| {
1561 (self.decl.build)(args, now_ms)
1562 })?)
1563 }
1564
1565 #[must_use]
1568 pub fn refining(mut self) -> Self {
1569 self.decl.refines = true;
1570 self
1571 }
1572
1573 #[must_use]
1578 pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
1579 self.decl.tags.retain(|tag| {
1580 tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
1581 });
1582 if let Some(tag) = audience.tag() {
1583 self.decl.tags.push(tag.to_owned());
1584 }
1585 self
1586 }
1587
1588 #[must_use]
1591 pub fn tagged(mut self, tag: impl Into<String>) -> Self {
1592 self.decl.tag(tag.into());
1593 self
1594 }
1595
1596 #[must_use]
1597 pub fn describe(mut self, description: impl Into<String>) -> Self {
1598 self.decl.description = Some(description.into());
1599 self
1600 }
1601
1602 #[must_use]
1605 pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
1606 self.decl.result = Some(result);
1607 self
1608 }
1609
1610 #[must_use]
1612 pub fn of_kind(mut self, kind: ActionKind) -> Self {
1613 self.decl.kind = kind;
1614 self
1615 }
1616
1617 #[must_use]
1619 pub fn below_field(mut self, field: &'static str) -> Self {
1620 self.decl.field = Some(field);
1621 self
1622 }
1623
1624 #[must_use]
1625 pub fn destructive(mut self) -> Self {
1626 self.decl.destructive = true;
1627 self
1628 }
1629
1630 #[must_use]
1633 pub fn writing(mut self, units: Vec<String>) -> Self {
1634 self.decl.writes = units;
1635 self
1636 }
1637
1638 #[must_use]
1641 pub fn answering(mut self) -> Self {
1642 self.decl.answer();
1643 self
1644 }
1645}
1646
1647impl Declaration {
1648 fn tag(&mut self, tag: String) {
1649 if !self.tags.contains(&tag) {
1650 self.tags.push(tag);
1651 }
1652 }
1653
1654 fn answer(&mut self) {
1655 self.result = Some(tilo_actions::ResultSpec::Json {
1656 schema: serde_json::json!({"type": "object"}),
1657 });
1658 }
1659}
1660
1661fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
1663 built
1664 .into_action::<R>()
1665 .ok_or_else(|| format!("not an action of a {}", R::LABEL))
1666}
1667
1668fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
1670 match args.to_json().remove(param) {
1671 Some(value) => Ok(value),
1672 None => Err(format!("`{param}` is missing")),
1673 }
1674}
1675
1676pub(crate) fn stamped_edit(
1679 vocabulary: &Vocabulary,
1680 edit: Edit<()>,
1681 now_ms: i64,
1682) -> Result<Built, String> {
1683 let Some(mut action) = (vocabulary.edit)(edit) else {
1684 return Err(format!("{} has no field edits", vocabulary.label));
1685 };
1686 action.stamp(now_ms);
1687 Ok(action)
1688}
1689
1690fn edit_declaration(
1692 vocabulary: &'static Vocabulary,
1693 id: &'static str,
1694 label: String,
1695 edit: Edit<()>,
1696) -> Declaration {
1697 let destructive = (vocabulary.edit)(edit.clone())
1698 .is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
1699 let invokes = serde_json::to_value(&edit).ok().map(|edit| {
1700 (
1701 FIELD_EDIT.to_owned(),
1702 serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
1703 )
1704 });
1705 let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
1706 let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
1707 decl.destructive = destructive;
1708 decl.invokes = invokes;
1709 decl
1710}
1711
1712thread_local! {
1713 static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
1716}
1717
1718#[must_use]
1722pub fn origin_now_ms() -> i64 {
1723 ORIGIN_CLOCK
1724 .with(std::cell::Cell::get)
1725 .unwrap_or_else(tilo_clock::unix_now_ms_i64)
1726}
1727
1728pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
1733 struct Restore(Option<i64>);
1734 impl Drop for Restore {
1735 fn drop(&mut self) {
1736 ORIGIN_CLOCK.with(|clock| clock.set(self.0));
1737 }
1738 }
1739 let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
1740 f()
1741}
1742
1743pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
1748 EncodedAction::encode(R::ACTION_TYPE, action)
1749}
1750
1751pub(crate) fn encoded(action: &Built) -> EncodedAction {
1754 match action.encode() {
1755 Ok(encoded) => encoded,
1756 Err(error) => refused(&error.to_string()),
1757 }
1758}
1759
1760pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
1763 match built {
1764 Ok(action) => encoded(&action),
1765 Err(reason) => refused(&reason),
1766 }
1767}
1768
1769pub fn child_by_id<R: Resource>(
1773 state: &R::State,
1774 doc: &Doc,
1775 id: &str,
1776) -> Option<tilo_actions::ResourceSpec> {
1777 if let Some(child) = R::child(state, id) {
1778 return Some(child);
1779 }
1780 let mut fresh = R::read(doc).ok()?;
1781 R::load(&mut fresh, doc, &child_demand(id)).ok()?;
1782 R::child(&fresh, id)
1783}
1784
1785#[inline(never)]
1788fn child_demand(id: &str) -> Demand {
1789 let key = id.rsplit('/').next().unwrap_or(id);
1792 Demand::none().with_keys([id, key])
1793}
1794
1795pub(crate) fn refused(reason: &str) -> EncodedAction {
1798 EncodedAction {
1799 type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
1800 payload: reason.as_bytes().to_vec(),
1801 }
1802}
1803
1804fn offered_bound_ids(
1806 children: &[tilo_actions::ResourceSpec],
1807 declarations: &[Declaration],
1808) -> Vec<&'static str> {
1809 let mut ids = Vec::new();
1810 for decl in declarations {
1811 if crate::items::offered_bound(children, decl) {
1812 ids.push(decl.id);
1813 }
1814 }
1815 ids
1816}
1817
1818fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
1820 least_need_of(declarations.iter().map(|decl| decl.kind))
1821}
1822
1823#[must_use]
1834pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
1835 needs.into_iter().min().map_or_else(
1836 || tilo_actions::ActionContract::default().need(),
1837 |kind| ActionNeed {
1838 kind,
1839 field: None,
1840 privileged: false,
1841 },
1842 )
1843}
1844
1845#[must_use]
1853pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
1854 spec_of_declaration(decl.as_ref())
1855}
1856
1857fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
1859 let build = Arc::clone(&decl.build);
1860 spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
1861}
1862
1863pub(crate) fn spec_of_declaration_on(
1866 decl: &Declaration,
1867 build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
1868) -> ActionSpec {
1869 let build = Arc::new(build);
1870 let label = decl.shown_label();
1871 let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
1872 encode_built(crate::content::invoking(|| {
1873 build(target, args, origin_now_ms())
1874 }))
1875 };
1876 let spec = if let Some(prompt) = &decl.content {
1877 let param = ActionParam::required_owned(
1878 tilo_actions::PROMPTED_PARAM,
1879 ParamType::Text,
1880 prompt.clone(),
1881 );
1882 ActionSpec::prompted_content_on(
1883 decl.id,
1884 label,
1885 prompt.clone(),
1886 "content hash",
1887 ExecutionLocus::ClientLocal,
1888 move |target, hash| {
1889 let supplied = [(
1890 tilo_actions::PROMPTED_PARAM.to_owned(),
1891 tilo_actions::ArgValue::Text(hash.to_owned()),
1892 )];
1893 match ActionArgs::bind(std::slice::from_ref(¶m), supplied) {
1894 Ok(args) => encoded(target, &args),
1895 Err(error) => refused(&error.to_string()),
1896 }
1897 },
1898 )
1899 } else if decl.params.is_empty() {
1900 let domain = format!("{}#{}", decl.resource, decl.id);
1904 let action_type = decl.action_type;
1905 ActionSpec::deferred_on(
1906 decl.id,
1907 label,
1908 ExecutionLocus::ClientLocal,
1909 action_type,
1910 move |target| encoded(target, &tilo_actions::ActionArgs::none()),
1911 )
1912 .with_continuation_identity(move |query| match query {
1913 tilo_actions::ContinuationQuery::Draft => {
1914 Some(tilo_actions::ContinuationEvidence::Draft {
1915 resolution_domain: tilo_actions::ContinuationKey::new(
1916 "verb",
1917 [domain.as_bytes()],
1918 ),
1919 handler: tilo_actions::ContinuationKey::new(
1920 "action-type",
1921 [action_type.as_bytes()],
1922 ),
1923 })
1924 }
1925 tilo_actions::ContinuationQuery::Exact(_) => None,
1926 })
1927 } else {
1928 ActionSpec::typed_on(
1929 decl.id,
1930 label.clone(),
1931 label,
1932 ExecutionLocus::ClientLocal,
1933 decl.shown_params(),
1934 encoded,
1935 )
1936 };
1937 let mut spec = spec.of_kind(decl.kind);
1938 if decl.by_arguments {
1942 let classify = Arc::clone(&decl.build);
1943 spec = spec.with_need_of(move |args| match classify(args, 0) {
1944 Ok(action) => action.need(),
1945 Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
1946 });
1947 }
1948 if let Some(field) = decl.field {
1949 spec = spec.below_field(field);
1950 }
1951 if let Some(description) = &decl.description {
1952 spec = spec.with_description(description.clone());
1953 }
1954 if !decl.keywords.is_empty() {
1955 spec = spec.with_keywords(decl.keywords.iter().cloned());
1956 }
1957 spec = with_declared_words(spec, decl);
1958 if decl.destructive {
1959 spec = spec.destructive();
1960 }
1961 let contract = &mut spec.type_mut().contract;
1962 (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1963 if let Some(result) = &decl.result {
1964 contract.result = result.clone();
1965 }
1966 for tag in &decl.tags {
1967 if !contract.tags.contains(tag) {
1968 contract.tags.push(tag.clone());
1969 }
1970 }
1971 contract.settle_confirmation();
1974 spec
1975}
1976
1977pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
1980 spec.type_mut().icon.clone_from(&decl.icon);
1981 spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
1982 spec
1983}
1984
1985fn declared_args(
1987 declarations: &[Declaration],
1988) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
1989 let mut args = std::collections::BTreeMap::new();
1990 for decl in declarations {
1991 args.insert(decl.id, crate::schema::args_schema(&decl.params));
1992 }
1993 args
1994}
1995
1996pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
2000 let param = ActionParam::required_owned(
2001 APPLY_PARAM,
2002 ParamType::Object,
2003 format!("A {} action, as JSON", vocabulary.label),
2004 );
2005 let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
2006 let schema = (vocabulary.action_schema)()?;
2007 Some(crate::schema::fold_declared(
2008 &schema,
2009 &declared_args(&vocabulary.declarations()),
2010 ))
2011 });
2012 match schema {
2013 Some(schema) => param.with_shared_schema(schema),
2014 None => param,
2015 }
2016}
2017
2018#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2020enum TypeSchema {
2021 Apply,
2022 Group,
2023 Edit,
2026}
2027
2028#[derive(Default)]
2029struct CompiledSchemas {
2030 epoch: u64,
2031 entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
2032}
2033
2034static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();
2035
2036#[doc(hidden)]
2040pub fn reset_type_schemas() {
2041 if let Some(cache) = SCHEMAS.get() {
2042 let mut store = cache.lock_recover();
2043 store.epoch = store.epoch.wrapping_add(1);
2044 store.entries.clear();
2045 }
2046}
2047
2048pub(crate) fn type_epoch() -> u64 {
2051 SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
2052}
2053
2054pub(crate) fn words_epoch() -> u64 {
2058 type_epoch() ^ crate::label::revision().rotate_left(32)
2059}
2060
2061fn per_type(
2064 vocabulary: &Vocabulary,
2065 schema: TypeSchema,
2066 build: &dyn Fn() -> Option<serde_json::Value>,
2067) -> Option<Arc<serde_json::Value>> {
2068 per_type_at(vocabulary, schema, "", build)
2069}
2070
2071fn per_type_at(
2073 vocabulary: &Vocabulary,
2074 schema: TypeSchema,
2075 at: &str,
2076 build: &dyn Fn() -> Option<serde_json::Value>,
2077) -> Option<Arc<serde_json::Value>> {
2078 let cache = SCHEMAS.get_or_init(Mutex::default);
2079 cached_schema(
2080 cache,
2081 ((vocabulary.type_id)(), schema, at.to_owned()),
2082 build,
2083 )
2084}
2085
2086fn cached_schema(
2087 cache: &Mutex<CompiledSchemas>,
2088 key: (TypeId, TypeSchema, String),
2089 build: &dyn Fn() -> Option<serde_json::Value>,
2090) -> Option<Arc<serde_json::Value>> {
2091 let epoch = {
2092 let store = cache.lock_recover();
2093 if let Some(found) = store.entries.get(&key) {
2094 let _phase = crate::profiling::Phase::start("schema.cached_clone");
2095 return found.clone();
2096 }
2097 store.epoch
2098 };
2099 let value = build().map(Arc::new);
2101 let mut store = cache.lock_recover();
2102 if store.epoch == epoch {
2104 store.entries.insert(key, value.clone());
2105 }
2106 value
2107}
2108
2109#[must_use]
2112pub fn by_app_refusal(label: &str) -> String {
2113 format!("{label} keeps this itself: it is not an action to invoke")
2114}
2115
2116fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
2121 let declarations = vocabulary.declarations();
2122 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2123 for decl in declarations.iter() {
2124 ids.push(decl.id);
2125 }
2126 if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
2127 && let Some(decl) = declarations.iter().find(|decl| decl.id == id)
2128 && let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
2129 {
2130 return Err(format!("{id}: {error}"));
2131 }
2132 if let Some(schema) = apply_param(vocabulary).schema {
2136 tilo_actions::validate_json_schema(&value, &schema)?;
2137 }
2138 let action = (vocabulary.read)(value)?;
2139 if action.by_app() {
2140 return Err(by_app_refusal(vocabulary.label));
2141 }
2142 Ok(action)
2143}
2144
2145pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
2154 let schema = per_type(vocabulary, TypeSchema::Group, &|| {
2155 let declarations = vocabulary.declarations();
2156 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2157 for decl in declarations.iter() {
2158 ids.push(decl.id);
2159 }
2160 Some(group_schema(&ids, vocabulary.edits))
2161 })
2162 .unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
2163 ActionParam::required_owned(
2164 crate::GROUP_PARAM,
2165 ParamType::Array,
2166 format!(
2167 "{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
2168 A member names an item an earlier member of the same group makes by its place, \
2169 {{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
2170 of the ids it made, which the group fills in as it applies",
2171 vocabulary.label
2172 ),
2173 )
2174 .with_shared_schema(schema)
2175}
2176
2177pub const APPLY_MEMBER: &str =
2180 "One action value, as the `apply` action's `apply` parameter describes it";
2181
2182pub const FIELD_EDIT_MEMBER: &str =
2185 "A field edit, as the `field-edit` action's `edit` parameter describes it";
2186
2187fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
2190 use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
2191 let mut members = Vec::new();
2192 if !ids.is_empty() {
2193 members.push(describe(
2194 object(vec![
2195 ("action", string_enum(ids), true),
2196 (
2197 "args",
2198 nullable(serde_json::json!({"type": "object"})),
2199 false,
2200 ),
2201 ]),
2202 "A named action, args as it takes them",
2203 ));
2204 }
2205 let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
2206 if edits {
2207 members.push(describe(
2208 object(vec![
2209 ("action", constant(FIELD_EDIT), true),
2210 (
2211 "args",
2212 object(vec![(
2213 EDIT_PARAM,
2214 describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
2215 true,
2216 )]),
2217 true,
2218 ),
2219 ]),
2220 "A field edit",
2221 ));
2222 }
2223 members.push(object(vec![
2224 ("action", constant(APPLY), true),
2225 ("args", object(vec![(APPLY_PARAM, action, true)]), true),
2226 ]));
2227 array(one_of(members))
2228}
2229
2230fn object_arg(
2232 args: &tilo_actions::ActionArgs,
2233 param: &str,
2234) -> Option<serde_json::Map<String, serde_json::Value>> {
2235 match args.get(param) {
2236 Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
2237 _ => None,
2238 }
2239}
2240
2241pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2242 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2243 let _phase = crate::profiling::Phase::start("resource.apply_spec");
2244 let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
2245 Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
2246 None => Err("missing action".to_owned()),
2247 };
2248 ActionSpec::typed(
2249 APPLY,
2250 format!("Apply {} edit", vocabulary.label),
2251 "Action as JSON",
2252 ExecutionLocus::ClientLocal,
2253 vec![apply_param(vocabulary)],
2254 move |args| match crate::content::invoking(|| read(args)) {
2255 Ok(mut action) => {
2256 action.stamp(origin_now_ms());
2257 encoded(&action)
2258 }
2259 Err(reason) => refused(&reason),
2260 },
2261 )
2262 .with_description(
2263 "One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
2264 )
2265 .for_audience(tilo_actions::Audience::Agents)
2268 .carrying()
2270 .with_need((vocabulary.least_need)())
2273 .of_kind((vocabulary.least_need)().kind)
2274 .with_need_of(move |args| match read(args) {
2275 Ok(action) => action.need(),
2276 Err(_) => tilo_actions::ActionContract::default().need(),
2277 })
2278 .with_risk(move |args| {
2281 let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
2282 match value.map(vocabulary.read) {
2283 Some(Ok(action)) => action.risk(),
2284 _ => tilo_actions::RiskLevel::Low,
2285 }
2286 })
2287 .with_undo_of(move |args| {
2293 let Some(value) = object_arg(args, APPLY_PARAM) else {
2294 return false;
2295 };
2296 let value = serde_json::Value::Object(value);
2297 let declarations = vocabulary.declarations();
2298 let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
2299 for decl in declarations.iter() {
2300 ids.push(decl.id);
2301 }
2302 let carried = crate::schema::declared_invocation(&value, &ids)
2303 .and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
2304 tilo_actions::undo_takes_back(
2305 carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
2306 tilo_actions::ChangeKind::Content,
2307 carried.is_some_and(|decl| {
2308 decl.tags
2309 .iter()
2310 .any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
2311 }),
2312 )
2313 })
2314}
2315
2316#[must_use]
2321pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
2322 spec.contract.kind
2323}
2324
2325pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
2327 ActionNeed {
2328 kind: R::kind_of(action),
2329 field: R::field_of(action).map(str::to_owned),
2330 privileged: false,
2331 }
2332}
2333
2334pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
2338 let mut needs = needs.into_iter();
2339 let Some(mut group) = needs.next() else {
2340 return tilo_actions::ActionContract::default().need();
2341 };
2342 for need in needs {
2343 group = ActionNeed {
2344 kind: group.kind.max(need.kind),
2345 field: group
2346 .field
2347 .filter(|field| need.field.as_ref() == Some(field)),
2348 privileged: group.privileged || need.privileged,
2349 };
2350 }
2351 group
2352}
2353
2354pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
2361 if let [only] = members {
2362 return encoded(only);
2363 }
2364 let mut payload = Vec::with_capacity(128);
2365 payload.push(b'[');
2366 for (index, member) in members.iter().enumerate() {
2367 if index > 0 {
2368 payload.push(b',');
2369 }
2370 if let Err(error) = member.write_json(&mut payload) {
2371 return refused(&error.to_string());
2372 }
2373 }
2374 payload.push(b']');
2375 EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
2376}
2377
2378pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
2379 #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
2380 let _phase = crate::profiling::Phase::start("resource.group_spec");
2381 let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
2382 crate::group::build_members(vocabulary, &args.to_json(), now_ms)
2383 };
2384 ActionSpec::typed(
2385 crate::GROUP,
2386 format!("Apply several {} edits as one", vocabulary.label),
2387 "Invocations as JSON",
2388 ExecutionLocus::ClientLocal,
2389 vec![group_param(vocabulary)],
2390 move |args| match build(args, origin_now_ms()) {
2391 Ok(members) => encode_group(vocabulary, &members),
2392 Err(reason) => refused(&reason),
2393 },
2394 )
2395 .with_description(
2396 "Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
2397 )
2398 .for_audience(tilo_actions::Audience::Agents)
2401 .carrying()
2403 .with_need((vocabulary.least_need)())
2405 .with_need_of(move |args| match build(args, 0) {
2406 Ok(members) => group_need(members.iter().map(Built::need)),
2407 Err(_) => tilo_actions::ActionContract::default().need(),
2408 })
2409 .with_risk(move |args| match build(args, 0) {
2411 Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
2412 Err(_) => tilo_actions::RiskLevel::Low,
2413 })
2414 .with_undo_of(move |args| match build(args, 0) {
2417 Ok(members) => members.iter().all(Built::undoable),
2418 Err(_) => false,
2419 })
2420}
2421
2422pub use crate::search_default::default_search;
2424
2425pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
2437 publish_parts::<R>(id, label, Some(state))
2438}
2439
2440pub fn state_from_reading<R: Resource>(
2456 reading: &serde_json::Value,
2457) -> Result<R::State, ModelError> {
2458 let table = R::RESOURCE_TABLE.ok_or_else(|| {
2459 ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
2460 })?;
2461 crate::table::Run(table).from_json(reading)
2462}
2463
2464pub(crate) fn publish_parts<R: Resource>(
2468 id: &str,
2469 label: &str,
2470 state: Option<&R::State>,
2471) -> tilo_actions::ResourceSpec {
2472 let vocabulary = vocabulary::<R>();
2473 let Some(state) = state else {
2474 let own = Own {
2475 availability: None,
2476 views: Vec::new(),
2477 local_operations: R::local_operations(),
2478 now: Vec::new(),
2479 };
2480 return publish_own(vocabulary, id, label, own, &|_| false);
2481 };
2482 let children = R::children(state);
2483 let own = Own {
2484 availability: Some(&|action| R::availability(state, action)),
2485 views: R::views(state),
2486 local_operations: R::local_operations(),
2487 now: weakening_now::<R>(state),
2488 };
2489 publish_own(vocabulary, id, label, own, &|decl| {
2490 crate::items::offered_bound(&children, decl)
2491 })
2492 .with_children(children)
2493}
2494
2495pub fn unreadable_parts<R: Resource>(
2503 id: &str,
2504 label: &str,
2505 reason: &str,
2506) -> tilo_actions::ResourceSpec {
2507 let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
2508 crate::unreadable::parts::<R>(id, &label, reason)
2509}
2510
2511struct Own<'a> {
2513 availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
2516 views: Vec<tilo_actions::ResourceViewSpec>,
2517 local_operations: Vec<ActionSpec>,
2518 now: Vec<(String, String)>,
2520}
2521
2522fn publish_own(
2526 vocabulary: &'static Vocabulary,
2527 id: &str,
2528 label: &str,
2529 own: Own<'_>,
2530 offered_bound: &dyn Fn(&Declaration) -> bool,
2531) -> tilo_actions::ResourceSpec {
2532 let _phase = crate::profiling::Phase::start("resource.published");
2533 let label = crate::label::published(
2536 vocabulary.kind,
2537 label,
2538 vocabulary.label,
2539 vocabulary.catalogue,
2540 );
2541 let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
2542 resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
2544 resource.app_id = Some(vocabulary.app.to_owned());
2547 resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
2553 let kept = own_specs(vocabulary);
2554 for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
2555 let _phase = crate::profiling::Phase::start("resource.declaration_spec");
2556 let mut spec = if decl.item.is_none() && offered_bound(decl) {
2560 declared.for_agents.clone()
2561 } else {
2562 declared.offered.clone()
2563 };
2564 if let Some(availability) = own.availability {
2567 let now = availability(decl.id);
2568 if spec.contract.availability != now {
2569 spec.type_mut().contract.availability = now;
2570 }
2571 }
2572 resource = resource.with_action(spec);
2573 }
2574 for view in own.views {
2575 resource = resource.with_view(view);
2576 }
2577 crate::share::offer(&mut resource);
2578 for spec in own.local_operations {
2579 if spec.kind == OperationKind::Document {
2580 continue;
2581 }
2582 resource = resource.with_action(spec);
2583 }
2584 resource = resource
2585 .with_action(kept.apply.clone())
2586 .with_action(kept.group.clone());
2587 if vocabulary.edits {
2588 resource = resource.with_action(field_edit_spec(vocabulary, own.now));
2589 }
2590 resource
2591}
2592
2593struct OwnSpecs {
2596 declared: Box<[DeclaredSpec]>,
2598 apply: ActionSpec,
2599 group: ActionSpec,
2600}
2601
2602struct DeclaredSpec {
2605 offered: ActionSpec,
2606 for_agents: ActionSpec,
2607}
2608
2609fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
2614 thread_local! {
2615 static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
2616 std::cell::RefCell::default();
2617 }
2618 crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
2619 let declared = vocabulary
2620 .declarations()
2621 .iter()
2622 .map(|decl| {
2623 let mut offered = spec_of_declaration(decl);
2624 if let Some(item) = decl.item {
2628 offered.type_mut().contract.item = Some(item.to_owned());
2629 }
2630 let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
2631 DeclaredSpec {
2632 offered,
2633 for_agents,
2634 }
2635 })
2636 .collect();
2637 std::rc::Rc::new(OwnSpecs {
2638 declared,
2639 apply: apply_spec(vocabulary),
2640 group: group_spec(vocabulary),
2641 })
2642 })
2643}
2644
2645pub fn build_action<R: Resource>(
2648 id: &str,
2649 arguments: &serde_json::Map<String, serde_json::Value>,
2650 now_ms: i64,
2651) -> Result<R::Action, String> {
2652 typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
2653}
2654
2655pub(crate) fn build_action_of(
2658 vocabulary: &Vocabulary,
2659 id: &str,
2660 arguments: &serde_json::Map<String, serde_json::Value>,
2661 now_ms: i64,
2662) -> Result<Built, String> {
2663 crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
2664}
2665
2666fn build_invoked(
2667 vocabulary: &Vocabulary,
2668 id: &str,
2669 arguments: &serde_json::Map<String, serde_json::Value>,
2670 now_ms: i64,
2671) -> Result<Built, String> {
2672 if id == crate::GROUP {
2673 return Err("a group is several actions; build it with `group::build_group`".into());
2674 }
2675 let read = if id == APPLY {
2676 Some((APPLY_PARAM, "missing action"))
2677 } else if id == FIELD_EDIT && vocabulary.edits {
2678 Some((EDIT_PARAM, "missing edit"))
2679 } else {
2680 None
2681 };
2682 if let Some((param, missing)) = read {
2683 let Some(value) = arguments.get(param).cloned() else {
2684 return Err(missing.to_owned());
2685 };
2686 let mut action = if id == APPLY {
2687 read_apply(vocabulary, value)?
2688 } else {
2689 read_edit(vocabulary, value)?
2690 };
2691 action.stamp(now_ms);
2692 return Ok(action);
2693 }
2694 let declarations = vocabulary.declarations();
2695 let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
2696 return Err(format!("{} has no action `{id}`", vocabulary.label));
2697 };
2698 let args = match ActionArgs::bind_json(&decl.params, arguments) {
2699 Ok(args) => args,
2700 Err(error) => return Err(error.to_string()),
2701 };
2702 (decl.build)(&args, now_ms)
2703}
2704
2705#[must_use]
2714pub fn bind_declaration(
2715 resource: tilo_actions::ResourceSpec,
2716 decl: &Declaration,
2717) -> tilo_actions::ResourceSpec {
2718 let spec = spec_of_declaration(decl);
2719 let mut resource = resource;
2720 match resource
2721 .actions
2722 .iter_mut()
2723 .find(|existing| existing.id == decl.id)
2724 {
2725 Some(declared) => {
2726 if decl.refines && same_shape(&spec, declared) {
2727 *declared = spec;
2728 }
2729 resource
2730 }
2731 None => resource.with_action(spec),
2732 }
2733}
2734
2735fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
2736 let shape = |spec: &ActionSpec| {
2737 spec.params()
2738 .iter()
2739 .map(|param| (param.name.to_string(), param.ty, param.required))
2740 .collect::<Vec<_>>()
2741 };
2742 bound.kind == declared.kind
2743 && shape(bound) == shape(declared)
2744 && bound.contract.kind == declared.contract.kind
2745 && bound.contract.field == declared.contract.field
2746 && bound.contract.risk == declared.contract.risk
2747}
2748
2749pub trait SharedResource: Resource {
2756 const OWNER: &'static str;
2759}
2760
2761#[derive(Clone, Debug, Default, PartialEq, Eq)]
2762pub struct SearchRow {
2763 pub subtitle: Option<String>,
2765 pub icon: Option<String>,
2768 pub shape: SearchRowShape,
2770}
2771
2772impl SearchRow {
2773 pub fn subtitle(subtitle: impl Into<String>) -> Self {
2775 Self {
2776 subtitle: Some(subtitle.into()),
2777 ..Self::default()
2778 }
2779 }
2780
2781 #[must_use]
2783 pub fn shaped(shape: SearchRowShape) -> Self {
2784 Self {
2785 shape,
2786 ..Self::default()
2787 }
2788 }
2789
2790 #[must_use]
2792 pub fn icon(mut self, name: impl Into<String>) -> Self {
2793 self.icon = Some(name.into());
2794 self
2795 }
2796}
2797
2798#[derive(Clone, Debug, Default, PartialEq, Eq)]
2799pub enum SearchRowShape {
2800 #[default]
2802 Plain,
2803 Message {
2805 sender: String,
2806 snippet: Option<String>,
2807 date: Option<String>,
2808 unread: bool,
2809 },
2810 Media {
2814 byline: Option<String>,
2815 duration: Option<String>,
2816 },
2817 FileHit {
2819 path: String,
2820 line: Option<u32>,
2821 snippet: String,
2822 },
2823}
2824
2825pub use tilo_actions::{ScopeDecl, scope_contains};
2826
2827#[cfg(test)]
2828mod schema_sharing_tests;
2829
2830#[cfg(test)]
2831mod selection_place_tests {
2832 use super::Place;
2833 use tilo_actions::SelectionPlace;
2834 use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;
2835
2836 #[test]
2837 fn a_selection_place_is_the_place_an_action_takes() {
2838 for (place, expected_json) in [
2839 (Place::Item("p1".into()), r#"{"item":"p1"}"#),
2840 (
2841 Place::Caret {
2842 item: "p1".into(),
2843 at: 3,
2844 },
2845 r#"{"item":"p1","at":3}"#,
2846 ),
2847 (
2848 Place::Range {
2849 item: "p1".into(),
2850 start: 2,
2851 end: 7,
2852 },
2853 r#"{"item":"p1","start":2,"end":7}"#,
2854 ),
2855 (
2856 Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
2857 &format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
2858 ),
2859 ] {
2860 let wire = serde_json::to_string(&place).unwrap();
2861 assert_eq!(wire, expected_json, "valid places serialise as before");
2862 let selection = SelectionPlace::from(place.clone());
2863 assert_eq!(
2864 serde_json::to_string(&selection).unwrap(),
2865 wire,
2866 "both travel in one wire form"
2867 );
2868 assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
2869 assert_eq!(Place::try_from(selection).unwrap(), place);
2870 }
2871
2872 let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
2873 let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
2874 assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);
2875
2876 for bad_item in [
2877 String::new(),
2878 overlong_ascii,
2879 overlong_utf8,
2880 "p\n1".to_owned(),
2881 "p\u{0}1".to_owned(),
2882 "p\x1b1".to_owned(),
2883 "p\t1".to_owned(),
2884 ] {
2885 for selection in [
2886 SelectionPlace::item(bad_item.clone()),
2887 SelectionPlace::caret(bad_item.clone(), 0),
2888 SelectionPlace::range(bad_item.clone(), 0, 1),
2889 ] {
2890 assert!(
2891 Place::try_from(selection.clone()).is_err(),
2892 "Place::try_from accepted invalid SelectionPlace: {selection:?}"
2893 );
2894 let json = serde_json::to_value(&selection).unwrap();
2895 assert!(
2896 serde_json::from_value::<Place>(json.clone()).is_err(),
2897 "Place::deserialize accepted invalid JSON: {json}"
2898 );
2899 }
2900 }
2901
2902 for malformed in [
2903 serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
2904 serde_json::json!({"item": "p1", "start": 2}),
2905 serde_json::json!({"item": "p1", "end": 2}),
2906 serde_json::json!({"item": "p1", "start": 5, "end": 2}),
2907 ] {
2908 let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
2909 let from_selection = Place::try_from(wire).unwrap_err();
2910 let from_json = serde_json::from_value::<Place>(malformed)
2911 .unwrap_err()
2912 .to_string();
2913 for error in [&from_selection, &from_json] {
2914 assert!(
2915 error.contains("at") && error.contains("start") && error.contains("end"),
2916 "malformed-shape error should name `at` and `start`/`end`: {error}"
2917 );
2918 }
2919 }
2920 assert!(
2921 serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
2922 .is_err()
2923 );
2924 }
2925}