1use std::any::Any;
38
39use tilo_actions::{ActionRegistry, EncodedAction};
40
41use crate::model::{Doc, ModelError};
42use crate::reader::Demand;
43use crate::resource::{self, Place, Resource, SearchEntry};
44
45#[derive(Clone, Copy)]
48pub struct ResourceKind {
49 kind: &'static str,
50 label: &'static str,
51 action_type: &'static str,
52 app: Option<(&'static str, &'static str)>,
53 version: u32,
54 read: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
55 read_for_search: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
58 name: fn(&dyn Any) -> Option<String>,
59 publish: fn(&str, &str, &dyn Any) -> Option<tilo_actions::ResourceSpec>,
60 search: fn(&dyn Any) -> Option<Vec<SearchEntry>>,
61 to_json: fn(&dyn Any) -> Option<serde_json::Value>,
62 child: fn(&dyn Any, &Doc, &str) -> Option<tilo_actions::ResourceSpec>,
63 content: fn(&dyn Any, &Doc, Option<&str>) -> Result<serde_json::Value, String>,
64 reads_item: fn(&str) -> bool,
65 opens_as_item: fn(&str) -> bool,
66 register: fn(&mut ActionRegistry),
67 initialize: fn(&mut Doc) -> Result<(), ModelError>,
68 rewrite: fn(&mut Doc, u32) -> Result<(), ModelError>,
69 needs_migrate: fn(&Doc) -> bool,
70 encode: fn(serde_json::Value) -> Result<EncodedAction, String>,
71 lands: fn(&Doc, &EncodedAction) -> Option<Place>,
72}
73
74impl std::fmt::Debug for ResourceKind {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 f.debug_struct("ResourceKind")
77 .field("kind", &self.kind)
78 .field("app", &self.app)
79 .finish_non_exhaustive()
80 }
81}
82
83pub const DEFAULT_APP: &str = "so.tilo.app";
86
87fn unavailable(_doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
91 Err(ModelError::Refused(
92 "a kind declared by name alone holds no record".to_owned(),
93 ))
94}
95
96fn no_name(_state: &dyn Any) -> Option<String> {
97 None
98}
99
100fn no_publish(_id: &str, _label: &str, _state: &dyn Any) -> Option<tilo_actions::ResourceSpec> {
101 None
102}
103
104fn no_search(_state: &dyn Any) -> Option<Vec<SearchEntry>> {
105 None
106}
107
108fn no_to_json(_state: &dyn Any) -> Option<serde_json::Value> {
109 None
110}
111
112fn no_child(_state: &dyn Any, _doc: &Doc, _id: &str) -> Option<tilo_actions::ResourceSpec> {
113 None
114}
115
116fn no_content(
117 _state: &dyn Any,
118 _doc: &Doc,
119 _item: Option<&str>,
120) -> Result<serde_json::Value, String> {
121 Err("a kind declared by name alone holds no record".to_owned())
122}
123
124fn no_item(_id: &str) -> bool {
125 false
126}
127
128fn no_register(_registry: &mut ActionRegistry) {}
129
130fn no_initialize(_doc: &mut Doc) -> Result<(), ModelError> {
131 Err(ModelError::Refused(
132 "a kind declared by name alone initialises no record".to_owned(),
133 ))
134}
135
136#[allow(
137 clippy::unnecessary_wraps,
138 reason = "a kind's rewrite answers as a type's migration does, whether or not it changes anything"
139)]
140fn no_rewrite(_doc: &mut Doc, _from: u32) -> Result<(), ModelError> {
141 Ok(())
142}
143
144fn no_needs_migrate(_doc: &Doc) -> bool {
145 false
146}
147
148fn no_encode(_action: serde_json::Value) -> Result<EncodedAction, String> {
149 Err("a kind declared by name alone has no action type of its own".to_owned())
150}
151
152fn no_lands(_doc: &Doc, _action: &EncodedAction) -> Option<Place> {
153 None
154}
155
156#[allow(
158 clippy::indexing_slicing,
159 reason = "both sides are walked to the shorter one's length"
160)]
161const fn app_eq(a: &str, b: &str) -> bool {
162 let (a, b) = (a.as_bytes(), b.as_bytes());
163 if a.len() != b.len() {
164 return false;
165 }
166 let mut i = 0;
167 while i < a.len() {
168 if a[i] != b[i] {
169 return false;
170 }
171 i = i.saturating_add(1);
172 }
173 true
174}
175
176#[allow(
178 clippy::unnecessary_wraps,
179 reason = "a kind names its records through a `Resource` method, whatever its state"
180)]
181fn naming<R: Resource>(_state: &dyn Any) -> Option<String> {
182 Some(R::label())
183}
184
185fn read<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
186 R::read(doc).map(|state| Box::new(state) as Box<dyn Any>)
187}
188
189fn read_for_search<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
193 let mut state = R::read(doc)?;
194 R::load(&mut state, doc, &Demand::none())?;
195 Ok(Box::new(state) as Box<dyn Any>)
196}
197
198fn resource_label<R: Resource>(state: &dyn Any) -> Option<String> {
199 state.downcast_ref::<R::State>().map(|_| R::label())
200}
201
202fn publish<R: Resource>(
203 id: &str,
204 label: &str,
205 state: &dyn Any,
206) -> Option<tilo_actions::ResourceSpec> {
207 state
208 .downcast_ref::<R::State>()
209 .map(|state| resource::publish::<R>(id, label, state))
210}
211
212fn child<R: Resource>(state: &dyn Any, doc: &Doc, id: &str) -> Option<tilo_actions::ResourceSpec> {
213 resource::child_by_id::<R>(state.downcast_ref::<R::State>()?, doc, id)
214}
215
216fn search<R: Resource>(state: &dyn Any) -> Option<Vec<SearchEntry>> {
217 state.downcast_ref::<R::State>().map(R::search)
218}
219
220fn to_json<R: Resource>(state: &dyn Any) -> Option<serde_json::Value> {
223 let table = R::RESOURCE_TABLE?;
224 state
225 .downcast_ref::<R::State>()
226 .map(|state| crate::table::Run(table).to_json(state))
227}
228
229fn content<R: Resource>(
231 state: &dyn Any,
232 doc: &Doc,
233 item: Option<&str>,
234) -> Result<serde_json::Value, String> {
235 let state = state
236 .downcast_ref::<R::State>()
237 .ok_or_else(|| format!("{} state is another type", R::KIND))?;
238 crate::read::content::<R>(state, doc, item)
239}
240
241fn reads_item<R: Resource>(item: &str) -> bool {
242 R::RESOURCE_TABLE.is_some_and(|table| crate::table::reads_item(table, R::KIND, item))
243}
244
245pub fn opens_as_item<R: Resource>(id: &str) -> bool {
252 match R::RESOURCE_TABLE {
253 Some(table) => crate::table::names_item(table, R::KIND, id),
254 None => crate::items::item_of_resource::<R>(id)
255 .is_some_and(|(_, item)| !item.as_str().contains('/')),
256 }
257}
258
259fn lands<R: Resource>(doc: &Doc, action: &EncodedAction) -> Option<Place> {
260 let action: R::Action = if action.type_id == R::ACTION_TYPE {
261 tilo_actions::decode_json(&action.payload).ok()?
262 } else if action.type_id == crate::group::group_type::<R>() {
263 tilo_actions::decode_payload::<crate::group::ActionGroup<R::Action>>(
264 &action.type_id,
265 &action.payload,
266 )
267 .ok()?
268 .actions
269 .pop()?
270 } else {
271 return None;
272 };
273 if !R::lands_on_state(&action) {
274 return None;
275 }
276 R::lands(&R::read(doc).ok()?, &action)
277}
278
279fn encode<R: Resource>(action: serde_json::Value) -> Result<EncodedAction, String> {
280 encode_in(crate::vocabulary::<R>(), action)
281}
282
283fn encode_in(
285 vocabulary: &crate::Vocabulary,
286 action: serde_json::Value,
287) -> Result<EncodedAction, String> {
288 let mut arguments = serde_json::Map::new();
289 arguments.insert(resource::APPLY_PARAM.to_owned(), action);
290 let action = resource::build_action_of(
291 vocabulary,
292 resource::APPLY,
293 &arguments,
294 resource::origin_now_ms(),
295 )?;
296 action.encode().map_err(|error| error.to_string())
297}
298
299impl ResourceKind {
300 #[must_use]
304 pub const fn of<R: Resource>() -> Self {
305 Self {
306 kind: R::KIND,
307 label: R::LABEL,
308 action_type: R::ACTION_TYPE,
309 app: Some((R::APP_ID, R::LABEL)),
310 version: R::VERSION,
311 read: read::<R>,
312 read_for_search: read_for_search::<R>,
313 name: resource_label::<R>,
314 publish: publish::<R>,
315 search: search::<R>,
316 to_json: to_json::<R>,
317 child: child::<R>,
318 content: content::<R>,
319 reads_item: reads_item::<R>,
320 opens_as_item: opens_as_item::<R>,
321 register: crate::group::register::<R>,
322 initialize: R::initialize,
323 rewrite: R::migrate,
324 needs_migrate: crate::evolution::needs_migrate::<R>,
325 encode: encode::<R>,
326 lands: lands::<R>,
327 }
328 }
329
330 #[must_use]
333 pub const fn hosted_by(mut self, app_id: &'static str, title: &'static str) -> Self {
334 self.app = Some((app_id, title));
335 self
336 }
337
338 #[must_use]
343 pub const fn of_effect<V: crate::Effect>(
344 kind: &'static str,
345 label: &'static str,
346 app: &'static str,
347 ) -> Self {
348 Self {
349 kind,
350 label,
351 action_type: kind,
352 app: Some((app, label)),
353 version: 0,
354 read: unavailable,
355 read_for_search: unavailable,
356 name: no_name,
357 publish: no_publish,
358 search: no_search,
359 to_json: no_to_json,
360 child: no_child,
361 content: no_content,
362 reads_item: no_item,
363 opens_as_item: no_item,
364 register: no_register,
365 initialize: no_initialize,
366 rewrite: no_rewrite,
367 needs_migrate: no_needs_migrate,
368 encode: no_encode,
369 lands: no_lands,
370 }
371 }
372
373 #[must_use]
380 pub const fn declaring<R>(app: &'static str, title: &'static str) -> Self
381 where
382 R: Resource,
383 {
384 Self::of::<R>().hosted_by(app, title).named(naming::<R>)
385 }
386
387 #[must_use]
392 pub const fn declared<R>(kind: &'static str, label: &'static str, app: &'static str) -> Self
393 where
394 R: Resource,
395 {
396 let mut declared = Self::of::<R>().hosted_by(app, label);
397 declared.kind = kind;
398 declared
399 }
400
401 #[must_use]
404 pub fn declaring_app(&self) -> &'static str {
405 self.app.map_or(DEFAULT_APP, |(id, _)| id)
406 }
407
408 #[must_use]
414 pub const fn declares(app: &str, declared: &str) -> bool {
415 if app_eq(declared, DEFAULT_APP) {
416 app_eq(app, DEFAULT_APP)
417 } else {
418 app_eq(app, declared)
419 }
420 }
421
422 #[must_use]
426 pub const fn named(mut self, name: fn(&dyn Any) -> Option<String>) -> Self {
427 self.name = name;
428 self
429 }
430
431 pub fn kind(&self) -> &'static str {
433 self.kind
434 }
435
436 pub fn label(&self) -> &'static str {
438 self.label
439 }
440
441 pub fn action_type(&self) -> &'static str {
443 self.action_type
444 }
445
446 pub fn lands(&self, doc: &Doc, action: &EncodedAction) -> Option<Place> {
451 (self.lands)(doc, action)
452 }
453
454 pub fn app_id(&self) -> Option<&'static str> {
456 self.app.map(|(id, _)| id)
457 }
458
459 pub fn app_title(&self) -> Option<&'static str> {
461 self.app.map(|(_, title)| title)
462 }
463
464 #[must_use]
467 pub fn version(&self) -> u32 {
468 self.version
469 }
470
471 pub fn read(&self, doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
477 (self.read)(doc)
478 }
479
480 pub fn read_as<S: 'static>(&self, doc: &Doc) -> Result<S, ModelError> {
486 self.read(doc)?
487 .downcast::<S>()
488 .map(|state| *state)
489 .map_err(|_| ModelError::invalid(format!("{} state is another type", self.kind)))
490 }
491
492 pub fn holds(&self, doc: &Doc) -> bool {
495 self.read(doc).is_ok()
496 }
497
498 pub fn holds_or_older(&self, doc: &Doc) -> bool {
503 crate::evolution::stored_version(doc) < self.version || self.holds(doc)
504 }
505
506 pub fn name(&self, state: &dyn Any) -> String {
509 (self.name)(state).unwrap_or_else(|| self.label.to_owned())
510 }
511
512 pub fn publish(&self, id: &str, doc: &Doc) -> Result<tilo_actions::ResourceSpec, ModelError> {
520 let state = self.read(doc)?;
521 self.publish_state(id, state.as_ref())
522 }
523
524 pub fn child(
527 &self,
528 doc: &Doc,
529 id: &str,
530 ) -> Result<Option<tilo_actions::ResourceSpec>, ModelError> {
531 let state = self.read(doc)?;
532 Ok((self.child)(state.as_ref(), doc, id))
533 }
534
535 pub fn content(&self, doc: &Doc, item: Option<&str>) -> Result<serde_json::Value, ModelError> {
546 let state = self.read(doc)?;
547 (self.content)(state.as_ref(), doc, item).map_err(ModelError::Refused)
548 }
549
550 #[must_use]
553 pub fn reads_item(&self, item: &str) -> bool {
554 (self.reads_item)(item)
555 }
556
557 #[must_use]
560 pub fn opens_as_item(&self, id: &str) -> bool {
561 (self.opens_as_item)(id)
562 }
563
564 pub fn publish_state(
569 &self,
570 id: &str,
571 state: &dyn Any,
572 ) -> Result<tilo_actions::ResourceSpec, ModelError> {
573 let name = self.name(state);
574 (self.publish)(id, &name, state)
575 .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
576 }
577
578 pub fn to_json(&self, state: &dyn Any) -> Result<serde_json::Value, ModelError> {
584 (self.to_json)(state)
585 .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
586 }
587
588 pub fn search(&self, doc: &Doc) -> Result<Vec<SearchEntry>, ModelError> {
593 let state = (self.read_for_search)(doc)?;
594 (self.search)(state.as_ref())
595 .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
596 }
597
598 pub fn register(&self, registry: &mut ActionRegistry) {
601 (self.register)(registry);
602 }
603
604 pub fn initialize(&self, doc: &mut Doc) -> Result<(), ModelError> {
606 (self.initialize)(doc)
607 }
608
609 pub fn rewrite(&self, doc: &mut Doc, from: u32) -> Result<(), ModelError> {
615 (self.rewrite)(doc, from)
616 }
617
618 #[must_use]
621 pub fn needs_migrate(&self, doc: &Doc) -> bool {
622 (self.needs_migrate)(doc)
623 }
624
625 pub fn encode(&self, action: serde_json::Value) -> Result<EncodedAction, String> {
629 (self.encode)(action)
630 }
631}
632
633#[derive(Clone, Debug, Default)]
635pub struct Kinds {
636 kinds: Vec<ResourceKind>,
637}
638
639impl Kinds {
640 #[must_use]
642 pub const fn new() -> Self {
643 Self { kinds: Vec::new() }
644 }
645
646 #[must_use]
648 pub fn with(mut self, kind: ResourceKind) -> Self {
649 self.insert(kind);
650 self
651 }
652
653 pub fn insert(&mut self, kind: ResourceKind) {
655 match self.kinds.iter_mut().find(|known| known.kind == kind.kind) {
656 Some(known) => *known = kind,
657 None => self.kinds.push(kind),
658 }
659 }
660
661 pub fn get(&self, kind: &str) -> Option<&ResourceKind> {
663 self.kinds.iter().find(|known| known.kind == kind)
664 }
665
666 pub fn hosted_by(&self, app_id: &str) -> Option<&ResourceKind> {
668 self.kinds
669 .iter()
670 .find(|known| known.app_id() == Some(app_id))
671 }
672
673 pub fn iter(&self) -> impl Iterator<Item = &ResourceKind> {
675 self.kinds.iter()
676 }
677
678 pub fn registry(&self) -> ActionRegistry {
681 let mut registry = ActionRegistry::new();
682 for kind in &self.kinds {
683 kind.register(&mut registry);
684 }
685 registry
686 }
687}