1use std::{
2 collections::HashMap,
3 path::{Path, PathBuf},
4 sync::Arc,
5};
6
7use serde::Serialize;
8
9use rusqlite::OptionalExtension;
10use tokio_rusqlite::Connection;
11
12use super::{
13 DATABASE, Execution, HumanClaim, Request,
14 definitions::Graph,
15 receipts::{Error, check_files, schema_initialized},
16};
17use crate::workspace::{canonical_target, outside_workspace};
18
19#[derive(Debug, Clone, Serialize)]
23pub struct RequestView {
24 #[serde(flatten)]
25 pub request: Arc<Request>,
26 pub claim: Option<HumanClaim>,
27 pub execution: Option<Arc<Execution>>,
28 pub definition: Option<RequestDefinition>,
29}
30
31#[derive(Clone)]
33pub struct RequestDefinition(Place);
34#[derive(Clone)]
35enum Place {
36 Graph {
38 graph: Arc<Graph>,
39 eval: usize,
41 artifact: crate::types::ArtifactName,
42 },
43 Own {
46 eval: Arc<super::definitions::Eval>,
47 artifact: Arc<super::definitions::Artifact>,
48 },
49}
50impl RequestDefinition {
51 pub fn eval(&self) -> &super::definitions::Eval {
52 match &self.0 {
53 Place::Graph { graph, eval, .. } => &graph.evals()[*eval],
54 Place::Own { eval, .. } => eval,
55 }
56 }
57 pub fn artifact(&self) -> &super::definitions::Artifact {
58 match &self.0 {
59 Place::Graph {
60 graph, artifact, ..
61 } => graph
62 .artifact(artifact)
63 .expect("an indexed request's Artifact is in its graph"),
64 Place::Own { artifact, .. } => artifact,
65 }
66 }
67}
68impl Serialize for RequestDefinition {
69 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
70 use serde::ser::SerializeStruct;
71 let mut definition = serializer.serialize_struct("RequestDefinition", 2)?;
72 definition.serialize_field("eval", self.eval())?;
73 definition.serialize_field("artifact", self.artifact())?;
74 definition.end()
75 }
76}
77impl std::fmt::Debug for RequestDefinition {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 f.debug_struct("RequestDefinition")
80 .field("eval", self.eval())
81 .field("artifact", self.artifact())
82 .finish()
83 }
84}
85
86#[derive(Default)]
87struct Filter<'a> {
88 run: Option<crate::types::RunId>,
89 id: Option<crate::types::RequestId>,
90 repo: Option<&'a Path>,
91 waiting: bool,
92 session: Option<crate::types::SessionId>,
93 statuses: &'a [crate::types::RequestStatus],
94 slice: Option<(Start, u32)>,
96 shown: Shown,
97 newest_waiting: bool,
98}
99
100#[derive(Debug, Clone)]
102pub enum Start {
103 Position(u64),
105 After(Mark),
107}
108
109#[derive(Debug, Clone)]
111pub struct Mark {
112 listed: String,
113 run: i64,
115 run_id: String,
116 ordinal: i64,
117}
118
119#[derive(Debug, Default)]
121pub struct Batch {
122 pub requests: Vec<(u32, RequestView, PathBuf)>,
124 pub read: u32,
126 pub next: Option<Start>,
128}
129
130#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
132pub enum Shown {
133 #[default]
136 Definitions,
137 Requests,
139}
140
141pub async fn read_requests(state: &Path, run: Option<&str>) -> Result<Vec<RequestView>, String> {
142 read_requests_in(state, run, None).await
143}
144
145pub async fn read_requests_in(
146 state: &Path,
147 run: Option<&str>,
148 repo: Option<&Path>,
149) -> Result<Vec<RequestView>, String> {
150 let run = run.map(str::parse).transpose()?;
151 read_requests_for_run(state, run, repo).await
152}
153
154pub(crate) async fn read_requests_for_run(
155 state: &Path,
156 run: Option<crate::types::RunId>,
157 repo: Option<&Path>,
158) -> Result<Vec<RequestView>, String> {
159 read(
160 state,
161 Filter {
162 run,
163 repo,
164 ..Filter::default()
165 },
166 )
167 .await
168}
169
170pub async fn read_request(state: &Path, id: &str) -> Result<RequestView, String> {
171 read_request_id(state, &id.parse()?).await
172}
173
174pub async fn read_request_id(
175 state: &Path,
176 id: &crate::types::RequestId,
177) -> Result<RequestView, String> {
178 read_request_by_id(state, id, Shown::Definitions).await
179}
180
181pub async fn read_request_as(state: &Path, id: &str, shown: Shown) -> Result<RequestView, String> {
183 read_request_by_id(state, &id.parse()?, shown).await
184}
185
186pub async fn read_request_by_id(
188 state: &Path,
189 id: &crate::types::RequestId,
190 shown: Shown,
191) -> Result<RequestView, String> {
192 read_optional_request(state, id, shown)
193 .await?
194 .ok_or_else(|| "Review request not found.".into())
195}
196
197pub async fn read_optional_request(
199 state: &Path,
200 id: &crate::types::RequestId,
201 shown: Shown,
202) -> Result<Option<RequestView>, String> {
203 Ok(read(
204 state,
205 Filter {
206 id: Some(id.clone()),
207 shown,
208 ..Filter::default()
209 },
210 )
211 .await?
212 .pop())
213}
214
215pub async fn read_session_request(state: &Path, id: &str) -> Result<Option<RequestView>, String> {
217 read_request_by_session(state, id.parse()?).await
218}
219
220pub(crate) async fn read_request_by_session(
221 state: &Path,
222 session: crate::types::SessionId,
223) -> Result<Option<RequestView>, String> {
224 Ok(read(
225 state,
226 Filter {
227 session: Some(session),
228 ..Filter::default()
229 },
230 )
231 .await?
232 .pop())
233}
234
235pub async fn read_original(state: &Path, view: &RequestView) -> Result<RequestView, String> {
239 read_original_as(state, view, Shown::Definitions).await
240}
241
242pub async fn read_original_as(
244 state: &Path,
245 view: &RequestView,
246 shown: Shown,
247) -> Result<RequestView, String> {
248 match original_id(view) {
249 Some(id) => read_request_by_id(state, id, shown).await,
250 None => Ok(view.clone()),
251 }
252}
253
254pub async fn read_review_owner(state: &Path, view: &RequestView) -> Result<RequestView, String> {
257 let Some(id) = original_id(view).filter(|_| view.request.status().is_human_wait()) else {
258 return Ok(view.clone());
259 };
260 let found = read(
261 state,
262 Filter {
263 id: Some(id.clone()),
264 shown: Shown::Requests,
265 ..Filter::default()
266 },
267 )
268 .await?;
269 Ok(found.into_iter().next().unwrap_or_else(|| view.clone()))
270}
271
272fn original_id(view: &RequestView) -> Option<&crate::types::RequestId> {
273 view.execution
274 .as_ref()
275 .map(|execution| &execution.provenance.request_id)
276 .or_else(|| {
277 view.request
278 .provenance
279 .as_ref()
280 .map(|source| &source.request_id)
281 })
282 .filter(|id| *id != &view.request.id)
283}
284
285pub async fn read_waiting_originals(
288 state: &Path,
289 repo: Option<&Path>,
290) -> Result<Vec<RequestView>, String> {
291 let waiting = read_waiting(state, repo).await?;
292 let by_id: std::collections::BTreeMap<_, _> = waiting
293 .iter()
294 .map(|view| (&view.request.id, view))
295 .collect();
296 let mut seen = std::collections::BTreeSet::new();
297 let mut originals: Vec<RequestView> = Vec::with_capacity(waiting.len());
298 for view in &waiting {
299 let source = view
300 .execution
301 .as_ref()
302 .map_or(&view.request.id, |execution| {
303 &execution.provenance.request_id
304 });
305 if seen.contains(source) {
306 continue;
307 }
308 let original = match by_id.get(source) {
309 Some(original) => Some((*original).clone()),
310 None => read_original(state, view).await.ok(),
311 };
312 let original = original
314 .filter(|original| original.request.status().is_human_wait())
315 .unwrap_or_else(|| view.clone());
316 if seen.insert(original.request.id.clone()) {
317 originals.push(original);
318 }
319 }
320 Ok(originals)
321}
322
323pub async fn read_request_batch(
327 state: &Path,
328 statuses: &[crate::types::RequestStatus],
329 start: Start,
330 limit: u32,
331 shown: Shown,
332) -> Result<Batch, String> {
333 read_batch(
334 state,
335 Filter {
336 statuses,
337 slice: Some((start, limit)),
338 shown,
339 ..Filter::default()
340 },
341 )
342 .await
343}
344
345pub(crate) async fn read_review_batch(
347 state: &Path,
348 statuses: &[crate::types::RequestStatus],
349 start: Start,
350 limit: u32,
351 shown: Shown,
352) -> Result<Batch, String> {
353 read_batch(
354 state,
355 Filter {
356 statuses,
357 slice: Some((start, limit)),
358 shown,
359 newest_waiting: true,
360 ..Filter::default()
361 },
362 )
363 .await
364}
365
366pub async fn read_waiting(state: &Path, repo: Option<&Path>) -> Result<Vec<RequestView>, String> {
370 read(
371 state,
372 Filter {
373 repo,
374 waiting: true,
375 shown: Shown::Requests,
376 ..Filter::default()
377 },
378 )
379 .await
380}
381
382async fn read(state: &Path, filter: Filter<'_>) -> Result<Vec<RequestView>, String> {
383 Ok(read_with_repo(state, filter)
384 .await?
385 .into_iter()
386 .map(|(view, _)| view)
387 .collect())
388}
389
390pub async fn read_request_repo(state: &Path, id: &str) -> Result<std::path::PathBuf, String> {
394 read_request_repo_by_id(state, id.parse()?).await
395}
396
397pub(crate) async fn read_request_repo_by_id(
398 state: &Path,
399 id: crate::types::RequestId,
400) -> Result<std::path::PathBuf, String> {
401 let not_found = || "Review request not found.".to_owned();
402 let state = canonical_target(state).map_err(|e| e.to_string())?;
403 let Some(connection) = open_read(&state).await? else {
404 return Err(not_found());
405 };
406 let result = connection
407 .call(move |db| -> Result<_, Error> {
408 super::wait_when_busy(db)?;
409 let transaction = db.transaction()?;
410 if !schema_initialized(&transaction)? {
411 return Ok(None);
412 }
413 let repo = transaction
414 .query_row(
415 "SELECT r.repo FROM requests q JOIN runs r ON r.id=q.run_id WHERE q.id=?",
416 [&id],
417 |row| super::path_column(row, 0),
418 )
419 .optional()?;
420 transaction.commit()?;
421 if let Some(repo) = &repo {
422 crate::workspace::outside_workspaces(std::iter::once(repo.as_path()), &state)
423 .map_err(|error| Error::Invalid(error.to_string()))?;
424 }
425 Ok(repo)
426 })
427 .await
428 .map_err(|e| e.to_string());
429 super::connection::finish(connection, result)
430 .await?
431 .ok_or_else(not_found)
432}
433
434pub(super) async fn open_read(state: &Path) -> Result<Option<Connection>, String> {
436 check_files(state)?;
437 if !state
438 .join(DATABASE)
439 .try_exists()
440 .map_err(|e| e.to_string())?
441 {
442 return Ok(None);
443 }
444 Connection::open_with_flags(
445 state.join(DATABASE),
446 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
447 )
448 .await
449 .map(Some)
450 .map_err(|e| e.to_string())
451}
452
453async fn read_with_repo(
454 state: &Path,
455 filter: Filter<'_>,
456) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
457 Ok(read_batch(state, filter)
458 .await?
459 .requests
460 .into_iter()
461 .map(|(_, view, repo)| (view, repo))
462 .collect())
463}
464
465async fn read_batch(state: &Path, filter: Filter<'_>) -> Result<Batch, String> {
466 let state = canonical_target(state).map_err(|e| e.to_string())?;
467 let repo = filter
468 .repo
469 .map(canonical_target)
470 .transpose()
471 .map_err(|e| e.to_string())?;
472 if let Some(repo) = &repo {
473 outside_workspace(repo, &state).map_err(|e| e.to_string())?;
474 }
475 let Filter {
476 run,
477 id,
478 waiting,
479 statuses,
480 slice,
481 session,
482 newest_waiting,
483 ..
484 } = filter;
485 let statuses = statuses.to_vec();
486 let shown = filter.shown;
487 let Some(connection) = open_read(&state).await? else {
488 return Ok(Batch::default());
489 };
490 let result = connection
491 .call(move |db| -> Result<_, Error> {
492 super::wait_when_busy(db)?;
493 let transaction = db.transaction()?;
494 if !schema_initialized(&transaction)? {
495 return Ok(Batch::default());
496 }
497 let filter = Query {
498 run,
499 id,
500 repo,
501 waiting,
502 session,
503 statuses,
504 slice,
505 ids: None,
506 newest_waiting,
507 };
508 let rows = rows(&transaction, &filter)?;
509 let ids: std::collections::BTreeSet<_> = rows.iter().map(|row| &row.run).collect();
510 let mut statement = transaction.prepare(match shown {
511 Shown::Definitions => "SELECT r.id,r.repo,r.data,d.data,d.body FROM runs r LEFT JOIN run_definitions d ON d.run_id=r.id WHERE r.id IN (SELECT value FROM json_each(?))",
512 Shown::Requests => "SELECT r.id,r.repo,NULL,NULL,NULL FROM runs r WHERE r.id IN (SELECT value FROM json_each(?))",
513 })?;
514 let runs = statement
515 .query_map([serde_json::to_string(&ids)?], |row| {
516 Ok((
517 row.get::<_, crate::types::RunId>(0)?,
518 row.get::<_, String>(1)?,
519 row.get::<_, Option<String>>(2)?,
520 row.get::<_, Option<String>>(3)?,
521 row.get::<_, Option<String>>(4)?,
522 ))
523 })?
524 .collect::<Result<Vec<_>, _>>()?;
525 let mut indexes = std::collections::BTreeMap::new();
526 let mut repos = Vec::new();
527 for (id, repo, state, definitions, body) in runs {
528 let index = match state {
529 None => DefinitionIndex::none(),
530 Some(state) => {
531 let read = definitions
532 .map(|data| super::run_record::text(&transaction, &id, data, body))
533 .transpose()?
534 .transpose()
535 .and_then(|definitions| {
536 super::run_record::whole(&id, &state, definitions.as_deref())
537 });
538 match read {
539 Ok(run) => DefinitionIndex::apart(&run),
540 Err(unreadable) => {
541 super::unreadable::skipped(&unreadable);
542 continue;
543 }
544 }
545 }
546 };
547 let repo = artifactize_tools::files::path_from_text(&repo)
548 .map_err(|error| Error::Invalid(error.to_string()))?;
549 repos.push(repo.clone());
550 indexes.insert(id, (index, repo));
551 }
552 crate::workspace::outside_workspaces(repos.iter().map(|repo| repo.as_path()), &state)
553 .map_err(|error| Error::Invalid(error.to_string()))?;
554 let batch = Batch {
555 read: u32::try_from(rows.len()).expect("a batch reads at most its u32 limit"),
556 next: rows.last().map(|row| Start::After(row.mark.clone())),
557 requests: rows
558 .into_iter()
559 .enumerate()
560 .filter_map(|(offset, row)| {
561 let (index, repo) = indexes.get_mut(&row.run)?;
562 let view = row.view(index)?;
563 Some((offset as u32, view, repo.clone()))
564 })
565 .collect(),
566 };
567 drop(statement);
568 transaction.commit()?;
569 Ok(batch)
570 })
571 .await
572 .map_err(|e| e.to_string());
573 super::connection::finish(connection, result).await
574}
575
576#[derive(Default)]
578pub(super) struct Query {
579 pub run: Option<crate::types::RunId>,
580 pub id: Option<crate::types::RequestId>,
581 pub repo: Option<std::path::PathBuf>,
582 pub waiting: bool,
583 pub session: Option<crate::types::SessionId>,
584 pub statuses: Vec<crate::types::RequestStatus>,
585 pub slice: Option<(Start, u32)>,
586 pub newest_waiting: bool,
587 pub ids: Option<Vec<crate::types::RequestId>>,
589}
590
591#[derive(Debug, Clone)]
592pub(super) struct Row {
593 pub id: crate::types::RequestId,
594 pub run: crate::types::RunId,
595 pub eval: crate::types::EvalId,
596 pub data: String,
597 pub execution: Option<String>,
598 pub execution_id: Option<crate::types::ExecutionId>,
599 pub claim: Option<(
600 crate::types::RequestId,
601 crate::types::ReviewerId,
602 crate::types::Timestamp,
603 )>,
604 pub mark: Mark,
606}
607
608pub(super) fn rows(db: &rusqlite::Connection, filter: &Query) -> Result<Vec<Row>, Error> {
609 let (mut predicates, mut values): (Vec<String>, Vec<rusqlite::types::Value>) = [
611 ("q.run_id", filter.run.as_ref().map(ToString::to_string)),
612 ("q.id", filter.id.as_ref().map(ToString::to_string)),
613 (
614 "r.repo",
615 filter.repo.as_deref().map(crate::platform::path_text),
616 ),
617 (
618 "json_extract(q.data,'$.sessionId')",
619 filter.session.as_ref().map(ToString::to_string),
620 ),
621 ]
622 .into_iter()
623 .filter_map(|(column, value)| Some((format!("{column}=?"), value?.into())))
624 .unzip();
625 if filter.waiting {
626 predicates.push("q.status IN ('WAITING_HUMAN','DEFERRED')".into());
627 }
628 if let Some(ids) = &filter.ids {
629 predicates.push("q.id IN (SELECT value FROM json_each(?))".into());
630 values.push(serde_json::to_string(ids)?.into());
631 }
632 if !filter.statuses.is_empty() {
633 let marks = vec!["?"; filter.statuses.len()].join(",");
634 predicates.push(format!("q.status IN ({marks})"));
635 values.extend(
636 filter
637 .statuses
638 .iter()
639 .map(|status| rusqlite::types::Value::from(status.as_str().to_owned())),
640 );
641 }
642 type After = fn(&Mark) -> (&'static str, Vec<rusqlite::types::Value>);
648 let (order, after): (_, After) = if filter.run.is_some() {
649 ("q.ordinal", |mark| {
650 ("q.ordinal>?", vec![mark.ordinal.into()])
651 })
652 } else if filter.newest_waiting {
653 ("q.listed DESC,q.run_id DESC,q.ordinal", |mark| {
654 (
655 "q.listed<=? AND (q.listed<? OR q.run_id<? OR (q.run_id=? AND q.ordinal>?))",
656 vec![
657 mark.listed.clone().into(),
658 mark.listed.clone().into(),
659 mark.run_id.clone().into(),
660 mark.run_id.clone().into(),
661 mark.ordinal.into(),
662 ],
663 )
664 })
665 } else {
666 ("r.rowid DESC,q.ordinal", |mark| {
667 (
668 "r.rowid<=? AND (r.rowid<? OR q.ordinal>?)",
669 vec![mark.run.into(), mark.run.into(), mark.ordinal.into()],
670 )
671 })
672 };
673 let mut limit = "";
674 if let Some((start, count)) = &filter.slice {
675 let offset = match start {
676 Start::Position(offset) => *offset,
677 Start::After(mark) => {
678 let (predicate, bound) = after(mark);
679 predicates.push(predicate.into());
680 values.extend(bound);
681 0
682 }
683 };
684 values.push(i64::from(*count).into());
685 values.push(i64::try_from(offset).unwrap_or(i64::MAX).into());
686 limit = " LIMIT ? OFFSET ?";
687 }
688 let predicate = if predicates.is_empty() {
689 String::new()
690 } else {
691 format!("WHERE {}", predicates.join(" AND "))
692 };
693 let mut statement = db.prepare_cached(&format!(
694 "SELECT q.id,q.run_id,q.data,e.data,h.id,h.claimed_by,h.claimed_at,q.eval_id,e.id,q.listed,r.rowid,q.ordinal
695 FROM requests q JOIN runs r ON r.id=q.run_id
696 LEFT JOIN executions e ON e.id=q.execution_id
697 LEFT JOIN requests h ON h.id=json_extract(e.data,'$.provenance.requestId') AND h.claimed_by IS NOT NULL
698 {predicate} ORDER BY {order}{limit}"
699 ))?;
700 #[cfg(test)]
701 statement.reset_status(rusqlite::StatementStatus::VmStep);
702 let rows = statement
703 .query_map(rusqlite::params_from_iter(values), |row| {
704 let id = row.get::<_, Option<crate::types::RequestId>>(4)?;
705 let reviewer = row.get::<_, Option<crate::types::ReviewerId>>(5)?;
706 let at = row.get::<_, Option<crate::types::Timestamp>>(6)?;
707 Ok(Row {
708 id: row.get(0)?,
709 run: row.get(1)?,
710 eval: row.get(7)?,
711 data: row.get(2)?,
712 execution: row.get(3)?,
713 execution_id: row.get(8)?,
714 claim: id
715 .zip(reviewer)
716 .zip(at)
717 .map(|((id, reviewer), at)| (id, reviewer, at)),
718 mark: Mark {
719 listed: row.get(9)?,
720 run: row.get(10)?,
721 run_id: row.get(1)?,
722 ordinal: row.get(11)?,
723 },
724 })
725 })?
726 .collect::<Result<_, _>>()?;
727 #[cfg(test)]
728 crate::performance::sql_steps(statement.reset_status(rusqlite::StatementStatus::VmStep));
729 Ok(rows)
730}
731
732pub(super) struct DefinitionIndex {
736 graph: Option<Arc<Graph>>,
737 evals: HashMap<crate::types::EvalId, usize>,
738 copies: Option<Copies>,
740}
741#[derive(Default)]
742struct Copies {
743 evals: HashMap<usize, Arc<super::definitions::Eval>>,
744 artifacts: HashMap<crate::types::ArtifactName, Arc<super::definitions::Artifact>>,
745}
746impl DefinitionIndex {
747 pub fn new(run: &super::Run) -> Self {
749 let graph = run.definitions.share();
750 let mut evals = HashMap::new();
751 for (position, eval) in graph.iter().flat_map(|graph| graph.evals()).enumerate() {
752 evals.entry(eval.id.clone()).or_insert(position);
753 }
754 Self {
755 graph,
756 evals,
757 copies: None,
758 }
759 }
760 fn apart(run: &super::Run) -> Self {
763 Self {
764 copies: Some(Copies::default()),
765 ..Self::new(run)
766 }
767 }
768 fn none() -> Self {
770 Self {
771 graph: None,
772 evals: HashMap::new(),
773 copies: None,
774 }
775 }
776 fn definition(
777 &mut self,
778 eval: &crate::types::EvalId,
779 artifact: &crate::types::ArtifactName,
780 ) -> Option<RequestDefinition> {
781 let graph = self.graph.as_ref()?;
782 let saved = graph.artifact(artifact)?;
783 let position = *self.evals.get(eval)?;
784 Some(RequestDefinition(match &mut self.copies {
785 None => Place::Graph {
786 graph: graph.clone(),
787 eval: position,
788 artifact: artifact.clone(),
789 },
790 Some(copies) => Place::Own {
791 eval: copies
792 .evals
793 .entry(position)
794 .or_insert_with(|| Arc::new(graph.evals()[position].clone()))
795 .clone(),
796 artifact: copies
797 .artifacts
798 .entry(artifact.clone())
799 .or_insert_with(|| Arc::new(saved.clone()))
800 .clone(),
801 },
802 }))
803 }
804}
805impl Row {
806 pub fn view(&self, index: &mut DefinitionIndex) -> Option<RequestView> {
807 let request = super::unreadable::evidence::<Request>("request", &self.data)?;
808 let execution = self
809 .execution
810 .as_deref()
811 .and_then(|data| super::unreadable::evidence("execution", data));
812 Some(self.with_evidence(index, request, execution))
813 }
814 pub fn read(
817 &self,
818 index: &mut DefinitionIndex,
819 ) -> (Option<RequestView>, Vec<super::Unreadable>) {
820 let mut unreadable = Vec::new();
821 let execution = self
822 .execution
823 .as_deref()
824 .zip(self.execution_id.as_ref())
825 .and_then(|(data, id)| {
826 super::unreadable::decode("execution", id, data)
827 .map_err(|record| unreadable.push(record))
828 .ok()
829 });
830 let view = super::unreadable::decode::<Request>("request", &self.id, &self.data)
831 .map_err(|record| unreadable.push(record))
832 .ok()
833 .map(|request| self.with_evidence(index, request, execution));
834 (view, unreadable)
835 }
836 fn with_evidence(
837 &self,
838 index: &mut DefinitionIndex,
839 request: Request,
840 execution: Option<Execution>,
841 ) -> RequestView {
842 let definition = index.definition(&self.eval, &request.target);
843 RequestView {
844 request: Arc::new(request),
845 definition,
846 execution: execution.map(Arc::new),
847 claim: self.claim.as_ref().map(|(id, reviewer, at)| HumanClaim {
848 request_id: id.clone(),
849 reviewer: reviewer.clone(),
850 claimed_at: *at,
851 }),
852 }
853 }
854}
855
856pub async fn read_run_requests(
858 state: &Path,
859 id: &str,
860) -> Result<(super::RunView, Vec<RequestView>), String> {
861 read_run_requests_by_id(state, &id.parse()?).await
862}
863
864pub async fn read_run_requests_by_id(
866 state: &Path,
867 id: &crate::types::RunId,
868) -> Result<(super::RunView, Vec<RequestView>), String> {
869 let state = state.to_path_buf();
870 let id = id.clone();
871 crate::task::joined(
872 tokio::task::spawn_blocking(move || {
873 let mut reader = super::reader::Reader::default();
874 reader
875 .snapshot(&state, |db, cache, state| {
876 cache.selected(db, state, &id, true)
877 })?
878 .ok_or_else(|| "Run not found.".into())
879 })
880 .await,
881 )
882 .map_err(|error| error.to_string())?
883}