1#[cfg(test)]
22mod tests;
23
24use crate::{
25 config::ProfileKind,
26 store::{self, RequestView},
27 types::{RequestStatus, ReviewerId},
28};
29use clap::ValueEnum;
30use std::{
31 collections::BTreeSet,
32 ops::ControlFlow,
33 path::{Path, PathBuf},
34};
35
36pub const DEFAULT: &str = "kind:human status:waiting_human";
38
39const BATCH: u32 = 400;
41pub const PAGE: usize = 100;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45enum TextField {
46 Repo,
47 Eval,
48 Request,
49 Reviewer,
50 Tag,
51}
52
53impl TextField {
54 fn name(self) -> &'static str {
55 match self {
56 Self::Repo => "repo",
57 Self::Eval => "eval",
58 Self::Request => "request",
59 Self::Reviewer => "reviewer",
60 Self::Tag => "tag",
61 }
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66enum Key {
67 Text(TextField),
68 Kind,
69 Status,
70 Is,
71}
72
73impl Key {
74 const ALL: [Self; 8] = [
75 Self::Text(TextField::Repo),
76 Self::Text(TextField::Eval),
77 Self::Text(TextField::Request),
78 Self::Text(TextField::Reviewer),
79 Self::Text(TextField::Tag),
80 Self::Kind,
81 Self::Status,
82 Self::Is,
83 ];
84
85 fn name(self) -> &'static str {
86 match self {
87 Self::Text(field) => field.name(),
88 Self::Kind => "kind",
89 Self::Status => "status",
90 Self::Is => "is",
91 }
92 }
93
94 fn parse(name: &str) -> Option<Self> {
95 Self::ALL
96 .into_iter()
97 .find(|key| key.name().eq_ignore_ascii_case(name))
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103enum Is {
104 Mine,
105 Claimed,
106 Unclaimed,
107}
108
109impl Is {
110 const ALL: [Self; 3] = [Self::Mine, Self::Claimed, Self::Unclaimed];
111
112 fn name(self) -> &'static str {
113 match self {
114 Self::Mine => "mine",
115 Self::Claimed => "claimed",
116 Self::Unclaimed => "unclaimed",
117 }
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122enum Term {
123 Text(String),
125 Field(TextField, String),
127 Kind(ProfileKind),
128 Status(RequestStatus),
129 Is(Is),
130}
131
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
134pub struct Query {
135 terms: Vec<Term>,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum Claim {
141 Unclaimed,
142 Mine(String),
144 Other(String),
146}
147
148impl Claim {
149 pub fn reviewer(&self) -> Option<&str> {
151 match self {
152 Self::Unclaimed => None,
153 Self::Mine(name) | Self::Other(name) => Some(name),
154 }
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct Entry {
161 pub repository: PathBuf,
162 pub eval: String,
163 pub request: String,
164 pub claim: Claim,
165 pub kind: ProfileKind,
166 pub status: RequestStatus,
167 pub tags: Vec<String>,
168}
169
170impl Entry {
171 pub fn new(view: &RequestView, repo: &Path, reviewer: &ReviewerId) -> Self {
173 let request = &view.request;
174 let tags = view
175 .definition
176 .as_ref()
177 .and_then(|definition| definition.artifact().tags.value())
178 .or_else(|| {
179 let artifacts = request.human_definition.as_ref()?.artifacts.value()?;
180 artifacts.get(&request.target)?.tags.value()
181 })
182 .cloned()
183 .unwrap_or_default();
184 Self {
185 repository: repo.to_owned(),
186 eval: request.eval_id.to_string(),
187 request: request.id.to_string(),
188 claim: match &view.claim {
189 None => Claim::Unclaimed,
190 Some(claim) if &claim.reviewer == reviewer => {
191 Claim::Mine(claim.reviewer.to_string())
192 }
193 Some(claim) => Claim::Other(claim.reviewer.to_string()),
194 },
195 kind: request.profile.kind(),
196 status: request.status(),
197 tags,
198 }
199 }
200}
201
202fn kind_name(kind: ProfileKind) -> &'static str {
203 kind.name()
204}
205
206fn status_name(status: RequestStatus) -> String {
207 status.as_str().to_ascii_lowercase()
208}
209
210struct Word {
213 start: usize,
214 text: String,
215 quoted: bool,
216}
217
218fn scan(text: &str) -> (Vec<Word>, bool) {
221 let mut words = Vec::new();
222 let mut word: Option<Word> = None;
223 let mut quoted = false;
224 for (index, character) in text.char_indices() {
225 if character.is_whitespace() && !quoted {
226 words.extend(word.take());
227 continue;
228 }
229 let current = word.get_or_insert_with(|| Word {
230 start: index,
231 text: String::new(),
232 quoted: character == '"',
233 });
234 if character == '"' {
235 quoted = !quoted;
236 } else {
237 current.text.push(character);
238 }
239 }
240 let open = word.is_some();
241 words.extend(word);
242 (words, open)
243}
244
245pub(crate) fn words(text: &str) -> Vec<(String, bool)> {
247 scan(text)
248 .0
249 .into_iter()
250 .map(|word| (word.text, word.quoted))
251 .collect()
252}
253
254impl std::str::FromStr for Query {
255 type Err = String;
256
257 fn from_str(text: &str) -> Result<Self, String> {
258 let terms = words(text)
259 .into_iter()
260 .map(|(word, quoted)| {
261 let Some((name, value)) = word.split_once(':').filter(|_| !quoted) else {
262 return Ok(Term::Text(word.to_lowercase()));
263 };
264 let key = Key::parse(name).ok_or_else(|| {
265 format!(
266 "Unknown filter key `{name}:`; use {}, or quote the word to search for it.",
267 keys()
268 )
269 })?;
270 if value.is_empty() {
271 return Err(format!("`{}:` needs a value.", key.name()));
272 }
273 let lower = value.to_lowercase();
274 match key {
275 Key::Kind => ProfileKind::value_variants()
276 .iter()
277 .copied()
278 .find(|kind| kind_name(*kind) == lower)
279 .map(Term::Kind)
280 .ok_or_else(|| {
281 format!("Unknown kind `{value}`; use {}.", list(kind_values()))
282 }),
283 Key::Status => RequestStatus::ALL
284 .iter()
285 .copied()
286 .find(|status| status_name(*status) == lower)
287 .map(Term::Status)
288 .ok_or_else(|| {
289 format!("Unknown status `{value}`; use {}.", list(status_values()))
290 }),
291 Key::Is => Is::ALL
292 .into_iter()
293 .find(|is| is.name() == lower)
294 .map(Term::Is)
295 .ok_or_else(|| {
296 format!(
297 "Unknown qualifier `is:{value}`; use {}.",
298 list(Is::ALL.iter().map(|is| format!("is:{}", is.name())))
299 )
300 }),
301 Key::Text(field) => Ok(Term::Field(field, lower)),
302 }
303 })
304 .collect::<Result<_, String>>()?;
305 Ok(Self { terms })
306 }
307}
308
309fn list(items: impl IntoIterator<Item = String>) -> String {
310 let items: Vec<String> = items.into_iter().collect();
311 match items.split_last() {
312 Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
313 _ => items.join(""),
314 }
315}
316
317fn keys() -> String {
318 list(Key::ALL.iter().map(|key| format!("{}:", key.name())))
319}
320
321fn kind_values() -> impl Iterator<Item = String> {
322 ProfileKind::value_variants()
323 .iter()
324 .map(|kind| kind_name(*kind).to_owned())
325}
326
327fn status_values() -> impl Iterator<Item = String> {
328 RequestStatus::ALL.iter().map(|status| status_name(*status))
329}
330
331fn contains(field: &str, text: &str) -> bool {
332 field.to_lowercase().contains(text)
333}
334
335impl Query {
336 pub fn text_for(repo: Option<&Path>) -> String {
338 match repo {
339 Some(repo) => format!(
340 "{DEFAULT} {}",
341 quote("repo", &crate::platform::path_text(repo))
342 ),
343 None => DEFAULT.to_owned(),
344 }
345 }
346
347 pub fn waiting_human(&self) -> bool {
349 self.terms.contains(&Term::Kind(ProfileKind::Human))
350 && self
351 .terms
352 .contains(&Term::Status(RequestStatus::WaitingHuman))
353 }
354
355 pub fn matches(&self, entry: &Entry) -> bool {
356 self.terms.iter().all(|term| match term {
357 Term::Text(text) => [
358 Some(crate::platform::path_text(&entry.repository).as_str()),
359 Some(entry.eval.as_str()),
360 Some(entry.request.as_str()),
361 entry.claim.reviewer(),
362 ]
363 .into_iter()
364 .flatten()
365 .any(|field| contains(field, text)),
366 Term::Field(TextField::Repo, text) => {
367 contains(&crate::platform::path_text(&entry.repository), text)
368 }
369 Term::Field(TextField::Eval, text) => contains(&entry.eval, text),
370 Term::Field(TextField::Request, text) => contains(&entry.request, text),
371 Term::Field(TextField::Reviewer, text) => entry
372 .claim
373 .reviewer()
374 .is_some_and(|reviewer| contains(reviewer, text)),
375 Term::Field(TextField::Tag, text) => entry.tags.iter().any(|tag| contains(tag, text)),
376 Term::Kind(kind) => entry.kind == *kind,
377 Term::Status(RequestStatus::WaitingHuman) => entry.status.is_human_wait(),
378 Term::Status(status) => entry.status == *status,
379 Term::Is(Is::Mine) => matches!(entry.claim, Claim::Mine(_)),
380 Term::Is(Is::Claimed) => entry.claim != Claim::Unclaimed,
381 Term::Is(Is::Unclaimed) => {
382 entry.status.is_human_wait() && entry.claim == Claim::Unclaimed
383 }
384 })
385 }
386
387 fn shown(&self) -> store::Shown {
391 if self
392 .terms
393 .iter()
394 .any(|term| matches!(term, Term::Field(TextField::Tag, _)))
395 {
396 store::Shown::Definitions
397 } else {
398 store::Shown::Requests
399 }
400 }
401
402 fn statuses(&self) -> Vec<RequestStatus> {
404 let statuses: BTreeSet<_> = self
405 .terms
406 .iter()
407 .filter_map(|term| match term {
408 Term::Status(status) => Some(*status),
409 Term::Is(Is::Mine | Is::Claimed | Is::Unclaimed) => {
411 Some(RequestStatus::WaitingHuman)
412 }
413 _ => None,
414 })
415 .collect();
416 match statuses.len() {
417 0 | 1 => statuses
419 .into_iter()
420 .flat_map(|status| {
421 if status == RequestStatus::WaitingHuman {
422 vec![status, RequestStatus::Deferred]
423 } else {
424 vec![status]
425 }
426 })
427 .collect(),
428 _ => vec![*statuses.first().expect("two statuses")],
429 }
430 }
431}
432
433pub(crate) fn quote(key: &str, value: &str) -> String {
435 if value
436 .chars()
437 .any(|character| character.is_whitespace() || character == '"')
438 {
439 format!("{key}:\"{}\"", value.replace('"', ""))
440 } else {
441 format!("{key}:{value}")
442 }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct Completion {
448 pub keep: String,
450 pub candidates: Vec<String>,
452}
453
454pub(crate) fn last_term(text: &str) -> (&str, &str) {
457 match scan(text) {
458 (words, true) => text.split_at(words.last().map_or(0, |word| word.start)),
459 (_, false) => (text, ""),
460 }
461}
462
463pub fn complete(text: &str, entries: &[Entry]) -> Completion {
466 let (keep, term) = last_term(text);
467 let candidates = match term.split_once(':').filter(|_| !term.starts_with('"')) {
469 None if term.starts_with('"') => Vec::new(),
470 None => {
471 let lower = term.to_lowercase();
472 Key::ALL
473 .iter()
474 .map(|key| format!("{}:", key.name()))
475 .filter(|key| key.starts_with(&lower))
476 .collect()
477 }
478 Some((name, partial)) => match Key::parse(name) {
479 None => Vec::new(),
480 Some(key) => {
481 let partial = partial.trim_matches('"').to_lowercase();
482 let values: BTreeSet<String> = match key {
483 Key::Text(TextField::Repo) => entries
484 .iter()
485 .map(|entry| {
486 entry.repository.file_name().map_or_else(
487 || crate::platform::path_text(&entry.repository),
488 |name| name.to_string_lossy().into_owned(),
489 )
490 })
491 .collect(),
492 Key::Text(TextField::Eval) => {
493 entries.iter().map(|entry| entry.eval.clone()).collect()
494 }
495 Key::Text(TextField::Request) => {
496 entries.iter().map(|entry| entry.request.clone()).collect()
497 }
498 Key::Text(TextField::Reviewer) => entries
499 .iter()
500 .filter_map(|entry| entry.claim.reviewer().map(str::to_owned))
501 .collect(),
502 Key::Text(TextField::Tag) => entries
503 .iter()
504 .flat_map(|entry| entry.tags.iter().cloned())
505 .collect(),
506 Key::Kind => kind_values().collect(),
507 Key::Status => status_values().collect(),
508 Key::Is => Is::ALL.iter().map(|is| is.name().to_owned()).collect(),
509 };
510 values
511 .into_iter()
512 .filter(|value| value.to_lowercase().contains(&partial))
513 .map(|value| quote(key.name(), &value))
514 .collect()
515 }
516 },
517 };
518 Completion {
519 keep: keep.to_owned(),
520 candidates,
521 }
522}
523
524pub async fn suggest(
527 state: &Path,
528 text: &str,
529 reviewer: &ReviewerId,
530) -> Result<Completion, String> {
531 let (keep, term) = last_term(text);
532 let key = term
533 .split_once(':')
534 .filter(|_| !term.starts_with('"'))
535 .and_then(|(name, _)| Key::parse(name));
536 let from_requests = matches!(key, Some(Key::Text(_)));
537 let shown = match key {
538 Some(Key::Text(TextField::Tag)) => store::Shown::Definitions,
539 _ => keep
540 .parse::<Query>()
541 .map_or(store::Shown::Requests, |query| query.shown()),
542 };
543 let entries = match keep.parse::<Query>() {
544 Ok(query) if from_requests => page(state, &query, reviewer, 0, shown)
546 .await?
547 .requests
548 .into_iter()
549 .map(|(_, entry)| entry)
550 .collect(),
551 _ => Vec::new(),
552 };
553 Ok(complete(text, &entries))
554}
555
556#[derive(Debug, Clone, Default)]
558pub struct Found {
559 pub requests: Vec<(RequestView, Entry)>,
560 pub next: Option<u64>,
562}
563
564pub async fn search(
572 state: &Path,
573 query: &Query,
574 reviewer: &ReviewerId,
575 start: u64,
576) -> Result<Found, String> {
577 if start == 0 {
578 store::retire_removed_signoffs(state).await?;
579 }
580 page(state, query, reviewer, start, query.shown()).await
581}
582
583async fn page(
585 state: &Path,
586 query: &Query,
587 reviewer: &ReviewerId,
588 start: u64,
589 shown: store::Shown,
590) -> Result<Found, String> {
591 let mut found = Found::default();
592 read_matching(
593 state,
594 query,
595 reviewer,
596 start,
597 shown,
598 |view, entry, position| {
599 found.requests.push((view, entry));
600 if found.requests.len() < PAGE {
601 return ControlFlow::Continue(());
602 }
603 found.next = Some(position + 1);
604 ControlFlow::Break(())
605 },
606 )
607 .await?;
608 Ok(found)
609}
610
611pub async fn count(state: &Path, query: &Query, reviewer: &ReviewerId) -> Result<u64, String> {
614 let mut count = 0;
615 read_matching(state, query, reviewer, 0, query.shown(), |_, _, _| {
616 count += 1;
617 ControlFlow::Continue(())
618 })
619 .await?;
620 Ok(count)
621}
622
623async fn read_matching(
627 state: &Path,
628 query: &Query,
629 reviewer: &ReviewerId,
630 start: u64,
631 shown: store::Shown,
632 mut found: impl FnMut(RequestView, Entry, u64) -> ControlFlow<()>,
633) -> Result<(), String> {
634 let statuses = query.statuses();
635 let mut position = start;
636 loop {
637 let batch = store::read_request_batch(state, &statuses, position, BATCH, shown).await?;
638 let read = batch.len() as u64;
639 for (offset, (view, repo)) in batch.into_iter().enumerate() {
640 if Box::pin(follows_waiting(state, &view)).await {
641 continue;
642 }
643 let entry = Entry::new(&view, &repo, reviewer);
644 if query.matches(&entry) && found(view, entry, position + offset as u64).is_break() {
645 return Ok(());
646 }
647 }
648 if read < u64::from(BATCH) {
649 return Ok(());
650 }
651 position += read;
652 }
653}
654
655async fn follows_waiting(state: &Path, view: &RequestView) -> bool {
657 if !view.request.status().is_human_wait() {
658 return false;
659 }
660 let Some(source) = view
661 .execution
662 .as_ref()
663 .map(|execution| &execution.provenance.request_id)
664 .filter(|source| **source != view.request.id)
665 else {
666 return false;
667 };
668 store::read_request_by_id(state, source, store::Shown::Requests)
670 .await
671 .is_ok_and(|original| original.request.status().is_human_wait())
672}