tilo_actions/tree/node.rs
1//! The directory model an address is read through: one resource as a caller
2//! names it, and the resources and actions one listing holds under a parent.
3
4use std::collections::{HashMap, HashSet};
5
6use crate::ActionDescriptor;
7use crate::api::ActionAddress;
8use crate::remote::CatalogueRow;
9use serde_json::{Value, json};
10
11use super::names::{bound_key, path_name};
12
13impl Node {
14 /// This resource as a row of a listing under `parent`: the name its line
15 /// prints, the actions it offers by their ids, and whether a read answers
16 /// it as a resource of its own (`reads`), or it is only a place inside
17 /// what it is listed under (an option, a choice): those are part of their
18 /// parent's read and name no resource, so a walk that reads resources one
19 /// by one reads only the rows that say so.
20 pub fn listing_row(&self, parent: &str, name: &str, resource_type: &str, reads: bool) -> Value {
21 json!({
22 "path": format!("{parent}/{name}"),
23 "name": name,
24 "id": self.id,
25 "key": self.key,
26 "label": self.label,
27 "kind": resource_type,
28 "has_children": self.container,
29 "reads": reads,
30 "actions": self
31 .listed_actions()
32 .map(|action| action.address.action.clone())
33 .collect::<Vec<_>>(),
34 })
35 }
36
37 /// The actions a listing shows it offering: what acts on an item it
38 /// holds is listed on that item, bound to it, and found here only by a
39 /// call that names it.
40 pub fn listed_actions(&self) -> impl Iterator<Item = &ActionDescriptor> {
41 self.actions
42 .iter()
43 .filter(|action| !action.contract.needs_an_item())
44 }
45}
46
47/// The names `rows` share, lowercased, each named among `siblings`
48/// ([`Node::name`]): a line named by one of them is told apart by its id
49/// beside it. Two titles used once each per parent are told apart by their
50/// places instead, so they are not shared.
51pub fn shared_names(rows: &[Node], siblings: &Names<'_>) -> std::collections::HashSet<String> {
52 let mut seen = std::collections::HashSet::new();
53 rows.iter()
54 .map(|row| row.name_in(siblings).trim().to_lowercase())
55 .filter(|name| !seen.insert(name.clone()))
56 .collect()
57}
58
59/// Siblings indexed by their titles: what tells whether a name sets one of
60/// them apart ([`Node::name_in`]) without reading every other sibling, so a
61/// listing of hundreds names each of its rows at the cost of one.
62pub struct Names<'a> {
63 siblings: Vec<&'a Node>,
64 /// Each sibling's index by its title, trimmed and lowercased, in order.
65 titled: HashMap<String, Vec<usize>>,
66}
67
68impl<'a> Names<'a> {
69 pub fn of(siblings: impl IntoIterator<Item = &'a Node>) -> Self {
70 let siblings: Vec<&'a Node> = siblings.into_iter().collect();
71 let mut titled: HashMap<String, Vec<usize>> = HashMap::new();
72 for (at, node) in siblings.iter().enumerate() {
73 titled
74 .entry(node.label.trim().to_ascii_lowercase())
75 .or_default()
76 .push(at);
77 }
78 Self { siblings, titled }
79 }
80
81 /// The siblings titled `title`, trimmed, whatever its case.
82 fn titled(&self, title: &str) -> impl Iterator<Item = &'a Node> + '_ {
83 self.titled
84 .get(&title.trim().to_ascii_lowercase())
85 .into_iter()
86 .flatten()
87 .filter_map(|at| self.siblings.get(*at).copied())
88 }
89
90 /// The siblings `name` names first ([`Node::answers_to`] ranks them `0`):
91 /// the one a title names, or the one whose place among those of its
92 /// title `name` gives (`TODO 2`). Any other answers to it after them, if
93 /// at all.
94 fn first_named(&self, name: &str) -> Vec<&'a Node> {
95 let mut named: Vec<&'a Node> = Vec::new();
96 let mut by_place: Option<&str> = None;
97 if let Some((base, place)) = name.rsplit_once(' ')
98 && !base.trim().is_empty()
99 && place.chars().all(|character| character.is_ascii_digit())
100 && let Ok(place) = place.parse::<usize>()
101 {
102 by_place = Some(base.trim());
103 named.extend(
104 self.titled(base)
105 .filter(|node| place == node.ordinal && place >= 2),
106 );
107 }
108 // A name that is the title itself names the first of that title; a
109 // title its place names above answers only to that place.
110 named.extend(self.titled(name).filter(|node| {
111 node.ordinal <= 1
112 && node.label.trim().eq_ignore_ascii_case(name)
113 && by_place.is_none_or(|base| !node.label.trim().eq_ignore_ascii_case(base))
114 }));
115 named
116 }
117}
118
119/// One resource of an app's directory, as an agent names it.
120#[derive(Clone, Debug)]
121pub struct Node {
122 /// The broker's id: never shown, only sent back.
123 pub id: String,
124 pub resource_type: String,
125 pub label: String,
126 /// The app's own stable name for it: its semantic key, else the logical
127 /// id inside a bound id, else the id.
128 pub key: String,
129 pub parent: String,
130 /// Its place among the siblings that share its title, from 1: what tells
131 /// two pages titled alike apart in a path (`TODO`, `TODO 2`).
132 pub ordinal: usize,
133 pub container: bool,
134 pub actions: Vec<ActionDescriptor>,
135}
136
137impl Node {
138 /// The part of the key that tells two resources of one type apart
139 /// (`notes.page:3fa2…` → `3fa2…`).
140 pub fn token(&self) -> &str {
141 self.key
142 .rsplit([':', '/'])
143 .find(|part| !part.is_empty())
144 .unwrap_or(&self.key)
145 }
146
147 /// Whether `other`'s key names this one's distinguishing part.
148 pub fn owns(&self, other: &Node) -> bool {
149 let token = self.token();
150 token.len() >= 8 && other.key != self.key && other.key.contains(token)
151 }
152
153 /// Whether `other` is this resource's own and not one of its children.
154 pub fn beside(&self, other: &Node) -> bool {
155 self.owns(other) && !other.key.starts_with(&self.key)
156 }
157
158 /// Whether this resource is one of `other`'s: it sits under the other's id.
159 pub fn within(&self, other: &Node) -> bool {
160 matches!(self.id.strip_prefix(other.id.as_str()), Some(rest) if rest.starts_with('/'))
161 }
162
163 /// How well `name` names this node: 0 its label, 1 its key (whole or last
164 /// part), 2 its resource type, 3 the start of either; `None` when it does not.
165 pub fn answers_to(&self, name: &str) -> Option<u8> {
166 let same = |text: &str| text.trim().eq_ignore_ascii_case(name);
167 // A name that is a title and its place among the siblings of that
168 // title (`TODO 2`) names the one whose place it is, and no other:
169 // the title alone names the first.
170 if let Some((base, place)) = name.rsplit_once(' ')
171 && !base.trim().is_empty()
172 && place.chars().all(|character| character.is_ascii_digit())
173 && let Ok(place) = place.parse::<usize>()
174 && self.label.trim().eq_ignore_ascii_case(base.trim())
175 {
176 return (place == self.ordinal && place >= 2).then_some(0);
177 }
178 if same(self.label.trim()) && self.ordinal > 1 {
179 return None;
180 }
181 let tail = |text: &str| {
182 text.rsplit(['.', ':', '/'])
183 .next()
184 .is_some_and(|tail| tail.eq_ignore_ascii_case(name))
185 };
186 if same(&self.label) {
187 return Some(0);
188 }
189 if self.names_id(name) {
190 return Some(1);
191 }
192 if same(&self.resource_type) || tail(&self.resource_type) {
193 return Some(2);
194 }
195 let lower = name.to_lowercase();
196 let starts = |text: &str| text.to_lowercase().starts_with(&lower);
197 (lower.chars().count() >= 3
198 && (starts(&self.label) || (lower.len() >= 6 && starts(self.token()))))
199 .then_some(3)
200 }
201
202 /// Whether `name` is this resource's own id, or the item part of it
203 /// (`<kind>/<field>/<item>`): an id names the resource before any label
204 /// does, whatever the label says.
205 pub fn names_id(&self, name: &str) -> bool {
206 let same = |text: &str| text.trim().eq_ignore_ascii_case(name);
207 let key_tail = self.key.rsplit('/').next().unwrap_or_default();
208 same(&self.key) || same(&self.id) || same(key_tail) || same(self.token())
209 }
210
211 /// The name that goes in a path: its label when it tells it apart from
212 /// `siblings`, else its key's last part (`body`), else its key.
213 pub fn name(&self, siblings: &[Node]) -> String {
214 self.name_in(&Names::of(siblings))
215 }
216
217 /// [`Self::name`] among siblings already indexed by their titles.
218 pub fn name_in(&self, siblings: &Names<'_>) -> String {
219 // Neither what belongs to this resource nor what it is a part of
220 // competes with it: a note titled like its notebook keeps its title.
221 let apart = |name: &str| {
222 !name.trim().is_empty()
223 && siblings
224 .first_named(name)
225 .into_iter()
226 .filter(|other| other.id != self.id)
227 .all(|other| self.owns(other) || self.within(other))
228 };
229 let label = self.label.trim();
230 // A page and the body published beside it share a title but not a
231 // level: only what sits beside this one takes its title.
232 let twin = !label.is_empty()
233 && siblings.titled(label).any(|other| {
234 other.id != self.id
235 && other.parent == self.parent
236 && other.label.trim().eq_ignore_ascii_case(label)
237 });
238 if !label.is_empty() && (apart(label) || twin) {
239 // The one a title names first keeps it; the others wear their
240 // place among them, which the path accepts back.
241 if twin && self.ordinal > 1 {
242 return path_name(&format!("{label} {}", self.ordinal));
243 }
244 return path_name(label);
245 }
246 let tail = self.key.rsplit('/').next().unwrap_or_default();
247 if tail != self.key && apart(tail) {
248 return path_name(tail);
249 }
250 path_name(&self.key)
251 }
252}
253
254/// The resources and actions one directory listing holds under `parent`.
255#[derive(Clone, Default)]
256pub struct Level {
257 /// Actions of the parent itself.
258 pub own: Vec<ActionDescriptor>,
259 pub children: Vec<Node>,
260 /// The directory revision it was read at.
261 pub revision: String,
262 /// The pages it was read from ([`LevelPages`]).
263 pub pages: std::sync::Arc<LevelPages>,
264}
265
266/// The level under `parent` that `rows`, one listing's rows, hold: its own
267/// actions and its children, each with the actions placed on it and its place
268/// among the resources beside it that share its title.
269#[must_use]
270pub fn level_of(rows: &[CatalogueRow], parent: &str) -> Level {
271 let mut level = Level::default();
272 let mut at: HashMap<&str, usize> = HashMap::new();
273 // The actions a page of compact rows described whole, by provider, kind and id: each row
274 // after names them by id ([`tilo_actions::remote::compact`]), and its node takes each
275 // placed on it straight from here, never a row per action first.
276 let mut described: HashMap<(&str, &str, &str), &ActionDescriptor> = HashMap::new();
277 let mut placed: Vec<ActionDescriptor> = Vec::new();
278 for row in rows {
279 placed.clear();
280 let mut identity = None;
281 match &row.offered {
282 Some(offered) => {
283 for action in &offered.described {
284 described.insert(
285 (
286 row.provider.as_str(),
287 action.resource_kind.as_str(),
288 action.address.action.as_str(),
289 ),
290 action,
291 );
292 }
293 identity = offered.semantic_identity.as_ref();
294 for id in &offered.actions {
295 let key = (
296 row.provider.as_str(),
297 row.resource.kind.as_str(),
298 id.as_str(),
299 );
300 let Some(like) = described.get(&key) else {
301 continue;
302 };
303 let mut action = (*like).clone();
304 action.address = ActionAddress::new(row.resource.id.as_str(), id);
305 action.resource_label.clone_from(&row.resource.label);
306 action
307 .semantic_identity
308 .clone_from(&offered.semantic_identity);
309 placed.push(action);
310 }
311 }
312 None => {
313 if let Some(action) = &row.action {
314 identity = action.semantic_identity.as_ref();
315 placed.push(action.clone());
316 }
317 }
318 }
319 if !parent.is_empty() && row.resource.id == parent {
320 level.own.append(&mut placed);
321 continue;
322 }
323 let key = identity
324 .map(|identity| identity.key.clone())
325 .or_else(|| bound_key(&row.resource.id));
326 let index = *at.entry(row.resource.id.as_str()).or_insert_with(|| {
327 level.children.push(Node {
328 id: row.resource.id.clone(),
329 resource_type: row.resource.kind.clone(),
330 label: row.resource.label.clone(),
331 key: key.clone().unwrap_or_else(|| row.resource.id.clone()),
332 parent: row.parent_resource.clone(),
333 ordinal: 1,
334 container: false,
335 actions: Vec::new(),
336 });
337 level.children.len().saturating_sub(1)
338 });
339 if let Some(node) = level.children.get_mut(index) {
340 node.container |= row.has_children;
341 if let Some(key) = key.filter(|_| node.key == node.id) {
342 node.key = key;
343 }
344 node.actions.append(&mut placed);
345 }
346 }
347 // Where each item stands among the siblings sharing its title: what a
348 // path names it by when its title alone would name several.
349 let mut seen: HashMap<String, usize> = HashMap::new();
350 for node in &mut level.children {
351 let title = node.label.trim().to_lowercase();
352 let count = seen.entry(title).or_insert(0);
353 *count = count.saturating_add(1);
354 node.ordinal = *count;
355 }
356 level
357}
358
359impl Node {
360 /// [`Self::name`] as a search result names it: a name that would be
361 /// written with escapes (a file's title, `files/legal/contract.txt`)
362 /// gives way to its key's last part, which an address takes as well, so
363 /// the path reads plainly and the title is shown beside it whole.
364 pub fn found_name(&self, among: &[Node]) -> String {
365 let name = self.name(among);
366 if !name.contains('\\') {
367 return name;
368 }
369 let tail = self.key.rsplit('/').next().unwrap_or_default();
370 for plain in [tail, self.token()] {
371 if !plain.is_empty() && !plain.contains(['/', '#', '\\']) {
372 return plain.to_owned();
373 }
374 }
375 name
376 }
377
378 /// Whether `address` names this resource whole, as an action answers it
379 /// (`tasks.tracker/issues/7`): the id it is published under, or its key.
380 pub fn address_is(&self, address: &str) -> bool {
381 self.id == address || self.key == address
382 }
383}
384
385/// The rows a [`Level`] was read from, where each of its pages after the
386/// first started, and, when the read stopped at its bound before the last
387/// page, where the directory goes on: a listing paging past what was read
388/// reads on from there (the walk that reads a level on), and the next page of
389/// a listing starts at the page its first resource was read in
390/// ([`LsCursor`]).
391#[derive(Clone, Default)]
392pub struct LevelPages {
393 pub rows: Vec<CatalogueRow>,
394 /// The page the rows start in, when the level was read on from a mark: a
395 /// page whose first resources are in it starts there. `None` when the level
396 /// was read from the directory's start, whose page is asked for with no
397 /// cursor.
398 pub first: Option<PageMark>,
399 pub marks: Vec<PageMark>,
400 pub rest: Option<PageMark>,
401}
402
403/// Where one page of a directory starts: the row it starts at among those
404/// read, and the cursor and revision that ask for it.
405#[derive(Clone, Debug, PartialEq, Eq)]
406pub struct PageMark {
407 pub row: usize,
408 pub cursor: Vec<u8>,
409 pub revision: String,
410}
411
412impl Level {
413 /// Whether the directory goes on past what was read.
414 pub fn unread(&self) -> bool {
415 self.pages.rest.is_some()
416 }
417
418 /// The resources of the level every row of which was read. A read that stopped at its
419 /// bound may have stopped inside its last resource, whose other rows (the actions it
420 /// offers, the one that reads it among them) are on the page after: that one is no
421 /// resource to name or act on until the level is read on.
422 pub fn whole_children(&self) -> &[Node] {
423 match self.children.split_last() {
424 Some((_, whole)) if self.unread() => whole,
425 _ => &self.children,
426 }
427 }
428
429 /// Whether the provider's cursors the level was read by are row offsets ([`row_offset`]),
430 /// as far as a cursor it handed out says.
431 fn pages_by_offset(&self) -> bool {
432 self.pages
433 .first
434 .iter()
435 .chain(self.pages.rest.iter())
436 .chain(&self.pages.marks)
437 .next()
438 .is_some_and(|mark| mark.cursor.len() == size_of::<u64>())
439 }
440
441 /// The provider's cursor for the row the resource at `child` among the
442 /// level's rows starts at, the revision it was read at, and how many
443 /// resources that cursor's page holds before it: where a listing's next
444 /// page asks for its first resource, so that page reads from there and not
445 /// from the level's first one. A provider that names its rows by offset is
446 /// asked at the row itself, so nothing of its page comes before it; one
447 /// whose cursors are its own names the page the row is in, and the
448 /// resources before it that page holds. A resource past the rows read
449 /// starts at the page the level goes on from; `None` only when the rows
450 /// read cover the directory whole, so there is nowhere to go on from.
451 pub fn row_mark(&self, parent: &str, child: usize) -> Option<(Vec<u8>, String, usize)> {
452 let rows = &self.pages.rows;
453 let mut seen: HashSet<&str> = HashSet::new();
454 let mut at = None;
455 for (index, row) in rows.iter().enumerate() {
456 let id = row.resource.id.as_str();
457 if (!parent.is_empty() && id == parent) || !seen.insert(id) {
458 continue;
459 }
460 if seen.len() == child.saturating_add(1) {
461 at = Some(index);
462 break;
463 }
464 }
465 let by_offset = self.pages_by_offset();
466 let Some(at) = at else {
467 // The page asks for a resource past those read: it stands on the
468 // page the directory goes on from, if it does, and else after
469 // every row read, where the directory holds nothing more.
470 if let Some(rest) = self.pages.rest.as_ref() {
471 return Some((rest.cursor.clone(), rest.revision.clone(), 0));
472 }
473 if !by_offset {
474 // A provider whose cursor is its own cannot be asked for a row
475 // past the page it last handed out: the page after reads the
476 // level again from its first page.
477 return None;
478 }
479 let mark = self.pages.marks.last()?;
480 let offset = row_offset(&mark.cursor)
481 .saturating_add(spanned(rows.get(mark.row..).unwrap_or_default()));
482 return Some((
483 u64::try_from(offset)
484 .unwrap_or(u64::MAX)
485 .to_le_bytes()
486 .to_vec(),
487 mark.revision.clone(),
488 0,
489 ));
490 };
491 // The marks a level leaves are pages of it, each with the provider's
492 // cursor it started at. A provider counting rows by offset is asked at
493 // the wanted row itself: the rows since the mark move that on by as many as each
494 // stands for. One whose cursors are its own names the page the row is in, and the
495 // resources before it that page holds. A row of the page the level started in,
496 // which leaves no mark, is that many resources into that page, asked for by the
497 // cursor the level was read on from, or by none when it was read from the start.
498 let Some(mark) = self.pages.marks.iter().rev().find(|mark| mark.row <= at) else {
499 let skip = distinct_children(rows.get(..at).unwrap_or_default(), parent);
500 if let Some(first) = self.pages.first.as_ref() {
501 // The level was read on from a mark, and the row is still in that mark's
502 // page: the page the level started in asks for it again.
503 if by_offset {
504 let offset = row_offset(&first.cursor)
505 .saturating_add(spanned(rows.get(..at).unwrap_or_default()));
506 return Some((
507 u64::try_from(offset)
508 .unwrap_or(u64::MAX)
509 .to_le_bytes()
510 .to_vec(),
511 first.revision.clone(),
512 0,
513 ));
514 }
515 return (!first.revision.is_empty()).then_some((
516 first.cursor.clone(),
517 first.revision.clone(),
518 skip,
519 ));
520 }
521 if !by_offset {
522 // The directory's start is asked for with no cursor, and its revision names
523 // the page read: a page that reads on from it is refused as stale once the
524 // directory moves on.
525 return (!self.revision.is_empty())
526 .then(|| (Vec::new(), self.revision.clone(), skip));
527 }
528 if self.revision.is_empty() {
529 return None;
530 }
531 let offset = spanned(rows.get(..at).unwrap_or_default());
532 return Some((
533 u64::try_from(offset)
534 .unwrap_or(u64::MAX)
535 .to_le_bytes()
536 .to_vec(),
537 self.revision.clone(),
538 0,
539 ));
540 };
541 if !by_offset {
542 return Some((
543 mark.cursor.clone(),
544 mark.revision.clone(),
545 distinct_children(rows.get(mark.row..at).unwrap_or_default(), parent),
546 ));
547 }
548 let offset = row_offset(&mark.cursor)
549 .saturating_add(spanned(rows.get(mark.row..at).unwrap_or_default()));
550 Some((
551 u64::try_from(offset)
552 .unwrap_or(u64::MAX)
553 .to_le_bytes()
554 .to_vec(),
555 mark.revision.clone(),
556 0,
557 ))
558 }
559}
560
561/// The row a provider's cursor names: how many rows of the directory it
562/// stands at.
563#[must_use]
564pub fn row_offset(cursor: &[u8]) -> usize {
565 <[u8; 8]>::try_from(cursor)
566 .map(u64::from_le_bytes)
567 .ok()
568 .and_then(|offset| usize::try_from(offset).ok())
569 .unwrap_or(0)
570}
571
572/// How many of the provider's rows `rows` stand for: a resource's actions sent as one row
573/// ([`CatalogueQuery::by_resource`]) are a row each where the provider counts its cursor.
574#[must_use]
575pub fn spanned(rows: &[CatalogueRow]) -> usize {
576 rows.iter()
577 .map(|row| {
578 row.offered
579 .as_ref()
580 .map_or(1, |offered| offered.actions.len().max(1))
581 })
582 .sum()
583}
584
585/// How many resources of the level under `parent` `rows` name: each once,
586/// and never `parent` itself, whose own actions are the level's own.
587#[must_use]
588pub fn distinct_children(rows: &[CatalogueRow], parent: &str) -> usize {
589 let mut seen = HashSet::new();
590 for row in rows {
591 if row.resource.id != parent {
592 seen.insert(row.resource.id.as_str());
593 }
594 }
595 seen.len()
596}