Skip to main content

tilo_actions/remote/
catalogue.rs

1//! Browsing what a provider offers: a paged, filtered catalogue query.
2//!
3//! A provider may offer many actions, some behind applications that publish a
4//! live, revision-bound directory rather than a flat list. A caller never
5//! pulls the whole corpus: it asks for one bounded [`CataloguePage`] at a
6//! time — everything, one provider, one application's rows, the children of
7//! one resource, rows matching a needle, or exactly one target re-materialized
8//! at the revision it was chosen from — and follows the opaque `next_cursor`.
9
10use serde::{Deserialize, Serialize};
11
12use crate::api::{ActionAddress, ActionDescriptor};
13use crate::contract::ActionContract;
14use crate::resource::ResourcePresentation;
15
16use super::RemoteActionTarget;
17
18/// Largest page a provider returns, whatever a query asks for.
19pub const MAX_CATALOGUE_PAGE: u32 = 256;
20
21/// The most bytes a page's rows take, encoded, whatever their count: half a
22/// frame ([`super::MAX_REMOTE_ACTION_FRAME_BYTES`]), so the page goes out as
23/// one with the publishers and packages beside it. A page that reaches it ends
24/// there and its cursor goes on from the first row it left out.
25pub const MAX_CATALOGUE_PAGE_BYTES: usize = super::MAX_REMOTE_ACTION_FRAME_BYTES / 2;
26
27/// The most rows a page of a listing taken a resource at a time
28/// ([`CatalogueQuery::by_resource`]) answers: a resource's rows travel as one
29/// there, so a page this long still holds a couple of hundred resources.
30pub const MAX_BY_RESOURCE_PAGE: u32 = 16_384;
31
32const fn default_page() -> u32 {
33    64
34}
35
36/// One exact existing resource whose inert local-view metadata is requested.
37/// The transport supplies identity and current workspace authority independently.
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct ViewResourceQuery {
41    /// Record-local resource address, never a display label.
42    pub id: String,
43    /// Expected resource kind; a different publisher cannot satisfy the lookup.
44    pub kind: String,
45}
46
47/// A provider-issued navigation locator. It carries no access grant or credentials.
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ResourceViewLocator {
51    /// Provider-configured HTTPS listener origin.
52    pub origin: String,
53    /// The workspace this locator is for, supplied by the provider.
54    pub workspace: String,
55    /// Certified provider device key as hexadecimal.
56    #[serde(rename = "hostDevice")]
57    pub host_device: String,
58    /// Exact existing record provider checked by the provider.
59    pub provider: String,
60    /// The web entry base (`https://tilo.so/`, ending in `/`) the operator serves
61    /// the browser bundle under; links to this provider's resources are minted
62    /// under it. Absent until a compatible bundle is hosted.
63    #[serde(default, rename = "webEntry", skip_serializing_if = "Option::is_none")]
64    pub web_entry: Option<String>,
65}
66
67/// Exact document route whose broker-owned live publisher is requested.
68/// This selects ownership, not permission: ordinary caller authorization still applies.
69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct CanonicalActionRoute {
72    pub workspace: String,
73    pub app_id: String,
74    /// Empty names the package-primary record, never any record.
75    pub document_id: String,
76}
77
78/// One bounded request for catalogue rows. Every field narrows; the empty
79/// query lists the first page of everything offered.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct CatalogueQuery {
82    /// Provider-only lookup of one exact route's owner. Cannot accompany
83    /// a provider, cursor, target, view lookup, or row filter.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub canonical_route: Option<CanonicalActionRoute>,
86    /// Only rows from this provider (a token a previous page issued).
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub provider: Option<String>,
89    /// Only rows published by this application. It narrows the rows a provider
90    /// builds and pages — before the page bound — while the providers the
91    /// caller may browse are listed either way.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub app_id: Option<String>,
94    /// Read-only view discovery, separate from the document action catalogue.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub view_resource: Option<ViewResourceQuery>,
97    /// Only the direct children of this resource; `None` is the top level
98    /// for a listing, and every level for a query that names words
99    /// ([`Self::needle`]): a search finds a row wherever in the tree it
100    /// stands.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub parent_resource: Option<String>,
103    /// Only rows whose labels, ids or parameters contain this text
104    /// (case-insensitive).
105    #[serde(default, skip_serializing_if = "String::is_empty")]
106    pub needle: String,
107    /// Only resources this names: their kind, or their label ignoring ASCII
108    /// case, at the top level or, with [`Self::parent_resource`], among that
109    /// resource's direct children. A provider answers it whole, wherever the
110    /// resource would fall in a paged listing; it takes no cursor or needle.
111    /// A provider from before parents were named answers with top-level rows,
112    /// whose parent says so.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub resource_name: Option<String>,
115    /// Only this exact action, re-resolved against the provider now: the
116    /// check to make immediately before invoking a row from an older page.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub target: Option<ActionAddress>,
119    /// Only the action with this id, wherever the provider publishes it: the
120    /// lookup of an action named by its app alone. An agent hears here of one
121    /// only the person at the publishing device takes
122    /// ([`crate::Availability::shown_here`]), which no listing offers it.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub action: Option<String>,
125    /// The revision `cursor` (or `target`) was obtained at. A provider refuses a
126    /// cursor from another revision as stale rather than skipping rows.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub revision: Option<String>,
129    /// Opaque continuation from the previous page; empty starts over.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub cursor: Vec<u8>,
132    /// Upper bound on rows, clamped to [`MAX_CATALOGUE_PAGE`]. With no
133    /// provider named, zero asks only for [`CataloguePage::providers`].
134    #[serde(default = "default_page")]
135    pub max_results: u32,
136    /// Optional upper bounds on the work a provider spends answering.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub limits: Option<CatalogueLimits>,
139    /// The rows each resource offers sent as one ([`CatalogueRow::offered`],
140    /// [`compact`]), and a page up to [`MAX_BY_RESOURCE_PAGE`] rows long:
141    /// what a listing of resources asks, which shows each resource's actions
142    /// by their ids. Cursors still count the rows each stands for.
143    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
144    pub by_resource: bool,
145    /// Upper bound on the resources a page holds rows of, as well as on its
146    /// rows: the page ends after the last row of that many resources. What a
147    /// caller listing a number of resources asks, so that a provider builds
148    /// those and not as many rows as it guessed they offer.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub max_resources: Option<u32>,
151}
152
153impl Default for CatalogueQuery {
154    fn default() -> Self {
155        Self {
156            canonical_route: None,
157            provider: None,
158            app_id: None,
159            view_resource: None,
160            parent_resource: None,
161            needle: String::new(),
162            resource_name: None,
163            target: None,
164            action: None,
165            revision: None,
166            cursor: Vec::new(),
167            max_results: default_page(),
168            limits: None,
169            by_resource: false,
170            max_resources: None,
171        }
172    }
173}
174
175impl CatalogueQuery {
176    /// A query that re-resolves exactly `target` at `revision`.
177    #[must_use]
178    pub fn resolve(target: &RemoteActionTarget, revision: impl Into<String>) -> Self {
179        Self {
180            provider: Some(target.provider.clone()),
181            target: Some(target.address.clone()),
182            revision: Some(revision.into()),
183            max_results: 1,
184            ..Self::default()
185        }
186    }
187
188    /// The resources a page may hold rows of ([`Self::max_resources`]), at
189    /// least one: a page always moves the listing on.
190    #[must_use]
191    pub fn resource_bound(&self) -> Option<usize> {
192        self.max_resources
193            .map(|most| usize::try_from(most).unwrap_or(usize::MAX).max(1))
194    }
195
196    /// The page size a provider honours for this query.
197    #[must_use]
198    pub fn page_size(&self) -> usize {
199        let most = if self.by_resource {
200            MAX_BY_RESOURCE_PAGE
201        } else {
202            MAX_CATALOGUE_PAGE
203        };
204        usize::try_from(self.max_results.clamp(1, most)).unwrap_or(1)
205    }
206}
207
208/// Bounds on how much work a provider spends on one page. Each is an upper
209/// bound a provider may lower, never a hint to exceed.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
211pub struct CatalogueLimits {
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub max_bytes: Option<u32>,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub max_work: Option<u32>,
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub max_depth: Option<u16>,
218}
219
220/// A resource as a catalogue row describes it.
221#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
222pub struct CatalogueResource {
223    pub id: String,
224    pub kind: String,
225    pub label: String,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub presentation: Option<ResourcePresentation>,
228}
229
230impl CatalogueResource {
231    /// Whether `name` names this resource: its id, the item part of its id
232    /// (an item's id is `<kind>/<field>/<item>`, and `<item>` names it as
233    /// its own id does), its kind, or its label ignoring ASCII case. An id
234    /// is matched exactly, where a label is matched in any case.
235    #[must_use]
236    pub fn is_named(&self, name: &str) -> bool {
237        let item_of_id = self.id.rsplit_once('/').map(|(_, item)| item);
238        self.id == name
239            || item_of_id == Some(name)
240            || self.kind == name
241            || self.label.eq_ignore_ascii_case(name)
242    }
243}
244
245/// One row: an action on a resource, or a resource that contains more.
246#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
247pub struct CatalogueRow {
248    /// Provider-issued token naming the publisher; copy it into an invocation.
249    pub provider: String,
250    /// Stable id of the publishing application.
251    pub app_id: String,
252    /// The resource this row sits under; empty at the top level.
253    #[serde(default, skip_serializing_if = "String::is_empty")]
254    pub parent_resource: String,
255    pub resource: CatalogueResource,
256    /// The action this row offers; `None` for a resource-only row.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub action: Option<ActionDescriptor>,
259    /// Whether querying with this resource as the parent yields more rows.
260    #[serde(default)]
261    pub has_children: bool,
262    /// For a resource-only row, the permission-bearing action that
263    /// discloses it, when the provider declared one.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub visibility: Option<RowVisibility>,
266    /// For an application, the surface its signed package publishes, in the
267    /// form it is kept by (`collab_types::surface::canonical`): what an agent
268    /// generates its typed client from, without the app having to open.
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub surface: Option<String>,
271    /// The actions the resource offers, in place of a row each, on a page of
272    /// a listing taken a resource at a time ([`CatalogueQuery::by_resource`]);
273    /// `action` is then none. [`expand`] gives the rows back.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub offered: Option<Box<Offered>>,
276}
277
278/// What one resource offers, as a row of a listing taken a resource at a
279/// time carries it ([`CatalogueRow::offered`]).
280#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
281pub struct Offered {
282    /// The ids of its actions, in the order its rows stood.
283    pub actions: Vec<String>,
284    /// The resource's semantic identity, as each of its actions carries it.
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub semantic_identity: Option<crate::ResourceSemanticIdentity>,
287    /// Its actions whole that no row before it on the page described for a
288    /// resource of its kind: the rows of that kind after it name them by id.
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub described: Vec<ActionDescriptor>,
291}
292
293impl CatalogueRow {
294    /// How many rows of its listing this row stands for: one, or each action
295    /// of a resource sent as one ([`compact`]). What a cursor counts.
296    #[must_use]
297    pub fn weight(&self) -> usize {
298        self.offered
299            .as_ref()
300            .map_or(1, |offered| offered.actions.len().max(1))
301    }
302}
303
304/// The rows `rows` stand for, each counted as its [`CatalogueRow::weight`].
305#[must_use]
306pub fn rows_weight(rows: &[CatalogueRow]) -> usize {
307    rows.iter().map(CatalogueRow::weight).sum()
308}
309
310/// `rows` cut to the first `count` rows they stand for: a resource sent as one
311/// row keeps the actions before the cut.
312pub fn truncate_rows(rows: &mut Vec<CatalogueRow>, count: usize) {
313    let mut kept = 0usize;
314    let mut cut = rows.len();
315    for (at, row) in rows.iter_mut().enumerate() {
316        let left = count.saturating_sub(kept);
317        if left == 0 {
318            cut = at;
319            break;
320        }
321        let weight = row.weight();
322        if weight > left
323            && let Some(offered) = row.offered.as_mut()
324        {
325            offered.actions.truncate(left);
326        }
327        kept = kept.saturating_add(weight.min(left));
328    }
329    rows.truncate(cut);
330}
331
332/// `rows` cut after the rows of their first `count` resources, each
333/// resource's rows next to each other: whether any were cut.
334pub fn truncate_resources(rows: &mut Vec<CatalogueRow>, count: usize) -> bool {
335    let mut seen = 0usize;
336    let mut last: Option<&str> = None;
337    let mut cut = rows.len();
338    for (at, row) in rows.iter().enumerate() {
339        let id = row.resource.id.as_str();
340        if last != Some(id) {
341            if seen == count {
342                cut = at;
343                break;
344            }
345            seen = seen.saturating_add(1);
346            last = Some(id);
347        }
348    }
349    let cutting = cut < rows.len();
350    rows.truncate(cut);
351    cutting
352}
353
354/// `rows` cut after the last of them that keeps their encoding within `budget`
355/// bytes, and whether any were cut. The first row always stays, so a page
356/// always moves its listing on. Each row is counted whole, as it is sent
357/// outside a listing taken a resource at a time, which a resource's rows sent
358/// as one ([`compact`]) never exceed.
359pub fn truncate_bytes(rows: &mut Vec<CatalogueRow>, budget: usize) -> bool {
360    let mut spent = 0usize;
361    let cut = rows.iter().enumerate().position(|(at, row)| {
362        // A comma between rows, and the row as serde writes it.
363        let size =
364            serde_json::to_vec(row).map_or(usize::MAX, |bytes| bytes.len().saturating_add(1));
365        spent = spent.saturating_add(size);
366        at > 0 && spent > budget
367    });
368    let Some(cut) = cut else {
369        return false;
370    };
371    rows.truncate(cut);
372    true
373}
374
375/// `rows` with each resource's consecutive action rows sent as one row
376/// ([`CatalogueRow::offered`]): an action is described whole the first time a
377/// resource of its kind offers it on the page, and by its id after that. A row
378/// naming no action is kept as it is. [`expand`] undoes it.
379#[must_use]
380pub fn compact(rows: Vec<CatalogueRow>) -> Vec<CatalogueRow> {
381    let mut described: std::collections::HashSet<(String, String, String)> =
382        std::collections::HashSet::new();
383    let mut out: Vec<CatalogueRow> = Vec::new();
384    for mut row in rows {
385        let Some(action) = row.action.take() else {
386            out.push(row);
387            continue;
388        };
389        let first = (action.resource_kind.clone(), action.address.action.clone());
390        let named = (row.provider.clone(), first.0, first.1);
391        let fresh = described.insert(named);
392        if let Some(last) = out.last_mut()
393            && let Some(offered) = last.offered.as_mut()
394            && last.resource.id == row.resource.id
395            && last.parent_resource == row.parent_resource
396            && last.provider == row.provider
397            && last.app_id == row.app_id
398        {
399            last.has_children |= row.has_children;
400            offered.actions.push(action.address.action.clone());
401            if fresh {
402                offered.described.push(action);
403            }
404            continue;
405        }
406        row.offered = Some(Box::new(Offered {
407            actions: vec![action.address.action.clone()],
408            semantic_identity: action.semantic_identity.clone(),
409            described: if fresh { vec![action] } else { Vec::new() },
410        }));
411        out.push(row);
412    }
413    out
414}
415
416/// The rows [`compact`] sent as one, a row per action again, each action
417/// described as the page first described it for a resource of its kind and
418/// placed on this one. A row whose action the page never described is kept
419/// as one row with no action, so nothing it lists is lost.
420#[must_use]
421pub fn expand(rows: Vec<CatalogueRow>) -> Vec<CatalogueRow> {
422    if rows.iter().all(|row| row.offered.is_none()) {
423        return rows;
424    }
425    let mut described: std::collections::HashMap<(String, String, String), ActionDescriptor> =
426        std::collections::HashMap::new();
427    let mut out = Vec::with_capacity(rows.len());
428    for mut row in rows {
429        let Some(offered) = row.offered.take() else {
430            out.push(row);
431            continue;
432        };
433        let Offered {
434            actions,
435            semantic_identity,
436            described: whole,
437        } = *offered;
438        for action in whole {
439            described.insert(
440                (
441                    row.provider.clone(),
442                    action.resource_kind.clone(),
443                    action.address.action.clone(),
444                ),
445                action,
446            );
447        }
448        let mut any = false;
449        for id in actions {
450            let key = (row.provider.clone(), row.resource.kind.clone(), id);
451            let Some(like) = described.get(&key) else {
452                continue;
453            };
454            let mut action = like.clone();
455            action.address = ActionAddress::new(row.resource.id.as_str(), &key.2);
456            action.resource_label.clone_from(&row.resource.label);
457            action.semantic_identity.clone_from(&semantic_identity);
458            let mut each = row.clone();
459            each.action = Some(action);
460            out.push(each);
461            any = true;
462        }
463        if !any {
464            out.push(row);
465        }
466    }
467    out
468}
469
470impl CatalogueRow {
471    /// A top-level row offering `action` on the resource it addresses.
472    #[must_use]
473    pub fn for_action(
474        provider: impl Into<String>,
475        app_id: impl Into<String>,
476        action: ActionDescriptor,
477    ) -> Self {
478        Self {
479            offered: None,
480            provider: provider.into(),
481            app_id: app_id.into(),
482            parent_resource: String::new(),
483            resource: CatalogueResource {
484                id: action.address.resource.clone(),
485                kind: action.resource_kind.clone(),
486                label: action.resource_label.clone(),
487                presentation: None,
488            },
489            action: Some(action),
490            has_children: false,
491            visibility: None,
492            surface: None,
493        }
494    }
495
496    /// A row offering `action` in the row it stands in: the resource of the
497    /// level above it, and whether its own resource holds rows below it, so a
498    /// reader that asks a level at a time knows where the listing continues.
499    #[must_use]
500    pub fn for_placed_action(
501        provider: impl Into<String>,
502        app_id: impl Into<String>,
503        placed: crate::api::PlacedAction,
504    ) -> Self {
505        let crate::api::PlacedAction {
506            parent,
507            has_children,
508            action,
509        } = placed;
510        Self {
511            parent_resource: parent,
512            has_children,
513            ..Self::for_action(provider, app_id, action)
514        }
515    }
516
517    /// The target that invokes this row's action.
518    #[must_use]
519    pub fn target(&self) -> Option<RemoteActionTarget> {
520        self.action.as_ref().map(|action| RemoteActionTarget {
521            provider: self.provider.clone(),
522            address: action.address.clone(),
523        })
524    }
525
526    /// Whether this row is worth returning for `needle`. A provider narrows a
527    /// query to one word here; whatever it keeps is then matched more
528    /// closely, so this keeps every row a word begins in any of the row's
529    /// names — the action's id, label and description, its parameters, the
530    /// resource's label and kind — rather than only those whose text holds
531    /// the needle verbatim. A caller asking for "draw" is after
532    /// "Draw a pointer path", and one asking for "scrolling" after a
533    /// "scroll" the description spells as "Scroll down with `PageDown`".
534    fn matches(&self, needle: &str) -> bool {
535        if needle.is_empty() {
536            return true;
537        }
538        let needle = needle.to_lowercase();
539        // The same word in another inflection names the same action: a
540        // caller asking for "scrolling" is after the row that spells
541        // "scroll", and one asking for "draw" after "drawing".
542        let stem = stem_word(&needle);
543        let mut fields = vec![
544            self.resource.label.as_str(),
545            self.resource.kind.as_str(),
546            self.resource.id.as_str(),
547            self.app_id.as_str(),
548        ];
549        if let Some(action) = &self.action {
550            fields.extend([action.action_label.as_str(), action.address.action.as_str()]);
551            fields.extend(action.keywords.iter().map(String::as_str));
552            fields.extend(action.description.as_deref());
553            for param in &action.params {
554                fields.extend([param.name.as_ref(), param.description.as_ref()]);
555            }
556        }
557        fields.iter().any(|field| {
558            let field = field.to_lowercase();
559            field.contains(&needle)
560                || field.split(|c: char| !c.is_alphanumeric()).any(|word| {
561                    word.starts_with(&needle)
562                        || (word.chars().count() >= 3 && stem_word(word) == stem)
563                })
564        })
565    }
566}
567
568/// The action that discloses a resource-only row, and its contract.
569#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
570pub struct RowVisibility {
571    pub action: String,
572    pub contract: ActionContract,
573    /// The operation whose contract discloses this row. Missing on legacy
574    /// publications; brokers must not infer that an unknown Read is public.
575    #[serde(default, skip_serializing_if = "Option::is_none")]
576    pub governing_kind: Option<crate::OperationKind>,
577}
578
579/// A publisher the caller may browse or invoke.
580#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
581pub struct CatalogueProvider {
582    pub provider: String,
583    pub app_id: String,
584    /// The workspace the publisher belongs to.
585    pub workspace: String,
586    /// The publisher's own record, when it names one.
587    #[serde(default, skip_serializing_if = "String::is_empty")]
588    pub document_id: String,
589    /// Whether it publishes a live directory worth browsing by parent.
590    #[serde(default)]
591    pub browsable: bool,
592}
593
594/// What a provider a device registered publishes, read as a package code calls its actions by
595/// (`use so.tilo.migrate.engine as engine`, then `engine.start(source: "home")`): the app its
596/// resources name, the name people call it, and each resource with the address its actions are
597/// called at. A call of one goes out as any app's call does; the device's dispatch finds the
598/// provider by the address.
599#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
600pub struct ProvidedPackage {
601    pub app: String,
602    pub title: String,
603    pub resources: Vec<ProvidedResource>,
604}
605
606/// One resource of a [`ProvidedPackage`]: where its actions are called, and what they take.
607#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
608pub struct ProvidedResource {
609    pub address: String,
610    pub surface: crate::surface::Surface,
611}
612
613impl ProvidedPackage {
614    /// The package `resources` make: named by the app the first of them says it is published
615    /// by, and by its label. `None` when none names an app: such a provider is reached by
616    /// querying it, not compiled against.
617    #[must_use]
618    pub fn of(resources: &[crate::ResourceSpec]) -> Option<Self> {
619        let named = resources.iter().find(|spec| spec.app_id.is_some())?;
620        Some(Self {
621            app: named.app_id.clone()?,
622            title: named.label.clone(),
623            resources: resources
624                .iter()
625                .map(|spec| ProvidedResource {
626                    address: spec.id.as_str().to_owned(),
627                    surface: crate::surface::of_resource(spec),
628                })
629                .collect(),
630        })
631    }
632}
633
634#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
635pub struct CataloguePage {
636    /// Opaque revision the page, its cursor and its targets belong to.
637    pub revision: String,
638    pub rows: Vec<CatalogueRow>,
639    /// Present only on a fresh authorized view lookup with a routable provider.
640    #[serde(default, skip_serializing_if = "Option::is_none")]
641    pub locator: Option<ResourceViewLocator>,
642    /// For a query naming no provider: the publishers the caller may use.
643    #[serde(default, skip_serializing_if = "Vec::is_empty")]
644    pub providers: Vec<CatalogueProvider>,
645    /// For a query naming no provider: what each provider this device registered publishes at
646    /// fixed addresses, as a package code calls it by ([`ProvidedPackage`]).
647    #[serde(default, skip_serializing_if = "Vec::is_empty")]
648    pub packages: Vec<ProvidedPackage>,
649    /// Continuation for the next page; empty when there is none.
650    #[serde(default, skip_serializing_if = "Vec::is_empty")]
651    pub next_cursor: Vec<u8>,
652    /// No rows remain past this page.
653    #[serde(default)]
654    pub exhausted: bool,
655    /// The query's cursor belonged to another revision; start over.
656    #[serde(default)]
657    pub stale_cursor: bool,
658    /// The provider stopped at a work limit, not at the end.
659    #[serde(default)]
660    pub budget_exhausted: bool,
661    /// Why the app the query named could not be listed: what it keeps did not
662    /// mount on this device, or the caller may not read it now. Such a page holds
663    /// no rows, and a caller tells the reason rather than taking the app for one
664    /// that lists nothing.
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub unavailable: Option<String>,
667}
668
669impl CataloguePage {
670    /// Filter and page rows a provider holds in memory: the publishing
671    /// application, parent, needle, exact target and the offset cursor, all
672    /// against `revision`. Every filter narrows before the page bound, so a
673    /// wanted row is never left out because another row came first.
674    #[must_use]
675    pub fn from_rows(revision: String, rows: Vec<CatalogueRow>, query: &CatalogueQuery) -> Self {
676        if !query.cursor.is_empty() && query.revision.as_deref() != Some(revision.as_str()) {
677            return Self::stale(revision);
678        }
679        let mut matching = rows.into_iter().filter(|row| query.admits(row));
680        let rows: Vec<_> = matching
681            .by_ref()
682            .skip(query.offset())
683            .take(query.page_size())
684            .collect();
685        let mut rows = rows;
686        let mut more = matching.next().is_some();
687        if let Some(most) = query.resource_bound() {
688            more |= truncate_resources(&mut rows, most);
689        }
690        Self::window(revision, rows, query, more)
691    }
692
693    /// The page `query` asks of the actions the tree `resources` publishes, offered as
694    /// `provider`: what a provider that serves one app's published tree answers. Its revision
695    /// names what the tree offers, so a cursor read before the tree changed starts again.
696    #[must_use]
697    pub fn published(
698        provider: &str,
699        resources: &[crate::ResourceSpec],
700        query: &CatalogueQuery,
701    ) -> Self {
702        let rows: Vec<CatalogueRow> = crate::api::survey_placed(resources)
703            .into_iter()
704            .map(|placed| CatalogueRow::for_placed_action(provider, provider, placed))
705            .collect();
706        let offered = serde_json::to_vec(&rows).unwrap_or_default();
707        let revision = format!("{provider}:{}", blake3::hash(&offered).to_hex());
708        Self::from_rows(revision, rows, query)
709    }
710
711    /// A page at `revision` whose cursor was read at another: the caller
712    /// starts again from the first page.
713    #[must_use]
714    pub fn stale(revision: String) -> Self {
715        Self {
716            revision,
717            stale_cursor: true,
718            ..Self::default()
719        }
720    }
721
722    /// A page at `revision` whose app `reason` says could not be listed:
723    /// no rows, and the reason in their place.
724    #[must_use]
725    pub fn unavailable(revision: String, reason: String) -> Self {
726        Self {
727            revision,
728            unavailable: Some(reason),
729            ..Self::default()
730        }
731    }
732
733    /// The page `query` asks for, from `rows`: the rows it admits
734    /// ([`CatalogueQuery::admits`]) from its cursor on ([`CatalogueQuery::offset`]),
735    /// at most [`CatalogueQuery::page_size`] of them, and whether `more` follow.
736    /// What a provider that pages its rows where they are kept answers with, so
737    /// that a page costs its rows and not every row there is.
738    #[must_use]
739    pub fn window(
740        revision: String,
741        rows: Vec<CatalogueRow>,
742        query: &CatalogueQuery,
743        more: bool,
744    ) -> Self {
745        let mut rows = rows;
746        let more = truncate_bytes(&mut rows, MAX_CATALOGUE_PAGE_BYTES) || more;
747        let next = query.offset().saturating_add(rows_weight(&rows));
748        // A listing taken a resource at a time is sent so; its cursor still
749        // counts the rows each resource stands for.
750        let rows = if query.by_resource {
751            compact(rows)
752        } else {
753            rows
754        };
755        Self {
756            revision,
757            rows,
758            locator: None,
759            next_cursor: if more {
760                u64::try_from(next)
761                    .unwrap_or(u64::MAX)
762                    .to_le_bytes()
763                    .to_vec()
764            } else {
765                Vec::new()
766            },
767            exhausted: !more,
768            ..Self::default()
769        }
770    }
771}
772
773impl CatalogueQuery {
774    /// Whether `row` is one this query lists: under the parent asked for,
775    /// of the app, view, words, name and action it names. An exact action
776    /// is found wherever it stands, since its address names it alone, and so
777    /// is a row whose words hold a needle asked for with no parent named: a
778    /// search ranges over the whole tree, where a browse names one place.
779    #[must_use]
780    pub fn admits(&self, row: &CatalogueRow) -> bool {
781        let named_parent = self.parent_resource.as_deref().unwrap_or("");
782        let searched = self.parent_resource.is_none() && !self.needle.is_empty();
783        (self.target.is_some()
784            || self.action.is_some()
785            || searched
786            || row.parent_resource == named_parent)
787            && self.app_id.as_deref().is_none_or(|app| row.app_id == app)
788            && self.view_resource.as_ref().is_none_or(|wanted| {
789                row.resource.id == wanted.id
790                    && row.resource.kind == wanted.kind
791                    && row
792                        .action
793                        .as_ref()
794                        .is_some_and(|action| action.kind == crate::OperationKind::View)
795            })
796            && row.matches(&self.needle)
797            && self
798                .resource_name
799                .as_deref()
800                .is_none_or(|name| row.resource.is_named(name))
801            && self
802                .action
803                .as_ref()
804                .is_none_or(|id| row.action.as_ref().is_some_and(|a| a.address.action == *id))
805            && self.target.as_ref().is_none_or(|target| {
806                row.action
807                    .as_ref()
808                    .is_some_and(|action| action.address == *target)
809            })
810    }
811
812    /// How many of the rows it admits this query's cursor is past.
813    #[must_use]
814    pub fn offset(&self) -> usize {
815        offset_of(&self.cursor)
816    }
817}
818
819fn offset_of(cursor: &[u8]) -> usize {
820    <[u8; 8]>::try_from(cursor)
821        .map(u64::from_le_bytes)
822        .ok()
823        .and_then(|offset| usize::try_from(offset).ok())
824        .unwrap_or(0)
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use crate::{ExecutionLocus, InputSpec, OperationKind};
831
832    fn row(resource: &str, action: Option<&str>, parent: &str) -> CatalogueRow {
833        CatalogueRow {
834            offered: None,
835            provider: "7".into(),
836            app_id: "notes".into(),
837            parent_resource: parent.into(),
838            resource: CatalogueResource {
839                id: resource.into(),
840                kind: "notes.note".into(),
841                label: resource.into(),
842                presentation: None,
843            },
844            action: action.map(|action| ActionDescriptor {
845                did: None,
846                state: crate::ActionState::default(),
847                semantic_identity: None,
848                address: ActionAddress::new(resource, action),
849                resource_kind: "notes.note".into(),
850                resource_label: resource.into(),
851                action_label: action.into(),
852                keywords: Vec::new(),
853                icon: None,
854                description: None,
855                locus: ExecutionLocus::ClientLocal,
856                kind: OperationKind::Document,
857                contract: ActionContract::default(),
858                input: InputSpec::None,
859                params: Vec::new(),
860                view: None,
861            }),
862            has_children: action.is_none(),
863            visibility: None,
864            surface: None,
865        }
866    }
867
868    /// A page bounded in resources ends after the last row of the last one
869    /// it may hold, says more follow, and its cursor goes on at the next
870    /// resource's first row: three resources of two actions each, asked two
871    /// at a time.
872    #[test]
873    fn a_page_bounded_in_resources_ends_after_its_last_resource() {
874        let rows: Vec<_> = ["note:a", "note:b", "note:c"]
875            .iter()
876            .flat_map(|note| [row(note, Some("open"), ""), row(note, Some("archive"), "")])
877            .collect();
878        let query = CatalogueQuery {
879            max_results: 64,
880            max_resources: Some(2),
881            ..CatalogueQuery::default()
882        };
883        let first = CataloguePage::from_rows("r1".into(), rows.clone(), &query);
884        let listed: Vec<_> = first
885            .rows
886            .iter()
887            .map(|row| row.resource.id.as_str())
888            .collect();
889        assert_eq!(listed, ["note:a", "note:a", "note:b", "note:b"]);
890        assert!(!first.exhausted, "a third resource follows");
891        let second = CataloguePage::from_rows(
892            "r1".into(),
893            rows,
894            &CatalogueQuery {
895                cursor: first.next_cursor,
896                revision: Some("r1".into()),
897                ..query
898            },
899        );
900        let listed: Vec<_> = second
901            .rows
902            .iter()
903            .map(|row| row.resource.id.as_str())
904            .collect();
905        assert_eq!(listed, ["note:c", "note:c"]);
906        assert!(second.exhausted);
907    }
908
909    /// The row `resource` of application `app`, with a `run` action.
910    fn app_row(app: &str, resource: &str) -> CatalogueRow {
911        let mut row = row(resource, Some("run"), "");
912        row.app_id = app.into();
913        row
914    }
915
916    tilo_test_env::scenario! {
917        fn a_catalogue_pages_filters_and_matches_its_rows;
918
919        phase in_memory_rows_page_filter_and_refuse_stale_cursors;
920        {
921            let rows = (0..5)
922                .map(|index| row(&format!("note:{index}"), Some("archive"), ""))
923                .chain([
924                    row("folder:a", None, ""),
925                    row("note:a1", Some("open"), "folder:a"),
926                ])
927                .collect::<Vec<_>>();
928            let first = CataloguePage::from_rows(
929                "r1".into(),
930                rows.clone(),
931                &CatalogueQuery {
932                    max_results: 4,
933                    ..CatalogueQuery::default()
934                },
935            );
936            assert_eq!(first.rows.len(), 4);
937            assert!(!first.exhausted);
938            let second = CataloguePage::from_rows(
939                "r1".into(),
940                rows.clone(),
941                &CatalogueQuery {
942                    max_results: 4,
943                    cursor: first.next_cursor.clone(),
944                    revision: Some("r1".into()),
945                    ..CatalogueQuery::default()
946                },
947            );
948            assert_eq!(second.rows.len(), 2, "the remaining top-level rows");
949            assert!(second.exhausted);
950            let stale = CataloguePage::from_rows(
951                "r2".into(),
952                rows.clone(),
953                &CatalogueQuery {
954                    cursor: first.next_cursor,
955                    revision: Some("r1".into()),
956                    ..CatalogueQuery::default()
957                },
958            );
959            assert!(stale.stale_cursor && stale.rows.is_empty());
960
961            let named = |name: &str| {
962                CataloguePage::from_rows(
963                    "r1".into(),
964                    rows.clone(),
965                    &CatalogueQuery {
966                        resource_name: Some(name.into()),
967                        max_results: 4,
968                        ..CatalogueQuery::default()
969                    },
970                )
971            };
972            let by_label = named("NOTE:4");
973            assert_eq!(by_label.rows.len(), 1, "a label past the first page");
974            assert_eq!(by_label.rows[0].resource.id, "note:4");
975            assert!(named("note:a1").rows.is_empty(), "only the top level");
976            assert_eq!(named("notes.note").rows.len(), 4, "a kind names each");
977
978            let children = CataloguePage::from_rows(
979                "r1".into(),
980                rows.clone(),
981                &CatalogueQuery {
982                    parent_resource: Some("folder:a".into()),
983                    ..CatalogueQuery::default()
984                },
985            );
986            assert_eq!(children.rows.len(), 1);
987            let needle = CataloguePage::from_rows(
988                "r1".into(),
989                rows.clone(),
990                &CatalogueQuery {
991                    needle: "NOTE:3".into(),
992                    ..CatalogueQuery::default()
993                },
994            );
995            assert_eq!(needle.rows.len(), 1);
996            let exact = CataloguePage::from_rows(
997                "r1".into(),
998                rows,
999                &CatalogueQuery::resolve(
1000                    &RemoteActionTarget {
1001                        provider: "7".into(),
1002                        address: ActionAddress::new("note:2", "archive"),
1003                    },
1004                    "r1",
1005                ),
1006            );
1007            assert_eq!(exact.rows.len(), 1);
1008            assert_eq!(
1009                exact.rows[0].target().map(|target| target.address),
1010                Some(ActionAddress::new("note:2", "archive"))
1011            );
1012        }
1013
1014        phase an_exact_action_is_found_below_the_top_level;
1015        {
1016            let rows = vec![
1017                row("folder:a", None, ""),
1018                row("note:a1", Some("open"), "folder:a"),
1019            ];
1020            let target = RemoteActionTarget {
1021                provider: "7".into(),
1022                address: ActionAddress::new("note:a1", "open"),
1023            };
1024            let page =
1025                CataloguePage::from_rows("r1".into(), rows, &CatalogueQuery::resolve(&target, "r1"));
1026            assert_eq!(page.rows.len(), 1);
1027        }
1028
1029        phase an_id_names_its_resource_and_an_items_id_part_names_the_item;
1030        {
1031            let mut item = row("tasks.issues/issues/7", Some("delete"), "");
1032            item.resource.label = "Fix the roof".into();
1033            let rows = vec![row("tracker", None, ""), item];
1034            let named = |name: &str| {
1035                CataloguePage::from_rows(
1036                    "r1".into(),
1037                    rows.clone(),
1038                    &CatalogueQuery {
1039                        resource_name: Some(name.into()),
1040                        ..CatalogueQuery::default()
1041                    },
1042                )
1043            };
1044            let whole = named("tasks.issues/issues/7");
1045            assert_eq!(whole.rows.len(), 1, "the id names the item");
1046            let part = named("7");
1047            assert_eq!(part.rows.len(), 1, "the item part of the id names it");
1048            assert_eq!(part.rows[0].resource.id, "tasks.issues/issues/7");
1049            assert!(named("issue").rows.is_empty(), "not the id's middle");
1050        }
1051
1052        phase an_app_filter_narrows_before_the_page_bound;
1053        {
1054            let wanted = app_row("so.tilo.shortcuts", "shortcuts.shortcut:tidy");
1055            let rows = (0..MAX_CATALOGUE_PAGE)
1056                .map(|index| app_row("so.tilo.notes", &format!("note:{index}")))
1057                .chain([wanted.clone()])
1058                .collect::<Vec<_>>();
1059            let query = |app_id: Option<&str>| CatalogueQuery {
1060                app_id: app_id.map(str::to_owned),
1061                max_results: MAX_CATALOGUE_PAGE,
1062                ..CatalogueQuery::default()
1063            };
1064            let scoped =
1065                CataloguePage::from_rows("r1".into(), rows.clone(), &query(Some("so.tilo.shortcuts")));
1066            assert_eq!(scoped.rows, [wanted], "the one row of the app asked for");
1067            assert!(scoped.exhausted && scoped.next_cursor.is_empty());
1068
1069            let unfiltered = CataloguePage::from_rows("r1".into(), rows, &query(None));
1070            assert_eq!(
1071                unfiltered.rows.len(),
1072                usize::try_from(MAX_CATALOGUE_PAGE).unwrap_or(usize::MAX)
1073            );
1074            assert!(
1075                unfiltered
1076                    .rows
1077                    .iter()
1078                    .all(|row| row.app_id == "so.tilo.notes"),
1079                "the wanted row sits past the first page when nothing narrows it"
1080            );
1081            assert!(!unfiltered.exhausted);
1082        }
1083
1084        phase an_app_filter_is_optional_on_the_wire;
1085        {
1086            let legacy: CatalogueQuery =
1087                serde_json::from_value(serde_json::json!({ "max_results": 4 })).unwrap();
1088            assert_eq!(legacy.app_id, None);
1089            let scoped = CatalogueQuery {
1090                app_id: Some("so.tilo.shortcuts".into()),
1091                ..CatalogueQuery::default()
1092            };
1093            assert_eq!(
1094                serde_json::to_value(&scoped).unwrap()["app_id"],
1095                "so.tilo.shortcuts"
1096            );
1097            assert!(
1098                serde_json::to_value(CatalogueQuery::default())
1099                    .unwrap()
1100                    .get("app_id")
1101                    .is_none(),
1102                "a query with no app filter says nothing about one"
1103            );
1104        }
1105
1106        phase a_needle_matches_an_inflection_of_a_described_word;
1107        {
1108            let mut scroll = row("page:1", Some("press-page"), "");
1109            if let Some(action) = scroll.action.as_mut() {
1110                action.description =
1111                    Some("Scroll down the page with PageDown, or Space for a screenful.".into());
1112            }
1113            let mut draw = row("page:1", Some("pointer-path"), "");
1114            if let Some(action) = draw.action.as_mut() {
1115                action.description = Some("Moves the pointer as drawing a signature does.".into());
1116            }
1117            let rows = vec![draw, scroll];
1118            let actions = |needle: &str| {
1119                CataloguePage::from_rows(
1120                    "r1".into(),
1121                    rows.clone(),
1122                    &CatalogueQuery {
1123                        needle: needle.into(),
1124                        ..CatalogueQuery::default()
1125                    },
1126                )
1127                .rows
1128                .iter()
1129                .filter_map(|row| row.action.as_ref().map(|a| a.address.action.clone()))
1130                .collect::<Vec<_>>()
1131            };
1132            // The word the caller types and the word the description spells are
1133            // the same word in another inflection.
1134            assert_eq!(actions("scrolling"), ["press-page"]);
1135            assert_eq!(actions("draw"), ["pointer-path"]);
1136            assert_eq!(actions("drawing"), ["pointer-path"]);
1137            // A word nothing spells still matches nothing.
1138            assert!(actions("printing").is_empty());
1139        }
1140
1141        phase a_needle_matches_parameter_names_and_descriptions;
1142        {
1143            let mut format = row("sheet:1", Some("format-cells"), "");
1144            if let Some(action) = format.action.as_mut() {
1145                action.params = vec![crate::ActionParam::optional(
1146                    "bold",
1147                    crate::ParamType::Boolean,
1148                    "Heavier text",
1149                )];
1150            }
1151            let rows = vec![row("sheet:1", Some("sort-rows"), ""), format];
1152            for needle in ["BOLD", "heavier"] {
1153                let page = CataloguePage::from_rows(
1154                    "r1".into(),
1155                    rows.clone(),
1156                    &CatalogueQuery {
1157                        needle: needle.into(),
1158                        ..CatalogueQuery::default()
1159                    },
1160                );
1161                let actions: Vec<_> = page
1162                    .rows
1163                    .iter()
1164                    .filter_map(|row| row.action.as_ref().map(|a| a.address.action.as_str()))
1165                    .collect();
1166                assert_eq!(actions, ["format-cells"], "{needle}");
1167            }
1168        }
1169
1170        phase a_needle_searches_every_level_of_the_tree_and_a_listing_names_one;
1171        {
1172            // A row standing under a parent, as a workspace's people name
1173            // themselves on the tree's own members path.
1174            let nested = row("workspace/members", Some("name"), "workspace");
1175            let root = row("workspace", Some("publish"), "");
1176            let rows = vec![root, nested];
1177            let listed = |query: CatalogueQuery| {
1178                CataloguePage::from_rows("r1".into(), rows.clone(), &query)
1179                    .rows
1180                    .iter()
1181                    .filter_map(|row| row.action.as_ref().map(|a| a.address.action.clone()))
1182                    .collect::<Vec<_>>()
1183            };
1184            assert_eq!(
1185                listed(CatalogueQuery::default()),
1186                ["publish"],
1187                "a listing with nothing named is the top level"
1188            );
1189            assert_eq!(
1190                listed(CatalogueQuery {
1191                    parent_resource: Some("workspace".into()),
1192                    ..CatalogueQuery::default()
1193                }),
1194                ["name"],
1195                "a listing that names a place is that place's children"
1196            );
1197            assert_eq!(
1198                listed(CatalogueQuery {
1199                    needle: "nam".into(),
1200                    ..CatalogueQuery::default()
1201                }),
1202                ["name"],
1203                "a search finds a row under a parent with no parent named"
1204            );
1205            assert_eq!(
1206                listed(CatalogueQuery {
1207                    needle: "publish".into(),
1208                    parent_resource: Some("workspace".into()),
1209                    ..CatalogueQuery::default()
1210                }),
1211                Vec::<String>::new(),
1212                "a needle asked inside a named place keeps to that place"
1213            );
1214        }
1215
1216        phase a_listing_by_resource_sends_each_resource_once_and_counts_its_rows;
1217        {
1218            // Three notes of one kind, each offering the same two actions, and a
1219            // folder that names none.
1220            let mut rows = Vec::new();
1221            for note in ["note:1", "note:2", "note:3"] {
1222                rows.push(row(note, Some("rename"), ""));
1223                rows.push(row(note, Some("archive"), ""));
1224            }
1225            rows.push(row("folder:a", None, ""));
1226            let sent = compact(rows.clone());
1227            assert_eq!(sent.len(), 4, "a row per resource");
1228            assert_eq!(rows_weight(&sent), rows.len(), "counting every row");
1229            let described: Vec<usize> = sent
1230                .iter()
1231                .map(|row| row.offered.as_ref().map_or(0, |offered| offered.described.len()))
1232                .collect();
1233            assert_eq!(described, [2, 0, 0, 0], "each action described once a page");
1234            assert_eq!(expand(sent.clone()), rows, "the rows come back as they were");
1235
1236            // A page cut inside a resource keeps the actions before the cut.
1237            let mut cut = sent;
1238            truncate_rows(&mut cut, 3);
1239            assert_eq!(rows_weight(&cut), 3);
1240            assert_eq!(expand(cut), rows[..3].to_vec());
1241
1242            // A page asked a resource at a time is sent so, and its cursor
1243            // counts the rows: the next page starts where these end.
1244            let query = CatalogueQuery {
1245                max_results: 4,
1246                by_resource: true,
1247                ..CatalogueQuery::default()
1248            };
1249            let page = CataloguePage::from_rows("r1".into(), rows.clone(), &query);
1250            assert_eq!(page.rows.len(), 2);
1251            let next = CataloguePage::from_rows(
1252                "r1".into(),
1253                rows.clone(),
1254                &CatalogueQuery {
1255                    cursor: page.next_cursor.clone(),
1256                    revision: Some("r1".into()),
1257                    ..query
1258                },
1259            );
1260            let mut both = expand(page.rows);
1261            both.extend(expand(next.rows));
1262            assert_eq!(both, rows, "the two pages hold every row once");
1263        }
1264    }
1265}
1266
1267/// The stem an English word is matched by: its plural, its participle and
1268/// its "-ing" form reduce to the word a description most likely spells
1269/// ("drawing" and "draw", "dragging" and "drag", "scrolling" and "scroll",
1270/// "signed" and "sign"). An inflection is only undone when what is left is
1271/// still a word of reasonable length, so "ring" and "thing" keep their own
1272/// letters rather than becoming "r" and "th".
1273#[must_use]
1274pub fn stem_word(word: &str) -> String {
1275    let letters = word.chars().count();
1276    let strip = |ending: &str, shortest: usize| -> Option<String> {
1277        let kept = word.strip_suffix(ending)?;
1278        (word.chars().count() >= shortest && kept.chars().count() >= 3).then(|| kept.to_owned())
1279    };
1280    if letters <= 3 {
1281        return word.to_owned();
1282    }
1283    // An "-ing" and an "-ed" are where a word of a single syllable doubles
1284    // its last consonant ("dragging", "dragged"), so those undo the
1285    // doubling; a plural never does.
1286    let inflected = strip("ing", 4)
1287        .or_else(|| strip("ed", 5))
1288        .map(|stemmed| (stemmed, true))
1289        .or_else(|| strip("ies", 5).map(|stemmed| (format!("{stemmed}y"), false)))
1290        .or_else(|| strip("es", 5).map(|stemmed| (stemmed, false)))
1291        // "press" is not "pres": a word already ending in a double s is the
1292        // form "-ing", "-ed" and "-es" reduce to.
1293        .or_else(|| {
1294            (!word.ends_with("ss"))
1295                .then(|| strip("s", 4))
1296                .flatten()
1297                .map(|stemmed| (stemmed, false))
1298        });
1299    let Some((mut stemmed, doubled)) = inflected else {
1300        return word.to_owned();
1301    };
1302    if doubled && doubles_its_last_letter(&stemmed) {
1303        stemmed.pop();
1304    }
1305    stemmed
1306}
1307
1308/// Whether a stem's last two letters are one consonant doubled, as "-ing"
1309/// and "-ed" leave it in "dragging" and "dragged": the "e" of "agreed", the
1310/// "l" of "called" and the "s" of "passed" are not doubled ones.
1311fn doubles_its_last_letter(stem: &str) -> bool {
1312    let mut doubled = stem.chars().rev().take(2);
1313    matches!(
1314        (doubled.next(), doubled.next()),
1315        (Some(last), Some(previous))
1316            if last == previous && !matches!(last, 'e' | 'l' | 's' | 'z')
1317    )
1318}
1319
1320#[cfg(test)]
1321mod stem_tests {
1322    use super::stem_word;
1323
1324    #[test]
1325    fn a_stem_undoes_an_inflection_and_nothing_else() {
1326        for (word, stem) in [
1327            ("drawing", "draw"),
1328            ("dragging", "drag"),
1329            ("dragged", "drag"),
1330            ("scrolling", "scroll"),
1331            ("scrolled", "scroll"),
1332            ("scrolls", "scroll"),
1333            ("signing", "sign"),
1334            ("signed", "sign"),
1335            ("signs", "sign"),
1336            ("presses", "press"),
1337            ("pressing", "press"),
1338            ("copies", "copy"),
1339        ] {
1340            assert_eq!(stem_word(word), stem, "{word}");
1341        }
1342        // A word that is already a stem keeps its letters.
1343        for word in ["press", "ring", "thing", "id", "use", "scroll", "drag"] {
1344            assert_eq!(stem_word(word), word, "{word}");
1345        }
1346    }
1347}