1mod downloads;
11mod journal;
12mod leases;
13mod mirror;
14mod owner;
15mod resources;
16mod rows;
17mod runs;
18mod schema;
19#[cfg(test)]
20mod tests;
21
22#[cfg(test)]
24pub(crate) use owner::tests::dead_pid;
25
26use std::path::{Path, PathBuf};
27use std::sync::atomic::{AtomicI64, Ordering};
28use std::sync::{Mutex, PoisonError};
29use std::time::Duration;
30
31use rusqlite::{Connection, TransactionBehavior};
32use serde::Serialize;
33use serde::de::DeserializeOwned;
34
35pub use leases::Reserver;
36pub use mirror::{MIRROR_FILE, Recovered};
37pub use owner::Owner;
38pub use rows::{
39 CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, PortReservation,
40 ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope,
41};
42
43use crate::Result;
44use crate::error::{Error, ErrorCode};
45
46pub(crate) const DB_FILE: &str = "state.db";
48
49const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
51
52pub struct Store {
54 conn: Mutex<Connection>,
55 path: PathBuf,
56 mirror: PathBuf,
58 mirrored: AtomicI64,
60 recovered: Option<Recovered>,
62}
63
64impl std::fmt::Debug for Store {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.debug_struct("Store").field("path", &self.path).finish_non_exhaustive()
67 }
68}
69
70pub struct Tx<'c> {
73 tx: rusqlite::Transaction<'c>,
74}
75
76impl Store {
77 pub fn open(home: &Path) -> Result<Store> {
89 let home = &std::path::absolute(home).map_err(Error::io(home, "made absolute"))?;
90 crate::store::create_dir(home)?;
91 let path = home.join(DB_FILE);
92 let mirror = home.join(MIRROR_FILE);
93 match Store::open_checked(&path, &mirror, Fresh::Suspect) {
94 Ok(store) => {
95 store.sync_mirror();
98 Ok(store)
99 }
100 Err(e) if e.code() == ErrorCode::StoreCorrupt => Store::rebuild(&path, &mirror, &e),
101 Err(e) => Err(e),
102 }
103 }
104
105 fn open_checked(path: &Path, mirror: &Path, fresh: Fresh) -> Result<Store> {
108 let conn = connect(path)?;
109 quick_check(&conn)?;
110 let store = Store {
111 conn: Mutex::new(conn),
112 path: path.to_path_buf(),
113 mirror: mirror.to_path_buf(),
114 mirrored: AtomicI64::new(-1),
115 recovered: None,
116 };
117 let was = store.migrate()?;
118 if was == 0 && fresh == Fresh::Suspect && mirror::read(mirror).is_some_and(|m| m.holds_rows()) {
121 return Err(Error::Store {
122 action: "opened",
123 code: ErrorCode::StoreCorrupt,
124 reason: "its file is empty, but its mirror holds runs, operations or resources".to_owned(),
125 });
126 }
127 Ok(store)
128 }
129
130 pub fn read_existing<T>(home: &Path, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<Option<T>> {
138 let path = home.join(DB_FILE);
139 if !path.is_file() {
140 return Ok(None);
141 }
142 let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;
143 let conn = Connection::open_with_flags(&path, flags).map_err(failed("opened"))?;
144 conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
145 let store = Store {
146 conn: Mutex::new(conn),
147 path,
148 mirror: home.join(MIRROR_FILE),
149 mirrored: AtomicI64::new(-1),
150 recovered: None,
151 };
152 store.read(f).map(Some)
153 }
154
155 fn rebuild(path: &Path, mirror: &Path, cause: &Error) -> Result<Store> {
158 let damaged = |reason: String| Error::Store {
159 action: "opened",
160 code: ErrorCode::StoreCorrupt,
161 reason,
162 };
163 let Some(copy) = mirror::read(mirror) else {
164 return Err(damaged(format!("{cause}; and there is no mirror to rebuild it from")));
165 };
166 let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
167 if copy.schema() != known {
168 return Err(damaged(format!("{cause}; and its mirror is of schema {}, not {known}", copy.schema())));
169 }
170 let kept = set_aside(path)?;
171 tracing::warn!(error = %cause, kept = %kept.display(), "the store was damaged: rebuilt from its mirror");
172 let mut store = Store::open_checked(path, mirror, Fresh::Expected)?;
173 {
174 let mut conn = store.conn.lock().unwrap_or_else(PoisonError::into_inner);
175 copy.restore(&mut conn)?;
176 }
177 store.sync_mirror();
178 store.recovered = Some(Recovered {
179 corrupt_kept_at: kept,
180 mirror_written_at: copy.written_at().to_owned(),
181 reason: cause.to_string(),
182 });
183 Ok(store)
184 }
185
186 #[must_use]
189 pub fn recovered(&self) -> Option<&Recovered> {
190 self.recovered.as_ref()
191 }
192
193 fn sync_mirror(&self) {
195 let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
196 match conn.transaction_with_behavior(TransactionBehavior::Deferred) {
197 Ok(tx) => self.mirror_within(&tx),
198 Err(e) => tracing::warn!(error = %e, "the store's mirror wasn't written"),
199 }
200 }
201
202 fn mirror_within(&self, conn: &Connection) {
206 let written = mirror::generation(conn).map_err(failed("read")).and_then(|n| {
207 if n == self.mirrored.load(Ordering::SeqCst) {
208 Ok(None)
209 } else {
210 mirror::write(conn, n, &self.mirror).map(|()| Some(n))
211 }
212 });
213 match written {
214 Ok(Some(n)) => self.mirrored.store(n, Ordering::SeqCst),
215 Ok(None) => {}
216 Err(e) => {
217 self.mirrored.store(-1, Ordering::SeqCst);
218 tracing::warn!(error = %e, "the store's mirror wasn't written");
219 }
220 }
221 }
222
223 #[must_use]
225 pub fn path(&self) -> &Path {
226 &self.path
227 }
228
229 pub fn read<T>(&self, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<T> {
235 let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
236 let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred).map_err(failed("read"))?;
237 let tx = Tx { tx };
238 let value = f(&tx)?;
239 tx.tx.finish().map_err(failed("read"))?;
240 Ok(value)
241 }
242
243 pub fn write<T>(&self, f: impl FnOnce(&mut Tx<'_>) -> Result<T>) -> Result<T> {
250 let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
251 let committed = {
252 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("written"))?;
253 let mut tx = Tx { tx };
254 let value = f(&mut tx)?;
255 self.mirror_within(&tx.tx);
258 tx.tx.commit().map(|()| value)
259 };
260 committed.map_err(|e| {
261 self.mirrored.store(-1, Ordering::SeqCst);
263 drop(conn);
264 self.sync_mirror();
265 failed("written")(e)
266 })
267 }
268
269 fn migrate(&self) -> Result<i64> {
272 let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
273 conn.execute_batch("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)")
274 .map_err(failed("migrated"))?;
275 let applied: i64 = conn
276 .query_row("SELECT COALESCE(MAX(version), 0) FROM schema_migrations", [], |r| r.get(0))
277 .map_err(failed("migrated"))?;
278 let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
279 if applied > known {
280 return Err(Error::Store {
281 action: "opened",
282 code: ErrorCode::StoreVersion,
283 reason: format!("its schema is version {applied}, newer than this runner's {known}: a newer runner wrote it"),
284 });
285 }
286 for (version, sql) in (1..).zip(schema::MIGRATIONS).skip(usize::try_from(applied).unwrap_or(0)) {
287 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("migrated"))?;
288 tx.execute_batch(sql).map_err(failed("migrated"))?;
289 tx.execute(
290 "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
291 rusqlite::params![version, now()],
292 )
293 .map_err(failed("migrated"))?;
294 tx.commit().map_err(failed("migrated"))?;
295 }
296 Ok(applied)
297 }
298}
299
300impl Tx<'_> {}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304enum Fresh {
305 Suspect,
307 Expected,
309}
310
311fn connect(path: &Path) -> Result<Connection> {
313 let conn = Connection::open(path).map_err(failed("opened"))?;
314 #[cfg(unix)]
315 restrict(path)?;
316 conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
317 conn.pragma_update(None, "journal_mode", "WAL").map_err(failed("opened"))?;
318 conn.pragma_update(None, "foreign_keys", "ON").map_err(failed("opened"))?;
319 conn.pragma_update(None, "synchronous", "NORMAL").map_err(failed("opened"))?;
320 Ok(conn)
321}
322
323const FINDINGS_SAID: usize = 3;
325
326fn quick_check(conn: &Connection) -> Result<()> {
332 let mut stmt = conn.prepare("PRAGMA quick_check").map_err(failed("checked"))?;
333 let findings: Vec<String> = stmt
334 .query_map([], |r| r.get::<_, String>(0))
335 .map_err(failed("checked"))?
336 .collect::<rusqlite::Result<_>>()
337 .map_err(failed("checked"))?;
338 if findings.iter().all(|f| f == "ok") {
339 return Ok(());
340 }
341 let said: Vec<&str> = findings.iter().take(FINDINGS_SAID).map(String::as_str).collect();
342 Err(Error::Store {
343 action: "checked",
344 code: ErrorCode::StoreCorrupt,
345 reason: format!("its integrity check failed ({} findings): {}", findings.len(), said.join("; ")),
346 })
347}
348
349fn set_aside(path: &Path) -> Result<PathBuf> {
352 let kept = path.with_file_name(format!("{DB_FILE}.corrupt-{}", epoch_now()));
353 for suffix in ["", "-wal", "-shm"] {
354 let with = |p: &Path| {
355 let mut name = p.as_os_str().to_owned();
356 name.push(suffix);
357 PathBuf::from(name)
358 };
359 let (from, to) = (with(path), with(&kept));
360 if from.exists() {
361 std::fs::rename(&from, &to).map_err(Error::io(&from, "moved aside"))?;
362 }
363 }
364 Ok(kept)
365}
366
367pub(crate) fn failed(action: &'static str) -> impl Fn(rusqlite::Error) -> Error {
370 move |e| {
371 let code = match e.sqlite_error_code() {
372 Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked) => ErrorCode::Locked,
373 Some(rusqlite::ErrorCode::NotADatabase | rusqlite::ErrorCode::DatabaseCorrupt) => ErrorCode::StoreCorrupt,
374 _ => ErrorCode::Io,
375 };
376 Error::Store {
377 action,
378 code,
379 reason: e.to_string(),
380 }
381 }
382}
383
384pub(crate) fn corrupt(what: &str, value: &str) -> Error {
386 Error::Store {
387 action: "read",
388 code: ErrorCode::StoreCorrupt,
389 reason: format!("a {what} column holds `{value}`, which this runner doesn't write"),
390 }
391}
392
393pub(crate) fn word<T: Serialize>(value: &T) -> String {
395 crate::encoding::wire_name(value)
396}
397
398pub(crate) fn from_word<T: DeserializeOwned>(what: &str, word: &str) -> Result<T> {
400 crate::encoding::from_wire_name(word).ok_or_else(|| corrupt(what, word))
401}
402
403pub(crate) fn to_json<T: Serialize>(value: &T) -> Result<String> {
405 serde_json::to_string(value).map_err(|e| Error::Store {
406 action: "written",
407 code: ErrorCode::Io,
408 reason: e.to_string(),
409 })
410}
411
412pub(crate) fn from_json<T: DeserializeOwned>(what: &str, text: &str) -> Result<T> {
414 serde_json::from_str(text).map_err(|e| Error::Store {
415 action: "read",
416 code: ErrorCode::StoreCorrupt,
417 reason: format!("its {what} doesn't parse: {e}"),
418 })
419}
420
421pub(crate) fn now() -> String {
423 crate::clock::rfc3339(std::time::SystemTime::now())
424}
425
426pub(crate) fn epoch_now() -> u64 {
428 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
429}
430
431#[cfg(unix)]
433fn restrict(path: &Path) -> Result<()> {
434 use std::os::unix::fs::PermissionsExt;
435 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(Error::io(path, "made owner-only"))
436}