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 list_limit: Option<u32>,
99}
100
101#[derive(Debug, Clone)]
103pub enum Start {
104 Position(u64),
106 After(Mark),
108}
109
110#[derive(Debug, Clone)]
112pub struct Mark {
113 listed: String,
114 run: i64,
116 run_id: String,
117 ordinal: i64,
118}
119
120#[derive(Debug, Default)]
122pub struct Batch {
123 pub requests: Vec<(u32, RequestView, PathBuf)>,
125 pub read: u32,
127 pub next: Option<Start>,
129}
130
131#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
133pub enum Shown {
134 #[default]
137 Definitions,
138 Requests,
140}
141
142pub async fn read_requests(state: &Path, run: Option<&str>) -> Result<Vec<RequestView>, String> {
143 read_requests_in(state, run, None).await
144}
145
146pub async fn read_requests_in(
147 state: &Path,
148 run: Option<&str>,
149 repo: Option<&Path>,
150) -> Result<Vec<RequestView>, String> {
151 read(
152 state,
153 Filter {
154 run: run.map(str::parse).transpose()?,
155 repo,
156 ..Filter::default()
157 },
158 )
159 .await
160}
161
162pub(crate) async fn read_request_list(
163 state: &Path,
164 run: Option<crate::types::RunId>,
165 repo: Option<&Path>,
166 limit: u32,
167) -> Result<Vec<RequestView>, String> {
168 if limit == 0 {
169 return Ok(Vec::new());
170 }
171 read(
172 state,
173 Filter {
174 run,
175 repo,
176 shown: Shown::Requests,
177 list_limit: Some(limit),
178 ..Filter::default()
179 },
180 )
181 .await
182}
183
184pub async fn read_request(state: &Path, id: &str) -> Result<RequestView, String> {
185 read_request_id(state, &id.parse()?).await
186}
187
188pub async fn read_request_id(
189 state: &Path,
190 id: &crate::types::RequestId,
191) -> Result<RequestView, String> {
192 read_request_by_id(state, id, Shown::Definitions).await
193}
194
195pub async fn read_request_as(state: &Path, id: &str, shown: Shown) -> Result<RequestView, String> {
197 read_request_by_id(state, &id.parse()?, shown).await
198}
199
200pub async fn read_request_by_id(
202 state: &Path,
203 id: &crate::types::RequestId,
204 shown: Shown,
205) -> Result<RequestView, String> {
206 read_optional_request(state, id, shown)
207 .await?
208 .ok_or_else(|| "Review request not found.".into())
209}
210
211pub async fn read_optional_request(
213 state: &Path,
214 id: &crate::types::RequestId,
215 shown: Shown,
216) -> Result<Option<RequestView>, String> {
217 Ok(read(
218 state,
219 Filter {
220 id: Some(id.clone()),
221 shown,
222 ..Filter::default()
223 },
224 )
225 .await?
226 .pop())
227}
228
229pub async fn read_session_request(state: &Path, id: &str) -> Result<Option<RequestView>, String> {
231 read_request_by_session(state, id.parse()?).await
232}
233
234pub(crate) async fn read_request_by_session(
235 state: &Path,
236 session: crate::types::SessionId,
237) -> Result<Option<RequestView>, String> {
238 Ok(read(
239 state,
240 Filter {
241 session: Some(session),
242 ..Filter::default()
243 },
244 )
245 .await?
246 .pop())
247}
248
249pub async fn read_original(state: &Path, view: &RequestView) -> Result<RequestView, String> {
253 read_original_as(state, view, Shown::Definitions).await
254}
255
256pub async fn read_original_as(
258 state: &Path,
259 view: &RequestView,
260 shown: Shown,
261) -> Result<RequestView, String> {
262 match original_id(view) {
263 Some(id) => read_request_by_id(state, id, shown).await,
264 None => Ok(view.clone()),
265 }
266}
267
268pub async fn read_review_owner(state: &Path, view: &RequestView) -> Result<RequestView, String> {
271 let Some(id) = original_id(view).filter(|_| view.request.status().is_human_wait()) else {
272 return Ok(view.clone());
273 };
274 let found = read(
275 state,
276 Filter {
277 id: Some(id.clone()),
278 shown: Shown::Requests,
279 ..Filter::default()
280 },
281 )
282 .await?;
283 Ok(found.into_iter().next().unwrap_or_else(|| view.clone()))
284}
285
286fn original_id(view: &RequestView) -> Option<&crate::types::RequestId> {
287 view.execution
288 .as_ref()
289 .map(|execution| &execution.provenance.request_id)
290 .or_else(|| {
291 view.request
292 .provenance
293 .as_ref()
294 .map(|source| &source.request_id)
295 })
296 .filter(|id| *id != &view.request.id)
297}
298
299pub async fn read_waiting_originals(
302 state: &Path,
303 repo: Option<&Path>,
304) -> Result<Vec<RequestView>, String> {
305 let waiting = read_waiting(state, repo).await?;
306 let by_id: std::collections::BTreeMap<_, _> = waiting
307 .iter()
308 .map(|view| (&view.request.id, view))
309 .collect();
310 let mut seen = std::collections::BTreeSet::new();
311 let mut originals: Vec<RequestView> = Vec::with_capacity(waiting.len());
312 for view in &waiting {
313 let source = view
314 .execution
315 .as_ref()
316 .map_or(&view.request.id, |execution| {
317 &execution.provenance.request_id
318 });
319 if seen.contains(source) {
320 continue;
321 }
322 let original = match by_id.get(source) {
323 Some(original) => Some((*original).clone()),
324 None => read_original(state, view).await.ok(),
325 };
326 let original = original
328 .filter(|original| original.request.status().is_human_wait())
329 .unwrap_or_else(|| view.clone());
330 if seen.insert(original.request.id.clone()) {
331 originals.push(original);
332 }
333 }
334 Ok(originals)
335}
336
337pub async fn read_request_batch(
341 state: &Path,
342 statuses: &[crate::types::RequestStatus],
343 start: Start,
344 limit: u32,
345 shown: Shown,
346) -> Result<Batch, String> {
347 read_batch(
348 state,
349 Filter {
350 statuses,
351 slice: Some((start, limit)),
352 shown,
353 ..Filter::default()
354 },
355 )
356 .await
357}
358
359pub(crate) async fn read_review_batch(
361 state: &Path,
362 statuses: &[crate::types::RequestStatus],
363 start: Start,
364 limit: u32,
365 shown: Shown,
366) -> Result<Batch, String> {
367 read_batch(
368 state,
369 Filter {
370 statuses,
371 slice: Some((start, limit)),
372 shown,
373 newest_waiting: true,
374 ..Filter::default()
375 },
376 )
377 .await
378}
379
380pub async fn read_waiting(state: &Path, repo: Option<&Path>) -> Result<Vec<RequestView>, String> {
384 read(
385 state,
386 Filter {
387 repo,
388 waiting: true,
389 shown: Shown::Requests,
390 ..Filter::default()
391 },
392 )
393 .await
394}
395
396async fn read(state: &Path, filter: Filter<'_>) -> Result<Vec<RequestView>, String> {
397 Ok(read_with_repo(state, filter)
398 .await?
399 .into_iter()
400 .map(|(view, _)| view)
401 .collect())
402}
403
404pub async fn read_request_repo(state: &Path, id: &str) -> Result<std::path::PathBuf, String> {
408 read_request_repo_by_id(state, id.parse()?).await
409}
410
411pub(crate) async fn read_request_repo_by_id(
412 state: &Path,
413 id: crate::types::RequestId,
414) -> Result<std::path::PathBuf, String> {
415 let not_found = || "Review request not found.".to_owned();
416 let state = canonical_target(state).map_err(|e| e.to_string())?;
417 let Some(connection) = open_read(&state).await? else {
418 return Err(not_found());
419 };
420 let result = connection
421 .call(move |db| -> Result<_, Error> {
422 super::wait_when_busy(db)?;
423 let transaction = db.transaction()?;
424 if !schema_initialized(&transaction)? {
425 return Ok(None);
426 }
427 let repo = transaction
428 .query_row(
429 "SELECT r.repo FROM requests q JOIN runs r ON r.id=q.run_id WHERE q.id=?",
430 [&id],
431 |row| super::path_column(row, 0),
432 )
433 .optional()?;
434 transaction.commit()?;
435 if let Some(repo) = &repo {
436 crate::workspace::outside_workspaces(std::iter::once(repo.as_path()), &state)
437 .map_err(|error| Error::Invalid(error.to_string()))?;
438 }
439 Ok(repo)
440 })
441 .await
442 .map_err(|e| e.to_string());
443 super::connection::finish(connection, result)
444 .await?
445 .ok_or_else(not_found)
446}
447
448pub(super) async fn open_read(state: &Path) -> Result<Option<Connection>, String> {
450 check_files(state)?;
451 if !state
452 .join(DATABASE)
453 .try_exists()
454 .map_err(|e| e.to_string())?
455 {
456 return Ok(None);
457 }
458 Connection::open_with_flags(
459 state.join(DATABASE),
460 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
461 )
462 .await
463 .map(Some)
464 .map_err(|e| e.to_string())
465}
466
467async fn read_with_repo(
468 state: &Path,
469 filter: Filter<'_>,
470) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
471 Ok(read_batch(state, filter)
472 .await?
473 .requests
474 .into_iter()
475 .map(|(_, view, repo)| (view, repo))
476 .collect())
477}
478
479async fn read_batch(state: &Path, filter: Filter<'_>) -> Result<Batch, String> {
480 let state = canonical_target(state).map_err(|e| e.to_string())?;
481 let repo = filter
482 .repo
483 .map(canonical_target)
484 .transpose()
485 .map_err(|e| e.to_string())?;
486 if let Some(repo) = &repo {
487 outside_workspace(repo, &state).map_err(|e| e.to_string())?;
488 }
489 let Filter {
490 run,
491 id,
492 waiting,
493 statuses,
494 slice,
495 session,
496 newest_waiting,
497 list_limit,
498 ..
499 } = filter;
500 let statuses = statuses.to_vec();
501 let shown = filter.shown;
502 let Some(connection) = open_read(&state).await? else {
503 return Ok(Batch::default());
504 };
505 let result = connection
506 .call(move |db| -> Result<_, Error> {
507 super::wait_when_busy(db)?;
508 if list_limit.is_some() && run.is_none() && repo.is_some() {
509 super::migrations::ensure_request_list_index(db, &state)?;
510 }
511 let transaction = db.transaction()?;
512 if !schema_initialized(&transaction)? {
513 return Ok(Batch::default());
514 }
515 let filter = Query {
516 run,
517 id,
518 repo,
519 waiting,
520 session,
521 statuses,
522 slice,
523 ids: None,
524 newest_waiting,
525 list_limit,
526 };
527 let rows = rows(&transaction, &filter)?;
528 let ids: std::collections::BTreeSet<_> = rows.iter().map(|row| &row.run).collect();
529 let mut statement = transaction.prepare(match shown {
530 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(?))",
531 Shown::Requests => "SELECT r.id,r.repo,NULL,NULL,NULL FROM runs r WHERE r.id IN (SELECT value FROM json_each(?))",
532 })?;
533 let runs = statement
534 .query_map([serde_json::to_string(&ids)?], |row| {
535 Ok((
536 row.get::<_, crate::types::RunId>(0)?,
537 row.get::<_, String>(1)?,
538 row.get::<_, Option<String>>(2)?,
539 row.get::<_, Option<String>>(3)?,
540 row.get::<_, Option<String>>(4)?,
541 ))
542 })?
543 .collect::<Result<Vec<_>, _>>()?;
544 let mut indexes = std::collections::BTreeMap::new();
545 let mut repos = Vec::new();
546 for (id, repo, state, definitions, body) in runs {
547 let index = match state {
548 None => DefinitionIndex::none(),
549 Some(state) => {
550 let read = definitions
551 .map(|data| super::run_record::text(&transaction, &id, data, body))
552 .transpose()?
553 .transpose()
554 .and_then(|definitions| {
555 super::run_record::whole(&id, &state, definitions.as_deref())
556 });
557 match read {
558 Ok(run) => DefinitionIndex::apart(&run),
559 Err(unreadable) => {
560 super::unreadable::skipped(&unreadable);
561 continue;
562 }
563 }
564 }
565 };
566 let repo = artifactize_tools::files::path_from_text(&repo)
567 .map_err(|error| Error::Invalid(error.to_string()))?;
568 repos.push(repo.clone());
569 indexes.insert(id, (index, repo));
570 }
571 crate::workspace::outside_workspaces(repos.iter().map(|repo| repo.as_path()), &state)
572 .map_err(|error| Error::Invalid(error.to_string()))?;
573 let batch = Batch {
574 read: u32::try_from(rows.len()).expect("a batch reads at most its u32 limit"),
575 next: rows.last().map(|row| Start::After(row.mark.clone())),
576 requests: rows
577 .into_iter()
578 .enumerate()
579 .filter_map(|(offset, row)| {
580 let (index, repo) = indexes.get_mut(&row.run)?;
581 let view = row.view(index)?;
582 Some((offset as u32, view, repo.clone()))
583 })
584 .collect(),
585 };
586 drop(statement);
587 transaction.commit()?;
588 Ok(batch)
589 })
590 .await
591 .map_err(|e| e.to_string());
592 super::connection::finish(connection, result).await
593}
594
595#[derive(Default)]
597pub(super) struct Query {
598 pub run: Option<crate::types::RunId>,
599 pub id: Option<crate::types::RequestId>,
600 pub repo: Option<std::path::PathBuf>,
601 pub waiting: bool,
602 pub session: Option<crate::types::SessionId>,
603 pub statuses: Vec<crate::types::RequestStatus>,
604 pub slice: Option<(Start, u32)>,
605 pub newest_waiting: bool,
606 pub list_limit: Option<u32>,
608 pub ids: Option<Vec<crate::types::RequestId>>,
610}
611
612#[derive(Debug, Clone)]
613pub(super) struct Row {
614 pub id: crate::types::RequestId,
615 pub run: crate::types::RunId,
616 pub eval: crate::types::EvalId,
617 pub data: String,
618 pub execution: Option<String>,
619 pub execution_id: Option<crate::types::ExecutionId>,
620 pub claim: Option<(
621 crate::types::RequestId,
622 crate::types::ReviewerId,
623 crate::types::Timestamp,
624 )>,
625 pub mark: Mark,
627}
628
629pub(super) fn rows(db: &rusqlite::Connection, filter: &Query) -> Result<Vec<Row>, Error> {
630 let (mut predicates, mut values): (Vec<String>, Vec<rusqlite::types::Value>) = [
632 ("q.run_id", filter.run.as_ref().map(ToString::to_string)),
633 ("q.id", filter.id.as_ref().map(ToString::to_string)),
634 (
635 "r.repo",
636 filter.repo.as_deref().map(crate::platform::path_text),
637 ),
638 (
639 "json_extract(q.data,'$.sessionId')",
640 filter.session.as_ref().map(ToString::to_string),
641 ),
642 ]
643 .into_iter()
644 .filter_map(|(column, value)| Some((format!("{column}=?"), value?.into())))
645 .unzip();
646 if filter.waiting {
647 predicates.push("q.status IN ('WAITING_HUMAN','DEFERRED')".into());
648 }
649 if let Some(ids) = &filter.ids {
650 predicates.push("q.id IN (SELECT value FROM json_each(?))".into());
651 values.push(serde_json::to_string(ids)?.into());
652 }
653 if !filter.statuses.is_empty() {
654 let marks = vec!["?"; filter.statuses.len()].join(",");
655 predicates.push(format!("q.status IN ({marks})"));
656 values.extend(
657 filter
658 .statuses
659 .iter()
660 .map(|status| rusqlite::types::Value::from(status.as_str().to_owned())),
661 );
662 }
663 type After = fn(&Mark) -> (&'static str, Vec<rusqlite::types::Value>);
669 let (order, after): (_, After) = if filter.run.is_some() {
670 ("q.ordinal", |mark| {
671 ("q.ordinal>?", vec![mark.ordinal.into()])
672 })
673 } else if filter.newest_waiting {
674 ("q.listed DESC,q.run_id DESC,q.ordinal", |mark| {
675 (
676 "q.listed<=? AND (q.listed<? OR q.run_id<? OR (q.run_id=? AND q.ordinal>?))",
677 vec![
678 mark.listed.clone().into(),
679 mark.listed.clone().into(),
680 mark.run_id.clone().into(),
681 mark.run_id.clone().into(),
682 mark.ordinal.into(),
683 ],
684 )
685 })
686 } else {
687 ("r.rowid DESC,q.ordinal", |mark| {
688 (
689 "r.rowid<=? AND (r.rowid<? OR q.ordinal>?)",
690 vec![mark.run.into(), mark.run.into(), mark.ordinal.into()],
691 )
692 })
693 };
694 let mut limit = "";
695 if let Some(count) = filter.list_limit.filter(|_| filter.run.is_none()) {
696 let scope = if let Some(repo) = &filter.repo {
701 values.push(crate::platform::path_text(repo).into());
702 "WHERE repo=?"
703 } else {
704 ""
705 };
706 predicates.push(format!(
707 "r.rowid IN (
708 SELECT rr.rowid FROM (
709 SELECT request_id FROM request_attempts {scope} ORDER BY sequence DESC LIMIT ?
710 ) recent
711 CROSS JOIN requests qq ON qq.id=recent.request_id
712 CROSS JOIN runs rr ON rr.id=qq.run_id
713 )"
714 ));
715 values.push(i64::from(count).into());
716 }
717 let from = if filter.list_limit.is_some() {
720 "runs r CROSS JOIN requests q ON q.run_id=r.id"
721 } else {
722 "requests q JOIN runs r ON r.id=q.run_id"
723 };
724 if let Some(count) = filter.list_limit {
725 values.push(i64::from(count).into());
726 limit = " LIMIT ?";
727 } else if let Some((start, count)) = &filter.slice {
728 let offset = match start {
729 Start::Position(offset) => *offset,
730 Start::After(mark) => {
731 let (predicate, bound) = after(mark);
732 predicates.push(predicate.into());
733 values.extend(bound);
734 0
735 }
736 };
737 values.push(i64::from(*count).into());
738 values.push(i64::try_from(offset).unwrap_or(i64::MAX).into());
739 limit = " LIMIT ? OFFSET ?";
740 }
741 let predicate = if predicates.is_empty() {
742 String::new()
743 } else {
744 format!("WHERE {}", predicates.join(" AND "))
745 };
746 let mut statement = db.prepare_cached(&format!(
747 "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
748 FROM {from}
749 LEFT JOIN executions e ON e.id=q.execution_id
750 LEFT JOIN requests h ON h.id=json_extract(e.data,'$.provenance.requestId') AND h.claimed_by IS NOT NULL
751 {predicate} ORDER BY {order}{limit}"
752 ))?;
753 #[cfg(test)]
754 statement.reset_status(rusqlite::StatementStatus::VmStep);
755 let rows = statement
756 .query_map(rusqlite::params_from_iter(values), |row| {
757 let id = row.get::<_, Option<crate::types::RequestId>>(4)?;
758 let reviewer = row.get::<_, Option<crate::types::ReviewerId>>(5)?;
759 let at = row.get::<_, Option<crate::types::Timestamp>>(6)?;
760 Ok(Row {
761 id: row.get(0)?,
762 run: row.get(1)?,
763 eval: row.get(7)?,
764 data: row.get(2)?,
765 execution: row.get(3)?,
766 execution_id: row.get(8)?,
767 claim: id
768 .zip(reviewer)
769 .zip(at)
770 .map(|((id, reviewer), at)| (id, reviewer, at)),
771 mark: Mark {
772 listed: row.get(9)?,
773 run: row.get(10)?,
774 run_id: row.get(1)?,
775 ordinal: row.get(11)?,
776 },
777 })
778 })?
779 .collect::<Result<_, _>>()?;
780 #[cfg(test)]
781 crate::performance::sql_steps(statement.reset_status(rusqlite::StatementStatus::VmStep));
782 Ok(rows)
783}
784
785pub(super) struct DefinitionIndex {
789 graph: Option<Arc<Graph>>,
790 evals: HashMap<crate::types::EvalId, usize>,
791 copies: Option<Copies>,
793}
794#[derive(Default)]
795struct Copies {
796 evals: HashMap<usize, Arc<super::definitions::Eval>>,
797 artifacts: HashMap<crate::types::ArtifactName, Arc<super::definitions::Artifact>>,
798}
799impl DefinitionIndex {
800 pub fn new(run: &super::Run) -> Self {
802 let graph = run.definitions.share();
803 let mut evals = HashMap::new();
804 for (position, eval) in graph.iter().flat_map(|graph| graph.evals()).enumerate() {
805 evals.entry(eval.id.clone()).or_insert(position);
806 }
807 Self {
808 graph,
809 evals,
810 copies: None,
811 }
812 }
813 fn apart(run: &super::Run) -> Self {
816 Self {
817 copies: Some(Copies::default()),
818 ..Self::new(run)
819 }
820 }
821 fn none() -> Self {
823 Self {
824 graph: None,
825 evals: HashMap::new(),
826 copies: None,
827 }
828 }
829 fn definition(
830 &mut self,
831 eval: &crate::types::EvalId,
832 artifact: &crate::types::ArtifactName,
833 ) -> Option<RequestDefinition> {
834 let graph = self.graph.as_ref()?;
835 let saved = graph.artifact(artifact)?;
836 let position = *self.evals.get(eval)?;
837 Some(RequestDefinition(match &mut self.copies {
838 None => Place::Graph {
839 graph: graph.clone(),
840 eval: position,
841 artifact: artifact.clone(),
842 },
843 Some(copies) => Place::Own {
844 eval: copies
845 .evals
846 .entry(position)
847 .or_insert_with(|| Arc::new(graph.evals()[position].clone()))
848 .clone(),
849 artifact: copies
850 .artifacts
851 .entry(artifact.clone())
852 .or_insert_with(|| Arc::new(saved.clone()))
853 .clone(),
854 },
855 }))
856 }
857}
858impl Row {
859 pub fn view(&self, index: &mut DefinitionIndex) -> Option<RequestView> {
860 let request = super::unreadable::evidence::<Request>("request", &self.data)?;
861 let execution = self
862 .execution
863 .as_deref()
864 .and_then(|data| super::unreadable::evidence("execution", data));
865 Some(self.with_evidence(index, request, execution))
866 }
867 pub fn read(
870 &self,
871 index: &mut DefinitionIndex,
872 ) -> (Option<RequestView>, Vec<super::Unreadable>) {
873 let mut unreadable = Vec::new();
874 let execution = self
875 .execution
876 .as_deref()
877 .zip(self.execution_id.as_ref())
878 .and_then(|(data, id)| {
879 super::unreadable::decode("execution", id, data)
880 .map_err(|record| unreadable.push(record))
881 .ok()
882 });
883 let view = super::unreadable::decode::<Request>("request", &self.id, &self.data)
884 .map_err(|record| unreadable.push(record))
885 .ok()
886 .map(|request| self.with_evidence(index, request, execution));
887 (view, unreadable)
888 }
889 fn with_evidence(
890 &self,
891 index: &mut DefinitionIndex,
892 request: Request,
893 execution: Option<Execution>,
894 ) -> RequestView {
895 let definition = index.definition(&self.eval, &request.target);
896 RequestView {
897 request: Arc::new(request),
898 definition,
899 execution: execution.map(Arc::new),
900 claim: self.claim.as_ref().map(|(id, reviewer, at)| HumanClaim {
901 request_id: id.clone(),
902 reviewer: reviewer.clone(),
903 claimed_at: *at,
904 }),
905 }
906 }
907}
908
909pub async fn read_run_requests(
911 state: &Path,
912 id: &str,
913) -> Result<(super::RunView, Vec<RequestView>), String> {
914 read_run_requests_by_id(state, &id.parse()?).await
915}
916
917pub async fn read_run_requests_by_id(
919 state: &Path,
920 id: &crate::types::RunId,
921) -> Result<(super::RunView, Vec<RequestView>), String> {
922 let state = state.to_path_buf();
923 let id = id.clone();
924 crate::task::joined(
925 tokio::task::spawn_blocking(move || {
926 let mut reader = super::reader::Reader::default();
927 reader
928 .snapshot(&state, |db, cache, state| {
929 cache.selected(db, state, &id, true)
930 })?
931 .ok_or_else(|| "Run not found.".into())
932 })
933 .await,
934 )
935 .map_err(|error| error.to_string())?
936}