Skip to main content

artifactize_core/store/receipts/
latest.rs

1//! Last-request pointers for browsing the saved audit.
2use super::{DATABASE, Error, Request, Run, check_files, schema_initialized};
3use crate::{
4    store,
5    types::{Fingerprint, RequestStatus, RunId},
6    workspace::{canonical_target, outside_workspace},
7};
8use serde::Serialize;
9use std::path::Path;
10use tokio_rusqlite::Connection;
11
12#[derive(Debug, Clone, Serialize)]
13#[serde(rename_all = "camelCase")]
14pub struct LastRequest {
15    pub run_id: RunId,
16    pub verdict: RequestStatus,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub fingerprint: Option<Fingerprint>,
19}
20
21/// Last attempts are audit pointers, never evidence for a new current-input query.
22pub async fn read_latest_requests(
23    state: &Path,
24    repo: &Path,
25) -> Result<std::collections::BTreeMap<crate::types::EvalId, LastRequest>, String> {
26    let state = canonical_target(state).map_err(|e| e.to_string())?;
27    outside_workspace(repo, &state).map_err(|e| e.to_string())?;
28    check_files(&state)?;
29    if !state
30        .join(DATABASE)
31        .try_exists()
32        .map_err(|e| e.to_string())?
33    {
34        return Ok(Default::default());
35    }
36    let connection = Connection::open_with_flags(
37        state.join(DATABASE),
38        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
39    )
40    .await
41    .map_err(|e| e.to_string())?;
42    let repo = repo.to_path_buf();
43    let result = connection
44        .call(move |db| -> Result<_, Error> {
45            store::wait_when_busy(db)?;
46            let transaction = db.transaction()?;
47            if !schema_initialized(&transaction)? {
48                return Ok(Default::default());
49            }
50            let latest = {
51                let mut statement = transaction.prepare(
52                    "SELECT data,run_id FROM (
53                SELECT q.eval_id,q.data,q.run_id,
54                    row_number() OVER (PARTITION BY q.eval_id ORDER BY r.rowid DESC) AS rank
55                FROM requests q JOIN runs r ON r.id=q.run_id
56                WHERE r.repo=?
57            ) WHERE rank=1 ORDER BY eval_id",
58                )?;
59                // A Run's record is large and most latest requests share a few Runs: read and
60                // decode each Run once, not once per eval.
61                let mut run_data = transaction.prepare("SELECT data FROM runs WHERE id=?")?;
62                let mut readable = std::collections::BTreeMap::<String, bool>::new();
63                statement
64                    .query_map([crate::platform::path_text(&repo)], |row| {
65                        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
66                    })?
67                    .filter_map(|row| match row {
68                        Err(error) => Some(Err(error)),
69                        Ok((data, run)) => {
70                            let run_readable = match readable.get(&run) {
71                                Some(known) => *known,
72                                None => {
73                                    let known = match run_data
74                                        .query_row([&run], |row| row.get::<_, String>(0))
75                                    {
76                                        Ok(run_data) => {
77                                            store::unreadable::evidence::<Run>("run", &run_data)
78                                                .is_some()
79                                        }
80                                        Err(error) => return Some(Err(error)),
81                                    };
82                                    readable.insert(run, known);
83                                    known
84                                }
85                            };
86                            run_readable
87                                .then(|| store::unreadable::evidence::<Request>("request", &data))
88                                .flatten()
89                                .map(|request| {
90                                    Ok((
91                                        request.eval_id.clone(),
92                                        LastRequest {
93                                            run_id: request.run_id.clone(),
94                                            verdict: request.status(),
95                                            fingerprint: request.fingerprint,
96                                        },
97                                    ))
98                                })
99                        }
100                    })
101                    .collect::<Result<_, _>>()?
102            };
103            transaction.commit()?;
104            Ok(latest)
105        })
106        .await
107        .map_err(|e| e.to_string());
108    store::connection::finish(connection, result).await
109}