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<(u64, u32)>,
96 shown: Shown,
97 newest_waiting: bool,
98}
99
100#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
102pub enum Shown {
103 #[default]
106 Definitions,
107 Requests,
109}
110
111pub async fn read_requests(state: &Path, run: Option<&str>) -> Result<Vec<RequestView>, String> {
112 read_requests_in(state, run, None).await
113}
114
115pub async fn read_requests_in(
116 state: &Path,
117 run: Option<&str>,
118 repo: Option<&Path>,
119) -> Result<Vec<RequestView>, String> {
120 let run = run.map(str::parse).transpose()?;
121 read_requests_for_run(state, run, repo).await
122}
123
124pub(crate) async fn read_requests_for_run(
125 state: &Path,
126 run: Option<crate::types::RunId>,
127 repo: Option<&Path>,
128) -> Result<Vec<RequestView>, String> {
129 read(
130 state,
131 Filter {
132 run,
133 repo,
134 ..Filter::default()
135 },
136 )
137 .await
138}
139
140pub async fn read_request(state: &Path, id: &str) -> Result<RequestView, String> {
141 read_request_id(state, &id.parse()?).await
142}
143
144pub async fn read_request_id(
145 state: &Path,
146 id: &crate::types::RequestId,
147) -> Result<RequestView, String> {
148 read_request_by_id(state, id, Shown::Definitions).await
149}
150
151pub async fn read_request_as(state: &Path, id: &str, shown: Shown) -> Result<RequestView, String> {
153 read_request_by_id(state, &id.parse()?, shown).await
154}
155
156pub async fn read_request_by_id(
158 state: &Path,
159 id: &crate::types::RequestId,
160 shown: Shown,
161) -> Result<RequestView, String> {
162 read_optional_request(state, id, shown)
163 .await?
164 .ok_or_else(|| "Review request not found.".into())
165}
166
167pub async fn read_optional_request(
169 state: &Path,
170 id: &crate::types::RequestId,
171 shown: Shown,
172) -> Result<Option<RequestView>, String> {
173 Ok(read(
174 state,
175 Filter {
176 id: Some(id.clone()),
177 shown,
178 ..Filter::default()
179 },
180 )
181 .await?
182 .pop())
183}
184
185pub async fn read_session_request(state: &Path, id: &str) -> Result<Option<RequestView>, String> {
187 read_request_by_session(state, id.parse()?).await
188}
189
190pub(crate) async fn read_request_by_session(
191 state: &Path,
192 session: crate::types::SessionId,
193) -> Result<Option<RequestView>, String> {
194 Ok(read(
195 state,
196 Filter {
197 session: Some(session),
198 ..Filter::default()
199 },
200 )
201 .await?
202 .pop())
203}
204
205pub async fn read_original(state: &Path, view: &RequestView) -> Result<RequestView, String> {
209 read_original_as(state, view, Shown::Definitions).await
210}
211
212pub async fn read_original_as(
214 state: &Path,
215 view: &RequestView,
216 shown: Shown,
217) -> Result<RequestView, String> {
218 match original_id(view) {
219 Some(id) => read_request_by_id(state, id, shown).await,
220 None => Ok(view.clone()),
221 }
222}
223
224pub async fn read_review_owner(state: &Path, view: &RequestView) -> Result<RequestView, String> {
227 let Some(id) = original_id(view).filter(|_| view.request.status().is_human_wait()) else {
228 return Ok(view.clone());
229 };
230 let found = read(
231 state,
232 Filter {
233 id: Some(id.clone()),
234 shown: Shown::Requests,
235 ..Filter::default()
236 },
237 )
238 .await?;
239 Ok(found.into_iter().next().unwrap_or_else(|| view.clone()))
240}
241
242fn original_id(view: &RequestView) -> Option<&crate::types::RequestId> {
243 view.execution
244 .as_ref()
245 .map(|execution| &execution.provenance.request_id)
246 .or_else(|| {
247 view.request
248 .provenance
249 .as_ref()
250 .map(|source| &source.request_id)
251 })
252 .filter(|id| *id != &view.request.id)
253}
254
255pub async fn read_waiting_originals(
258 state: &Path,
259 repo: Option<&Path>,
260) -> Result<Vec<RequestView>, String> {
261 let waiting = read_waiting(state, repo).await?;
262 let by_id: std::collections::BTreeMap<_, _> = waiting
263 .iter()
264 .map(|view| (&view.request.id, view))
265 .collect();
266 let mut seen = std::collections::BTreeSet::new();
267 let mut originals: Vec<RequestView> = Vec::with_capacity(waiting.len());
268 for view in &waiting {
269 let source = view
270 .execution
271 .as_ref()
272 .map_or(&view.request.id, |execution| {
273 &execution.provenance.request_id
274 });
275 if seen.contains(source) {
276 continue;
277 }
278 let original = match by_id.get(source) {
279 Some(original) => Some((*original).clone()),
280 None => read_original(state, view).await.ok(),
281 };
282 let original = original
284 .filter(|original| original.request.status().is_human_wait())
285 .unwrap_or_else(|| view.clone());
286 if seen.insert(original.request.id.clone()) {
287 originals.push(original);
288 }
289 }
290 Ok(originals)
291}
292
293pub async fn read_request_batch(
297 state: &Path,
298 statuses: &[crate::types::RequestStatus],
299 offset: u64,
300 limit: u32,
301 shown: Shown,
302) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
303 read_with_repo(
304 state,
305 Filter {
306 statuses,
307 slice: Some((offset, limit)),
308 shown,
309 ..Filter::default()
310 },
311 )
312 .await
313}
314
315pub(crate) async fn read_review_batch(
317 state: &Path,
318 statuses: &[crate::types::RequestStatus],
319 offset: u64,
320 limit: u32,
321 shown: Shown,
322) -> Result<Vec<(RequestView, PathBuf)>, String> {
323 read_with_repo(
324 state,
325 Filter {
326 statuses,
327 slice: Some((offset, limit)),
328 shown,
329 newest_waiting: true,
330 ..Filter::default()
331 },
332 )
333 .await
334}
335
336pub async fn read_waiting(state: &Path, repo: Option<&Path>) -> Result<Vec<RequestView>, String> {
340 read(
341 state,
342 Filter {
343 repo,
344 waiting: true,
345 shown: Shown::Requests,
346 ..Filter::default()
347 },
348 )
349 .await
350}
351
352async fn read(state: &Path, filter: Filter<'_>) -> Result<Vec<RequestView>, String> {
353 Ok(read_with_repo(state, filter)
354 .await?
355 .into_iter()
356 .map(|(view, _)| view)
357 .collect())
358}
359
360pub async fn read_request_repo(state: &Path, id: &str) -> Result<std::path::PathBuf, String> {
364 read_request_repo_by_id(state, id.parse()?).await
365}
366
367pub(crate) async fn read_request_repo_by_id(
368 state: &Path,
369 id: crate::types::RequestId,
370) -> Result<std::path::PathBuf, String> {
371 let not_found = || "Review request not found.".to_owned();
372 let state = canonical_target(state).map_err(|e| e.to_string())?;
373 let Some(connection) = open_read(&state).await? else {
374 return Err(not_found());
375 };
376 let result = connection
377 .call(move |db| -> Result<_, Error> {
378 super::wait_when_busy(db)?;
379 let transaction = db.transaction()?;
380 if !schema_initialized(&transaction)? {
381 return Ok(None);
382 }
383 let repo = transaction
384 .query_row(
385 "SELECT r.repo FROM requests q JOIN runs r ON r.id=q.run_id WHERE q.id=?",
386 [&id],
387 |row| super::path_column(row, 0),
388 )
389 .optional()?;
390 transaction.commit()?;
391 if let Some(repo) = &repo {
392 crate::workspace::outside_workspaces(std::iter::once(repo.as_path()), &state)
393 .map_err(|error| Error::Invalid(error.to_string()))?;
394 }
395 Ok(repo)
396 })
397 .await
398 .map_err(|e| e.to_string());
399 super::connection::finish(connection, result)
400 .await?
401 .ok_or_else(not_found)
402}
403
404pub(super) async fn open_read(state: &Path) -> Result<Option<Connection>, String> {
406 check_files(state)?;
407 if !state
408 .join(DATABASE)
409 .try_exists()
410 .map_err(|e| e.to_string())?
411 {
412 return Ok(None);
413 }
414 Connection::open_with_flags(
415 state.join(DATABASE),
416 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
417 )
418 .await
419 .map(Some)
420 .map_err(|e| e.to_string())
421}
422
423async fn read_with_repo(
424 state: &Path,
425 filter: Filter<'_>,
426) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
427 let state = canonical_target(state).map_err(|e| e.to_string())?;
428 let repo = filter
429 .repo
430 .map(canonical_target)
431 .transpose()
432 .map_err(|e| e.to_string())?;
433 if let Some(repo) = &repo {
434 outside_workspace(repo, &state).map_err(|e| e.to_string())?;
435 }
436 let Filter {
437 run,
438 id,
439 waiting,
440 statuses,
441 slice,
442 session,
443 newest_waiting,
444 ..
445 } = filter;
446 let statuses = statuses.to_vec();
447 let shown = filter.shown;
448 let Some(connection) = open_read(&state).await? else {
449 return Ok(Vec::new());
450 };
451 let result = connection
452 .call(move |db| -> Result<_, Error> {
453 super::wait_when_busy(db)?;
454 let transaction = db.transaction()?;
455 if !schema_initialized(&transaction)? {
456 return Ok(Vec::new());
457 }
458 let filter = Query {
459 run,
460 id,
461 repo,
462 waiting,
463 session,
464 statuses,
465 slice,
466 ids: None,
467 newest_waiting,
468 };
469 let rows = rows(&transaction, &filter)?;
470 let ids: std::collections::BTreeSet<_> = rows.iter().map(|row| &row.run).collect();
471 let mut statement = transaction.prepare(match shown {
472 Shown::Definitions => "SELECT r.id,r.repo,r.data,d.data FROM runs r LEFT JOIN run_definitions d ON d.run_id=r.id WHERE r.id IN (SELECT value FROM json_each(?))",
473 Shown::Requests => "SELECT r.id,r.repo,NULL,NULL FROM runs r WHERE r.id IN (SELECT value FROM json_each(?))",
474 })?;
475 let runs = statement
476 .query_map([serde_json::to_string(&ids)?], |row| {
477 Ok((
478 row.get::<_, crate::types::RunId>(0)?,
479 row.get::<_, String>(1)?,
480 row.get::<_, Option<String>>(2)?,
481 row.get::<_, Option<String>>(3)?,
482 ))
483 })?
484 .collect::<Result<Vec<_>, _>>()?;
485 let mut indexes = std::collections::BTreeMap::new();
486 let mut repos = Vec::new();
487 for (id, repo, state, definitions) in runs {
488 let index = match state {
489 None => DefinitionIndex::none(),
490 Some(state) => {
491 match super::run_record::whole(&id, &state, definitions.as_deref()) {
492 Ok(run) => DefinitionIndex::apart(&run),
493 Err(unreadable) => {
494 super::unreadable::skipped(&unreadable);
495 continue;
496 }
497 }
498 }
499 };
500 let repo = artifactize_tools::files::path_from_text(&repo)
501 .map_err(|error| Error::Invalid(error.to_string()))?;
502 repos.push(repo.clone());
503 indexes.insert(id, (index, repo));
504 }
505 crate::workspace::outside_workspaces(repos.iter().map(|repo| repo.as_path()), &state)
506 .map_err(|error| Error::Invalid(error.to_string()))?;
507 let views = rows
508 .into_iter()
509 .filter_map(|row| {
510 indexes
511 .get_mut(&row.run)
512 .and_then(|(index, repo)| row.view(index).map(|view| (view, repo.clone())))
513 })
514 .collect();
515 drop(statement);
516 transaction.commit()?;
517 Ok(views)
518 })
519 .await
520 .map_err(|e| e.to_string());
521 super::connection::finish(connection, result).await
522}
523
524#[derive(Default)]
526pub(super) struct Query {
527 pub run: Option<crate::types::RunId>,
528 pub id: Option<crate::types::RequestId>,
529 pub repo: Option<std::path::PathBuf>,
530 pub waiting: bool,
531 pub session: Option<crate::types::SessionId>,
532 pub statuses: Vec<crate::types::RequestStatus>,
533 pub slice: Option<(u64, u32)>,
534 pub newest_waiting: bool,
535 pub ids: Option<Vec<crate::types::RequestId>>,
537}
538
539#[derive(Debug, Clone)]
540pub(super) struct Row {
541 pub id: crate::types::RequestId,
542 pub run: crate::types::RunId,
543 pub eval: crate::types::EvalId,
544 pub data: String,
545 pub execution: Option<String>,
546 pub execution_id: Option<crate::types::ExecutionId>,
547 pub claim: Option<(
548 crate::types::RequestId,
549 crate::types::ReviewerId,
550 crate::types::Timestamp,
551 )>,
552}
553
554pub(super) fn rows(db: &rusqlite::Connection, filter: &Query) -> Result<Vec<Row>, Error> {
555 let (mut predicates, mut values): (Vec<String>, Vec<rusqlite::types::Value>) = [
557 ("q.run_id", filter.run.as_ref().map(ToString::to_string)),
558 ("q.id", filter.id.as_ref().map(ToString::to_string)),
559 (
560 "r.repo",
561 filter.repo.as_deref().map(crate::platform::path_text),
562 ),
563 (
564 "json_extract(q.data,'$.sessionId')",
565 filter.session.as_ref().map(ToString::to_string),
566 ),
567 ]
568 .into_iter()
569 .filter_map(|(column, value)| Some((format!("{column}=?"), value?.into())))
570 .unzip();
571 if filter.waiting {
572 predicates.push("q.status IN ('WAITING_HUMAN','DEFERRED')".into());
573 }
574 if let Some(ids) = &filter.ids {
575 predicates.push("q.id IN (SELECT value FROM json_each(?))".into());
576 values.push(serde_json::to_string(ids)?.into());
577 }
578 if !filter.statuses.is_empty() {
579 let marks = vec!["?"; filter.statuses.len()].join(",");
580 predicates.push(format!("q.status IN ({marks})"));
581 values.extend(
582 filter
583 .statuses
584 .iter()
585 .map(|status| rusqlite::types::Value::from(status.as_str().to_owned())),
586 );
587 }
588 let predicate = if predicates.is_empty() {
589 String::new()
590 } else {
591 format!("WHERE {}", predicates.join(" AND "))
592 };
593 let limit = match filter.slice {
594 Some((offset, count)) => {
595 values.push(i64::from(count).into());
596 values.push(i64::try_from(offset).unwrap_or(i64::MAX).into());
597 " LIMIT ? OFFSET ?"
598 }
599 None => "",
600 };
601 let order = if filter.run.is_some() {
602 "q.ordinal"
603 } else if filter.newest_waiting {
604 "CASE WHEN json_valid(q.data) THEN rtrim(coalesce(json_extract(q.data,'$.startedAt'),json_extract(q.data,'$.createdAt')),'Z') END DESC,r.rowid DESC,q.ordinal"
607 } else {
608 "r.rowid DESC,q.ordinal"
609 };
610 let mut statement = db.prepare_cached(&format!(
611 "SELECT q.id,q.run_id,q.data,e.data,h.id,h.claimed_by,h.claimed_at,q.eval_id,e.id
612 FROM requests q JOIN runs r ON r.id=q.run_id
613 LEFT JOIN executions e ON e.id=q.execution_id
614 LEFT JOIN requests h ON h.id=json_extract(e.data,'$.provenance.requestId') AND h.claimed_by IS NOT NULL
615 {predicate} ORDER BY {order}{limit}"
616 ))?;
617 Ok(statement
618 .query_map(rusqlite::params_from_iter(values), |row| {
619 let id = row.get::<_, Option<crate::types::RequestId>>(4)?;
620 let reviewer = row.get::<_, Option<crate::types::ReviewerId>>(5)?;
621 let at = row.get::<_, Option<crate::types::Timestamp>>(6)?;
622 Ok(Row {
623 id: row.get(0)?,
624 run: row.get(1)?,
625 eval: row.get(7)?,
626 data: row.get(2)?,
627 execution: row.get(3)?,
628 execution_id: row.get(8)?,
629 claim: id
630 .zip(reviewer)
631 .zip(at)
632 .map(|((id, reviewer), at)| (id, reviewer, at)),
633 })
634 })?
635 .collect::<Result<_, _>>()?)
636}
637
638pub(super) struct DefinitionIndex {
642 graph: Option<Arc<Graph>>,
643 evals: HashMap<crate::types::EvalId, usize>,
644 copies: Option<Copies>,
646}
647#[derive(Default)]
648struct Copies {
649 evals: HashMap<usize, Arc<super::definitions::Eval>>,
650 artifacts: HashMap<crate::types::ArtifactName, Arc<super::definitions::Artifact>>,
651}
652impl DefinitionIndex {
653 pub fn new(run: &super::Run) -> Self {
655 let graph = run.definitions.share();
656 let mut evals = HashMap::new();
657 for (position, eval) in graph.iter().flat_map(|graph| graph.evals()).enumerate() {
658 evals.entry(eval.id.clone()).or_insert(position);
659 }
660 Self {
661 graph,
662 evals,
663 copies: None,
664 }
665 }
666 fn apart(run: &super::Run) -> Self {
669 Self {
670 copies: Some(Copies::default()),
671 ..Self::new(run)
672 }
673 }
674 fn none() -> Self {
676 Self {
677 graph: None,
678 evals: HashMap::new(),
679 copies: None,
680 }
681 }
682 fn definition(
683 &mut self,
684 eval: &crate::types::EvalId,
685 artifact: &crate::types::ArtifactName,
686 ) -> Option<RequestDefinition> {
687 let graph = self.graph.as_ref()?;
688 let saved = graph.artifact(artifact)?;
689 let position = *self.evals.get(eval)?;
690 Some(RequestDefinition(match &mut self.copies {
691 None => Place::Graph {
692 graph: graph.clone(),
693 eval: position,
694 artifact: artifact.clone(),
695 },
696 Some(copies) => Place::Own {
697 eval: copies
698 .evals
699 .entry(position)
700 .or_insert_with(|| Arc::new(graph.evals()[position].clone()))
701 .clone(),
702 artifact: copies
703 .artifacts
704 .entry(artifact.clone())
705 .or_insert_with(|| Arc::new(saved.clone()))
706 .clone(),
707 },
708 }))
709 }
710}
711impl Row {
712 pub fn view(&self, index: &mut DefinitionIndex) -> Option<RequestView> {
713 let request = super::unreadable::evidence::<Request>("request", &self.data)?;
714 let execution = self
715 .execution
716 .as_deref()
717 .and_then(|data| super::unreadable::evidence("execution", data));
718 Some(self.with_evidence(index, request, execution))
719 }
720 pub fn read(
723 &self,
724 index: &mut DefinitionIndex,
725 ) -> (Option<RequestView>, Vec<super::Unreadable>) {
726 let mut unreadable = Vec::new();
727 let execution = self
728 .execution
729 .as_deref()
730 .zip(self.execution_id.as_ref())
731 .and_then(|(data, id)| {
732 super::unreadable::decode("execution", id, data)
733 .map_err(|record| unreadable.push(record))
734 .ok()
735 });
736 let view = super::unreadable::decode::<Request>("request", &self.id, &self.data)
737 .map_err(|record| unreadable.push(record))
738 .ok()
739 .map(|request| self.with_evidence(index, request, execution));
740 (view, unreadable)
741 }
742 fn with_evidence(
743 &self,
744 index: &mut DefinitionIndex,
745 request: Request,
746 execution: Option<Execution>,
747 ) -> RequestView {
748 let definition = index.definition(&self.eval, &request.target);
749 RequestView {
750 request: Arc::new(request),
751 definition,
752 execution: execution.map(Arc::new),
753 claim: self.claim.as_ref().map(|(id, reviewer, at)| HumanClaim {
754 request_id: id.clone(),
755 reviewer: reviewer.clone(),
756 claimed_at: *at,
757 }),
758 }
759 }
760}
761
762pub async fn read_run_requests(
764 state: &Path,
765 id: &str,
766) -> Result<(super::RunView, Vec<RequestView>), String> {
767 read_run_requests_by_id(state, &id.parse()?).await
768}
769
770pub async fn read_run_requests_by_id(
772 state: &Path,
773 id: &crate::types::RunId,
774) -> Result<(super::RunView, Vec<RequestView>), String> {
775 let state = state.to_path_buf();
776 let id = id.clone();
777 crate::task::joined(
778 tokio::task::spawn_blocking(move || {
779 let mut reader = super::reader::Reader::default();
780 reader
781 .snapshot(&state, |db, cache, state| {
782 cache.selected(db, state, &id, true)
783 })?
784 .ok_or_else(|| "Run not found.".into())
785 })
786 .await,
787 )
788 .map_err(|error| error.to_string())?
789}