Skip to main content

artifactize_core/review/
search.rs

1//! The review list's request search: a query of free text and `key:value` terms, matched
2//! against saved requests, completed from the requests shown, and read page by page from the
3//! state. Every review frontend (the terminal `review` and the desktop app) uses this one rule.
4//!
5//! Terms are ANDed. A plain word matches, case-insensitively, a substring of the repository,
6//! eval, request ID or claimant. A `key:value` term restricts the match to one field:
7//!
8//! | Key | Matches |
9//! |---|---|
10//! | `repo:` | a substring of the repository path |
11//! | `eval:` | a substring of the eval ID |
12//! | `request:` | a substring of the request ID |
13//! | `reviewer:` | a substring of the claimant; unclaimed requests never match |
14//! | `tag:` | a substring of a tag of the eval's Artifact |
15//! | `kind:`, `type:` | the eval kind exactly: `runtime`, `agent` or `human` |
16//! | `status:` | the request status; `waiting_human` includes `deferred` sign-offs |
17//! | `is:` | `mine`, `claimed` or `unclaimed` (claims exist only on waiting Human requests) |
18//!
19//! The bare term `waiting` matches unclaimed waiting Human requests, including deferred
20//! sign-offs. It is the short spelling of `is:unclaimed`.
21//!
22//! Values with spaces are quoted: `repo:"/work/my repo"`. A quoted word is always free text, so
23//! `"type:style"` searches for that text rather than naming a key.
24#[cfg(test)]
25mod tests;
26
27use crate::{
28    config::ProfileKind,
29    monitor::live::{Label, Labels},
30    store::{self, RequestView},
31    types::{RequestId, RequestStatus, ReviewerId},
32};
33use clap::ValueEnum;
34use std::{
35    collections::BTreeSet,
36    ops::ControlFlow,
37    path::{Path, PathBuf},
38};
39
40/// The query the review list starts with: the waiting Human sign-offs.
41pub const DEFAULT: &str = "type:human waiting";
42const WAITING: &str = "waiting";
43
44/// Requests read from the state per batch while a page is filled.
45const BATCH: u32 = 400;
46/// Matching requests per page, as the monitor pages its Runs.
47pub const PAGE: usize = 100;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50enum TextField {
51    Repo,
52    Branch,
53    Eval,
54    Request,
55    Reviewer,
56    Tag,
57}
58
59impl TextField {
60    fn name(self) -> &'static str {
61        match self {
62            Self::Repo => "repo",
63            Self::Branch => "branch",
64            Self::Eval => "eval",
65            Self::Request => "request",
66            Self::Reviewer => "reviewer",
67            Self::Tag => "tag",
68        }
69    }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73enum Key {
74    Text(TextField),
75    Kind,
76    Type,
77    Status,
78    Is,
79}
80
81impl Key {
82    const ALL: [Self; 10] = [
83        Self::Text(TextField::Repo),
84        Self::Text(TextField::Branch),
85        Self::Text(TextField::Eval),
86        Self::Text(TextField::Request),
87        Self::Text(TextField::Reviewer),
88        Self::Text(TextField::Tag),
89        Self::Kind,
90        Self::Type,
91        Self::Status,
92        Self::Is,
93    ];
94
95    fn name(self) -> &'static str {
96        match self {
97            Self::Text(field) => field.name(),
98            Self::Kind => "kind",
99            Self::Type => "type",
100            Self::Status => "status",
101            Self::Is => "is",
102        }
103    }
104
105    fn parse(name: &str) -> Option<Self> {
106        Self::ALL
107            .into_iter()
108            .find(|key| key.name().eq_ignore_ascii_case(name))
109    }
110}
111
112/// A claim fact of a request.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114enum Is {
115    Mine,
116    Claimed,
117    Unclaimed,
118}
119
120impl Is {
121    const ALL: [Self; 3] = [Self::Mine, Self::Claimed, Self::Unclaimed];
122
123    fn name(self) -> &'static str {
124        match self {
125            Self::Mine => "mine",
126            Self::Claimed => "claimed",
127            Self::Unclaimed => "unclaimed",
128        }
129    }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
133enum Term {
134    /// Lowercased text found in any listed column.
135    Text(String),
136    /// Lowercased text found in one field.
137    Field(TextField, String),
138    Kind(ProfileKind),
139    Status(RequestStatus),
140    Is(Is),
141}
142
143/// A parsed query; every term must match.
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
145pub struct Query {
146    terms: Vec<Term>,
147    places: bool,
148    live: bool,
149}
150
151/// Who holds a request's claim, as the current reviewer sees it.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum Claim {
154    Unclaimed,
155    /// Claimed by the current reviewer, named.
156    Mine(String),
157    /// Claimed by another reviewer, named.
158    Other(String),
159}
160
161impl Claim {
162    /// The claimant's name, whoever it is.
163    pub fn reviewer(&self) -> Option<&str> {
164        match self {
165            Self::Unclaimed => None,
166            Self::Mine(name) | Self::Other(name) => Some(name),
167        }
168    }
169}
170
171/// The fields of one request that a query matches.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Entry {
174    pub repository: PathBuf,
175    pub label: Option<Label>,
176    pub eval: String,
177    pub request: String,
178    pub claim: Claim,
179    pub kind: ProfileKind,
180    pub status: RequestStatus,
181    pub tags: Vec<String>,
182}
183
184impl Entry {
185    /// The searchable facts of `view` from repository `repo`, for the current `reviewer`.
186    pub fn new(view: &RequestView, repo: &Path, reviewer: &ReviewerId) -> Self {
187        let request = &view.request;
188        let tags = view
189            .definition
190            .as_ref()
191            .and_then(|definition| definition.artifact().tags.value())
192            .or_else(|| {
193                let artifacts = request.human_definition.as_ref()?.artifacts.value()?;
194                artifacts.get(&request.target)?.tags.value()
195            })
196            .cloned()
197            .unwrap_or_default();
198        Self {
199            repository: repo.to_owned(),
200            label: None,
201            eval: request.eval_id.to_string(),
202            request: request.id.to_string(),
203            claim: match &view.claim {
204                None => Claim::Unclaimed,
205                Some(claim) if &claim.reviewer == reviewer => {
206                    Claim::Mine(claim.reviewer.to_string())
207                }
208                Some(claim) => Claim::Other(claim.reviewer.to_string()),
209            },
210            kind: request.profile.kind(),
211            status: request.status(),
212            tags,
213        }
214    }
215}
216
217fn kind_name(kind: ProfileKind) -> &'static str {
218    kind.name()
219}
220
221fn status_name(status: RequestStatus) -> String {
222    status.as_str().to_ascii_lowercase()
223}
224
225/// One word of a query: where it starts in the text, its text without quotes, and whether it
226/// began quoted.
227struct Word {
228    start: usize,
229    text: String,
230    quoted: bool,
231}
232
233/// Words of `text`, a double-quoted run counting as one word, and whether the text ends inside
234/// a word (no whitespace after it outside quotes): the term still being typed.
235fn scan(text: &str) -> (Vec<Word>, bool) {
236    let mut words = Vec::new();
237    let mut word: Option<Word> = None;
238    let mut quoted = false;
239    for (index, character) in text.char_indices() {
240        if character.is_whitespace() && !quoted {
241            words.extend(word.take());
242            continue;
243        }
244        let current = word.get_or_insert_with(|| Word {
245            start: index,
246            text: String::new(),
247            quoted: character == '"',
248        });
249        if character == '"' {
250            quoted = !quoted;
251        } else {
252            current.text.push(character);
253        }
254    }
255    let open = word.is_some();
256    words.extend(word);
257    (words, open)
258}
259
260/// Words of `text` and whether each began quoted.
261pub(crate) fn words(text: &str) -> Vec<(String, bool)> {
262    scan(text)
263        .0
264        .into_iter()
265        .map(|word| (word.text, word.quoted))
266        .collect()
267}
268
269impl std::str::FromStr for Query {
270    type Err = String;
271
272    fn from_str(text: &str) -> Result<Self, String> {
273        let terms = words(text)
274            .into_iter()
275            .map(|(word, quoted)| {
276                if !quoted && word.eq_ignore_ascii_case(WAITING) {
277                    return Ok(Term::Is(Is::Unclaimed));
278                }
279                let Some((name, value)) = word.split_once(':').filter(|_| !quoted) else {
280                    return Ok(Term::Text(word.to_lowercase()));
281                };
282                let key = Key::parse(name).ok_or_else(|| {
283                    format!(
284                        "Unknown filter key `{name}:`; use {}, or quote the word to search for it.",
285                        keys()
286                    )
287                })?;
288                if value.is_empty() {
289                    return Err(format!("`{}:` needs a value.", key.name()));
290                }
291                let lower = value.to_lowercase();
292                match key {
293                    Key::Kind | Key::Type => ProfileKind::value_variants()
294                        .iter()
295                        .copied()
296                        .find(|kind| kind_name(*kind) == lower)
297                        .map(Term::Kind)
298                        .ok_or_else(|| {
299                            format!("Unknown kind `{value}`; use {}.", list(kind_values()))
300                        }),
301                    Key::Status => RequestStatus::ALL
302                        .iter()
303                        .copied()
304                        .find(|status| status_name(*status) == lower)
305                        .map(Term::Status)
306                        .ok_or_else(|| {
307                            format!("Unknown status `{value}`; use {}.", list(status_values()))
308                        }),
309                    Key::Is => Is::ALL
310                        .into_iter()
311                        .find(|is| is.name() == lower)
312                        .map(Term::Is)
313                        .ok_or_else(|| {
314                            format!(
315                                "Unknown qualifier `is:{value}`; use {}.",
316                                list(Is::ALL.iter().map(|is| format!("is:{}", is.name())))
317                            )
318                        }),
319                    Key::Text(field) => Ok(Term::Field(field, lower)),
320                }
321            })
322            .collect::<Result<_, String>>()?;
323        Ok(Self {
324            terms,
325            places: false,
326            live: false,
327        })
328    }
329}
330
331fn list(items: impl IntoIterator<Item = String>) -> String {
332    let items: Vec<String> = items.into_iter().collect();
333    match items.split_last() {
334        Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
335        _ => items.join(""),
336    }
337}
338
339fn keys() -> String {
340    list(Key::ALL.iter().map(|key| format!("{}:", key.name())))
341}
342
343fn kind_values() -> impl Iterator<Item = String> {
344    ProfileKind::value_variants()
345        .iter()
346        .map(|kind| kind_name(*kind).to_owned())
347}
348
349fn status_values() -> impl Iterator<Item = String> {
350    RequestStatus::ALL.iter().map(|status| status_name(*status))
351}
352
353fn contains(field: &str, text: &str) -> bool {
354    field.to_lowercase().contains(text)
355}
356
357impl Query {
358    /// Search the displayed projects and branches, instead of raw checkout paths.
359    pub fn for_places(mut self) -> Self {
360        self.places = true;
361        self
362    }
363
364    /// Hide requests whose workspace is gone, without hiding the record from CLI history.
365    pub fn for_live_repositories(mut self) -> Self {
366        self.live = true;
367        self
368    }
369
370    /// The query of `--repo PATH`: the default with that repository's term.
371    pub fn text_for(repo: Option<&Path>) -> String {
372        match repo {
373            Some(repo) => format!(
374                "{DEFAULT} {}",
375                quote("repo", &crate::platform::path_text(repo))
376            ),
377            None => DEFAULT.to_owned(),
378        }
379    }
380
381    /// Whether only waiting Human reviews can match, as with the default query.
382    pub fn waiting_human(&self) -> bool {
383        self.terms.contains(&Term::Kind(ProfileKind::Human))
384            && self.terms.iter().any(|term| {
385                matches!(
386                    term,
387                    Term::Status(RequestStatus::WaitingHuman | RequestStatus::Deferred)
388                        | Term::Is(_)
389                )
390            })
391    }
392
393    pub fn matches(&self, entry: &Entry) -> bool {
394        let repository = entry.label.as_ref().map_or_else(
395            || crate::platform::path_text(&entry.repository),
396            |label| label.project.clone(),
397        );
398        self.terms.iter().all(|term| match term {
399            Term::Text(text) => [
400                Some(repository.as_str()),
401                entry.label.as_ref().map(|label| label.branch.as_str()),
402                Some(entry.eval.as_str()),
403                Some(entry.request.as_str()),
404                entry.claim.reviewer(),
405            ]
406            .into_iter()
407            .flatten()
408            .any(|field| contains(field, text)),
409            Term::Field(TextField::Repo, text) => contains(&repository, text),
410            Term::Field(TextField::Branch, text) => entry
411                .label
412                .as_ref()
413                .is_some_and(|label| contains(&label.branch, text)),
414            Term::Field(TextField::Eval, text) => contains(&entry.eval, text),
415            Term::Field(TextField::Request, text) => contains(&entry.request, text),
416            Term::Field(TextField::Reviewer, text) => entry
417                .claim
418                .reviewer()
419                .is_some_and(|reviewer| contains(reviewer, text)),
420            Term::Field(TextField::Tag, text) => entry.tags.iter().any(|tag| contains(tag, text)),
421            Term::Kind(kind) => entry.kind == *kind,
422            Term::Status(RequestStatus::WaitingHuman) => entry.status.is_human_wait(),
423            Term::Status(status) => entry.status == *status,
424            Term::Is(Is::Mine) => matches!(entry.claim, Claim::Mine(_)),
425            Term::Is(Is::Claimed) => entry.claim != Claim::Unclaimed,
426            Term::Is(Is::Unclaimed) => {
427                entry.status.is_human_wait() && entry.claim == Claim::Unclaimed
428            }
429        })
430    }
431
432    /// What the state read shows besides the requests: their Runs' definitions only for a
433    /// `tag:` term, the one term matched against them. They hold a Run's whole graph, which
434    /// for a large Run costs seconds and gigabytes to decode for each batch.
435    fn shown(&self) -> store::Shown {
436        if self
437            .terms
438            .iter()
439            .any(|term| matches!(term, Term::Field(TextField::Tag, _)))
440        {
441            store::Shown::Definitions
442        } else {
443            store::Shown::Requests
444        }
445    }
446
447    fn wants_labels(&self) -> bool {
448        self.places
449            || self
450                .terms
451                .iter()
452                .any(|term| matches!(term, Term::Field(TextField::Branch, _)))
453    }
454
455    /// The statuses every match must have, for the state read to select up front.
456    fn statuses(&self) -> Vec<RequestStatus> {
457        let statuses: BTreeSet<_> = self
458            .terms
459            .iter()
460            .filter_map(|term| match term {
461                Term::Status(status) => Some(*status),
462                // Claims exist only on waiting Human requests.
463                Term::Is(Is::Mine | Is::Claimed | Is::Unclaimed) => {
464                    Some(RequestStatus::WaitingHuman)
465                }
466                _ => None,
467            })
468            .collect();
469        match statuses.len() {
470            // Two different required statuses match nothing; reading one keeps it bounded.
471            0 | 1 => statuses
472                .into_iter()
473                .flat_map(|status| {
474                    if status == RequestStatus::WaitingHuman {
475                        vec![status, RequestStatus::Deferred]
476                    } else {
477                        vec![status]
478                    }
479                })
480                .collect(),
481            _ => vec![*statuses.first().expect("two statuses")],
482        }
483    }
484}
485
486/// `key:value`, quoted when the value has spaces or quotes.
487pub(crate) fn quote(key: &str, value: &str) -> String {
488    if value
489        .chars()
490        .any(|character| character.is_whitespace() || character == '"')
491    {
492        format!("{key}:\"{}\"", value.replace('"', ""))
493    } else {
494        format!("{key}:{value}")
495    }
496}
497
498/// Completion of the query's last term.
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct Completion {
501    /// The query before the completed term; a candidate replaces everything after it.
502    pub keep: String,
503    /// Whole terms, keys first (`repo:`) or `key:value` once a key is typed.
504    pub candidates: Vec<String>,
505}
506
507/// `text` split before the term still being typed, as the parser reads words: a space inside
508/// quotes (`repo:"my r`) stays in the term; after a finished word the term is empty.
509pub(crate) fn last_term(text: &str) -> (&str, &str) {
510    match scan(text) {
511        (words, true) => text.split_at(words.last().map_or(0, |word| word.start)),
512        (_, false) => (text, ""),
513    }
514}
515
516/// The candidates for the query's last term: keys whose names start with it, or after a key
517/// the values of that field among `entries` (fixed vocabularies for `kind:`, `status:`, `is:`).
518pub fn complete(text: &str, entries: &[Entry]) -> Completion {
519    let (keep, term) = last_term(text);
520    // A quoted word is searched for literally: nothing to complete.
521    let candidates = match term.split_once(':').filter(|_| !term.starts_with('"')) {
522        None if term.starts_with('"') => Vec::new(),
523        None => {
524            let lower = term.to_lowercase();
525            Key::ALL
526                .iter()
527                .map(|key| format!("{}:", key.name()))
528                .chain(std::iter::once(WAITING.to_owned()))
529                .filter(|key| key.starts_with(&lower))
530                .collect()
531        }
532        Some((name, partial)) => match Key::parse(name) {
533            None => Vec::new(),
534            Some(key) => {
535                let partial = partial.trim_matches('"').to_lowercase();
536                let values: BTreeSet<String> = match key {
537                    Key::Text(TextField::Repo) => entries
538                        .iter()
539                        .map(|entry| {
540                            if let Some(label) = &entry.label {
541                                return label.project.clone();
542                            }
543                            entry.repository.file_name().map_or_else(
544                                || crate::platform::path_text(&entry.repository),
545                                crate::platform::display_name,
546                            )
547                        })
548                        .collect(),
549                    Key::Text(TextField::Branch) => entries
550                        .iter()
551                        .filter_map(|entry| entry.label.as_ref())
552                        .filter(|label| !label.branch.is_empty())
553                        .map(|label| label.branch.clone())
554                        .collect(),
555                    Key::Text(TextField::Eval) => {
556                        entries.iter().map(|entry| entry.eval.clone()).collect()
557                    }
558                    Key::Text(TextField::Request) => {
559                        entries.iter().map(|entry| entry.request.clone()).collect()
560                    }
561                    Key::Text(TextField::Reviewer) => entries
562                        .iter()
563                        .filter_map(|entry| entry.claim.reviewer().map(str::to_owned))
564                        .collect(),
565                    Key::Text(TextField::Tag) => entries
566                        .iter()
567                        .flat_map(|entry| entry.tags.iter().cloned())
568                        .collect(),
569                    Key::Kind | Key::Type => kind_values().collect(),
570                    Key::Status => status_values().collect(),
571                    Key::Is => Is::ALL.iter().map(|is| is.name().to_owned()).collect(),
572                };
573                values
574                    .into_iter()
575                    .filter(|value| value.to_lowercase().contains(&partial))
576                    .map(|value| quote(key.name(), &value))
577                    .collect()
578            }
579        },
580    };
581    Completion {
582        keep: keep.to_owned(),
583        candidates,
584    }
585}
586
587/// Complete the last term of `text` from the requests the terms before it find (their first
588/// page): what the rest of the query lists, never the half-typed term itself.
589pub async fn suggest(
590    state: &Path,
591    text: &str,
592    reviewer: &ReviewerId,
593) -> Result<Completion, String> {
594    suggest_in(state, text, reviewer, false).await
595}
596
597pub async fn suggest_places(
598    state: &Path,
599    text: &str,
600    reviewer: &ReviewerId,
601) -> Result<Completion, String> {
602    suggest_in(state, text, reviewer, true).await
603}
604
605async fn suggest_in(
606    state: &Path,
607    text: &str,
608    reviewer: &ReviewerId,
609    places: bool,
610) -> Result<Completion, String> {
611    let (keep, term) = last_term(text);
612    let key = term
613        .split_once(':')
614        .filter(|_| !term.starts_with('"'))
615        .and_then(|(name, _)| Key::parse(name));
616    let from_requests = matches!(key, Some(Key::Text(_)));
617    let shown = match key {
618        Some(Key::Text(TextField::Tag)) => store::Shown::Definitions,
619        _ => keep
620            .parse::<Query>()
621            .map_or(store::Shown::Requests, |query| query.shown()),
622    };
623    let entries = match keep.parse::<Query>() {
624        // Tags are completed from the definitions the matches' Runs saved.
625        Ok(mut query) if from_requests => {
626            query.places = places || matches!(key, Some(Key::Text(TextField::Branch)));
627            query.live = places;
628            page(state, &query, reviewer, 0, shown)
629                .await?
630                .requests
631                .into_iter()
632                .map(|(_, entry)| entry)
633                .collect()
634        }
635        _ => Vec::new(),
636    };
637    Ok(complete(text, &entries))
638}
639
640/// One page of matching requests, newest Run first, and where the next page starts.
641#[derive(Debug, Clone, Default)]
642pub struct Found {
643    pub requests: Vec<(RequestView, Entry)>,
644    /// The position of the next page in the state's request order; `None` on the last page.
645    pub next: Option<u64>,
646}
647
648/// The exact saved request and whether it appears in the current search, regardless of page.
649#[derive(Debug, Clone)]
650pub struct Opened {
651    pub view: RequestView,
652    pub outside_reason: Option<String>,
653}
654
655impl Opened {
656    pub fn outside_filter(&self) -> bool {
657        self.outside_reason.is_some()
658    }
659}
660
661/// Resolve a direct reference without changing its query or redirecting to an original request.
662pub async fn open(
663    state: &Path,
664    id: &RequestId,
665    query: &Query,
666    reviewer: &ReviewerId,
667) -> Result<Opened, String> {
668    let view = store::read_request_by_id(state, id, query.shown()).await?;
669    let repo = store::read_request_repo_by_id(state, id.clone()).await?;
670    let mut entry = Entry::new(&view, &repo, reviewer);
671    if query.wants_labels() {
672        entry.label = labels(state, vec![view.request.run_id.clone()])
673            .await?
674            .remove(&view.request.run_id);
675    }
676    let outside_reason = if query.live && !repo.is_dir() {
677        Some("This review's repository folder no longer exists.".into())
678    } else if Box::pin(follows_waiting(state, &view, query.live)).await {
679        Some("This review shares the original request's sign-off.".into())
680    } else if query.matches(&entry) {
681        None
682    } else {
683        Some(outside_reason(&entry))
684    };
685    Ok(Opened {
686        view,
687        outside_reason,
688    })
689}
690
691fn outside_reason(entry: &Entry) -> String {
692    if entry.kind != ProfileKind::Human {
693        return "This is not a Human review.".into();
694    }
695    match (&entry.claim, entry.status) {
696        (Claim::Mine(_), _) => "Claimed by you.".into(),
697        (Claim::Other(reviewer), _) => format!("Claimed by {reviewer}."),
698        (_, RequestStatus::Green | RequestStatus::Red) => "This review was submitted.".into(),
699        _ => "This review does not match the current filter.".into(),
700    }
701}
702
703/// Up to [`PAGE`] requests matching `query` from position `start` on, read in bounded batches.
704///
705/// A waiting Human request that joined another waiting request's execution (a follower) is
706/// listed once, as the original that records its definition and receives every action; a
707/// follower whose original no longer waits is listed as itself. The first page first ends the
708/// sign-offs whose repository folder is gone ([`store::retire_removed_signoffs`]): nothing can
709/// be reviewed in them any more.
710pub async fn search(
711    state: &Path,
712    query: &Query,
713    reviewer: &ReviewerId,
714    start: u64,
715) -> Result<Found, String> {
716    if start == 0 {
717        store::retire_removed_signoffs(state).await?;
718    }
719    page(state, query, reviewer, start, query.shown()).await
720}
721
722/// One [`search`] page, its views showing what `shown` names besides their requests.
723async fn page(
724    state: &Path,
725    query: &Query,
726    reviewer: &ReviewerId,
727    start: u64,
728    shown: store::Shown,
729) -> Result<Found, String> {
730    let mut found = Found::default();
731    read_matching(
732        state,
733        query,
734        reviewer,
735        start,
736        shown,
737        |view, entry, position| {
738            found.requests.push((view, entry));
739            if found.requests.len() < PAGE {
740                return ControlFlow::Continue(());
741            }
742            found.next = Some(position + 1);
743            ControlFlow::Break(())
744        },
745    )
746    .await?;
747    Ok(found)
748}
749
750/// How many requests `query` finds on all its pages together, each counted as [`search`]
751/// lists it.
752pub async fn count(state: &Path, query: &Query, reviewer: &ReviewerId) -> Result<u64, String> {
753    let mut count = 0;
754    read_matching(state, query, reviewer, 0, query.shown(), |_, _, _| {
755        count += 1;
756        ControlFlow::Continue(())
757    })
758    .await?;
759    Ok(count)
760}
761
762/// Pass each request matching `query` from position `start` on to `found` with its position,
763/// in the state's request order, until `found` breaks or the requests end. Each view shows what
764/// `shown` names besides its request.
765async fn read_matching(
766    state: &Path,
767    query: &Query,
768    reviewer: &ReviewerId,
769    start: u64,
770    shown: store::Shown,
771    mut found: impl FnMut(RequestView, Entry, u64) -> ControlFlow<()>,
772) -> Result<(), String> {
773    let statuses = query.statuses();
774    let mut position = start;
775    let mut exists = std::collections::BTreeMap::new();
776    loop {
777        let batch = if query.live {
778            store::read_review_batch(state, &statuses, position, BATCH, shown).await?
779        } else {
780            store::read_request_batch(state, &statuses, position, BATCH, shown).await?
781        };
782        let read = batch.len() as u64;
783        let labels = if query.wants_labels() {
784            let ids: BTreeSet<_> = batch
785                .iter()
786                .map(|(view, _)| view.request.run_id.clone())
787                .collect();
788            labels(state, ids.into_iter().collect()).await?
789        } else {
790            Labels::new()
791        };
792        for (offset, (view, repo)) in batch.into_iter().enumerate() {
793            if (query.live && !*exists.entry(repo.clone()).or_insert_with(|| repo.is_dir()))
794                || Box::pin(follows_waiting(state, &view, query.live)).await
795            {
796                continue;
797            }
798            let mut entry = Entry::new(&view, &repo, reviewer);
799            entry.label = labels.get(&view.request.run_id).cloned();
800            if query.matches(&entry) && found(view, entry, position + offset as u64).is_break() {
801                return Ok(());
802            }
803        }
804        if read < u64::from(BATCH) {
805            return Ok(());
806        }
807        position += read;
808    }
809}
810
811async fn labels(state: &Path, ids: Vec<crate::types::RunId>) -> Result<Labels, String> {
812    let catalog = store::read_run_places(state, ids).await?;
813    crate::task::joined(
814        tokio::task::spawn_blocking(move || {
815            let mut legacy = std::collections::BTreeMap::new();
816            catalog
817                .into_iter()
818                .map(|(id, run)| {
819                    let label = if run.repository.common_dir.is_some() {
820                        Label::for_identity(&run.repo_path, &run.repository)
821                    } else {
822                        legacy
823                            .entry(run.repo_path.clone())
824                            .or_insert_with(|| Label::at(&run.repo_path))
825                            .clone()
826                    };
827                    (id, label)
828                })
829                .collect()
830        })
831        .await,
832    )
833    .map_err(|error| error.to_string())
834}
835
836/// A waiting follower whose original still waits: the original's own row lists it.
837async fn follows_waiting(state: &Path, view: &RequestView, live: bool) -> bool {
838    if !view.request.status().is_human_wait() {
839        return false;
840    }
841    let Some(source) = view
842        .execution
843        .as_ref()
844        .map(|execution| &execution.provenance.request_id)
845        .filter(|source| **source != view.request.id)
846    else {
847        return false;
848    };
849    // Only the original's status matters, never what its Run's definitions hold.
850    if !store::read_request_by_id(state, source, store::Shown::Requests)
851        .await
852        .is_ok_and(|original| original.request.status().is_human_wait())
853    {
854        return false;
855    }
856    !live
857        || store::read_request_repo_by_id(state, source.clone())
858            .await
859            .is_ok_and(|repo| repo.is_dir())
860}