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 pub fn readable(&self) -> bool {
33 !self.unreadable.iter().any(|record| record.kind == "run")
34 }
35}
36
37pub 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
48pub 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 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}
100
101pub(super) fn in_snapshot(
102 db: &rusqlite::Connection,
103 state: &Path,
104 repos: Option<&str>,
105 limit: u32,
106 offset: u32,
107) -> Result<Vec<RunSummary>, Error> {
108 in_snapshot_cached(
109 db,
110 state,
111 repos,
112 limit,
113 offset,
114 None,
115 &mut super::unreadable::Audit::default(),
116 )
117}
118
119pub(super) fn in_snapshot_cached(
120 db: &rusqlite::Connection,
121 state: &Path,
122 repos: Option<&str>,
123 limit: u32,
124 offset: u32,
125 pinned: Option<&crate::types::RunId>,
126 audit: &mut super::unreadable::Audit,
127) -> Result<Vec<RunSummary>, Error> {
128 let mut runs = {
129 let mut statement = db.prepare_cached(
130 "WITH page AS (
131 SELECT id,repo,json_extract(data,'$.createdAt') created,json_extract(data,'$.completedAt') completed,status,rowid serial
132 FROM runs WHERE (?1 IS NULL OR repo IN (SELECT value FROM json_each(?1)))
133 ORDER BY json_extract(data,'$.createdAt') DESC,rowid DESC LIMIT ?2 OFFSET ?3)
134 SELECT id,repo,created,completed,status,0,serial FROM page UNION ALL
135 SELECT id,repo,json_extract(data,'$.createdAt'),json_extract(data,'$.completedAt'),status,1,rowid FROM runs
136 WHERE id=?4 AND id NOT IN (SELECT id FROM page)
137 AND (?1 IS NULL OR repo IN (SELECT value FROM json_each(?1))) ORDER BY 3 DESC,7 DESC",
138 )?;
139 statement
140 .query_map(params![repos, limit, offset, pinned], |row| {
141 Ok(RunSummary {
142 id: row.get(0)?,
143 repo_path: PathBuf::from(row.get::<_, String>(1)?),
144 created_at: row.get(2)?,
145 completed_at: row.get(3)?,
146 status: row.get(4)?,
147 counts: BTreeMap::new(),
148 unreadable: Vec::new(),
149 })
150 })?
151 .collect::<Result<Vec<_>, _>>()?
152 };
153 audit.selected = pinned
154 .cloned()
155 .filter(|id| runs.iter().any(|run| &run.id == id))
156 .or_else(|| runs.first().map(|run| run.id.clone()));
157 let ids: Vec<_> = runs.iter().map(|run| run.id.clone()).collect();
158 let mut unreadable = super::unreadable::in_runs_cached(db, &ids, audit)?;
159 let invalid: Vec<_> = unreadable
160 .values()
161 .flatten()
162 .filter(|record| record.kind == "request")
163 .map(|record| &record.id)
164 .collect();
165 let mut counts: BTreeMap<crate::types::RunId, BTreeMap<crate::types::RequestStatus, u64>> =
166 BTreeMap::new();
167 let mut statement = db.prepare_cached(
168 "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",
169 )?;
170 let rows = statement.query_map(
171 params![
172 serde_json::to_string(&ids)?,
173 serde_json::to_string(&invalid)?
174 ],
175 |row| {
176 Ok((
177 row.get::<_, crate::types::RunId>(0)?,
178 row.get::<_, crate::types::RequestStatus>(1)?,
179 row.get::<_, i64>(2)? as u64,
180 ))
181 },
182 )?;
183 for row in rows {
184 let (run, status, count) = row?;
185 counts.entry(run).or_default().insert(status, count);
186 }
187 crate::workspace::outside_workspaces(runs.iter().map(|run| run.repo_path.as_path()), state)
188 .map_err(|error| Error::Invalid(error.to_string()))?;
189 for run in &mut runs {
190 run.unreadable = unreadable.remove(&run.id).unwrap_or_default();
191 run.counts = counts.remove(&run.id).unwrap_or_default();
192 }
193 Ok(runs)
194}