Skip to main content

tilo_resource/resource/
head.rs

1use super::{
2    ActionSpec, Own, Resource, Vocabulary, publish_own, type_epoch, vocabulary, weakening_now,
3};
4
5/// [`publish`](super::publish) without the children: the resource's identity, actions and
6/// views exactly as `publish` gives them, at a cost that does not grow with
7/// the children ([`Resource::children_offer_bound`]). What controls bind to.
8pub fn publish_head<R: Resource>(
9    id: &str,
10    label: &str,
11    state: &R::State,
12) -> tilo_actions::ResourceSpec {
13    publish_head_of::<R>(id, label, &head_inputs::<R>(state))
14}
15
16/// What [`publish_head`] reads of a state. Two states with equal inputs
17/// publish the same head, so a publisher holding the head of one keeps it
18/// for the other.
19#[derive(Clone, Debug, PartialEq)]
20pub struct HeadInputs {
21    epoch: u64,
22    offered: Vec<&'static str>,
23    availability: Vec<tilo_actions::Availability>,
24    views: Vec<tilo_actions::ResourceViewSpec>,
25    now: Vec<(String, String)>,
26}
27
28/// [`HeadInputs`] of `state`: what its head is published from, read
29/// without publishing a child or an action.
30#[must_use]
31pub fn head_inputs<R: Resource>(state: &R::State) -> HeadInputs {
32    let declarations = vocabulary::<R>().declarations();
33    HeadInputs {
34        epoch: type_epoch(),
35        offered: R::children_offer_bound(state),
36        availability: declarations
37            .iter()
38            .map(|decl| R::availability(state, decl.id))
39            .collect(),
40        views: R::views(state),
41        now: weakening_now::<R>(state),
42    }
43}
44
45/// [`publish_head`] of a state whose inputs are `inputs`.
46#[must_use]
47pub fn publish_head_of<R: Resource>(
48    id: &str,
49    label: &str,
50    inputs: &HeadInputs,
51) -> tilo_actions::ResourceSpec {
52    publish_head_from(vocabulary::<R>(), R::local_operations(), id, label, inputs)
53}
54
55/// Kept apart from the resource type so it is compiled once, in the runtime,
56/// and not again into every app for each resource it declares.
57fn publish_head_from(
58    vocabulary: &'static Vocabulary,
59    local_operations: Vec<ActionSpec>,
60    id: &str,
61    label: &str,
62    inputs: &HeadInputs,
63) -> tilo_actions::ResourceSpec {
64    let declarations = vocabulary.declarations();
65    let availability = |action: &str| {
66        declarations
67            .iter()
68            .position(|decl| decl.id == action)
69            .and_then(|at| inputs.availability.get(at))
70            .cloned()
71            .unwrap_or_default()
72    };
73    let own = Own {
74        availability: Some(&availability),
75        views: inputs.views.clone(),
76        local_operations,
77        now: inputs.now.clone(),
78    };
79    publish_own(vocabulary, id, label, own, &|decl| {
80        inputs.offered.contains(&decl.id)
81    })
82}