1use std::path::{Path, PathBuf};
4
5use crate::{platform, workspace::canonical_target};
6
7mod blocked;
8pub(crate) mod chat;
9pub mod definitions;
10mod executions;
11pub(crate) mod history;
12mod human;
13pub use human::HumanClaim;
14mod catalog;
15pub(crate) mod connection;
16pub mod prune;
17pub(crate) mod receipts;
18mod result;
19mod run_record;
20mod runs;
21mod snapshots;
22mod touched;
23mod unreadable;
24mod validation;
25pub use unreadable::{Unreadable, read_unreadable};
26mod lifecycle;
27pub(crate) mod migrations;
28pub(crate) mod run_control;
29mod run_read;
30pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
31pub use result::{ExecutionResult, Field as ResultField, RuntimeResult};
32pub use run_control::read_run_repo;
33pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
34pub use run_read::{read_run, read_run_snapshot};
35pub use snapshots::{
36 ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
37 ValidationSnapshot,
38};
39mod wait_timeout;
40pub(crate) use catalog::places as read_run_places;
41pub use catalog::{
42 CatalogRun, Signoff, read_catalog, read_catalog_run, read_open_run_ids, run_checkout,
43 viewer_checkout,
44};
45pub use runs::{RunSummary, read_runs, read_scoped_runs};
46pub(crate) mod reader;
47mod removed;
48pub use removed::retire_removed_signoffs;
49mod requests;
50pub(crate) use executions::read_profiled_executions;
51pub use executions::{
52 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
53 read_keyed_executions, read_latest_cached,
54};
55#[cfg(any(test, feature = "test-support"))]
56pub use receipts::OwnedReceipts;
57pub(crate) use receipts::regular_files as check_probe_files;
58pub use receipts::{
59 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
60 StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
61};
62pub use requests::read_request_repo;
63pub use requests::{
64 RequestView, Shown, read_optional_request, read_original, read_original_as, read_request,
65 read_request_as, read_request_batch, read_request_by_id, read_request_id, read_requests,
66 read_requests_in, read_review_owner, read_run_requests, read_run_requests_by_id,
67 read_session_request, read_waiting, read_waiting_originals,
68};
69pub(crate) use requests::{
70 read_request_by_session, read_request_repo_by_id, read_requests_for_run, read_review_batch,
71};
72
73pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
77
78const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
83
84pub(crate) fn path_column(
88 row: &rusqlite::Row<'_>,
89 index: usize,
90) -> rusqlite::Result<std::path::PathBuf> {
91 let text: String = row.get(index)?;
92 artifactize_tools::files::path_from_text(&text).map_err(|error| {
93 rusqlite::Error::FromSqlConversionFailure(
94 index,
95 rusqlite::types::Type::Text,
96 Box::new(error),
97 )
98 })
99}
100
101pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
102 db.busy_handler(Some(busy))
103}
104
105fn busy(tries: i32) -> bool {
108 thread_local! {
109 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
110 }
111 let now = std::time::Instant::now();
112 if tries == 0 {
113 SINCE.set(now);
114 }
115 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
116 return false;
117 }
118 std::thread::sleep(SQLITE_BUSY_POLL);
119 true
120}
121
122const TRANSIENT_ACCESS_RETRIES: u32 = 5;
125const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
126
127fn retry<T, E>(
131 mut attempt: impl FnMut() -> Result<T, E>,
132 transient: impl Fn(&E) -> bool,
133 mut before_retry: impl FnMut(),
134) -> Result<T, E> {
135 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
136 match attempt() {
137 Ok(value) => return Ok(value),
138 Err(error) if remaining > 0 && transient(&error) => {
139 before_retry();
140 }
141 Err(error) => return Err(error),
142 }
143 }
144 unreachable!("the loop above always returns by its last attempt")
145}
146
147pub(crate) fn retry_transient_access<T>(
153 attempt: impl FnMut() -> std::io::Result<T>,
154 before_retry: impl FnMut(),
155) -> std::io::Result<T> {
156 retry(attempt, platform::transient_file_access, before_retry)
157}
158
159#[cfg(test)]
160mod retry_tests {
161 use std::{cell::Cell, io};
162
163 #[test]
164 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
165 let calls = Cell::new(0);
166 let result = super::retry_transient_access(
167 || {
168 calls.set(calls.get() + 1);
169 Ok(7)
170 },
171 || panic!("successful probes need no backoff"),
172 );
173 assert_eq!(result.unwrap(), 7);
174 assert_eq!(calls.get(), 1);
175
176 let calls = Cell::new(0);
177 let result = super::retry_transient_access(
178 || {
179 calls.set(calls.get() + 1);
180 Err::<(), _>(io::Error::other("permanent probe failure"))
181 },
182 || panic!("permanent errors cannot be retried"),
183 );
184 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
185 assert_eq!(calls.get(), 1);
186 }
187}
188
189pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
191 let path = match explicit {
192 Some(path) => path.to_path_buf(),
193 None => state_home().map_err(|e| e.to_string())?,
194 };
195 canonical_target(&path).map_err(|e| e.to_string())
196}
197
198pub const STATE_SCHEMA_VERSION: u32 = 11;
203
204#[derive(Debug, thiserror::Error)]
205#[error("cannot resolve state home: set {}", state_home_variables())]
206pub struct StateHomeError;
207
208fn state_home_variables() -> String {
210 let names: Vec<_> = platform::state_home_variables().collect();
211 let (last, rest) = names.split_last().expect("constant names");
212 format!("{}, or {last}", rest.join(", "))
213}
214
215pub fn state_home() -> Result<PathBuf, StateHomeError> {
218 platform::state_directory().ok_or(StateHomeError)
219}
220
221#[cfg(test)]
222#[path = "store/file_tests.rs"]
223mod file_tests;