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 runs;
19mod snapshots;
20mod unreadable;
21mod validation;
22pub use unreadable::{Unreadable, read_unreadable};
23mod lifecycle;
24pub(crate) mod migrations;
25pub(crate) mod run_control;
26pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
27pub use result::{ExecutionResult, Field as ResultField, RuntimeResult};
28pub use snapshots::{
29 ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
30 ValidationSnapshot,
31};
32mod wait_timeout;
33pub use catalog::{CatalogRun, Signoff, read_catalog};
34pub use runs::{RunSummary, read_runs, read_scoped_runs};
35pub(crate) mod reader;
36mod requests;
37pub use executions::{
38 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
39 read_keyed_executions, read_latest_cached,
40};
41#[cfg(any(test, feature = "test-support"))]
42pub use receipts::OwnedReceipts;
43pub(crate) use receipts::regular_files as check_probe_files;
44pub use receipts::{
45 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
46 StoppedBackend, read_latest_requests, read_run, read_state_id, schema_error, state_schema,
47};
48pub(crate) use requests::read_request_repo;
49pub use requests::{
50 RequestView, read_original, read_request, read_request_batch, read_requests, read_requests_in,
51 read_run_requests, read_session_request, read_waiting, read_waiting_originals,
52};
53
54pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
57
58const TRANSIENT_ACCESS_RETRIES: u32 = 5;
61const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
62
63fn retry<T, E>(
67 mut attempt: impl FnMut() -> Result<T, E>,
68 transient: impl Fn(&E) -> bool,
69 mut before_retry: impl FnMut(),
70) -> Result<T, E> {
71 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
72 match attempt() {
73 Ok(value) => return Ok(value),
74 Err(error) if remaining > 0 && transient(&error) => {
75 before_retry();
76 }
77 Err(error) => return Err(error),
78 }
79 }
80 unreachable!("the loop above always returns by its last attempt")
81}
82
83pub(crate) fn retry_transient_access<T>(
89 attempt: impl FnMut() -> std::io::Result<T>,
90 before_retry: impl FnMut(),
91) -> std::io::Result<T> {
92 retry(attempt, platform::transient_file_access, before_retry)
93}
94
95#[cfg(test)]
96mod retry_tests {
97 use std::{cell::Cell, io};
98
99 #[test]
100 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
101 let calls = Cell::new(0);
102 let result = super::retry_transient_access(
103 || {
104 calls.set(calls.get() + 1);
105 Ok(7)
106 },
107 || panic!("successful probes need no backoff"),
108 );
109 assert_eq!(result.unwrap(), 7);
110 assert_eq!(calls.get(), 1);
111
112 let calls = Cell::new(0);
113 let result = super::retry_transient_access(
114 || {
115 calls.set(calls.get() + 1);
116 Err::<(), _>(io::Error::other("permanent probe failure"))
117 },
118 || panic!("permanent errors cannot be retried"),
119 );
120 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
121 assert_eq!(calls.get(), 1);
122 }
123}
124
125pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
127 let path = match explicit {
128 Some(path) => path.to_path_buf(),
129 None => state_home().map_err(|e| e.to_string())?,
130 };
131 canonical_target(&path).map_err(|e| e.to_string())
132}
133
134pub const STATE_SCHEMA_VERSION: u32 = 7;
137
138#[derive(Debug, thiserror::Error)]
139#[error("cannot resolve state home: set {}", state_home_variables())]
140pub struct StateHomeError;
141
142fn state_home_variables() -> String {
144 let names: Vec<&str> = std::iter::once("ARTIFACTIZE_STATE_HOME")
145 .chain(platform::STATE_VARIABLES.iter().copied())
146 .chain([platform::HOME_VARIABLE])
147 .collect();
148 let (last, rest) = names.split_last().expect("constant names");
149 format!("{}, or {last}", rest.join(", "))
150}
151
152pub fn state_home() -> Result<PathBuf, StateHomeError> {
155 platform::state_directory().ok_or(StateHomeError)
156}
157
158#[cfg(test)]
159#[path = "store/file_tests.rs"]
160mod file_tests;