Skip to main content

artifactize_core/
store.rs

1//! The state database and storage maintenance.
2
3use 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
54/// Let concurrent readers/writers finish short SQLite transactions without an
55/// immediate busy error, while limiting how long one database operation can block.
56pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
57
58/// Allow four short backoffs for a pending-delete handle to close, bounding the extra
59/// latency of a real file-access failure to 80ms. This is a retry policy, not a test deadline.
60const TRANSIENT_ACCESS_RETRIES: u32 = 5;
61const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
62
63/// Retry `attempt` while `transient` says its error can clear on its own, before giving up
64/// with its last error. `transient` decides alone: a non-transient error, or the bound run out,
65/// both stop the loop and return that error immediately, never retried further.
66fn 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
83/// Retry `attempt` past [`platform::transient_file_access`] (Windows transiently denying a
84/// metadata or open probe while another handle finishes closing a just-deleted WAL sidecar)
85/// before giving up with its last error. Every read-only state open reaches this through
86/// [`receipts::check_files`]/[`check_probe_files`], which every reader calls first, so this is
87/// the one place the retry needs to live.
88pub(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
125/// Resolve the single state directory without creating it.
126pub 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
134/// SQLite `user_version`; caller attempt keys extend Runs additively in schema 7.
135/// Earlier state is not migrated.
136pub 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
142/// The variables `state_home` reads, in order, for the error that names them.
143fn 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
152/// Resolve the default state home without creating directories; empty variables are ignored.
153/// The platform's state variables come after `ARTIFACTIZE_STATE_HOME` and before the home.
154pub 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;