1use std::path::{Path, PathBuf};
4
5use crate::{platform, workspace::canonical_target};
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 use result::{ExecutionResult, Field as ResultField, RuntimeResult};
31pub use run_control::read_run_repo;
32pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
33pub use run_read::{read_run, read_run_snapshot};
34pub use snapshots::{
35 ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
36 ValidationSnapshot,
37};
38mod wait_timeout;
39pub use catalog::{CatalogRun, Signoff, read_catalog};
40pub use runs::{RunSummary, read_runs, read_scoped_runs};
41pub(crate) mod reader;
42mod removed;
43pub use removed::retire_removed_signoffs;
44mod requests;
45pub(crate) use executions::read_profiled_executions;
46pub use executions::{
47 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
48 read_keyed_executions, read_latest_cached,
49};
50#[cfg(any(test, feature = "test-support"))]
51pub use receipts::OwnedReceipts;
52pub(crate) use receipts::regular_files as check_probe_files;
53pub use receipts::{
54 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
55 StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
56};
57pub use requests::read_request_repo;
58pub use requests::{
59 RequestView, Shown, read_original, read_original_as, read_request, read_request_as,
60 read_request_batch, read_requests, read_requests_in, read_run_requests, read_session_request,
61 read_waiting, read_waiting_originals,
62};
63pub(crate) use requests::{
64 read_request_by_id, read_request_by_session, read_request_id, read_request_repo_by_id,
65 read_requests_for_run,
66};
67
68pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
72
73const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
78
79pub(crate) fn path_column(
83 row: &rusqlite::Row<'_>,
84 index: usize,
85) -> rusqlite::Result<std::path::PathBuf> {
86 let text: String = row.get(index)?;
87 artifactize_tools::files::path_from_text(&text).map_err(|error| {
88 rusqlite::Error::FromSqlConversionFailure(
89 index,
90 rusqlite::types::Type::Text,
91 Box::new(error),
92 )
93 })
94}
95
96pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
97 db.busy_handler(Some(busy))
98}
99
100fn busy(tries: i32) -> bool {
103 thread_local! {
104 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
105 }
106 let now = std::time::Instant::now();
107 if tries == 0 {
108 SINCE.set(now);
109 }
110 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
111 return false;
112 }
113 std::thread::sleep(SQLITE_BUSY_POLL);
114 true
115}
116
117const TRANSIENT_ACCESS_RETRIES: u32 = 5;
120const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
121
122fn retry<T, E>(
126 mut attempt: impl FnMut() -> Result<T, E>,
127 transient: impl Fn(&E) -> bool,
128 mut before_retry: impl FnMut(),
129) -> Result<T, E> {
130 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
131 match attempt() {
132 Ok(value) => return Ok(value),
133 Err(error) if remaining > 0 && transient(&error) => {
134 before_retry();
135 }
136 Err(error) => return Err(error),
137 }
138 }
139 unreachable!("the loop above always returns by its last attempt")
140}
141
142pub(crate) fn retry_transient_access<T>(
148 attempt: impl FnMut() -> std::io::Result<T>,
149 before_retry: impl FnMut(),
150) -> std::io::Result<T> {
151 retry(attempt, platform::transient_file_access, before_retry)
152}
153
154#[cfg(test)]
155mod retry_tests {
156 use std::{cell::Cell, io};
157
158 #[test]
159 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
160 let calls = Cell::new(0);
161 let result = super::retry_transient_access(
162 || {
163 calls.set(calls.get() + 1);
164 Ok(7)
165 },
166 || panic!("successful probes need no backoff"),
167 );
168 assert_eq!(result.unwrap(), 7);
169 assert_eq!(calls.get(), 1);
170
171 let calls = Cell::new(0);
172 let result = super::retry_transient_access(
173 || {
174 calls.set(calls.get() + 1);
175 Err::<(), _>(io::Error::other("permanent probe failure"))
176 },
177 || panic!("permanent errors cannot be retried"),
178 );
179 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
180 assert_eq!(calls.get(), 1);
181 }
182}
183
184pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
186 let path = match explicit {
187 Some(path) => path.to_path_buf(),
188 None => state_home().map_err(|e| e.to_string())?,
189 };
190 canonical_target(&path).map_err(|e| e.to_string())
191}
192
193pub const STATE_SCHEMA_VERSION: u32 = 10;
198
199#[derive(Debug, thiserror::Error)]
200#[error("cannot resolve state home: set {}", state_home_variables())]
201pub struct StateHomeError;
202
203fn state_home_variables() -> String {
205 let names: Vec<_> = platform::state_home_variables().collect();
206 let (last, rest) = names.split_last().expect("constant names");
207 format!("{}, or {last}", rest.join(", "))
208}
209
210pub fn state_home() -> Result<PathBuf, StateHomeError> {
213 platform::state_directory().ok_or(StateHomeError)
214}
215
216#[cfg(test)]
217#[path = "store/file_tests.rs"]
218mod file_tests;