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;
28pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
29pub use result::{ExecutionResult, Field as ResultField, RuntimeResult};
30pub use snapshots::{
31 ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
32 ValidationSnapshot,
33};
34mod wait_timeout;
35pub use catalog::{CatalogRun, Signoff, read_catalog};
36pub use runs::{RunSummary, read_runs, read_scoped_runs};
37pub(crate) mod reader;
38mod requests;
39pub(crate) use executions::read_profiled_executions;
40pub use executions::{
41 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
42 read_keyed_executions, read_latest_cached,
43};
44#[cfg(any(test, feature = "test-support"))]
45pub use receipts::OwnedReceipts;
46pub(crate) use receipts::regular_files as check_probe_files;
47pub use receipts::{
48 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
49 StoppedBackend, read_latest_requests, read_run, read_state_id, schema_error, state_schema,
50};
51pub use requests::read_request_repo;
52pub use requests::{
53 RequestView, read_original, read_request, read_request_batch, read_requests, read_requests_in,
54 read_run_requests, read_session_request, read_waiting, read_waiting_originals,
55};
56
57pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
61
62const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
67
68pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
71 db.busy_handler(Some(busy))
72}
73
74fn busy(tries: i32) -> bool {
77 thread_local! {
78 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
79 }
80 let now = std::time::Instant::now();
81 if tries == 0 {
82 SINCE.set(now);
83 }
84 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
85 return false;
86 }
87 std::thread::sleep(SQLITE_BUSY_POLL);
88 true
89}
90
91const TRANSIENT_ACCESS_RETRIES: u32 = 5;
94const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
95
96fn retry<T, E>(
100 mut attempt: impl FnMut() -> Result<T, E>,
101 transient: impl Fn(&E) -> bool,
102 mut before_retry: impl FnMut(),
103) -> Result<T, E> {
104 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
105 match attempt() {
106 Ok(value) => return Ok(value),
107 Err(error) if remaining > 0 && transient(&error) => {
108 before_retry();
109 }
110 Err(error) => return Err(error),
111 }
112 }
113 unreachable!("the loop above always returns by its last attempt")
114}
115
116pub(crate) fn retry_transient_access<T>(
122 attempt: impl FnMut() -> std::io::Result<T>,
123 before_retry: impl FnMut(),
124) -> std::io::Result<T> {
125 retry(attempt, platform::transient_file_access, before_retry)
126}
127
128#[cfg(test)]
129mod retry_tests {
130 use std::{cell::Cell, io};
131
132 #[test]
133 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
134 let calls = Cell::new(0);
135 let result = super::retry_transient_access(
136 || {
137 calls.set(calls.get() + 1);
138 Ok(7)
139 },
140 || panic!("successful probes need no backoff"),
141 );
142 assert_eq!(result.unwrap(), 7);
143 assert_eq!(calls.get(), 1);
144
145 let calls = Cell::new(0);
146 let result = super::retry_transient_access(
147 || {
148 calls.set(calls.get() + 1);
149 Err::<(), _>(io::Error::other("permanent probe failure"))
150 },
151 || panic!("permanent errors cannot be retried"),
152 );
153 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
154 assert_eq!(calls.get(), 1);
155 }
156}
157
158pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
160 let path = match explicit {
161 Some(path) => path.to_path_buf(),
162 None => state_home().map_err(|e| e.to_string())?,
163 };
164 canonical_target(&path).map_err(|e| e.to_string())
165}
166
167pub const STATE_SCHEMA_VERSION: u32 = 10;
172
173#[derive(Debug, thiserror::Error)]
174#[error("cannot resolve state home: set {}", state_home_variables())]
175pub struct StateHomeError;
176
177fn state_home_variables() -> String {
179 let names: Vec<&str> = std::iter::once("ARTIFACTIZE_STATE_HOME")
180 .chain(platform::STATE_VARIABLES.iter().copied())
181 .chain([platform::HOME_VARIABLE])
182 .collect();
183 let (last, rest) = names.split_last().expect("constant names");
184 format!("{}, or {last}", rest.join(", "))
185}
186
187pub fn state_home() -> Result<PathBuf, StateHomeError> {
190 platform::state_directory().ok_or(StateHomeError)
191}
192
193#[cfg(test)]
194#[path = "store/file_tests.rs"]
195mod file_tests;