1use std::{collections::HashMap, path::Path, sync::Arc};
2
3use serde::Serialize;
4
5use rusqlite::OptionalExtension;
6use tokio_rusqlite::Connection;
7
8use super::{
9 DATABASE, Execution, HumanClaim, Request,
10 definitions::Graph,
11 receipts::{Error, check_files, schema_initialized},
12};
13use crate::workspace::{canonical_target, outside_workspace};
14
15#[derive(Debug, Clone, Serialize)]
19pub struct RequestView {
20 #[serde(flatten)]
21 pub request: Arc<Request>,
22 pub claim: Option<HumanClaim>,
23 pub execution: Option<Arc<Execution>>,
24 pub definition: Option<RequestDefinition>,
25}
26
27#[derive(Clone)]
29pub struct RequestDefinition(Place);
30#[derive(Clone)]
31enum Place {
32 Graph {
34 graph: Arc<Graph>,
35 eval: usize,
37 artifact: crate::types::ArtifactName,
38 },
39 Own {
42 eval: Arc<super::definitions::Eval>,
43 artifact: Arc<super::definitions::Artifact>,
44 },
45}
46impl RequestDefinition {
47 pub fn eval(&self) -> &super::definitions::Eval {
48 match &self.0 {
49 Place::Graph { graph, eval, .. } => &graph.evals()[*eval],
50 Place::Own { eval, .. } => eval,
51 }
52 }
53 pub fn artifact(&self) -> &super::definitions::Artifact {
54 match &self.0 {
55 Place::Graph {
56 graph, artifact, ..
57 } => graph
58 .artifact(artifact)
59 .expect("an indexed request's Artifact is in its graph"),
60 Place::Own { artifact, .. } => artifact,
61 }
62 }
63}
64impl Serialize for RequestDefinition {
65 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
66 use serde::ser::SerializeStruct;
67 let mut definition = serializer.serialize_struct("RequestDefinition", 2)?;
68 definition.serialize_field("eval", self.eval())?;
69 definition.serialize_field("artifact", self.artifact())?;
70 definition.end()
71 }
72}
73impl std::fmt::Debug for RequestDefinition {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.debug_struct("RequestDefinition")
76 .field("eval", self.eval())
77 .field("artifact", self.artifact())
78 .finish()
79 }
80}
81
82#[derive(Default)]
83struct Filter<'a> {
84 run: Option<crate::types::RunId>,
85 id: Option<crate::types::RequestId>,
86 repo: Option<&'a Path>,
87 waiting: bool,
88 session: Option<crate::types::SessionId>,
89 statuses: &'a [crate::types::RequestStatus],
90 slice: Option<(u64, u32)>,
92 shown: Shown,
93}
94
95#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
97pub enum Shown {
98 #[default]
101 Definitions,
102 Requests,
104}
105
106pub async fn read_requests(state: &Path, run: Option<&str>) -> Result<Vec<RequestView>, String> {
107 read_requests_in(state, run, None).await
108}
109
110pub async fn read_requests_in(
111 state: &Path,
112 run: Option<&str>,
113 repo: Option<&Path>,
114) -> Result<Vec<RequestView>, String> {
115 let run = run.map(str::parse).transpose()?;
116 read_requests_for_run(state, run, repo).await
117}
118
119pub(crate) async fn read_requests_for_run(
120 state: &Path,
121 run: Option<crate::types::RunId>,
122 repo: Option<&Path>,
123) -> Result<Vec<RequestView>, String> {
124 read(
125 state,
126 Filter {
127 run,
128 repo,
129 ..Filter::default()
130 },
131 )
132 .await
133}
134
135pub async fn read_request(state: &Path, id: &str) -> Result<RequestView, String> {
136 read_request_id(state, &id.parse()?).await
137}
138
139pub(crate) async fn read_request_id(
140 state: &Path,
141 id: &crate::types::RequestId,
142) -> Result<RequestView, String> {
143 read_request_by_id(state, id, Shown::Definitions).await
144}
145
146pub async fn read_request_as(state: &Path, id: &str, shown: Shown) -> Result<RequestView, String> {
148 read_request_by_id(state, &id.parse()?, shown).await
149}
150
151pub(crate) async fn read_request_by_id(
152 state: &Path,
153 id: &crate::types::RequestId,
154 shown: Shown,
155) -> Result<RequestView, String> {
156 read(
157 state,
158 Filter {
159 id: Some(id.clone()),
160 shown,
161 ..Filter::default()
162 },
163 )
164 .await?
165 .pop()
166 .ok_or_else(|| "Review request not found.".into())
167}
168
169pub async fn read_session_request(state: &Path, id: &str) -> Result<Option<RequestView>, String> {
171 read_request_by_session(state, id.parse()?).await
172}
173
174pub(crate) async fn read_request_by_session(
175 state: &Path,
176 session: crate::types::SessionId,
177) -> Result<Option<RequestView>, String> {
178 Ok(read(
179 state,
180 Filter {
181 session: Some(session),
182 ..Filter::default()
183 },
184 )
185 .await?
186 .pop())
187}
188
189pub async fn read_original(state: &Path, view: &RequestView) -> Result<RequestView, String> {
193 read_original_as(state, view, Shown::Definitions).await
194}
195
196pub async fn read_original_as(
198 state: &Path,
199 view: &RequestView,
200 shown: Shown,
201) -> Result<RequestView, String> {
202 let original = view
203 .execution
204 .as_ref()
205 .map(|execution| &execution.provenance.request_id)
206 .or_else(|| {
207 view.request
208 .provenance
209 .as_ref()
210 .map(|source| &source.request_id)
211 });
212 match original.filter(|id| *id != &view.request.id) {
213 Some(id) => read_request_by_id(state, id, shown).await,
214 None => Ok(view.clone()),
215 }
216}
217
218pub async fn read_waiting_originals(
221 state: &Path,
222 repo: Option<&Path>,
223) -> Result<Vec<RequestView>, String> {
224 let waiting = read_waiting(state, repo).await?;
225 let by_id: std::collections::BTreeMap<_, _> = waiting
226 .iter()
227 .map(|view| (&view.request.id, view))
228 .collect();
229 let mut seen = std::collections::BTreeSet::new();
230 let mut originals: Vec<RequestView> = Vec::with_capacity(waiting.len());
231 for view in &waiting {
232 let source = view
233 .execution
234 .as_ref()
235 .map_or(&view.request.id, |execution| {
236 &execution.provenance.request_id
237 });
238 if seen.contains(source) {
239 continue;
240 }
241 let original = match by_id.get(source) {
242 Some(original) => Some((*original).clone()),
243 None => read_original(state, view).await.ok(),
244 };
245 let original = original
247 .filter(|original| original.request.status().is_human_wait())
248 .unwrap_or_else(|| view.clone());
249 if seen.insert(original.request.id.clone()) {
250 originals.push(original);
251 }
252 }
253 Ok(originals)
254}
255
256pub async fn read_request_batch(
260 state: &Path,
261 statuses: &[crate::types::RequestStatus],
262 offset: u64,
263 limit: u32,
264 shown: Shown,
265) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
266 read_with_repo(
267 state,
268 Filter {
269 statuses,
270 slice: Some((offset, limit)),
271 shown,
272 ..Filter::default()
273 },
274 )
275 .await
276}
277
278pub async fn read_waiting(state: &Path, repo: Option<&Path>) -> Result<Vec<RequestView>, String> {
282 read(
283 state,
284 Filter {
285 repo,
286 waiting: true,
287 shown: Shown::Requests,
288 ..Filter::default()
289 },
290 )
291 .await
292}
293
294async fn read(state: &Path, filter: Filter<'_>) -> Result<Vec<RequestView>, String> {
295 Ok(read_with_repo(state, filter)
296 .await?
297 .into_iter()
298 .map(|(view, _)| view)
299 .collect())
300}
301
302pub async fn read_request_repo(state: &Path, id: &str) -> Result<std::path::PathBuf, String> {
306 read_request_repo_by_id(state, id.parse()?).await
307}
308
309pub(crate) async fn read_request_repo_by_id(
310 state: &Path,
311 id: crate::types::RequestId,
312) -> Result<std::path::PathBuf, String> {
313 let not_found = || "Review request not found.".to_owned();
314 let state = canonical_target(state).map_err(|e| e.to_string())?;
315 let Some(connection) = open_read(&state).await? else {
316 return Err(not_found());
317 };
318 let result = connection
319 .call(move |db| -> Result<_, Error> {
320 super::wait_when_busy(db)?;
321 let transaction = db.transaction()?;
322 if !schema_initialized(&transaction)? {
323 return Ok(None);
324 }
325 let repo = transaction
326 .query_row(
327 "SELECT r.repo FROM requests q JOIN runs r ON r.id=q.run_id WHERE q.id=?",
328 [&id],
329 |row| super::path_column(row, 0),
330 )
331 .optional()?;
332 transaction.commit()?;
333 if let Some(repo) = &repo {
334 crate::workspace::outside_workspaces(std::iter::once(repo.as_path()), &state)
335 .map_err(|error| Error::Invalid(error.to_string()))?;
336 }
337 Ok(repo)
338 })
339 .await
340 .map_err(|e| e.to_string());
341 super::connection::finish(connection, result)
342 .await?
343 .ok_or_else(not_found)
344}
345
346pub(super) async fn open_read(state: &Path) -> Result<Option<Connection>, String> {
348 check_files(state)?;
349 if !state
350 .join(DATABASE)
351 .try_exists()
352 .map_err(|e| e.to_string())?
353 {
354 return Ok(None);
355 }
356 Connection::open_with_flags(
357 state.join(DATABASE),
358 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
359 )
360 .await
361 .map(Some)
362 .map_err(|e| e.to_string())
363}
364
365async fn read_with_repo(
366 state: &Path,
367 filter: Filter<'_>,
368) -> Result<Vec<(RequestView, std::path::PathBuf)>, String> {
369 let state = canonical_target(state).map_err(|e| e.to_string())?;
370 let repo = filter
371 .repo
372 .map(canonical_target)
373 .transpose()
374 .map_err(|e| e.to_string())?;
375 if let Some(repo) = &repo {
376 outside_workspace(repo, &state).map_err(|e| e.to_string())?;
377 }
378 let Filter {
379 run,
380 id,
381 waiting,
382 statuses,
383 slice,
384 session,
385 ..
386 } = filter;
387 let statuses = statuses.to_vec();
388 let shown = filter.shown;
389 let Some(connection) = open_read(&state).await? else {
390 return Ok(Vec::new());
391 };
392 let result = connection
393 .call(move |db| -> Result<_, Error> {
394 super::wait_when_busy(db)?;
395 let transaction = db.transaction()?;
396 if !schema_initialized(&transaction)? {
397 return Ok(Vec::new());
398 }
399 let filter = Query {
400 run,
401 id,
402 repo,
403 waiting,
404 session,
405 statuses,
406 slice,
407 ids: None,
408 };
409 let rows = rows(&transaction, &filter)?;
410 let ids: std::collections::BTreeSet<_> = rows.iter().map(|row| &row.run).collect();
411 let mut statement = transaction.prepare(match shown {
412 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(?))",
413 Shown::Requests => "SELECT r.id,r.repo,NULL,NULL FROM runs r WHERE r.id IN (SELECT value FROM json_each(?))",
414 })?;
415 let runs = statement
416 .query_map([serde_json::to_string(&ids)?], |row| {
417 Ok((
418 row.get::<_, crate::types::RunId>(0)?,
419 row.get::<_, String>(1)?,
420 row.get::<_, Option<String>>(2)?,
421 row.get::<_, Option<String>>(3)?,
422 ))
423 })?
424 .collect::<Result<Vec<_>, _>>()?;
425 let mut indexes = std::collections::BTreeMap::new();
426 let mut repos = Vec::new();
427 for (id, repo, state, definitions) in runs {
428 let index = match state {
429 None => DefinitionIndex::none(),
430 Some(state) => {
431 match super::run_record::whole(&id, &state, definitions.as_deref()) {
432 Ok(run) => DefinitionIndex::apart(&run),
433 Err(unreadable) => {
434 super::unreadable::skipped(&unreadable);
435 continue;
436 }
437 }
438 }
439 };
440 let repo = artifactize_tools::files::path_from_text(&repo)
441 .map_err(|error| Error::Invalid(error.to_string()))?;
442 repos.push(repo.clone());
443 indexes.insert(id, (index, repo));
444 }
445 crate::workspace::outside_workspaces(repos.iter().map(|repo| repo.as_path()), &state)
446 .map_err(|error| Error::Invalid(error.to_string()))?;
447 let views = rows
448 .into_iter()
449 .filter_map(|row| {
450 indexes
451 .get_mut(&row.run)
452 .and_then(|(index, repo)| row.view(index).map(|view| (view, repo.clone())))
453 })
454 .collect();
455 drop(statement);
456 transaction.commit()?;
457 Ok(views)
458 })
459 .await
460 .map_err(|e| e.to_string());
461 super::connection::finish(connection, result).await
462}
463
464#[derive(Default)]
466pub(super) struct Query {
467 pub run: Option<crate::types::RunId>,
468 pub id: Option<crate::types::RequestId>,
469 pub repo: Option<std::path::PathBuf>,
470 pub waiting: bool,
471 pub session: Option<crate::types::SessionId>,
472 pub statuses: Vec<crate::types::RequestStatus>,
473 pub slice: Option<(u64, u32)>,
474 pub ids: Option<Vec<crate::types::RequestId>>,
476}
477
478#[derive(Debug, Clone)]
479pub(super) struct Row {
480 pub id: crate::types::RequestId,
481 pub run: crate::types::RunId,
482 pub eval: crate::types::EvalId,
483 pub data: String,
484 pub execution: Option<String>,
485 pub execution_id: Option<crate::types::ExecutionId>,
486 pub claim: Option<(
487 crate::types::RequestId,
488 crate::types::ReviewerId,
489 crate::types::Timestamp,
490 )>,
491}
492
493pub(super) fn rows(db: &rusqlite::Connection, filter: &Query) -> Result<Vec<Row>, Error> {
494 let (mut predicates, mut values): (Vec<String>, Vec<rusqlite::types::Value>) = [
496 ("q.run_id", filter.run.as_ref().map(ToString::to_string)),
497 ("q.id", filter.id.as_ref().map(ToString::to_string)),
498 (
499 "r.repo",
500 filter.repo.as_deref().map(crate::platform::path_text),
501 ),
502 (
503 "json_extract(q.data,'$.sessionId')",
504 filter.session.as_ref().map(ToString::to_string),
505 ),
506 ]
507 .into_iter()
508 .filter_map(|(column, value)| Some((format!("{column}=?"), value?.into())))
509 .unzip();
510 if filter.waiting {
511 predicates.push("q.status IN ('WAITING_HUMAN','DEFERRED')".into());
512 }
513 if let Some(ids) = &filter.ids {
514 predicates.push("q.id IN (SELECT value FROM json_each(?))".into());
515 values.push(serde_json::to_string(ids)?.into());
516 }
517 if !filter.statuses.is_empty() {
518 let marks = vec!["?"; filter.statuses.len()].join(",");
519 predicates.push(format!("q.status IN ({marks})"));
520 values.extend(
521 filter
522 .statuses
523 .iter()
524 .map(|status| rusqlite::types::Value::from(status.as_str().to_owned())),
525 );
526 }
527 let predicate = if predicates.is_empty() {
528 String::new()
529 } else {
530 format!("WHERE {}", predicates.join(" AND "))
531 };
532 let limit = match filter.slice {
533 Some((offset, count)) => {
534 values.push(i64::from(count).into());
535 values.push(i64::try_from(offset).unwrap_or(i64::MAX).into());
536 " LIMIT ? OFFSET ?"
537 }
538 None => "",
539 };
540 let order = if filter.run.is_some() {
541 "q.ordinal"
542 } else {
543 "r.rowid DESC,q.ordinal"
544 };
545 let mut statement = db.prepare_cached(&format!(
546 "SELECT q.id,q.run_id,q.data,e.data,h.id,h.claimed_by,h.claimed_at,q.eval_id,e.id
547 FROM requests q JOIN runs r ON r.id=q.run_id
548 LEFT JOIN executions e ON e.id=q.execution_id
549 LEFT JOIN requests h ON h.id=json_extract(e.data,'$.provenance.requestId') AND h.claimed_by IS NOT NULL
550 {predicate} ORDER BY {order}{limit}"
551 ))?;
552 Ok(statement
553 .query_map(rusqlite::params_from_iter(values), |row| {
554 let id = row.get::<_, Option<crate::types::RequestId>>(4)?;
555 let reviewer = row.get::<_, Option<crate::types::ReviewerId>>(5)?;
556 let at = row.get::<_, Option<crate::types::Timestamp>>(6)?;
557 Ok(Row {
558 id: row.get(0)?,
559 run: row.get(1)?,
560 eval: row.get(7)?,
561 data: row.get(2)?,
562 execution: row.get(3)?,
563 execution_id: row.get(8)?,
564 claim: id
565 .zip(reviewer)
566 .zip(at)
567 .map(|((id, reviewer), at)| (id, reviewer, at)),
568 })
569 })?
570 .collect::<Result<_, _>>()?)
571}
572
573pub(super) struct DefinitionIndex {
577 graph: Option<Arc<Graph>>,
578 evals: HashMap<crate::types::EvalId, usize>,
579 copies: Option<Copies>,
581}
582#[derive(Default)]
583struct Copies {
584 evals: HashMap<usize, Arc<super::definitions::Eval>>,
585 artifacts: HashMap<crate::types::ArtifactName, Arc<super::definitions::Artifact>>,
586}
587impl DefinitionIndex {
588 pub fn new(run: &super::Run) -> Self {
590 let graph = run.definitions.share();
591 let mut evals = HashMap::new();
592 for (position, eval) in graph.iter().flat_map(|graph| graph.evals()).enumerate() {
593 evals.entry(eval.id.clone()).or_insert(position);
594 }
595 Self {
596 graph,
597 evals,
598 copies: None,
599 }
600 }
601 fn apart(run: &super::Run) -> Self {
604 Self {
605 copies: Some(Copies::default()),
606 ..Self::new(run)
607 }
608 }
609 fn none() -> Self {
611 Self {
612 graph: None,
613 evals: HashMap::new(),
614 copies: None,
615 }
616 }
617 fn definition(
618 &mut self,
619 eval: &crate::types::EvalId,
620 artifact: &crate::types::ArtifactName,
621 ) -> Option<RequestDefinition> {
622 let graph = self.graph.as_ref()?;
623 let saved = graph.artifact(artifact)?;
624 let position = *self.evals.get(eval)?;
625 Some(RequestDefinition(match &mut self.copies {
626 None => Place::Graph {
627 graph: graph.clone(),
628 eval: position,
629 artifact: artifact.clone(),
630 },
631 Some(copies) => Place::Own {
632 eval: copies
633 .evals
634 .entry(position)
635 .or_insert_with(|| Arc::new(graph.evals()[position].clone()))
636 .clone(),
637 artifact: copies
638 .artifacts
639 .entry(artifact.clone())
640 .or_insert_with(|| Arc::new(saved.clone()))
641 .clone(),
642 },
643 }))
644 }
645}
646impl Row {
647 pub fn view(&self, index: &mut DefinitionIndex) -> Option<RequestView> {
648 let request = super::unreadable::evidence::<Request>("request", &self.data)?;
649 let execution = self
650 .execution
651 .as_deref()
652 .and_then(|data| super::unreadable::evidence("execution", data));
653 Some(self.with_evidence(index, request, execution))
654 }
655 pub fn read(
658 &self,
659 index: &mut DefinitionIndex,
660 ) -> (Option<RequestView>, Vec<super::Unreadable>) {
661 let mut unreadable = Vec::new();
662 let execution = self
663 .execution
664 .as_deref()
665 .zip(self.execution_id.as_ref())
666 .and_then(|(data, id)| {
667 super::unreadable::decode("execution", id, data)
668 .map_err(|record| unreadable.push(record))
669 .ok()
670 });
671 let view = super::unreadable::decode::<Request>("request", &self.id, &self.data)
672 .map_err(|record| unreadable.push(record))
673 .ok()
674 .map(|request| self.with_evidence(index, request, execution));
675 (view, unreadable)
676 }
677 fn with_evidence(
678 &self,
679 index: &mut DefinitionIndex,
680 request: Request,
681 execution: Option<Execution>,
682 ) -> RequestView {
683 let definition = index.definition(&self.eval, &request.target);
684 RequestView {
685 request: Arc::new(request),
686 definition,
687 execution: execution.map(Arc::new),
688 claim: self.claim.as_ref().map(|(id, reviewer, at)| HumanClaim {
689 request_id: id.clone(),
690 reviewer: reviewer.clone(),
691 claimed_at: *at,
692 }),
693 }
694 }
695}
696
697pub async fn read_run_requests(
699 state: &Path,
700 id: &str,
701) -> Result<(super::RunView, Vec<RequestView>), String> {
702 let state = state.to_path_buf();
703 let id: crate::types::RunId = id.parse()?;
704 crate::task::joined(
705 tokio::task::spawn_blocking(move || {
706 let mut reader = super::reader::Reader::default();
707 reader
708 .snapshot(&state, |db, cache, state| {
709 cache.selected(db, state, &id, true)
710 })?
711 .ok_or_else(|| "Run not found.".into())
712 })
713 .await,
714 )
715 .map_err(|error| error.to_string())?
716}