1use std::path::{Path, PathBuf};
4
5use crate::platform;
6
7mod blocked;
8pub mod definitions;
9mod executions;
10pub(crate) mod history;
11mod human;
12pub use human::HumanClaim;
13mod catalog;
14pub(crate) mod connection;
15pub mod prune;
16pub(crate) mod receipts;
17mod result;
18mod run_record;
19mod runs;
20mod snapshots;
21mod touched;
22mod unreadable;
23mod validation;
24pub use unreadable::{Unreadable, read_unreadable};
25mod lifecycle;
26pub(crate) mod migrations;
27pub(crate) mod run_control;
28mod run_read;
29pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
30pub(crate) use result::tail as output_tail;
31pub use result::{
32 AgentIssue, ExecutionResult, HumanIssue, Issue, RuntimeIssue, RuntimeResult, exited_with,
33};
34pub use run_control::read_run_repo;
35pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
36pub use run_read::{read_run, read_run_snapshot, read_run_sources};
37pub use snapshots::{
38 ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
39 ValidationSnapshot,
40};
41mod wait_timeout;
42pub(crate) use catalog::places as read_run_places;
43pub use catalog::{
44 CatalogRun, Signoff, read_catalog, read_catalog_run, read_open_run_ids, run_checkout,
45 viewer_checkout,
46};
47pub use runs::{RunSummary, read_runs, read_scoped_runs};
48pub(crate) mod reader;
49mod removed;
50pub use removed::retire_removed_signoffs;
51mod requests;
52pub(crate) use executions::read_profiled_executions;
53pub use executions::{
54 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
55 read_keyed_executions, read_latest_cached,
56};
57#[cfg(any(test, feature = "test-support"))]
58pub use receipts::OwnedReceipts;
59pub use receipts::{
60 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
61 StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
62};
63pub(crate) use receipts::{read_attempts, read_deferred, regular_files as check_probe_files};
64pub use requests::read_request_repo;
65pub use requests::{
66 Batch, Mark, RequestView, Shown, Start, read_optional_request, read_original, read_original_as,
67 read_request, read_request_as, read_request_batch, read_request_by_id, read_request_id,
68 read_requests, read_requests_in, read_review_owner, read_run_requests, read_run_requests_by_id,
69 read_session_request, read_waiting, read_waiting_originals,
70};
71pub(crate) use requests::{
72 read_request_by_session, read_request_list, read_request_repo_by_id, read_review_batch,
73};
74
75pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
79
80const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
85
86pub(crate) fn path_column(
90 row: &rusqlite::Row<'_>,
91 index: usize,
92) -> rusqlite::Result<std::path::PathBuf> {
93 let text: String = row.get(index)?;
94 artifactize_tools::files::path_from_text(&text).map_err(|error| {
95 rusqlite::Error::FromSqlConversionFailure(
96 index,
97 rusqlite::types::Type::Text,
98 Box::new(error),
99 )
100 })
101}
102
103pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
104 #[cfg(test)]
105 crate::performance::count_connection_sql(db)?;
106 db.busy_handler(Some(busy))
107}
108
109fn busy(tries: i32) -> bool {
112 thread_local! {
113 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
114 }
115 let now = std::time::Instant::now();
116 if tries == 0 {
117 SINCE.set(now);
118 }
119 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
120 return false;
121 }
122 std::thread::sleep(SQLITE_BUSY_POLL);
123 true
124}
125
126const TRANSIENT_ACCESS_RETRIES: u32 = 5;
129const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
130
131fn retry<T, E>(
135 mut attempt: impl FnMut() -> Result<T, E>,
136 transient: impl Fn(&E) -> bool,
137 mut before_retry: impl FnMut(),
138) -> Result<T, E> {
139 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
140 match attempt() {
141 Ok(value) => return Ok(value),
142 Err(error) if remaining > 0 && transient(&error) => {
143 before_retry();
144 }
145 Err(error) => return Err(error),
146 }
147 }
148 unreachable!("the loop above always returns by its last attempt")
149}
150
151pub(crate) fn retry_transient_access<T>(
157 attempt: impl FnMut() -> std::io::Result<T>,
158 before_retry: impl FnMut(),
159) -> std::io::Result<T> {
160 retry(attempt, platform::transient_file_access, before_retry)
161}
162
163#[cfg(test)]
164#[path = "store/tests/retry.rs"]
165mod retry_tests;
166
167pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
169 let path = match explicit {
170 Some(path) => path.to_path_buf(),
171 None => state_home().map_err(|e| e.to_string())?,
172 };
173 crate::platform::paths::resolve_target(&path).map_err(|e| e.to_string())
174}
175
176pub const STATE_SCHEMA_VERSION: u32 = 15;
183
184#[derive(Debug, thiserror::Error)]
185#[error("cannot resolve state home: set {}", state_home_variables())]
186pub struct StateHomeError;
187
188fn state_home_variables() -> String {
190 let names: Vec<_> = platform::state_home_variables().collect();
191 let (last, rest) = names.split_last().expect("constant names");
192 format!("{}, or {last}", rest.join(", "))
193}
194
195pub fn state_home() -> Result<PathBuf, StateHomeError> {
198 platform::state_directory().ok_or(StateHomeError)
199}
200
201#[cfg(test)]
202#[path = "store/tests/file.rs"]
203mod file_tests;