Skip to main content

tilo_actions/tree/
level.rs

1//! How far a directory listing is read: the reads that page a level in, up to
2//! the pages a first read is bound to or on to the resource a listing wants.
3
4use super::walk::{
5    LEVEL_PAGES, LEVEL_WAIT, Levels, PAGE_ROWS, ROOT_PEEK, Tree, Unresolved, as_the_service,
6    cannot_be_read_now, is_chain, restart_pause,
7};
8use super::{Level, LevelPages, Node, PageMark, distinct_children, level_of};
9use crate::ActionDescriptor;
10use crate::remote::{ActionProvider, CatalogueLimits, CatalogueQuery, CatalogueRow};
11
12/// How often [`Tree::level_from`] reads on from where it stood at the revision a
13/// directory moved on to, while writes beside it keep moving it on.
14const RESUMES: u32 = 16;
15
16/// Whether `level` was read on past the pages its first read is bound to
17/// ([`LEVEL_PAGES`]): each page after the first leaves its mark.
18pub fn read_on(level: &Level) -> bool {
19    level.pages.marks.len() >= LEVEL_PAGES
20}
21
22/// What to ask a provider for so a page reaches `reach` resources of the
23/// level under `parent`, from what `rows` already read: as many rows as a page
24/// taken a resource at a time holds ([`CatalogueQuery::by_resource`]), and the
25/// resources still wanted, one past them to say whether the level goes on
26/// ([`CatalogueQuery::max_resources`]). The provider stops there, building
27/// the resources the page shows and not as many as a guess at the rows each
28/// offers. A read of the whole level keeps to the pages it is bounded to.
29fn page_bounds(rows: &[CatalogueRow], parent: &str, reach: usize) -> (u32, Option<u32>) {
30    if reach == usize::MAX {
31        return (PAGE_ROWS, None);
32    }
33    let wanted = reach
34        .saturating_sub(distinct_children(rows, parent))
35        .saturating_add(1);
36    (
37        crate::remote::MAX_BY_RESOURCE_PAGE,
38        Some(u32::try_from(wanted).unwrap_or(u32::MAX)),
39    )
40}
41
42/// Why a read of a level's pages gave no level.
43enum Unread {
44    /// The app's directory moved on between pages, to the revision named.
45    MovedOn(String),
46    /// The app cannot read its directory right now ([`cannot_be_read_now`]).
47    CannotNow,
48    /// The app the query named could not be listed, and why: what it keeps did
49    /// not mount yet, or the caller may not read it now.
50    Unavailable(String),
51}
52
53impl<P: ActionProvider + Sync + Clone + Send + 'static> Tree<P> {
54    /// `level`, read on until it holds more than `children` resources or
55    /// the directory ends: what a listing paging past the first bounded
56    /// read needs, so every resource a directory holds is reachable.
57    pub async fn level_reaching(
58        &self,
59        provider: &str,
60        parent: &str,
61        mut level: Level,
62        children: usize,
63    ) -> Result<Level, Unresolved> {
64        while level.children.len() <= children && level.unread() {
65            let had = level.children.len();
66            level = self
67                .read_level(provider, parent, Some(level), children.saturating_add(1))
68                .await?
69                .ok_or(Unresolved::KeptChanging)?;
70            // A directory that moved on between every two pages gave its
71            // first pages again: what they hold is what can be listed now.
72            if level.children.len() <= had {
73                break;
74            }
75        }
76        Ok(level)
77    }
78
79    /// The directory level under `parent`, and the resource `find` picks out of it: the
80    /// level is read on past its bound until `find` picks one or the directory ends. A read
81    /// that names one resource so finds it wherever it falls in the directory, where a level
82    /// read only to its bound would say a resource past it is not there. `find` picks among
83    /// [`Level::whole_children`], so the resource it finds has all its actions. The level,
84    /// as far as it was read, is kept in `levels`.
85    pub async fn level_holding(
86        &self,
87        provider: &str,
88        parent: &str,
89        levels: &mut Levels,
90        find: impl Fn(&Level) -> Result<Option<Node>, Unresolved> + Send,
91    ) -> Result<(Option<Node>, Level), Unresolved> {
92        let mut level = self.level(provider, parent, levels).await?;
93        let mut found = find(&level)?;
94        while found.is_none() && level.unread() {
95            level = self
96                .read_level(provider, parent, Some(level), usize::MAX)
97                .await?
98                .ok_or(Unresolved::KeptChanging)?;
99            levels.insert(parent.to_owned(), level.clone());
100            found = find(&level)?;
101        }
102        Ok((found, level))
103    }
104
105    /// The directory under `parent` from the page `mark` names on, until it
106    /// holds more than `children` resources or ends.
107    ///
108    /// A directory that moved on since `mark` was read is read on from the same row at the
109    /// revision it stands at now, as often as it moves on meanwhile ([`RESUMES`]): writes
110    /// beside a listing (an import's) move a directory on between every two pages of it, and
111    /// read again from its first page, a listing of thousands never got back to where it
112    /// stood before the next write, and answered pages of nothing while its cursor went on.
113    /// A provider whose cursor does not carry over to another revision refuses it again, and
114    /// the read is `None` as the directory moved on.
115    pub async fn level_from(
116        &self,
117        provider: &str,
118        parent: &str,
119        mark: PageMark,
120        children: usize,
121    ) -> Result<Option<Level>, Unresolved> {
122        let mut level = Level {
123            pages: std::sync::Arc::new(LevelPages {
124                first: Some(mark.clone()),
125                rest: Some(mark),
126                ..LevelPages::default()
127            }),
128            ..Level::default()
129        };
130        let mut resumed = 0_u32;
131        while level.children.len() <= children && level.unread() {
132            let before = level.clone();
133            let read = match self
134                .read_pages(provider, parent, level, children.saturating_add(1))
135                .await
136            {
137                Ok(read) => read,
138                // The continuation names a page read before the directory
139                // changed, which its source no longer holds: there is no
140                // level from that mark, and the caller reads the level from
141                // its first page.
142                Err(Unresolved::Asked(crate::remote::ActionCallError::StaleRevision)) => {
143                    return Ok(None);
144                }
145                Err(error) => return Err(error),
146            };
147            match read {
148                Ok(read) => level = read,
149                Err(Unread::MovedOn(now)) if resumed < RESUMES && !now.is_empty() => {
150                    resumed = resumed.saturating_add(1);
151                    let mut pages = std::sync::Arc::unwrap_or_clone(before.pages);
152                    // A mark that names the directory's start carries no source cursor: the
153                    // start read at another revision is not the row the page stood at, so the
154                    // caller reads the level from its first page instead.
155                    let Some(rest) = pages
156                        .rest
157                        .as_mut()
158                        .filter(|rest| rest.revision != now && !rest.cursor.is_empty())
159                    else {
160                        return Ok(None);
161                    };
162                    // A page the level started in reads on at the revision the directory
163                    // stands at now, as the mark it was read from does.
164                    let cursor = rest.cursor.clone();
165                    if let Some(first) = pages.first.as_mut().filter(|first| first.cursor == cursor)
166                    {
167                        first.revision.clone_from(&now);
168                    }
169                    rest.revision = now;
170                    level = Level {
171                        pages: std::sync::Arc::new(pages),
172                        ..before
173                    };
174                }
175                Err(_) => return Ok(None),
176            }
177        }
178        Ok(Some(level))
179    }
180
181    /// Up to [`LEVEL_PAGES`] pages of the directory under `parent`, from
182    /// the start or on from where `from` stopped, and no page past the
183    /// `reach`th resource while fewer would not do: a listing asks for the
184    /// resources its page holds, not a fixed stretch of the directory. It
185    /// starts again from the first page while the directory moves on between
186    /// pages or the app cannot read it.
187    pub async fn read_level(
188        &self,
189        provider: &str,
190        parent: &str,
191        from: Option<Level>,
192        reach: usize,
193    ) -> Result<Option<Level>, Unresolved> {
194        // A level is one snapshot: every page of it at one revision. When the
195        // app's directory moves on between pages (its document changed, or an
196        // invocation refreshed it), what was read belongs to the old revision
197        // and the read starts again from the first page at the new one, for
198        // as long as an action is waited for, pausing longer each time a
199        // directory that keeps changing is read again. An app that cannot
200        // read its directory right now, as while another actor's action is
201        // being applied, is read again the same way: that is not a level
202        // with nothing in it, and once the wait is over the caller is told
203        // the app cannot list, never that it lacks what was named.
204        let deadline = self.pause().now().checked_add(LEVEL_WAIT);
205        let mut from = from.unwrap_or_default();
206        let mut reads: u32 = 0;
207        loop {
208            let pause = restart_pause(reads);
209            if !pause.is_zero()
210                && let Some(deadline) = deadline
211            {
212                let now = self.pause().now();
213                let until = now
214                    .checked_add(pause)
215                    .map_or(deadline, |until| until.min(deadline));
216                self.pause().pause(until.saturating_sub(now)).await;
217            }
218            reads = reads.saturating_add(1);
219            let unread = match self.read_pages(provider, parent, from, reach).await? {
220                Ok(read) => return Ok(Some(read)),
221                Err(unread) => unread,
222            };
223            if deadline.is_none_or(|deadline| self.pause().now() >= deadline) {
224                return match unread {
225                    Unread::MovedOn(_) => Ok(None),
226                    Unread::CannotNow => Err(Unresolved::CannotListNow),
227                    Unread::Unavailable(reason) => Err(Unresolved::Unavailable(reason)),
228                };
229            }
230            from = Level::default();
231        }
232    }
233
234    /// Up to [`LEVEL_PAGES`] pages of the directory under `parent` on from where `from` stopped,
235    /// without starting again, saying why they gave no level when they gave none, and stopping
236    /// once the directory holds more than `reach` resources.
237    async fn read_pages(
238        &self,
239        provider: &str,
240        parent: &str,
241        from: Level,
242        reach: usize,
243    ) -> Result<Result<Level, Unread>, Unresolved> {
244        let LevelPages {
245            mut rows,
246            first,
247            mut marks,
248            rest,
249        } = std::sync::Arc::unwrap_or_clone(from.pages);
250        let (mut cursor, mut revision) = rest.map_or((Vec::new(), None), |mark| {
251            (mark.cursor, Some(mark.revision))
252        });
253        let mut read_at = from.revision;
254        let mut rest = None;
255        let held = rows.len();
256        for page in 0..LEVEL_PAGES {
257            if !cursor.is_empty() {
258                marks.push(PageMark {
259                    row: rows.len(),
260                    cursor: cursor.clone(),
261                    revision: revision.clone().unwrap_or_default(),
262                });
263            }
264            let (max_results, max_resources) = page_bounds(&rows, parent, reach);
265            let asked = self
266                .ask(CatalogueQuery {
267                    provider: Some(provider.to_owned()),
268                    parent_resource: (!parent.is_empty()).then(|| parent.to_owned()),
269                    cursor: std::mem::take(&mut cursor),
270                    revision: revision.take(),
271                    max_results,
272                    max_resources,
273                    limits: Some(CatalogueLimits {
274                        max_bytes: Some(65536),
275                        max_work: Some(512),
276                        max_depth: Some(16),
277                    }),
278                    by_resource: true,
279                    ..CatalogueQuery::default()
280                })
281                .await?;
282            if asked.stale_cursor {
283                // A read bounded to what a listing shows keeps the pages it
284                // holds, all of one revision, and leaves the rest to whoever
285                // pages past them: while an import writes between every two
286                // pages, starting again never read past the first, and the
287                // listing failed after its whole wait.
288                if reach != usize::MAX
289                    && rows.len() > held
290                    && marks.last().is_some_and(|mark| mark.row == rows.len())
291                {
292                    rest = marks.pop();
293                    break;
294                }
295                return Ok(Err(Unread::MovedOn(asked.revision)));
296            }
297            // What the caller named could not be listed: said in place of a
298            // level with nothing in it, and looked for again while the wait
299            // lasts, as a directory still being read is.
300            if let Some(reason) = &asked.unavailable {
301                return Ok(Err(Unread::Unavailable(reason.clone())));
302            }
303            if cannot_be_read_now(&asked) {
304                return Ok(Err(Unread::CannotNow));
305            }
306            rows.extend(asked.rows);
307            read_at.clone_from(&asked.revision);
308            if asked.exhausted || asked.next_cursor.is_empty() {
309                break;
310            }
311            // Enough resources for the caller: where the directory goes on
312            // is kept, so reading the next page starts there.
313            if reach != usize::MAX && distinct_children(&rows, parent) > reach {
314                rest = Some(PageMark {
315                    row: rows.len(),
316                    cursor: asked.next_cursor,
317                    revision: asked.revision,
318                });
319                break;
320            }
321            if page.saturating_add(1) == LEVEL_PAGES {
322                rest = Some(PageMark {
323                    row: rows.len(),
324                    cursor: asked.next_cursor,
325                    revision: asked.revision,
326                });
327                break;
328            }
329            revision = Some(asked.revision);
330            cursor = asked.next_cursor;
331        }
332        let mut read = level_of(&rows, parent);
333        read.revision = read_at;
334        read.pages = std::sync::Arc::new(LevelPages {
335            rows,
336            first,
337            marks,
338            rest,
339        });
340        Ok(Ok(read))
341    }
342
343    /// The resources an app's path starts from: its top-level resources and
344    /// the resources inside its containers (a notebook's pages are the app's
345    /// own), with the containers' own actions (`notes#new-page`). A root
346    /// resource's actions are the app's too, each under the root it is
347    /// published on (`notes/Notes#new_note`). A chain among them holds the
348    /// app's items: it is listed first, with the items it holds, and its
349    /// actions are the app's before any other's (`notes#new_note`).
350    pub async fn app_children(
351        &self,
352        provider: &str,
353        levels: &mut Levels,
354    ) -> Result<Level, Unresolved> {
355        self.app_children_reading(provider, levels, None).await
356    }
357
358    /// [`Self::app_children`] for a listing: what each container and chain
359    /// holds is read as far as one page of the listing reaches, `reaching`
360    /// resources and one past them so that the page and whether more follow
361    /// are whole ([`Self::listed_level`]), not the whole of it. A tracker of
362    /// thousands of issues read whole took several pages, each waiting behind
363    /// whatever the workspace was writing, and while an import wrote between
364    /// every two of them the read never held one revision and the listing
365    /// failed.
366    pub async fn app_children_listed(
367        &self,
368        provider: &str,
369        levels: &mut Levels,
370        reaching: usize,
371    ) -> Result<Level, Unresolved> {
372        self.app_children_reading(provider, levels, Some(reaching))
373            .await
374    }
375
376    /// The level under `parent` a listing shows: read near first, so a
377    /// level it does not page past costs a page ([`Self::level_near`]), then
378    /// on until it holds more than `reaching` resources ([`Self::level_reaching`]).
379    /// A listing of an app's own page merges what its containers hold and
380    /// pages it by offset: the rows it merges are the ones up to the page's
381    /// end, one past it saying more follow, and no resource later is built.
382    async fn listed_level(
383        &self,
384        provider: &str,
385        parent: &str,
386        levels: &mut Levels,
387        reaching: usize,
388    ) -> Result<Level, Unresolved> {
389        let near = self.level_near(provider, parent, levels).await?;
390        self.level_reaching(provider, parent, near, reaching).await
391    }
392
393    async fn app_children_reading(
394        &self,
395        provider: &str,
396        levels: &mut Levels,
397        listing: Option<usize>,
398    ) -> Result<Level, Unresolved> {
399        let mut root = self.level(provider, "", levels).await?;
400        // The app's own resources, before a container's items are listed beside them: a root
401        // resource is one of these, and what it offers is the app's to name.
402        let roots: Vec<Node> = root.children.clone();
403        let containers: Vec<Node> = root
404            .children
405            .iter()
406            .filter(|node| node.container)
407            .take(ROOT_PEEK)
408            .cloned()
409            .collect();
410        for node in containers {
411            let inside = match listing {
412                Some(reaching) => {
413                    self.listed_level(provider, &node.id, levels, reaching)
414                        .await?
415                }
416                None => self.level(provider, &node.id, levels).await?,
417            };
418            for child in inside.whole_children() {
419                if !root.children.iter().any(|seen| seen.id == child.id) {
420                    root.children.push(child.clone());
421                }
422            }
423            root.own.extend(inside.own);
424        }
425        let chains: Vec<Node> = root
426            .children
427            .iter()
428            .filter(|node| is_chain(&node.id))
429            .take(ROOT_PEEK)
430            .cloned()
431            .collect();
432        let mut own: Vec<ActionDescriptor> = Vec::new();
433        for chain in chains.iter().rev() {
434            root.children.retain(|node| node.id != chain.id);
435            root.children.insert(0, chain.clone());
436        }
437        for chain in &chains {
438            for action in &chain.actions {
439                if !own
440                    .iter()
441                    .any(|seen| seen.address.action == action.address.action)
442                {
443                    own.push(action.clone());
444                }
445            }
446            if chain.container {
447                let inside = match listing {
448                    Some(reaching) => {
449                        self.listed_level(provider, &chain.id, levels, reaching)
450                            .await?
451                    }
452                    None => self.level(provider, &chain.id, levels).await?,
453                };
454                for child in inside.whole_children() {
455                    if !root.children.iter().any(|seen| seen.id == child.id) {
456                        root.children.push(child.clone());
457                    }
458                }
459            }
460        }
461        // An action of the same id elsewhere is reached through its resource.
462        root.own.retain(|action| {
463            !own.iter()
464                .any(|chain| chain.address.action == action.address.action)
465        });
466        own.append(&mut root.own);
467        root.own = own;
468        // A host service's one resource is the service itself, before its actions are taken
469        // for an app's root's.
470        as_the_service(provider, &mut root);
471        // A root resource's actions are the app's own, each under the root it is published on
472        // (`notes/Notes#new_note`), so a listing of the app offers them one call away. A control
473        // the window draws, or a host's operation, is no root: it is addressed, never listed.
474        for node in roots
475            .iter()
476            .filter(|node| !crate::kind_mirrors_a_control(&node.resource_type))
477        {
478            for action in node.listed_actions() {
479                if !root
480                    .own
481                    .iter()
482                    .any(|seen| seen.address.action == action.address.action)
483                {
484                    root.own.push(action.clone());
485                }
486            }
487        }
488        let all = root.children.clone();
489        root.children
490            .retain(|node| !all.iter().any(|owner| owner.beside(node)));
491        Ok(root)
492    }
493}