Skip to main content

tilo_actions/tree/
target.rs

1//! Reaching an action once its address resolved: a resource named the way an answer names it
2//! (`tasks.tracker/issues/7`), starting the app that publishes it when none runs, and the
3//! call itself, followed until it settles.
4
5use std::time::Duration;
6
7use super::walk::{AppRef, Levels, ROOT_PEEK, Resolved, SETTLE_WAIT, START_WAIT, Tree, Unresolved};
8use super::{Level, Node};
9use crate::remote::{
10    APPLICATION_RESOURCE_PREFIX, APPLICATION_START_ACTION, ActionCallError, ActionProvider,
11    InvocationReceipt, InvocationState, InvokeArgument, InvokeRequest, ReceiptStatus,
12    RemoteActionTarget, workspace_provider,
13};
14use crate::{ActionAddress, InvocationId, InvocationUpdate};
15
16/// What one call came to: its receipt, and the state it settled in (or stood in when the
17/// wait ended) for an admitted one.
18#[derive(Clone, Debug)]
19pub struct Called {
20    pub receipt: InvocationReceipt,
21    pub state: Option<InvocationState>,
22}
23
24impl Called {
25    /// Whether the call has ended: rejected, finished, or settled while it was followed.
26    #[must_use]
27    pub fn ended(&self) -> bool {
28        self.receipt.status.is_terminal()
29            || self
30                .state
31                .as_ref()
32                .is_some_and(InvocationState::is_terminal)
33    }
34
35    /// The update it ended with, when it ended in one.
36    #[must_use]
37    pub fn update(&self) -> Option<&InvocationUpdate> {
38        self.state.as_ref().map(|state| &state.update)
39    }
40}
41
42impl<P: ActionProvider + Sync + Clone + Send + 'static> Tree<P> {
43    /// Call `target` with `argument` under `invocation`, at `revision` when the caller read it
44    /// at one, and follow it for `wait` (none: [`SETTLE_WAIT`]).
45    ///
46    /// A revision is one the caller read a few calls ago, and a directory moves on whenever
47    /// its app's page does: the caller is after the action, not that snapshot. A call refused
48    /// as named at a revision the directory left behind is made once more without one, which
49    /// the provider resolves against the directory as it is now.
50    ///
51    /// # Errors
52    /// The provider refused it before admitting it, or dropped it unanswered.
53    pub async fn invoke(
54        &self,
55        target: RemoteActionTarget,
56        argument: InvokeArgument,
57        invocation: InvocationId,
58        revision: Option<String>,
59        wait: Option<Duration>,
60    ) -> Result<Called, Unresolved> {
61        let request = |revision: Option<String>| InvokeRequest {
62            invocation,
63            target: target.clone(),
64            argument: argument.clone(),
65            context: None,
66            confirmation: None,
67            revision,
68            on_behalf_of: None,
69            wait_ms: None,
70            appearance: None,
71            signed: None,
72        };
73        let named = revision.clone().filter(|revision| !revision.is_empty());
74        let mut receipt = self.admit(request(revision)).await;
75        if named.is_some()
76            && matches!(
77                receipt,
78                Err(Unresolved::Asked(ActionCallError::StaleRevision))
79            )
80        {
81            receipt = self.admit(request(None)).await;
82        }
83        let receipt = receipt?;
84        if let ReceiptStatus::Rejected { error } = &receipt.status {
85            return Err(Unresolved::Asked(error.clone()));
86        }
87        let state = if receipt.status.is_terminal() {
88            self.observed(&receipt.invocation).await
89        } else {
90            self.settled(&receipt.invocation, wait.unwrap_or(SETTLE_WAIT))
91                .await
92        };
93        Ok(Called { receipt, state })
94    }
95
96    async fn admit(&self, request: InvokeRequest) -> Result<InvocationReceipt, Unresolved> {
97        match self.provider().invoke(self.caller(), request).await {
98            Some(Ok(receipt)) => Ok(receipt),
99            Some(Err(refused)) => Err(Unresolved::Asked(refused)),
100            None => Err(Unresolved::Stopped),
101        }
102    }
103
104    /// The state of `invocation` once it settles, or as it stands when `wait` has passed:
105    /// looked at again each time the provider says it may have moved, else after a pause.
106    pub async fn settled(
107        &self,
108        invocation: &InvocationId,
109        wait: Duration,
110    ) -> Option<InvocationState> {
111        let until = self.pause().now().saturating_add(wait);
112        loop {
113            let change = self.provider().next_change(self.caller(), invocation);
114            let state = self.observed(invocation).await;
115            let now = self.pause().now();
116            if state.as_ref().is_none_or(InvocationState::is_terminal) || now >= until {
117                return state;
118            }
119            let left = until.saturating_sub(now);
120            let pause = self.pause().pause(left.min(Duration::from_millis(250)));
121            match change {
122                Some(change) => {
123                    super::walk::within(
124                        &**self.pause(),
125                        left.min(Duration::from_millis(250)),
126                        change,
127                    )
128                    .await;
129                }
130                None => pause.await,
131            }
132        }
133    }
134
135    /// The provider of a running instance of the installed app `app_id`, starting the app in
136    /// the workspace when none runs yet, without a window: where an invocation of the app's
137    /// own actions goes. `wait` is how long its first wait lasts.
138    ///
139    /// # Errors
140    /// The caller may not start it, or it did not start.
141    pub async fn started_provider(
142        &self,
143        app_id: &str,
144        wait: Option<Duration>,
145    ) -> Result<String, Unresolved> {
146        let (app_id, opens) = match self.app_ref(app_id).await? {
147            AppRef::Running { provider, .. } => return Ok(provider),
148            AppRef::Installed { app_id, opens } => (app_id, opens),
149        };
150        if !opens {
151            return Err(Unresolved::MayNotOpen { name: app_id });
152        }
153        // A start still pending is followed under its own id, which answers how it went
154        // rather than starting the app again: a workspace starting many apps at once (hundreds
155        // of fresh ones on a host, each its first) takes longer than one wait, and the call
156        // waits for its app rather than failing.
157        let start = InvocationId::new();
158        let target = RemoteActionTarget {
159            provider: workspace_provider(self.workspace()),
160            address: ActionAddress::new(
161                format!("{APPLICATION_RESOURCE_PREFIX}{app_id}"),
162                APPLICATION_START_ACTION,
163            ),
164        };
165        let deadline = self.pause().now().saturating_add(START_WAIT);
166        let mut called = self
167            .invoke(
168                target.clone(),
169                InvokeArgument::Json(serde_json::Map::new()),
170                start,
171                None,
172                wait,
173            )
174            .await?;
175        while !called.ended() && self.pause().now() < deadline {
176            called = self
177                .invoke(
178                    target.clone(),
179                    InvokeArgument::Json(serde_json::Map::new()),
180                    start,
181                    None,
182                    None,
183                )
184                .await?;
185        }
186        let output = match (&called.receipt.status, called.update()) {
187            (_, Some(InvocationUpdate::Succeeded { output, .. }))
188            | (ReceiptStatus::Completed { output }, None) => output.value.clone(),
189            (_, Some(InvocationUpdate::Failed { error, .. }))
190            | (ReceiptStatus::Failed { error }, None) => {
191                return Err(Unresolved::NotStarted {
192                    app_id,
193                    why: error.message.clone(),
194                    code: error.code.clone(),
195                });
196            }
197            (_, Some(InvocationUpdate::Cancelled { .. }))
198            | (ReceiptStatus::Cancelled { .. }, None) => {
199                return Err(Unresolved::NotStarted {
200                    app_id,
201                    why: "it was cancelled".to_owned(),
202                    code: String::new(),
203                });
204            }
205            _ => {
206                return Err(Unresolved::NotStarted {
207                    app_id,
208                    why: "it is still starting; ask again".to_owned(),
209                    code: String::new(),
210                });
211            }
212        };
213        // The instance the workspace started, as it names it; a host serving the workspace's
214        // records names the record it started the app on.
215        let output = output.unwrap_or_default();
216        let started = output
217            .get("peer_id")
218            .and_then(serde_json::Value::as_u64)
219            .map(|peer| peer.to_string())
220            .or_else(|| {
221                output
222                    .get("provider")
223                    .and_then(serde_json::Value::as_str)
224                    .filter(|provider| crate::remote::is_resource_provider(provider))
225                    .map(str::to_owned)
226            })
227            .ok_or_else(|| {
228                Unresolved::Said(format!("{app_id} started, but named no instance of it"))
229            })?;
230        // The app runs now on `started`: the call after this one invokes it where it is rather
231        // than starting it again.
232        self.saw_running(&app_id, &started);
233        Ok(started)
234    }
235
236    /// The resource `address` names, written either as its listing publishes
237    /// it (`chat.messages/messages/m1`) or in the stable form a link carries
238    /// (`chat.messages.messages:m1`): both name one resource, so both are
239    /// answered alike.
240    ///
241    /// # Errors
242    /// A level on the way could not be read.
243    pub async fn by_item_address(
244        &self,
245        app_id: &str,
246        provider: &str,
247        address: &str,
248        levels: &mut Levels,
249    ) -> Result<Option<Resolved>, Unresolved> {
250        if let Some(found) = self.by_address(app_id, provider, address, levels).await? {
251            return Ok(Some(found));
252        }
253        let Some(form) = crate::item_form_of(address) else {
254            return Ok(None);
255        };
256        self.by_address(app_id, provider, &form, levels).await
257    }
258
259    /// The resource the app lists under exactly `address`, with its actions
260    /// and what it holds: an answer's own naming of what it made or changed.
261    ///
262    /// # Errors
263    /// A level on the way could not be read.
264    pub async fn by_address(
265        &self,
266        app_id: &str,
267        provider: &str,
268        address: &str,
269        levels: &mut Levels,
270    ) -> Result<Option<Resolved>, Unresolved> {
271        let root = self.app_children(provider, levels).await?;
272        let mut found = root
273            .children
274            .iter()
275            .find(|node| node.address_is(address))
276            .cloned();
277        // What a folder of a resource holds is a level further down than
278        // the app's own listing reaches (`notes.notebook/page/<id>/body`).
279        if found.is_none() {
280            let containers: Vec<Node> = root
281                .children
282                .iter()
283                .filter(|node| node.container)
284                .take(ROOT_PEEK)
285                .cloned()
286                .collect();
287            let addressed = |level: &Level| -> Result<Option<Node>, Unresolved> {
288                Ok(level
289                    .whole_children()
290                    .iter()
291                    .find(|node| node.address_is(address))
292                    .cloned())
293            };
294            for container in containers {
295                // An address that begins with a container's key names one of the
296                // container's own, so its level is read on past its bound to find
297                // it; any other container is looked through as far as it was read.
298                let own = address
299                    .strip_prefix(container.key.as_str())
300                    .is_some_and(|rest| rest.starts_with('/'));
301                let node = if own {
302                    self.level_holding(provider, &container.id, levels, addressed)
303                        .await?
304                        .0
305                } else {
306                    addressed(&self.level(provider, &container.id, levels).await?)?
307                };
308                if let Some(node) = node {
309                    found = Some(node);
310                    break;
311                }
312            }
313        }
314        let Some(node) = found else {
315            return Ok(None);
316        };
317        let here = self.level(provider, &node.id, levels).await?;
318        Ok(Some(Resolved {
319            app_id: app_id.to_owned(),
320            provider: provider.to_owned(),
321            path: address.to_owned(),
322            actions: if here.own.is_empty() {
323                node.actions.clone()
324            } else {
325                here.own.clone()
326            },
327            children: here.children.clone(),
328            node: Some(node.clone()),
329            chain: vec![node],
330            levels: std::mem::take(levels),
331            revision: here.revision,
332        }))
333    }
334}