Skip to main content

artifactize_core/store/
catalog.rs

1//! Global monitor catalog, intentionally independent of any visible Run page.
2use super::{
3    DATABASE, Unreadable,
4    receipts::{Error, check_files, schema_initialized},
5    unreadable::decode,
6};
7use crate::{
8    repository::Identity,
9    types::{ExecutionId, RequestId, RequestStatus, RunStatus},
10    workspace::{canonical_target, outside_workspaces},
11};
12use serde::Deserialize;
13use std::path::{Path, PathBuf};
14
15#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
16pub enum Signoff {
17    Execution(ExecutionId),
18    Request(RequestId),
19}
20
21#[derive(Debug, Clone)]
22pub struct CatalogRun {
23    pub id: crate::types::RunId,
24    pub created_at: crate::types::Timestamp,
25    pub completed_at: Option<crate::types::Timestamp>,
26    pub repo_path: PathBuf,
27    pub repository: Identity,
28    pub status: RunStatus,
29    /// What the requester said it is working on (`verify --comment`).
30    pub comment: Option<crate::types::RunComment>,
31    pub red: u64,
32    pub error: u64,
33    pub waiting: Vec<Signoff>,
34}
35
36impl CatalogRun {
37    /// The Run's recorded branch, independent of the current checkout or any search filter.
38    pub async fn branch(&self) -> Result<crate::monitor::live::Place, String> {
39        let place = crate::monitor::live::Place::for_checkout;
40        if self.repository.common_dir.is_some() && self.repository.worktree_path.is_some() {
41            return Ok(place(&self.repo_path, &self.repository));
42        }
43        let repo = self.repo_path.clone();
44        crate::task::blocking(move || place(&repo, &crate::repository::identify(&repo))).await
45    }
46}
47
48#[derive(Deserialize)]
49#[serde(rename_all = "camelCase")]
50struct Metadata {
51    #[serde(with = "crate::platform::path_serde")]
52    repo_path: PathBuf,
53    #[serde(flatten)]
54    repository: Identity,
55    status: RunStatus,
56    created_at: crate::types::Timestamp,
57    completed_at: Option<crate::types::Timestamp>,
58    error: Option<String>,
59    comment: Option<crate::types::RunComment>,
60}
61
62impl Metadata {
63    fn state(&mut self) -> Result<super::RunState, String> {
64        super::RunState::from_parts(self.status, self.completed_at, self.error.take())
65    }
66}
67
68#[derive(Deserialize)]
69#[serde(rename_all = "camelCase")]
70pub(crate) struct RunPlace {
71    #[serde(with = "crate::platform::path_serde")]
72    pub repo_path: PathBuf,
73    #[serde(flatten)]
74    pub repository: Identity,
75}
76
77/// The saved repository identity of one Run, without decoding its definitions.
78pub async fn run_checkout(
79    state: &Path,
80    run: &crate::types::RunId,
81) -> Result<(PathBuf, Identity), String> {
82    places(state, vec![run.clone()])
83        .await?
84        .into_iter()
85        .next()
86        .map(|(_, place)| (place.repo_path, place.repository))
87        .ok_or_else(|| "Run's checkout was not found.".into())
88}
89
90/// Resolve the Run's recorded workspace. Older records did not retain Git metadata; in that
91/// case use the live identity of the exact recorded directory, never a different worktree.
92pub async fn viewer_checkout(
93    state: &Path,
94    run: &crate::types::RunId,
95) -> Result<(PathBuf, Identity), String> {
96    let (worktree, saved) = run_checkout(state, run).await?;
97    if saved != Identity::default() {
98        return Ok((worktree, saved));
99    }
100    crate::task::blocking(move || {
101        let identity = crate::repository::identify(&worktree);
102        (worktree, identity)
103    })
104    .await
105}
106
107/// Only the saved display identities of the named Runs. No Run states, attention counts or
108/// definitions are returned to Review, which already has the request page.
109pub(crate) async fn places(
110    state: &Path,
111    ids: Vec<crate::types::RunId>,
112) -> Result<Vec<(crate::types::RunId, RunPlace)>, String> {
113    if ids.is_empty() {
114        return Ok(Vec::new());
115    }
116    let Some(connection) = super::requests::open_read(state).await? else {
117        return Ok(Vec::new());
118    };
119    let result = connection
120        .call(move |db| {
121            super::wait_when_busy(db)?;
122            let transaction = db.transaction()?;
123            if !schema_initialized(&transaction)? {
124                return Ok(Vec::new());
125            }
126            let mut statement = transaction.prepare("SELECT id,CASE WHEN json_valid(data) THEN json_object(
127                'repoPath',repo,'commonDir',json_extract(data,'$.commonDir'),
128                'worktreePath',json_extract(data,'$.worktreePath'),'branch',json_extract(data,'$.branch')) END
129                FROM runs WHERE id IN (SELECT value FROM json_each(?1))")?;
130            let mut rows = statement.query([serde_json::to_string(&ids)?])?;
131            let mut places = Vec::new();
132            while let Some(row) = rows.next()? {
133                let id: crate::types::RunId = row.get(0)?;
134                let data = row.get_ref(1)?.as_str().unwrap_or("null");
135                if let Ok(place) = decode("run", &id, data) {
136                    places.push((id, place));
137                }
138            }
139            Ok::<_, Error>(places)
140        })
141        .await
142        .map_err(|error| error.to_string());
143    super::connection::finish(connection, result).await
144}
145
146/// Read only open Run IDs, irrespective of which checkout or screen displays them.
147pub async fn read_open_run_ids(state: &Path) -> Result<Vec<crate::types::RunId>, String> {
148    let Some(connection) = super::requests::open_read(state).await? else {
149        return Ok(Vec::new());
150    };
151    let result = connection
152        .call(move |db| {
153            super::wait_when_busy(db)?;
154            let transaction = db.transaction()?;
155            if !schema_initialized(&transaction)? {
156                return Ok(Vec::new());
157            }
158            let mut query = transaction.prepare(
159                "SELECT id FROM runs WHERE CASE WHEN json_valid(data) THEN json_extract(data,'$.status') IN (?1,?2) ELSE 0 END",
160            )?;
161            let ids = query
162                .query_map([RunStatus::Running, RunStatus::WaitingHuman], |row| row.get(0))?
163                .collect::<Result<Vec<_>, _>>()?;
164            Ok::<_, Error>(ids)
165        })
166        .await
167        .map_err(|error| error.to_string());
168    super::connection::finish(connection, result).await
169}
170
171/// Global attention facts; unreadable Runs are skipped individually with their reason.
172pub async fn read_catalog(state: &Path) -> Result<Vec<CatalogRun>, String> {
173    catalog(state, None).await
174}
175
176/// The small timeline record for a Run named by a state change hint.
177pub async fn read_catalog_run(
178    state: &Path,
179    id: &crate::types::RunId,
180) -> Result<Option<CatalogRun>, String> {
181    Ok(catalog(state, Some(id.clone())).await?.into_iter().next())
182}
183
184async fn catalog(state: &Path, id: Option<crate::types::RunId>) -> Result<Vec<CatalogRun>, String> {
185    let state = canonical_target(state).map_err(|error| error.to_string())?;
186    check_files(&state)?;
187    if !state
188        .join(DATABASE)
189        .try_exists()
190        .map_err(|error| error.to_string())?
191    {
192        return Ok(Vec::new());
193    }
194    let connection = tokio_rusqlite::Connection::open_with_flags(
195        state.join(DATABASE),
196        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
197    )
198    .await
199    .map_err(|error| error.to_string())?;
200    let result = connection
201        .call(move |db| -> Result<_, Error> {
202            super::wait_when_busy(db)?;
203            let transaction = db.transaction()?;
204            if !schema_initialized(&transaction)? {
205                return Ok(Vec::new());
206            }
207            let catalog = in_snapshot(&transaction, &state, id.as_ref().map(std::slice::from_ref))?;
208            transaction.commit()?;
209            Ok(catalog.runs)
210        })
211        .await
212        .map_err(|error| error.to_string());
213    super::connection::finish(connection, result).await
214}
215
216/// The saved Runs, oldest first, and the Run records that could not be read.
217pub(crate) struct Catalog {
218    pub runs: Vec<CatalogRun>,
219    pub unreadable: Vec<Unreadable>,
220}
221
222/// Read every saved Run's state, or only the state of the Runs `only` names, never their
223/// definitions: they live in their own row, so a Run's state is small however many Artifacts
224/// it has.
225pub(super) fn in_snapshot(
226    db: &rusqlite::Connection,
227    state: &Path,
228    only: Option<&[crate::types::RunId]>,
229) -> Result<Catalog, Error> {
230    let ids = only.map(serde_json::to_string).transpose()?;
231    let filtered = ids.as_ref();
232    let predicate = if filtered.is_some() {
233        " WHERE id IN (SELECT value FROM json_each(?1))"
234    } else {
235        ""
236    };
237    // Keep the SQL projection small. Full Run state contains validation and evidence that are
238    // not part of the timeline, and collecting those blobs made every cold read expensive.
239    let sql = format!("SELECT id,CASE WHEN json_valid(data) THEN json_object(
240        'repoPath',repo,'status',json_extract(data,'$.status'),'createdAt',json_extract(data,'$.createdAt'),
241        'completedAt',json_extract(data,'$.completedAt'),'comment',json_extract(data,'$.comment'),
242        'error',CASE coalesce(json_type(data,'$.error'),'null') WHEN 'text' THEN '' WHEN 'null' THEN NULL ELSE 0 END,
243        'commonDir',json_extract(data,'$.commonDir'),'worktreePath',json_extract(data,'$.worktreePath'),
244        'branch',json_extract(data,'$.branch')) END FROM runs{predicate} ORDER BY rowid");
245    let mut statement = db.prepare_cached(&sql)?;
246    let mut rows = statement.query(rusqlite::params_from_iter(filtered))?;
247    let mut catalog = std::collections::BTreeMap::new();
248    let mut order = Vec::new();
249    let mut unreadable = Vec::new();
250    while let Some(row) = rows.next()? {
251        let id: crate::types::RunId = row.get(0)?;
252        let data = row.get_ref(1)?.as_str().unwrap_or("null");
253        let metadata = decode::<Metadata>("run", &id, data).and_then(|mut run| {
254            let state = run.state().map_err(|reason| Unreadable {
255                kind: "run".into(),
256                id: id.to_string(),
257                reason,
258            })?;
259            Ok((run, state))
260        });
261        match metadata {
262            Ok((run, lifecycle)) => {
263                order.push(id.clone());
264                catalog.insert(
265                    id.clone(),
266                    CatalogRun {
267                        id,
268                        created_at: run.created_at,
269                        completed_at: lifecycle.completed_at(),
270                        repo_path: run.repo_path,
271                        repository: run.repository,
272                        status: lifecycle.status(),
273                        comment: run.comment,
274                        red: 0,
275                        error: 0,
276                        waiting: Vec::new(),
277                    },
278                );
279            }
280            Err(error) => unreadable.push(error),
281        }
282    }
283    outside_workspaces(catalog.values().map(|run| run.repo_path.as_path()), state)
284        .map_err(|error| Error::Invalid(error.to_string()))?;
285    // Counts come from the status column alone; only a sign-off still waiting reads its records.
286    let filter = if filtered.is_some() {
287        " AND run_id IN (SELECT value FROM json_each(?1))"
288    } else {
289        ""
290    };
291    let sql = format!(
292        "SELECT run_id,status,count(*) FROM requests WHERE status IN ('RED','ERROR'){filter} GROUP BY run_id,status"
293    );
294    let mut statement = db.prepare_cached(&sql)?;
295    let counts = statement.query_map(rusqlite::params_from_iter(filtered), |row| {
296        Ok((
297            row.get::<_, crate::types::RunId>(0)?,
298            row.get::<_, RequestStatus>(1)?,
299            row.get::<_, i64>(2)?,
300        ))
301    })?;
302    for row in counts {
303        let (id, status, count) = row?;
304        let count = u64::try_from(count).expect("COUNT(*) is nonnegative");
305        if let Some(run) = catalog.get_mut(&id) {
306            match status {
307                RequestStatus::Red => run.red = count,
308                RequestStatus::Error => run.error = count,
309                _ => unreachable!("count query filters states"),
310            }
311        }
312    }
313    let filter = if filtered.is_some() {
314        " AND q.run_id IN (SELECT value FROM json_each(?1))"
315    } else {
316        ""
317    };
318    let sql = format!("SELECT q.run_id,q.execution_id,coalesce(json_extract(e.data,'$.provenance.requestId'),json_extract(q.data,'$.provenance.requestId'),q.id)
319        FROM requests q LEFT JOIN executions e ON e.id=q.execution_id WHERE q.status IN ('WAITING_HUMAN','DEFERRED'){filter} ORDER BY q.run_id,q.ordinal");
320    let mut statement = db.prepare_cached(&sql)?;
321    let waiting = statement.query_map(rusqlite::params_from_iter(filtered), |row| {
322        Ok((
323            row.get::<_, crate::types::RunId>(0)?,
324            row.get::<_, Option<ExecutionId>>(1)?,
325            row.get::<_, RequestId>(2)?,
326        ))
327    })?;
328    for row in waiting {
329        let (id, execution, request) = row?;
330        // A deferred sign-off waits for a person as well, after its Run has ended too.
331        if let Some(run) = catalog.get_mut(&id) {
332            run.waiting
333                .push(execution.map_or(Signoff::Request(request), Signoff::Execution));
334        }
335    }
336    for run in catalog.values_mut() {
337        run.status = run.status.with_signoffs(!run.waiting.is_empty());
338    }
339    Ok(Catalog {
340        runs: order
341            .into_iter()
342            .filter_map(|id| catalog.remove(&id))
343            .collect(),
344        unreadable,
345    })
346}