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