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(crate) use runs::for_chat_session as read_chat_runs;
46pub use runs::{RunSummary, read_runs, read_scoped_runs};
47pub(crate) mod reader;
48mod removed;
49pub use removed::retire_removed_signoffs;
50mod requests;
51pub(crate) use executions::read_profiled_executions;
52pub use executions::{
53 Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
54 read_keyed_executions, read_latest_cached,
55};
56#[cfg(any(test, feature = "test-support"))]
57pub use receipts::OwnedReceipts;
58pub(crate) use receipts::regular_files as check_probe_files;
59pub use receipts::{
60 DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
61 StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
62};
63pub use requests::read_request_repo;
64pub use requests::{
65 RequestView, Shown, read_optional_request, read_original, read_original_as, read_request,
66 read_request_as, read_request_batch, read_request_by_id, read_request_id, read_requests,
67 read_requests_in, read_review_owner, read_run_requests, read_run_requests_by_id,
68 read_session_request, read_waiting, read_waiting_originals,
69};
70pub(crate) use requests::{
71 read_request_by_session, read_request_repo_by_id, read_requests_for_run, read_review_batch,
72};
73
74pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
78
79const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
84
85pub(crate) fn path_column(
89 row: &rusqlite::Row<'_>,
90 index: usize,
91) -> rusqlite::Result<std::path::PathBuf> {
92 let text: String = row.get(index)?;
93 artifactize_tools::files::path_from_text(&text).map_err(|error| {
94 rusqlite::Error::FromSqlConversionFailure(
95 index,
96 rusqlite::types::Type::Text,
97 Box::new(error),
98 )
99 })
100}
101
102pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
103 db.busy_handler(Some(busy))
104}
105
106fn busy(tries: i32) -> bool {
109 thread_local! {
110 static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
111 }
112 let now = std::time::Instant::now();
113 if tries == 0 {
114 SINCE.set(now);
115 }
116 if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
117 return false;
118 }
119 std::thread::sleep(SQLITE_BUSY_POLL);
120 true
121}
122
123const TRANSIENT_ACCESS_RETRIES: u32 = 5;
126const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
127
128fn retry<T, E>(
132 mut attempt: impl FnMut() -> Result<T, E>,
133 transient: impl Fn(&E) -> bool,
134 mut before_retry: impl FnMut(),
135) -> Result<T, E> {
136 for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
137 match attempt() {
138 Ok(value) => return Ok(value),
139 Err(error) if remaining > 0 && transient(&error) => {
140 before_retry();
141 }
142 Err(error) => return Err(error),
143 }
144 }
145 unreachable!("the loop above always returns by its last attempt")
146}
147
148pub(crate) fn retry_transient_access<T>(
154 attempt: impl FnMut() -> std::io::Result<T>,
155 before_retry: impl FnMut(),
156) -> std::io::Result<T> {
157 retry(attempt, platform::transient_file_access, before_retry)
158}
159
160#[cfg(test)]
161mod retry_tests {
162 use std::{cell::Cell, io};
163
164 #[test]
165 fn file_probe_returns_success_and_permanent_errors_without_backoff() {
166 let calls = Cell::new(0);
167 let result = super::retry_transient_access(
168 || {
169 calls.set(calls.get() + 1);
170 Ok(7)
171 },
172 || panic!("successful probes need no backoff"),
173 );
174 assert_eq!(result.unwrap(), 7);
175 assert_eq!(calls.get(), 1);
176
177 let calls = Cell::new(0);
178 let result = super::retry_transient_access(
179 || {
180 calls.set(calls.get() + 1);
181 Err::<(), _>(io::Error::other("permanent probe failure"))
182 },
183 || panic!("permanent errors cannot be retried"),
184 );
185 assert_eq!(result.unwrap_err().to_string(), "permanent probe failure");
186 assert_eq!(calls.get(), 1);
187 }
188}
189
190pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
192 let path = match explicit {
193 Some(path) => path.to_path_buf(),
194 None => state_home().map_err(|e| e.to_string())?,
195 };
196 canonical_target(&path).map_err(|e| e.to_string())
197}
198
199pub const STATE_SCHEMA_VERSION: u32 = 12;
205
206#[derive(Debug, thiserror::Error)]
207#[error("cannot resolve state home: set {}", state_home_variables())]
208pub struct StateHomeError;
209
210fn state_home_variables() -> String {
212 let names: Vec<_> = platform::state_home_variables().collect();
213 let (last, rest) = names.split_last().expect("constant names");
214 format!("{}, or {last}", rest.join(", "))
215}
216
217pub fn state_home() -> Result<PathBuf, StateHomeError> {
220 platform::state_directory().ok_or(StateHomeError)
221}
222
223#[cfg(test)]
224#[path = "store/file_tests.rs"]
225mod file_tests;