Skip to main content

artifactize_core/store/
runs.rs

1use std::{
2    collections::BTreeMap,
3    path::{Path, PathBuf},
4};
5
6use rusqlite::params;
7use serde::Serialize;
8use tokio_rusqlite::Connection;
9
10use super::{
11    DATABASE,
12    receipts::{Error, check_files, schema_initialized},
13};
14use crate::workspace::{canonical_target, outside_workspace};
15
16#[derive(Debug, Clone, Serialize)]
17#[serde(rename_all = "camelCase")]
18pub struct RunSummary {
19    pub id: crate::types::RunId,
20    #[serde(serialize_with = "crate::platform::path_serde::serialize")]
21    pub repo_path: PathBuf,
22    pub created_at: crate::types::Timestamp,
23    pub completed_at: Option<crate::types::Timestamp>,
24    pub status: crate::types::RunStatus,
25    pub counts: BTreeMap<crate::types::RequestStatus, u64>,
26    #[serde(skip_serializing_if = "Vec::is_empty")]
27    pub unreadable: Vec<super::Unreadable>,
28}
29
30impl RunSummary {
31    /// Whether the Run's own record reads; a Run with only unreadable requests still opens.
32    pub fn readable(&self) -> bool {
33        !self.unreadable.iter().any(|record| record.kind == "run")
34    }
35}
36
37/// Saved request-state counts in one read-only snapshot; no repository discovery.
38pub async fn read_runs(
39    state: &Path,
40    repo: Option<&Path>,
41    limit: u32,
42    offset: u32,
43) -> Result<Vec<RunSummary>, String> {
44    let repos = repo.map(|path| vec![path.to_path_buf()]);
45    read_scoped_runs(state, repos.as_deref(), limit, offset).await
46}
47
48/// Filter workspace paths before sorting and paging; an empty scope has no Runs.
49pub async fn read_scoped_runs(
50    state: &Path,
51    repos: Option<&[PathBuf]>,
52    limit: u32,
53    offset: u32,
54) -> Result<Vec<RunSummary>, String> {
55    let state = canonical_target(state).map_err(|e| e.to_string())?;
56    let repos = repos
57        .map(|paths| {
58            paths
59                .iter()
60                .map(|path| {
61                    let path = canonical_target(path).map_err(|error| error.to_string())?;
62                    outside_workspace(&path, &state).map_err(|error| error.to_string())?;
63                    Ok(crate::platform::path_text(&path))
64                })
65                .collect::<Result<Vec<_>, String>>()
66        })
67        .transpose()?;
68    let repos = repos
69        .map(|paths| serde_json::to_string(&paths))
70        .transpose()
71        .map_err(|error| error.to_string())?;
72    check_files(&state)?;
73    if !state
74        .join(DATABASE)
75        .try_exists()
76        .map_err(|e| e.to_string())?
77    {
78        return Ok(Vec::new());
79    }
80    let connection = Connection::open_with_flags(
81        state.join(DATABASE),
82        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
83    )
84    .await
85    .map_err(|e| e.to_string())?;
86    let result = connection
87        .call(move |db| -> Result<_, Error> {
88            db.busy_timeout(super::SQLITE_BUSY_TIMEOUT)?;
89            let transaction = db.transaction()?;
90            if !schema_initialized(&transaction)? {
91                return Ok(Vec::new());
92            }
93            let runs = in_snapshot(&transaction, &state, repos.as_deref(), limit, offset)?;
94            transaction.commit()?;
95            Ok(runs)
96        })
97        .await
98        .map_err(|e| e.to_string());
99    super::connection::finish(connection, result).await
100}
101
102pub(super) fn in_snapshot(
103    db: &rusqlite::Connection,
104    state: &Path,
105    repos: Option<&str>,
106    limit: u32,
107    offset: u32,
108) -> Result<Vec<RunSummary>, Error> {
109    in_snapshot_cached(
110        db,
111        state,
112        repos,
113        limit,
114        offset,
115        None,
116        &mut super::unreadable::Audit::default(),
117    )
118}
119
120pub(super) fn in_snapshot_cached(
121    db: &rusqlite::Connection,
122    state: &Path,
123    repos: Option<&str>,
124    limit: u32,
125    offset: u32,
126    pinned: Option<&crate::types::RunId>,
127    audit: &mut super::unreadable::Audit,
128) -> Result<Vec<RunSummary>, Error> {
129    let mut runs = {
130        let mut statement = db.prepare_cached(
131                    "WITH page AS (
132                 SELECT id,repo,json_extract(data,'$.createdAt') created,json_extract(data,'$.completedAt') completed,status,rowid serial
133                 FROM runs WHERE (?1 IS NULL OR repo IN (SELECT value FROM json_each(?1)))
134                 ORDER BY json_extract(data,'$.createdAt') DESC,rowid DESC LIMIT ?2 OFFSET ?3)
135                 SELECT id,repo,created,completed,status,0,serial FROM page UNION ALL
136                 SELECT id,repo,json_extract(data,'$.createdAt'),json_extract(data,'$.completedAt'),status,1,rowid FROM runs
137                 WHERE id=?4 AND id NOT IN (SELECT id FROM page)
138                 AND (?1 IS NULL OR repo IN (SELECT value FROM json_each(?1))) ORDER BY 3 DESC,7 DESC",
139                )?;
140        statement
141            .query_map(params![repos, limit, offset, pinned], |row| {
142                Ok(RunSummary {
143                    id: row.get(0)?,
144                    repo_path: PathBuf::from(row.get::<_, String>(1)?),
145                    created_at: row.get(2)?,
146                    completed_at: row.get(3)?,
147                    status: row.get(4)?,
148                    counts: BTreeMap::new(),
149                    unreadable: Vec::new(),
150                })
151            })?
152            .collect::<Result<Vec<_>, _>>()?
153    };
154    audit.selected = pinned
155        .cloned()
156        .filter(|id| runs.iter().any(|run| &run.id == id))
157        .or_else(|| runs.first().map(|run| run.id.clone()));
158    let ids: Vec<_> = runs.iter().map(|run| run.id.clone()).collect();
159    let mut unreadable = super::unreadable::in_runs_cached(db, &ids, audit)?;
160    let invalid: Vec<_> = unreadable
161        .values()
162        .flatten()
163        .filter(|record| record.kind == "request")
164        .map(|record| &record.id)
165        .collect();
166    let mut counts: BTreeMap<crate::types::RunId, BTreeMap<crate::types::RequestStatus, u64>> =
167        BTreeMap::new();
168    let mut statement = db.prepare_cached(
169        "SELECT run_id,status,count(*) FROM requests WHERE run_id IN (SELECT value FROM json_each(?1)) AND id NOT IN (SELECT value FROM json_each(?2)) GROUP BY run_id,status",
170    )?;
171    let rows = statement.query_map(
172        params![
173            serde_json::to_string(&ids)?,
174            serde_json::to_string(&invalid)?
175        ],
176        |row| {
177            Ok((
178                row.get::<_, crate::types::RunId>(0)?,
179                row.get::<_, crate::types::RequestStatus>(1)?,
180                row.get::<_, i64>(2)? as u64,
181            ))
182        },
183    )?;
184    for row in rows {
185        let (run, status, count) = row?;
186        counts.entry(run).or_default().insert(status, count);
187    }
188    crate::workspace::outside_workspaces(runs.iter().map(|run| run.repo_path.as_path()), state)
189        .map_err(|error| Error::Invalid(error.to_string()))?;
190    for run in &mut runs {
191        run.unreadable = unreadable.remove(&run.id).unwrap_or_default();
192        run.counts = counts.remove(&run.id).unwrap_or_default();
193    }
194    Ok(runs)
195}