1use std::any::TypeId;
22use std::cell::RefCell;
23use std::collections::HashMap;
24use std::marker::PhantomData;
25use std::rc::Rc;
26
27use serde::Serialize;
28
29use crate::action::ActionRef;
30use crate::path::{Path, Segment};
31use crate::resource::{ActionDecl, Resource};
32use crate::vocabulary::Declaration;
33
34pub struct Bound<R> {
36 verb: BoundVerb,
37 marker: PhantomData<fn() -> R>,
38}
39
40#[derive(Clone, Debug, PartialEq)]
43struct BoundVerb {
44 action: &'static str,
45 values: Vec<(String, serde_json::Value)>,
46}
47
48impl<R> Clone for Bound<R> {
49 fn clone(&self) -> Self {
50 Self {
51 verb: self.verb.clone(),
52 marker: PhantomData,
53 }
54 }
55}
56
57impl<R> PartialEq for Bound<R> {
58 fn eq(&self, other: &Self) -> bool {
59 self.verb == other.verb
60 }
61}
62
63impl<R> std::fmt::Debug for Bound<R> {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("Bound")
66 .field("action", &self.verb.action)
67 .field("values", &self.verb.values)
68 .finish()
69 }
70}
71
72impl<R> Bound<R> {
73 fn new(action: &'static str, values: Vec<(String, serde_json::Value)>) -> Self {
74 Self {
75 verb: BoundVerb { action, values },
76 marker: PhantomData,
77 }
78 }
79
80 #[must_use]
82 pub fn and<P, V: Serialize>(mut self, param: Path<P, V>, value: V) -> Self {
83 self.verb.values.push(bound_value(param, &value));
84 self
85 }
86
87 pub fn action(&self) -> &'static str {
88 self.verb.action
89 }
90
91 pub fn values(&self) -> &[(String, serde_json::Value)] {
92 &self.verb.values
93 }
94}
95
96impl<R: Resource> Bound<R> {
97 #[must_use]
102 pub fn declaration(
103 &self,
104 id: &'static str,
105 label: crate::label::Word,
106 ) -> Option<ActionDecl<R>> {
107 bound_declaration(
108 crate::vocabulary::<R>(),
109 self.verb.action,
110 &self.verb.values,
111 id,
112 label,
113 )
114 .map(ActionDecl::declared)
115 }
116}
117
118fn bound_declaration(
121 vocabulary: &crate::Vocabulary,
122 action: &str,
123 values: &[(String, serde_json::Value)],
124 id: &'static str,
125 label: crate::label::Word,
126) -> Option<Declaration> {
127 let declarations = vocabulary.declarations();
128 let verb = declarations.iter().find(|decl| decl.id == action)?;
129 let mut params = Vec::new();
130 for param in &verb.params {
131 if !values.iter().any(|(name, _)| param.name == name.as_str()) {
132 params.push(param.clone());
133 }
134 }
135 let all = verb.params.clone();
136 let build = std::sync::Arc::clone(&verb.build);
137 let invokes = (
138 verb.id.to_owned(),
139 values
140 .iter()
141 .filter(|(_, value)| !value.is_null())
142 .cloned()
143 .collect(),
144 );
145 let values = values.to_vec();
146 let build: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
147 let mut arguments = args.to_json();
148 for (name, value) in &values {
149 if !value.is_null() {
151 arguments.insert(name.clone(), value.clone());
152 }
153 }
154 match tilo_actions::ActionArgs::bind_json(&all, &arguments) {
155 Ok(args) => build(&args, now_ms),
156 Err(error) => Err(error.to_string()),
157 }
158 });
159 let mut decl = Declaration::new(vocabulary, id, label.source.to_owned(), params, build);
160 decl.word = Some(label);
161 decl.icon.clone_from(&verb.icon);
164 decl.keywords.clone_from(&verb.keywords);
165 decl.invokes = Some(invokes);
166 decl.kind = verb.kind;
167 decl.field = verb.field;
168 decl.description.clone_from(&verb.description);
169 decl.destructive = verb.destructive;
170 decl.step = verb.step;
171 decl.creates = verb.creates;
172 decl.tags.extend(
175 verb.tags
176 .iter()
177 .filter(|tag| {
178 *tag == tilo_actions::COMPENSATED_UNDO_TAG
179 || *tag == tilo_actions::IRREVERSIBLE_TAG
180 || *tag == tilo_actions::HOUSEKEEPING_TAG
181 })
182 .cloned(),
183 );
184 Some(decl)
185}
186
187fn bound_value<P, V: Serialize>(param: Path<P, V>, value: &V) -> (String, serde_json::Value) {
188 let segments = param.into_segments();
189 let name = match segments.as_slice() {
190 [Segment::Field(name)] => name.clone(),
191 other => other
192 .iter()
193 .map(ToString::to_string)
194 .collect::<Vec<_>>()
195 .join("."),
196 };
197 (
198 name,
199 crate::__private::json_via_bytes(value).unwrap_or(serde_json::Value::Null),
200 )
201}
202
203impl<R, P: Serialize> ActionRef<R, P> {
204 #[must_use]
207 pub fn bind<V: Serialize>(&self, param: Path<P, V>, value: V) -> Bound<R> {
208 Bound::new(self.id, vec![bound_value(param, &value)])
209 }
210
211 #[must_use]
214 pub fn unbound(&self) -> Bound<R> {
215 Bound::new(self.id, Vec::new())
216 }
217}
218
219pub struct Derived<R> {
221 place: Place,
222 marker: PhantomData<fn() -> R>,
223}
224
225#[derive(Clone)]
229struct Place {
230 id: String,
231 addressed: bool,
234 field: Option<String>,
237 label: String,
238 kind: Option<String>,
239 words: Option<tilo_actions::ResourceType>,
242 actions: Vec<BoundVerb>,
243 effects: Vec<tilo_actions::ActionSpec>,
244 offers: Vec<Offer>,
246 children: Rc<Vec<Place>>,
249}
250
251#[derive(Clone, Debug, PartialEq)]
254enum Offer {
255 Effect {
256 operation: &'static str,
257 id: &'static str,
258 arguments: serde_json::Map<String, serde_json::Value>,
259 asking: Vec<String>,
260 },
261 Edit {
262 id: &'static str,
263 label: String,
264 path: Vec<Segment>,
265 op: crate::EditOp,
266 },
267 Asking,
270 Stated {
274 id: String,
275 label: String,
276 availability: tilo_actions::Availability,
277 },
278}
279
280impl PartialEq for Place {
281 fn eq(&self, other: &Self) -> bool {
282 self.id == other.id
283 && self.addressed == other.addressed
284 && self.field == other.field
285 && self.label == other.label
286 && self.kind == other.kind
287 && self.words == other.words
288 && self.actions == other.actions
289 && self.offers == other.offers
290 && !self.offers.contains(&Offer::Asking)
291 && (Rc::ptr_eq(&self.children, &other.children) || self.children == other.children)
292 }
293}
294
295impl Place {
296 fn publish(&self, vocabulary: &'static crate::Vocabulary) -> tilo_actions::ResourceSpec {
299 self.publish_under(
300 &format!(
301 "{}/{}",
302 vocabulary.kind,
303 self.field.as_deref().unwrap_or("derived")
304 ),
305 vocabulary,
306 )
307 }
308
309 fn publish_under(
310 &self,
311 parent: &str,
312 vocabulary: &'static crate::Vocabulary,
313 ) -> tilo_actions::ResourceSpec {
314 let id = if self.addressed {
315 self.id.clone()
316 } else {
317 format!("{parent}/{}", self.id)
318 };
319 let declarations = if self.actions.is_empty() {
322 Vec::new().into()
323 } else {
324 vocabulary.declarations()
325 };
326 let kind = self.kind.as_deref().unwrap_or("derived");
327 let mut child = tilo_actions::ResourceSpec::new(
328 &id,
329 if kind.contains('.') {
332 kind.to_owned()
333 } else {
334 format!("{}.{kind}", vocabulary.kind)
335 },
336 &self.label,
337 );
338 for bound in &self.actions {
339 if let Some(decl) = declarations.iter().find(|decl| decl.id == bound.action) {
340 child = child.with_action(crate::items::bound(decl, &bound.values));
341 }
342 }
343 for effect in &self.effects {
344 child = child.with_action(effect.clone());
345 }
346 if let Some(words) = &self.words {
347 child = child.with_type(words.clone());
348 }
349 child.with_children(
350 self.children
351 .iter()
352 .map(|nested| nested.publish_under(&id, vocabulary)),
353 )
354 }
355}
356
357impl<R> Clone for Derived<R> {
358 fn clone(&self) -> Self {
359 Self {
360 place: self.place.clone(),
361 marker: PhantomData,
362 }
363 }
364}
365
366impl<R> PartialEq for Derived<R> {
367 fn eq(&self, other: &Self) -> bool {
368 self.place == other.place
369 }
370}
371
372impl<R> Derived<R> {
373 pub fn new(label: impl Into<String>) -> Self {
376 let label = label.into();
377 Self {
378 place: Place {
379 id: label.clone(),
380 addressed: false,
381 field: None,
382 label,
383 kind: None,
384 words: None,
385 actions: Vec::new(),
386 effects: Vec::new(),
387 offers: Vec::new(),
388 children: Rc::default(),
389 },
390 marker: PhantomData,
391 }
392 }
393
394 #[must_use]
396 pub fn with_child(mut self, child: Self) -> Self {
397 Rc::make_mut(&mut self.place.children).push(child.place);
398 self
399 }
400
401 #[must_use]
405 pub fn of_kind(mut self, kind: impl Into<String>) -> Self {
406 self.place.kind = Some(kind.into());
407 self
408 }
409
410 #[must_use]
415 pub fn typed<T: crate::words::RowType>(mut self) -> Self {
416 self.place.words = Some(T::words());
417 self
418 }
419
420 #[must_use]
425 pub fn with_operation(mut self, spec: tilo_actions::ActionSpec) -> Self {
426 self.place.offers.push(Offer::Stated {
427 id: spec.id.clone(),
428 label: spec.label.clone(),
429 availability: spec.contract.availability.clone(),
430 });
431 self.place.effects.push(spec);
432 self
433 }
434
435 #[must_use]
438 pub fn with_effect<E: crate::Effect>(mut self, effect: &E) -> Self {
439 self.place.effects.push(effect.bound());
440 self.place.offers.push(Offer::Effect {
441 operation: E::OPERATION,
442 id: effect.id(),
443 arguments: effect.arguments(),
444 asking: Vec::new(),
445 });
446 self
447 }
448
449 #[must_use]
453 pub fn with_effect_asking<E: crate::Effect>(mut self, effect: &E, asking: &[&str]) -> Self {
454 self.place.effects.push(effect.bound_asking(asking));
455 self.place.offers.push(Offer::Effect {
456 operation: E::OPERATION,
457 id: effect.id(),
458 arguments: effect.arguments(),
459 asking: asking.iter().map(|name| (*name).to_owned()).collect(),
460 });
461 self
462 }
463
464 #[must_use]
466 pub fn identified(mut self, id: impl Into<String>) -> Self {
467 self.place.id = id.into();
468 self
469 }
470
471 #[must_use]
476 pub fn addressed(mut self, id: impl Into<String>) -> Self {
477 self.place.id = id.into();
478 self.place.addressed = true;
479 self
480 }
481
482 #[must_use]
486 pub fn in_field(mut self, field: impl Into<String>) -> Self {
487 self.place.field = Some(field.into());
488 self
489 }
490
491 #[must_use]
493 pub fn with(mut self, action: Bound<R>) -> Self {
494 self.place.actions.push(action.verb);
495 self
496 }
497
498 pub fn id(&self) -> &str {
499 &self.place.id
500 }
501
502 pub fn label(&self) -> &str {
503 &self.place.label
504 }
505}
506
507impl<R: Resource> Derived<R> {
508 #[must_use]
512 pub fn with_edit(
513 mut self,
514 id: &'static str,
515 label: impl Into<String>,
516 edit: crate::Edit<R>,
517 ) -> Self
518 where
519 crate::Edit<R>: Send + Sync,
520 {
521 let label = label.into();
522 self.place.offers.push(Offer::Edit {
523 id,
524 label: label.clone(),
525 path: edit.path().to_vec(),
526 op: edit.op().clone(),
527 });
528 let decl = ActionDecl::<R>::edit(id, label, edit);
529 self.place
530 .effects
531 .push(crate::resource::declaration_spec(&decl));
532 self
533 }
534
535 #[must_use]
538 pub fn with_edit_asking<V>(
539 mut self,
540 id: &'static str,
541 label: impl Into<String>,
542 param: &'static str,
543 description: &'static str,
544 make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
545 ) -> Self
546 where
547 V: serde::de::DeserializeOwned + crate::JsonSchema,
548 {
549 let decl = ActionDecl::<R>::edit_asking(id, label, param, description, make);
550 self.place
551 .effects
552 .push(crate::resource::declaration_spec(&decl));
553 self.place.offers.push(Offer::Asking);
554 self
555 }
556
557 #[must_use]
559 pub fn publish(&self) -> tilo_actions::ResourceSpec {
560 self.place.publish(crate::vocabulary::<R>())
561 }
562
563 #[must_use]
565 pub fn find(derived: &[Self], id: &str) -> Option<tilo_actions::ResourceSpec> {
566 let vocabulary = crate::vocabulary::<R>();
567 derived
568 .iter()
569 .find_map(|entry| find_published(entry.place.publish(vocabulary), id))
570 }
571}
572
573fn find_published(
575 resource: tilo_actions::ResourceSpec,
576 id: &str,
577) -> Option<tilo_actions::ResourceSpec> {
578 if resource.id.as_str() == id {
579 return Some(resource);
580 }
581 resource
582 .children
583 .into_iter()
584 .find_map(|child| find_published(child, id))
585}
586
587#[derive(Default)]
591pub struct PublishedDerived {
592 resources: Rc<[Rc<tilo_actions::ResourceSpec>]>,
593 offered: HashMap<String, usize>,
596}
597
598impl PublishedDerived {
599 #[must_use]
602 pub fn resources(&self) -> &Rc<[Rc<tilo_actions::ResourceSpec>]> {
603 &self.resources
604 }
605
606 #[must_use]
609 pub fn offers_bound(&self, id: &str, params: usize) -> bool {
610 self.offered.get(id).is_some_and(|&taken| taken < params)
611 }
612
613 #[must_use]
615 pub fn to_resources(&self) -> Vec<tilo_actions::ResourceSpec> {
616 self.resources
617 .iter()
618 .map(|resource| (**resource).clone())
619 .collect()
620 }
621
622 #[must_use]
624 pub fn find(&self, id: &str) -> Option<tilo_actions::ResourceSpec> {
625 fn walk<'a>(
626 resource: &'a tilo_actions::ResourceSpec,
627 id: &str,
628 ) -> Option<&'a tilo_actions::ResourceSpec> {
629 if resource.id.as_str() == id {
630 return Some(resource);
631 }
632 resource.children.iter().find_map(|child| walk(child, id))
633 }
634 self.resources
635 .iter()
636 .find_map(|resource| walk(resource, id))
637 .cloned()
638 }
639}
640
641trait Places {
643 fn len(&self) -> usize;
644 fn place(&self, index: usize) -> Option<&Place>;
645 fn address(&self) -> *const ();
647}
648
649impl<R: 'static> Places for Rc<[Derived<R>]> {
650 fn len(&self) -> usize {
651 <[Derived<R>]>::len(self)
652 }
653
654 fn place(&self, index: usize) -> Option<&Place> {
655 self.get(index).map(|derived| &derived.place)
656 }
657
658 fn address(&self) -> *const () {
659 Rc::as_ptr(self).cast()
660 }
661}
662
663struct Kept {
665 epoch: u64,
666 derived: Rc<dyn Places>,
667 published: Rc<PublishedDerived>,
668}
669
670thread_local! {
671 static PUBLISHED: RefCell<HashMap<TypeId, Rc<Kept>>> = RefCell::new(HashMap::new());
672}
673
674#[must_use]
682pub fn published<R: Resource>(derived: impl Into<Rc<[Derived<R>]>>) -> Rc<PublishedDerived> {
683 let derived: Rc<[Derived<R>]> = derived.into();
684 published_places(
685 TypeId::of::<R>(),
686 crate::vocabulary::<R>(),
687 Rc::new(derived),
688 )
689}
690
691#[must_use]
693pub fn published_nested<R: Resource>() -> Rc<PublishedDerived> {
694 published_places(
695 TypeId::of::<R>(),
696 crate::vocabulary::<R>(),
697 Rc::new(NoPlaces),
698 )
699}
700
701struct NoPlaces;
703
704impl Places for NoPlaces {
705 fn len(&self) -> usize {
706 0
707 }
708
709 fn place(&self, _index: usize) -> Option<&Place> {
710 None
711 }
712
713 fn address(&self) -> *const () {
714 std::ptr::null()
715 }
716}
717
718fn published_places(
720 of: TypeId,
721 vocabulary: &'static crate::Vocabulary,
722 derived: Rc<dyn Places>,
723) -> Rc<PublishedDerived> {
724 let epoch = crate::resource::words_epoch();
725 let kept = PUBLISHED
726 .with_borrow(|kept| kept.get(&of).cloned())
727 .filter(|kept| kept.epoch == epoch);
728 if let Some(kept) = kept.as_ref().filter(|kept| {
729 std::ptr::eq(kept.derived.address(), derived.address()) || equal(&*kept.derived, &*derived)
730 }) {
731 return Rc::clone(&kept.published);
732 }
733 let resources: Rc<[Rc<tilo_actions::ResourceSpec>]> = match &kept {
734 Some(kept) => {
735 let last = &*kept.derived;
736 let nested = kept.published.resources.len().saturating_sub(last.len());
737 let at: HashMap<&str, usize> = (0..last.len())
738 .filter_map(|index| Some((last.place(index)?.id.as_str(), index)))
739 .collect();
740 let published = |index: usize| {
741 kept.published
742 .resources
743 .get(nested.saturating_add(index))
744 .cloned()
745 };
746 kept.published
747 .resources
748 .iter()
749 .take(nested)
750 .cloned()
751 .chain((0..derived.len()).filter_map(|index| {
752 let next = derived.place(index)?;
753 let same = if last.place(index) == Some(next) {
754 Some(index)
755 } else {
756 at.get(next.id.as_str())
757 .copied()
758 .filter(|&at| last.place(at) == Some(next))
759 };
760 Some(
761 same.and_then(published)
762 .unwrap_or_else(|| Rc::new(next.publish(vocabulary))),
763 )
764 }))
765 .collect()
766 }
767 None => crate::child::nested_children_of(vocabulary)
768 .into_iter()
769 .map(Rc::new)
770 .chain(
771 (0..derived.len())
772 .filter_map(|index| derived.place(index))
773 .map(|next| Rc::new(next.publish(vocabulary))),
774 )
775 .collect(),
776 };
777 let mut offered = HashMap::new();
778 for resource in resources.iter() {
779 offered_on(resource, &mut offered);
780 }
781 let published = Rc::new(PublishedDerived { resources, offered });
782 let kept = Rc::new(Kept {
783 epoch,
784 derived,
785 published: Rc::clone(&published),
786 });
787 PUBLISHED.with_borrow_mut(|all| all.insert(of, kept));
788 published
789}
790
791fn equal(a: &dyn Places, b: &dyn Places) -> bool {
793 a.len() == b.len() && (0..a.len()).all(|index| a.place(index) == b.place(index))
794}
795
796fn offered_on(resource: &tilo_actions::ResourceSpec, offered: &mut HashMap<String, usize>) {
799 for spec in &resource.actions {
800 let taken = spec.params().len();
801 offered
802 .entry(spec.id.clone())
803 .and_modify(|fewest| *fewest = (*fewest).min(taken))
804 .or_insert(taken);
805 }
806 for child in &resource.children {
807 offered_on(child, offered);
808 }
809}