Skip to main content

tilo_resource/
derived.rs

1//! Derived resources: things computed from a record's state that people act
2//! on (the folders of a snippet library, its tags, a smart list), published
3//! as children whose actions are the record's own verbs with some arguments
4//! bound.
5//!
6//! ```ignore
7//! #[resource(kind = "snippets.library", children = Snippets::folders)]
8//! impl Snippets { /* … */ }
9//!
10//! impl Snippets {
11//!     fn folders(&self) -> Vec<Derived<Self>> {
12//!         self.folder_names().map(|name| {
13//!             Derived::new(&name).with(
14//!                 Snippets::NEW_SNIPPET.bind(snippets::NewSnippet::paths().folder, name.clone()),
15//!             )
16//!         }).collect()
17//!     }
18//! }
19//! ```
20
21use 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
34/// A verb with some of its parameters bound: what a derived resource offers.
35pub struct Bound<R> {
36    verb: BoundVerb,
37    marker: PhantomData<fn() -> R>,
38}
39
40/// A [`Bound`] without its resource type, so a [`Place`] holding it is
41/// compared and published by code compiled once.
42#[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    /// Bind one more parameter.
81    #[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    /// This verb, its bound arguments filled, as a declaration of its own
98    /// under `id`, named `label` (`word!("video-editor-split-here")`): what a
99    /// surface offers bound to its view state ("split the clip at the
100    /// playhead"), built and checked as the verb is.
101    #[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
118/// [`Bound::declaration`] of the verb `action` of the resource `vocabulary`
119/// with `values` bound.
120fn 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            // An optional parameter bound to nothing is left out.
150            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    // The same act with some of its arguments given: it wears the verb's
162    // picture, and is found by the words people use for the verb.
163    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    // Bound or not, the verb is undone the same way (or not at all), and
173    // housekeeping stays housekeeping.
174    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    /// This verb with the parameter at `param` (a path of its parameter
205    /// struct, `NewSnippet::paths().folder`) bound to `value`.
206    #[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    /// This verb with nothing bound: every parameter still asked, offered on
212    /// a place as it is on the record (the terminal's verbs on its place).
213    #[must_use]
214    pub fn unbound(&self) -> Bound<R> {
215        Bound::new(self.id, Vec::new())
216    }
217}
218
219/// One derived resource. See the module docs.
220pub struct Derived<R> {
221    place: Place,
222    marker: PhantomData<fn() -> R>,
223}
224
225/// A [`Derived`] without its resource type: what it publishes, compared and
226/// published by code compiled once, in the runtime, rather than into every
227/// app for each resource it declares.
228#[derive(Clone)]
229struct Place {
230    id: String,
231    /// `id` is the whole published address, not a name among its siblings
232    /// beneath the record ([`Derived::addressed`]).
233    addressed: bool,
234    /// The field of the record it is an item of (`blocks`), published as
235    /// `<record kind>/<field>/<id>`; `None` for `<record kind>/derived/<id>`.
236    field: Option<String>,
237    label: String,
238    kind: Option<String>,
239    /// The declared type it is an entity of ([`Derived::typed`]): what search
240    /// names it by, as a document's item names its own type.
241    words: Option<tilo_actions::ResourceType>,
242    actions: Vec<BoundVerb>,
243    effects: Vec<tilo_actions::ActionSpec>,
244    /// What each of `effects` was made from, in order.
245    offers: Vec<Offer>,
246    /// Shared between copies, so a copy is as cheap as the resource alone
247    /// and is told equal to its original without comparing its children.
248    children: Rc<Vec<Place>>,
249}
250
251/// What an offered effect or edit of a [`Derived`] was made from: two equal
252/// offers publish the same action.
253#[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    /// Made by a function of its caller's value, which cannot be compared:
268    /// equal to no other.
269    Asking,
270    /// An operation stated for the row as it stands now, with its own label
271    /// and availability ([`Derived::with_operation`]): compared by what it
272    /// states, so an unchanged one is the resource published last.
273    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    /// The child resource this is published as, among the derived resources
297    /// of a record of `vocabulary`.
298    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        // Built only when a verb is bound here: a long list of derived
320        // places offering effects alone stays cheap to publish.
321        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            // A kind that names its own namespace already is the whole kind;
330            // a bare one (`book`) sits under the record's.
331            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    /// A derived resource named `label`, identified by it among its
374    /// siblings.
375    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    /// Nest `child` beneath it (a table's cells), identified within it.
395    #[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    /// What kind of thing it is among the record's derived resources
402    /// (`folder`, `tag`), published as `<record kind>.<kind>`; a kind that
403    /// names its own namespace (`music.track`) is published as it is.
404    #[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    /// Say what the place is as people name it: it is an entity of the
411    /// declared row type `R`, so search names it by `R`'s words and
412    /// [`LiveRow::declared`](crate::row::LiveRow::declared) publishes it as a
413    /// row of that type.
414    #[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    /// Offer `spec`, an operation of the row as the row stands now: its
421    /// label follows what it shows (`Play`/`Pause`), and one that cannot
422    /// act offers its reason ([`tilo_actions::ActionSpec::unavailable`]).
423    /// [`Self::with_effect`] offers the effect as its declaration reads.
424    #[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    /// Offer the effect `effect` on it, its arguments bound (a view that
436    /// reveals the folder).
437    #[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    /// Offer the effect `effect` on it with the arguments named in `asking`
450    /// left to its caller, the rest bound (select a passage of *this* book,
451    /// from a chapter the caller names).
452    #[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    /// Identify it by `id` rather than its label, when the label can change.
465    #[must_use]
466    pub fn identified(mut self, id: impl Into<String>) -> Self {
467        self.place.id = id.into();
468        self
469    }
470
471    /// Publish it under `id` as a whole rather than as a name among the
472    /// record's derived resources: for a row that already has an address of
473    /// its own, which a search hit, a script or an agent names as it was
474    /// named before (`music.track:<id>`).
475    #[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    /// Publish it as an item of the record's `field` (a document's
483    /// paragraphs, `blocks`), as `<record kind>/<field>/<id>`: what a place
484    /// parameter naming that field takes (`place = "blocks"`).
485    #[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    /// Offer `action` on it.
492    #[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    /// Offer the field edit `edit` on it as the action `id` labelled
509    /// `label`, its value bound ("Use Proton for Adobe Reader" on the app
510    /// it routes): the same edit, checked and recorded as any other.
511    #[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    /// Offer a field edit whose one value its caller supplies
536    /// ([`ActionDecl::edit_asking`]): "Rename playlist" on the playlist.
537    #[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    /// The child resource this is published as.
558    #[must_use]
559    pub fn publish(&self) -> tilo_actions::ResourceSpec {
560        self.place.publish(crate::vocabulary::<R>())
561    }
562
563    /// The published resource `id` among `derived` and their children.
564    #[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
573/// The resource `id` among `resource` and its children.
574fn 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/// A record's nested resources ([`crate::child::record_nested_children`])
588/// and derived ones ([`Derived`]) as published, with the declarations they
589/// offer with arguments bound.
590#[derive(Default)]
591pub struct PublishedDerived {
592    resources: Rc<[Rc<tilo_actions::ResourceSpec>]>,
593    /// Each action id they offer, with the fewest parameters it takes on
594    /// one of them.
595    offered: HashMap<String, usize>,
596}
597
598impl PublishedDerived {
599    /// The published resources, in order: each the very one published last
600    /// while the derived resource it publishes is unchanged.
601    #[must_use]
602    pub fn resources(&self) -> &Rc<[Rc<tilo_actions::ResourceSpec>]> {
603        &self.resources
604    }
605
606    /// Whether some resource offers the declaration `id` with `params`
607    /// parameters with some of its arguments bound.
608    #[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    /// Copies of the published resources, in order.
614    #[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    /// The published resource `id` among them and their children.
623    #[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
641/// The derived resources of one record type, seen without that type.
642trait Places {
643    fn len(&self) -> usize;
644    fn place(&self, index: usize) -> Option<&Place>;
645    /// Where they are held, which stays theirs while they are kept.
646    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
663/// The derived resources a record type published last.
664struct 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/// The nested resources of the record `R` followed by `derived`, published:
675/// the very publication of the last ones of the same resource type when
676/// `derived` are the same ones or equal to them, so a change that leaves a
677/// record's derived resources as they were publishes nothing again and hands
678/// its publisher what it already holds. Otherwise each derived resource
679/// equal to one published last is that very resource again, and only the
680/// others are published. The nested resources depend on the type alone.
681#[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/// [`published`] of a record that derives no resources: its nested ones.
692#[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
701/// The derived resources of a record that derives none.
702struct 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
718/// [`published`] for the record type `of`, whose vocabulary is `vocabulary`.
719fn 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
791/// Whether `a` and `b` are equal, one by one.
792fn 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
796/// Note each action `resource` and its children offer in `offered`, with
797/// the fewest parameters it takes on one of them.
798fn 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}