1use std::any::{Any, TypeId};
13use std::cell::RefCell;
14use std::collections::HashMap;
15use std::rc::Rc;
16use std::sync::Arc;
17
18use tilo_actions::{
19 ActionArgs, ActionError, ActionNeed, ActionParam, ActionSpec, EncodedAction, ResourceViewSpec,
20 RiskLevel,
21};
22
23use crate::action::ActionKind;
24use crate::collection::Id;
25use crate::path::Edit;
26use crate::resource::Resource;
27use crate::shape::Shape;
28
29pub struct Built(Box<dyn AnyAction>);
31
32trait AnyAction {
34 fn stamp(&mut self, now_ms: i64);
35 fn action_type(&self) -> &'static str;
36 fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error>;
37 fn need(&self) -> ActionNeed;
38 fn risk(&self) -> RiskLevel;
39 fn undoable(&self) -> bool;
40 fn by_app(&self) -> bool;
41 fn into_any(self: Box<Self>) -> Box<dyn Any>;
42}
43
44struct Typed<R: Resource>(R::Action);
45
46impl<R: Resource> AnyAction for Typed<R> {
47 fn stamp(&mut self, now_ms: i64) {
48 R::stamp(&mut self.0, now_ms);
49 }
50
51 fn action_type(&self) -> &'static str {
52 R::ACTION_TYPE
53 }
54
55 fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
56 serde_json::to_writer(out, &self.0)
57 }
58
59 fn need(&self) -> ActionNeed {
60 crate::resource::need_of::<R>(&self.0)
61 }
62
63 fn risk(&self) -> RiskLevel {
64 tilo_actions::Action::risk(&self.0)
65 }
66
67 fn undoable(&self) -> bool {
68 tilo_actions::undo_takes_back(
69 tilo_actions::Action::action_kind(&self.0),
70 tilo_actions::Action::change_kind(&self.0),
71 tilo_actions::Action::irreversible(&self.0),
72 )
73 }
74
75 fn by_app(&self) -> bool {
76 R::by_app(&self.0)
77 }
78
79 fn into_any(self: Box<Self>) -> Box<dyn Any> {
80 Box::new(self.0)
81 }
82}
83
84impl Built {
85 #[must_use]
86 pub fn of<R: Resource>(action: R::Action) -> Self {
87 Self(Box::new(Typed::<R>(action)))
88 }
89
90 pub fn stamp(&mut self, now_ms: i64) {
92 self.0.stamp(now_ms);
93 }
94
95 #[must_use]
97 pub fn need(&self) -> ActionNeed {
98 self.0.need()
99 }
100
101 #[must_use]
103 pub fn risk(&self) -> RiskLevel {
104 self.0.risk()
105 }
106
107 #[must_use]
109 pub fn undoable(&self) -> bool {
110 self.0.undoable()
111 }
112
113 #[must_use]
116 pub fn by_app(&self) -> bool {
117 self.0.by_app()
118 }
119
120 pub fn encode(&self) -> Result<EncodedAction, ActionError> {
125 let mut payload = Vec::with_capacity(128);
126 self.0
127 .write_json(&mut payload)
128 .map_err(ActionError::Encode)?;
129 Ok(EncodedAction {
130 type_id: self.0.action_type().to_owned(),
131 payload,
132 })
133 }
134
135 pub(crate) fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
137 self.0.write_json(out)
138 }
139
140 #[must_use]
143 pub fn into_action<R: Resource>(self) -> Option<R::Action> {
144 self.0
145 .into_any()
146 .downcast::<R::Action>()
147 .ok()
148 .map(|action| *action)
149 }
150}
151
152pub type Builds = Arc<dyn Fn(&ActionArgs, i64) -> Result<Built, String> + Send + Sync>;
156
157#[derive(Clone)]
160pub struct Declaration {
161 pub id: &'static str,
162 pub label: String,
164 pub word: Option<crate::label::Word>,
167 pub keywords: Vec<String>,
170 pub icon: Option<String>,
173 pub did: Option<String>,
177 pub description: Option<String>,
178 pub params: Vec<ActionParam>,
179 pub kind: ActionKind,
181 pub by_arguments: bool,
184 pub field: Option<&'static str>,
186 pub destructive: bool,
187 pub result: Option<tilo_actions::ResultSpec>,
190 pub tags: Vec<String>,
193 pub content: Option<String>,
198 pub refines: bool,
203 pub step: Option<tilo_actions::StepKind>,
206 pub creates: Option<&'static str>,
210 pub item: Option<&'static str>,
215 pub writes: Vec<String>,
218 pub resource: &'static str,
220 pub action_type: &'static str,
223 pub build: Builds,
224 pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
229 pub param_types: Vec<(&'static str, ParamFieldType)>,
234 pub flat_types: Option<crate::surface::FlatTypes>,
237 pub result_type: Option<ParamFieldType>,
241}
242
243pub type ParamFieldType = crate::surface::FieldTypeOf;
246
247impl AsRef<Self> for Declaration {
248 fn as_ref(&self) -> &Self {
249 self
250 }
251}
252
253impl Declaration {
254 #[must_use]
256 pub fn shown_label(&self) -> String {
257 self.word
258 .as_ref()
259 .map_or_else(|| self.label.clone(), crate::label::Word::read)
260 }
261
262 #[must_use]
265 pub fn shown_params(&self) -> Vec<ActionParam> {
266 match &self.word {
267 Some(word) => crate::label::titled(word, self.resource, self.params.clone()),
268 None => self.params.clone(),
269 }
270 }
271
272 pub(crate) fn new(
275 vocabulary: &Vocabulary,
276 id: &'static str,
277 label: String,
278 params: Vec<ActionParam>,
279 build: Builds,
280 ) -> Self {
281 Self {
282 id,
283 label,
284 word: None,
285 keywords: Vec::new(),
286 icon: None,
287 did: None,
288 description: None,
289 params,
290 kind: ActionKind::Undoable,
291 by_arguments: false,
292 field: None,
293 destructive: false,
294 result: None,
295 tags: Vec::new(),
296 content: None,
297 refines: false,
298 step: None,
299 creates: None,
300 item: None,
301 writes: vec![crate::footprint::RESOURCE_UNIT.to_owned()],
302 resource: vocabulary.kind,
303 action_type: vocabulary.action_type,
304 build,
305 invokes: None,
306 param_types: Vec::new(),
307 flat_types: None,
308 result_type: None,
309 }
310 }
311}
312
313pub struct Vocabulary {
316 pub kind: &'static str,
318 pub app: &'static str,
320 pub label: &'static str,
322 pub catalogue: Option<&'static crate::label::Catalogue>,
324 pub action_type: &'static str,
326 pub edits: bool,
328 pub readers: &'static str,
330 pub(crate) resource_table: Option<&'static crate::table::ModelTable>,
332 pub(crate) type_id: fn() -> TypeId,
333 pub(crate) shape: fn() -> Option<Shape>,
334 pub(crate) op_schemas: fn() -> Vec<(String, serde_json::Value)>,
335 pub(crate) action_schema: fn() -> Option<serde_json::Value>,
336 pub(crate) least_need: fn() -> ActionNeed,
337 pub(crate) declare: fn() -> Vec<Declaration>,
340 pub(crate) item_effects: fn(&str, &Id) -> Vec<ActionSpec>,
341 pub(crate) item_views: fn(&str, &Id) -> Vec<ResourceViewSpec>,
342 pub(crate) read: fn(serde_json::Value) -> Result<Built, String>,
344 pub(crate) edit: fn(Edit<()>) -> Option<Built>,
346}
347
348impl Vocabulary {
349 pub(crate) fn rooted_edit(&self, edit: Edit<()>) -> Result<Edit<()>, String> {
353 let Some(shape) = (self.shape)() else {
354 return Ok(edit);
355 };
356 let kind = self.kind.rsplit('.').next().unwrap_or(self.kind);
357 edit.past_resource_name(shape, &[kind, self.label])
358 }
359
360 #[must_use]
366 pub fn declarations(&self) -> Rc<[Declaration]> {
367 type Kept = (u64, HashMap<TypeId, Rc<[Declaration]>>);
368 thread_local! {
369 static KEPT: RefCell<Kept> = RefCell::new((0, HashMap::new()));
370 }
371 let epoch = crate::resource::type_epoch();
372 let key = (self.type_id)();
373 let found = KEPT.with(|kept| {
374 let kept = kept.borrow();
375 if kept.0 == epoch {
376 kept.1.get(&key).cloned()
377 } else {
378 None
379 }
380 });
381 if let Some(found) = found {
382 return found;
383 }
384 let built: Rc<[Declaration]> = (self.declare)().into();
387 KEPT.with(|kept| {
388 let mut kept = kept.borrow_mut();
389 if kept.0 != epoch {
390 *kept = (epoch, HashMap::new());
391 }
392 kept.1.insert(key, Rc::clone(&built));
393 });
394 built
395 }
396}
397
398fn declarations<R: Resource>() -> Vec<Declaration> {
399 let mut out = Vec::new();
400 for decl in R::declarations() {
401 out.push(decl.into_declaration());
402 }
403 out
404}
405
406fn read<R: Resource>(value: serde_json::Value) -> Result<Built, String> {
407 match serde_json::from_value::<R::Action>(value) {
408 Ok(action) => Ok(Built::of::<R>(action)),
409 Err(error) => Err(error.to_string()),
410 }
411}
412
413fn edit<R: Resource>(edit: Edit<()>) -> Option<Built> {
414 R::edit_action(edit.retyped()).map(Built::of::<R>)
415}
416
417struct VocabularyOf<R>(std::marker::PhantomData<R>);
418
419#[cfg(tilo_model_guest)]
422fn least_need_default() -> ActionNeed {
423 tilo_actions::ActionContract::default().need()
424}
425
426#[cfg(tilo_model_guest)]
427fn empty_op_schemas() -> Vec<(String, serde_json::Value)> {
428 Vec::new()
429}
430
431#[cfg(tilo_model_guest)]
432fn no_item_effects(_: &str, _: &Id) -> Vec<ActionSpec> {
433 Vec::new()
434}
435
436#[cfg(tilo_model_guest)]
437fn no_item_views(_: &str, _: &Id) -> Vec<ResourceViewSpec> {
438 Vec::new()
439}
440
441impl<R: Resource> VocabularyOf<R> {
442 const VOCABULARY: Vocabulary = Vocabulary {
443 kind: R::KIND,
444 app: R::APP_ID,
445 label: R::LABEL,
446 #[cfg(tilo_model_guest)]
452 catalogue: None,
453 #[cfg(not(tilo_model_guest))]
454 catalogue: R::CATALOGUE,
455 action_type: R::ACTION_TYPE,
456 edits: R::EDITS,
457 readers: R::READERS,
458 resource_table: R::RESOURCE_TABLE,
459 type_id: TypeId::of::<R>,
460 shape: R::shape,
461 #[cfg(tilo_model_guest)]
462 op_schemas: empty_op_schemas,
463 #[cfg(not(tilo_model_guest))]
464 op_schemas: R::op_schemas,
465 action_schema: R::action_schema,
466 #[cfg(tilo_model_guest)]
467 least_need: least_need_default,
468 #[cfg(not(tilo_model_guest))]
469 least_need: R::least_need,
470 declare: declarations::<R>,
471 #[cfg(tilo_model_guest)]
472 item_effects: no_item_effects,
473 #[cfg(not(tilo_model_guest))]
474 item_effects: R::item_effects,
475 #[cfg(tilo_model_guest)]
476 item_views: no_item_views,
477 #[cfg(not(tilo_model_guest))]
478 item_views: R::item_views,
479 read: read::<R>,
480 edit: edit::<R>,
481 };
482}
483
484#[must_use]
485pub fn vocabulary<R: Resource>() -> &'static Vocabulary {
486 &VocabularyOf::<R>::VOCABULARY
487}