1use serde::{Deserialize, Serialize};
11
12use crate::api::{ActionAddress, ActionDescriptor};
13use crate::contract::ActionContract;
14use crate::resource::ResourcePresentation;
15
16use super::RemoteActionTarget;
17
18pub const MAX_CATALOGUE_PAGE: u32 = 256;
20
21pub const MAX_CATALOGUE_PAGE_BYTES: usize = super::MAX_REMOTE_ACTION_FRAME_BYTES / 2;
26
27pub const MAX_BY_RESOURCE_PAGE: u32 = 16_384;
31
32const fn default_page() -> u32 {
33 64
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct ViewResourceQuery {
41 pub id: String,
43 pub kind: String,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ResourceViewLocator {
51 pub origin: String,
53 pub workspace: String,
55 #[serde(rename = "hostDevice")]
57 pub host_device: String,
58 pub provider: String,
60 #[serde(default, rename = "webEntry", skip_serializing_if = "Option::is_none")]
64 pub web_entry: Option<String>,
65}
66
67#[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 pub document_id: String,
76}
77
78#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct CatalogueQuery {
82 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub canonical_route: Option<CanonicalActionRoute>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub provider: Option<String>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub app_id: Option<String>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub view_resource: Option<ViewResourceQuery>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub parent_resource: Option<String>,
103 #[serde(default, skip_serializing_if = "String::is_empty")]
106 pub needle: String,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub resource_name: Option<String>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub target: Option<ActionAddress>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub action: Option<String>,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub revision: Option<String>,
129 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub cursor: Vec<u8>,
132 #[serde(default = "default_page")]
135 pub max_results: u32,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub limits: Option<CatalogueLimits>,
139 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
144 pub by_resource: bool,
145 #[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 #[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 #[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 #[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#[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#[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 #[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
247pub struct CatalogueRow {
248 pub provider: String,
250 pub app_id: String,
252 #[serde(default, skip_serializing_if = "String::is_empty")]
254 pub parent_resource: String,
255 pub resource: CatalogueResource,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub action: Option<ActionDescriptor>,
259 #[serde(default)]
261 pub has_children: bool,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
265 pub visibility: Option<RowVisibility>,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub surface: Option<String>,
271 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub offered: Option<Box<Offered>>,
276}
277
278#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
281pub struct Offered {
282 pub actions: Vec<String>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
286 pub semantic_identity: Option<crate::ResourceSemanticIdentity>,
287 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 pub described: Vec<ActionDescriptor>,
291}
292
293impl CatalogueRow {
294 #[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#[must_use]
306pub fn rows_weight(rows: &[CatalogueRow]) -> usize {
307 rows.iter().map(CatalogueRow::weight).sum()
308}
309
310pub 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
332pub 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
354pub 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 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#[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#[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 #[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 #[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 #[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 fn matches(&self, needle: &str) -> bool {
535 if needle.is_empty() {
536 return true;
537 }
538 let needle = needle.to_lowercase();
539 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
570pub struct RowVisibility {
571 pub action: String,
572 pub contract: ActionContract,
573 #[serde(default, skip_serializing_if = "Option::is_none")]
576 pub governing_kind: Option<crate::OperationKind>,
577}
578
579#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
581pub struct CatalogueProvider {
582 pub provider: String,
583 pub app_id: String,
584 pub workspace: String,
586 #[serde(default, skip_serializing_if = "String::is_empty")]
588 pub document_id: String,
589 #[serde(default)]
591 pub browsable: bool,
592}
593
594#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
608pub struct ProvidedResource {
609 pub address: String,
610 pub surface: crate::surface::Surface,
611}
612
613impl ProvidedPackage {
614 #[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 pub revision: String,
638 pub rows: Vec<CatalogueRow>,
639 #[serde(default, skip_serializing_if = "Option::is_none")]
641 pub locator: Option<ResourceViewLocator>,
642 #[serde(default, skip_serializing_if = "Vec::is_empty")]
644 pub providers: Vec<CatalogueProvider>,
645 #[serde(default, skip_serializing_if = "Vec::is_empty")]
648 pub packages: Vec<ProvidedPackage>,
649 #[serde(default, skip_serializing_if = "Vec::is_empty")]
651 pub next_cursor: Vec<u8>,
652 #[serde(default)]
654 pub exhausted: bool,
655 #[serde(default)]
657 pub stale_cursor: bool,
658 #[serde(default)]
660 pub budget_exhausted: bool,
661 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub unavailable: Option<String>,
667}
668
669impl CataloguePage {
670 #[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 #[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 #[must_use]
714 pub fn stale(revision: String) -> Self {
715 Self {
716 revision,
717 stale_cursor: true,
718 ..Self::default()
719 }
720 }
721
722 #[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 #[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 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 #[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 #[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 #[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 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 assert_eq!(actions("scrolling"), ["press-page"]);
1135 assert_eq!(actions("draw"), ["pointer-path"]);
1136 assert_eq!(actions("drawing"), ["pointer-path"]);
1137 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 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 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 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 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#[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 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 .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
1308fn 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 for word in ["press", "ring", "thing", "id", "use", "scroll", "drag"] {
1344 assert_eq!(stem_word(word), word, "{word}");
1345 }
1346 }
1347}