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 use run_read::read_run;
33pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
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 requests;
43pub(crate) use executions::read_profiled_executions;
44pub use executions::{
45 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
46 read_keyed_executions, read_latest_cached,
47};
48#[cfg(any(test, feature = "test-support"))]
49pub use receipts::OwnedReceipts;
50pub(crate) use receipts::regular_files as check_probe_files;
51pub use receipts::{
52 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
53 StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
54};
55pub use requests::read_request_repo;
56pub use requests::{
57 RequestView, read_original, read_request, read_request_batch, read_requests, read_requests_in,
58 read_run_requests, read_session_request, read_waiting, read_waiting_originals,
59};
60
61pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
65
66const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
71
72pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
75 db.busy_handler(Some(busy))
76}
77
78fn busy(tries: i32) -> bool {
81 thread_local! {
82 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
83 }
84 let now = std::time::Instant::now();
85 if tries == 0 {
86 SINCE.set(now);
87 }
88 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
89 return false;
90 }
91 std::thread::sleep(SQLITE_BUSY_POLL);
92 true
93}
94
95const TRANSIENT_ACCESS_RETRIES: u32 = 5;
98const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
99
100fn retry<T, E>(
104 mut attempt: impl FnMut() -> Result<T, E>,
105 transient: impl Fn(&E) -> bool,
106 mut before_retry: impl FnMut(),
107) -> Result<T, E> {
108 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
109 match attempt() {
110 Ok(value) => return Ok(value),
111 Err(error) if remaining > 0 && transient(&error) => {
112 before_retry();
113 }
114 Err(error) => return Err(error),
115 }
116 }
117 unreachable!("the loop above always returns by its last attempt")
118}
119
120pub(crate) fn retry_transient_access<T>(
126 attempt: impl FnMut() -> std::io::Result<T>,
127 before_retry: impl FnMut(),
128) -> std::io::Result<T> {
129 retry(attempt, platform::transient_file_access, before_retry)
130}
131
132#[cfg(test)]
133mod retry_tests {
134 use std::{cell::Cell, io};
135
136 #[test]
137 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
138 let calls = Cell::new(0);
139 let result = super::retry_transient_access(
140 || {
141 calls.set(calls.get() + 1);
142 Ok(7)
143 },
144 || panic!("successful probes need no backoff"),
145 );
146 assert_eq!(result.unwrap(), 7);
147 assert_eq!(calls.get(), 1);
148
149 let calls = Cell::new(0);
150 let result = super::retry_transient_access(
151 || {
152 calls.set(calls.get() + 1);
153 Err::<(), _>(io::Error::other("permanent probe failure"))
154 },
155 || panic!("permanent errors cannot be retried"),
156 );
157 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
158 assert_eq!(calls.get(), 1);
159 }
160}
161
162pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
164 let path = match explicit {
165 Some(path) => path.to_path_buf(),
166 None => state_home().map_err(|e| e.to_string())?,
167 };
168 canonical_target(&path).map_err(|e| e.to_string())
169}
170
171pub const STATE_SCHEMA_VERSION: u32 = 10;
176
177#[derive(Debug, thiserror::Error)]
178#[error("cannot resolve state home: set {}", state_home_variables())]
179pub struct StateHomeError;
180
181fn state_home_variables() -> String {
183 let names: Vec<&str> = std::iter::once("ARTIFACTIZE_STATE_HOME")
184 .chain(platform::STATE_VARIABLES.iter().copied())
185 .chain([platform::HOME_VARIABLE])
186 .collect();
187 let (last, rest) = names.split_last().expect("constant names");
188 format!("{}, or {last}", rest.join(", "))
189}
190
191pub fn state_home() -> Result<PathBuf, StateHomeError> {
194 platform::state_directory().ok_or(StateHomeError)
195}
196
197#[cfg(test)]
198#[path = "store/file_tests.rs"]
199mod file_tests;