Skip to main content

stackless_core/state/
store.rs

1//! SQLite state owned by one controller. Remote clients submit operations to
2//! that controller; they never share database connections.
3
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, Mutex, MutexGuard};
6use std::time::Duration;
7
8use rusqlite::Connection;
9
10use crate::paths::Paths;
11
12use super::error::StateError;
13use super::row::Row;
14use super::value::Value;
15
16const MIGRATIONS: &[&str] = &[
17    include_str!("migrations/001_init.sql"),
18    include_str!("migrations/002_definition_dir.sql"),
19    include_str!("migrations/003_reaper.sql"),
20    include_str!("migrations/004_lock_host.sql"),
21    include_str!("migrations/005_dirty.sql"),
22    include_str!("migrations/006_operation_identity.sql"),
23    include_str!("migrations/007_resources.sql"),
24    include_str!("migrations/008_operations.sql"),
25    include_str!("migrations/009_stripe_contexts.sql"),
26    include_str!("migrations/010_secret_history.sql"),
27    include_str!("migrations/011_revisions.sql"),
28    include_str!("migrations/012_execution_grants.sql"),
29    include_str!("migrations/013_operation_inputs.sql"),
30    include_str!("migrations/014_placements.sql"),
31];
32
33#[derive(Clone)]
34pub struct Store {
35    conn: Arc<Mutex<Connection>>,
36}
37
38impl std::fmt::Debug for Store {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Store").finish_non_exhaustive()
41    }
42}
43
44impl Store {
45    /// Open (creating and migrating as needed) a local file store.
46    pub fn open(path: &Path) -> Result<Self, StateError> {
47        if let Some(dir) = path.parent() {
48            std::fs::create_dir_all(dir).map_err(|source| StateError::StateDir {
49                path: dir.display().to_string(),
50                source,
51            })?;
52        }
53        // Never open and close an existing SQLite file outside SQLite. POSIX
54        // closes release this process's database locks held by other connections.
55        #[cfg(unix)]
56        {
57            use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
58            let file_error = |source| StateError::StateFile {
59                path: path.display().to_string(),
60                source,
61            };
62            match std::fs::OpenOptions::new()
63                .create_new(true)
64                .write(true)
65                .mode(0o600)
66                .open(path)
67            {
68                Ok(file) => file
69                    .set_permissions(std::fs::Permissions::from_mode(0o600))
70                    .map_err(file_error)?,
71                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
72                    if !std::fs::symlink_metadata(path)
73                        .map_err(file_error)?
74                        .file_type()
75                        .is_file()
76                    {
77                        return Err(file_error(std::io::Error::other(
78                            "state path must be an ordinary file",
79                        )));
80                    }
81                    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
82                        .map_err(file_error)?;
83                }
84                Err(error) => return Err(file_error(error)),
85            }
86        }
87        let canonical = std::fs::canonicalize(path).map_err(|source| StateError::StateFile {
88            path: path.display().to_string(),
89            source,
90        })?;
91        let conn = Connection::open_with_flags(
92            &canonical,
93            rusqlite::OpenFlags::default() | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW,
94        )
95        .map_err(|source| StateError::Open {
96            path: path.display().to_string(),
97            source,
98        })?;
99        conn.busy_timeout(Duration::from_secs(5))?;
100        conn.pragma_update(None, "journal_mode", "wal")?;
101        conn.pragma_update(None, "foreign_keys", "on")?;
102        let store = Self {
103            conn: Arc::new(Mutex::new(conn)),
104        };
105        store.migrate()?;
106        Ok(store)
107    }
108
109    /// Direct remote databases cannot own lifecycle execution. Kept as an
110    /// explicit error for callers migrating to the controller transport.
111    pub fn open_remote(_url: &str, _token: &str) -> Result<Self, StateError> {
112        Err(StateError::RemoteDisabled)
113    }
114
115    /// Open this controller's local state and reject obsolete fleet config.
116    pub fn open_configured() -> Result<Self, StateError> {
117        Self::open_with_paths(&Paths::from_env())
118    }
119
120    pub fn open_with_paths(paths: &Paths) -> Result<Self, StateError> {
121        if std::env::var_os("STACKLESS_STATE_URL").is_some_and(|url| !url.is_empty()) {
122            return Err(StateError::RemoteDisabled);
123        }
124        Self::open(&paths.db_path())
125    }
126
127    /// `$XDG_STATE_HOME/stackless`, falling back to `~/.local/state/stackless`.
128    pub fn state_dir() -> PathBuf {
129        Paths::from_env().state_dir().to_path_buf()
130    }
131
132    /// The default per-user location: `$XDG_STATE_HOME/stackless/state.db`,
133    /// falling back to `~/.local/state/stackless/state.db`.
134    pub fn default_path() -> PathBuf {
135        Paths::from_env().db_path()
136    }
137
138    fn migrate(&self) -> Result<(), StateError> {
139        let mut conn = self.conn.lock().map_err(|_| StateError::Poisoned)?;
140        let migration_error = |source| StateError::Migrate { source };
141        let transaction = conn
142            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
143            .map_err(migration_error)?;
144        let mut version: i64 = transaction
145            .pragma_query_value(None, "user_version", |row| row.get(0))
146            .map_err(migration_error)?;
147        let legacy: bool = transaction
148            .query_row(
149                "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='_stackless_schema_version')",
150                [],
151                |row| row.get(0),
152            )
153            .map_err(migration_error)?;
154        if legacy {
155            let recorded: i64 = transaction
156                .query_row(
157                    "SELECT COALESCE(MAX(version), 0) FROM _stackless_schema_version",
158                    [],
159                    |row| row.get(0),
160                )
161                .map_err(migration_error)?;
162            if version != 0 && version != recorded {
163                return Err(schema_error("SQLite and legacy schema versions disagree"));
164            }
165            validate_legacy_schema(&transaction, recorded)?;
166            version = recorded;
167        }
168        if !(0..=MIGRATIONS.len() as i64).contains(&version) {
169            return Err(schema_error(
170                "state schema version is not supported by this controller",
171            ));
172        }
173        for sql in &MIGRATIONS[version as usize..] {
174            transaction.execute_batch(sql).map_err(migration_error)?;
175        }
176        transaction
177            .pragma_update(None, "user_version", MIGRATIONS.len() as i64)
178            .map_err(migration_error)?;
179        if legacy {
180            transaction
181                .execute_batch("DROP TABLE _stackless_schema_version")
182                .map_err(migration_error)?;
183        }
184        transaction.commit().map_err(migration_error)
185    }
186
187    /// Commit a batch only when every statement affects exactly one row.
188    pub(super) fn execute_atomic(
189        &self,
190        statements: &[(&str, Vec<Value>)],
191    ) -> Result<(), StateError> {
192        let mut conn = self.conn.lock().map_err(|_| StateError::Poisoned)?;
193        let transaction =
194            conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
195        for (sql, params) in statements {
196            if transaction.execute(
197                sql,
198                rusqlite::params_from_iter(params.iter().map(to_rusqlite)),
199            )? != 1
200            {
201                return Err(StateError::ResourceInvariant {
202                    detail: "atomic state update did not match its expected owner or revision"
203                        .into(),
204                });
205            }
206        }
207        transaction.commit()?;
208        Ok(())
209    }
210
211    /// Run a statement, returning the number of rows changed.
212    pub(super) fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, StateError> {
213        self.conn
214            .lock()
215            .map_err(|_| StateError::Poisoned)?
216            .execute(
217                sql,
218                rusqlite::params_from_iter(params.iter().map(to_rusqlite)),
219            )
220            .map(|n| n as u64)
221            .map_err(Into::into)
222    }
223
224    /// Query a single row, mapping it to `T`. `None` only when no row
225    /// matched — driver and mapper errors propagate (the `.optional()`
226    /// contract the callers rely on).
227    pub(super) fn query_row<T, F>(
228        &self,
229        sql: &str,
230        params: &[Value],
231        map: F,
232    ) -> Result<Option<T>, StateError>
233    where
234        F: FnOnce(&Row) -> Result<T, StateError>,
235    {
236        match self.query_first(sql, params)? {
237            Some(row) => map(&row).map(Some),
238            None => Ok(None),
239        }
240    }
241
242    /// Query many rows, mapping each to `T`.
243    pub(super) fn query_map<T, F>(
244        &self,
245        sql: &str,
246        params: &[Value],
247        map: F,
248    ) -> Result<Vec<T>, StateError>
249    where
250        F: FnMut(&Row) -> Result<T, StateError>,
251    {
252        let rows = self.collect_rows(sql, params, usize::MAX)?;
253        rows.iter().map(map).collect()
254    }
255
256    /// First row, materialized into the driver-agnostic [`Row`].
257    fn query_first(&self, sql: &str, params: &[Value]) -> Result<Option<Row>, StateError> {
258        Ok(self.collect_rows(sql, params, 1)?.into_iter().next())
259    }
260
261    /// Collect up to `limit` rows into driver-agnostic [`Row`]s.
262    fn collect_rows(
263        &self,
264        sql: &str,
265        params: &[Value],
266        limit: usize,
267    ) -> Result<Vec<Row>, StateError> {
268        let conn = self.conn.lock().map_err(|_| StateError::Poisoned)?;
269        let mut stmt = conn.prepare(sql)?;
270        let col_count = stmt.column_count();
271        let mut out = Vec::new();
272        let mut rows = stmt.query(rusqlite::params_from_iter(params.iter().map(to_rusqlite)))?;
273        while let Some(row) = rows.next()? {
274            let mut columns = Vec::with_capacity(col_count);
275            for i in 0..col_count {
276                columns.push(from_rusqlite(row, i)?);
277            }
278            out.push(Row::from_columns(columns));
279            if out.len() >= limit {
280                break;
281            }
282        }
283        Ok(out)
284    }
285
286    /// Raw connection access for tests that deliberately corrupt state.
287    #[doc(hidden)]
288    #[allow(clippy::expect_used)]
289    pub fn conn_for_tests(&self) -> MutexGuard<'_, Connection> {
290        self.conn.lock().expect("test database mutex poisoned")
291    }
292
293    /// Run an arbitrary statement for tests that inject stale or foreign claims.
294    #[doc(hidden)]
295    pub fn execute_for_tests(&self, sql: &str, params: &[&str]) -> Result<u64, StateError> {
296        let owned: Vec<Value> = params
297            .iter()
298            .map(|s| Value::Text((*s).to_owned()))
299            .collect();
300        self.execute(sql, &owned)
301    }
302
303    /// This machine's hostname. Imported claims retain their original host.
304    /// Empty only if the OS refuses to report one.
305    pub(super) fn hostname() -> String {
306        sysinfo::System::host_name().unwrap_or_default()
307    }
308
309    /// Unix seconds; the one clock all state rows share.
310    pub(super) fn now() -> i64 {
311        std::time::SystemTime::now()
312            .duration_since(std::time::UNIX_EPOCH)
313            .map(|d| d.as_secs() as i64)
314            .unwrap_or(0)
315    }
316
317    /// The shared clock, for callers outside the store (the reaper's
318    /// tick). Same value [`Store::now`] writes into rows.
319    pub fn now_secs() -> i64 {
320        Self::now()
321    }
322}
323
324fn schema_error(message: &str) -> StateError {
325    StateError::Migrate {
326        source: rusqlite::Error::SqliteFailure(
327            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_SCHEMA),
328            Some(message.into()),
329        ),
330    }
331}
332
333/// A legacy export must match the schema its version table claims. Never skip
334/// migrations based only on that marker or infer ownership from missing tables.
335fn validate_legacy_schema(conn: &Connection, version: i64) -> Result<(), StateError> {
336    if !(0..=MIGRATIONS.len() as i64).contains(&version) {
337        return Err(schema_error(
338            "legacy export schema version is not supported",
339        ));
340    }
341    let expected = Connection::open_in_memory()?;
342    for sql in &MIGRATIONS[..version as usize] {
343        expected.execute_batch(sql)?;
344    }
345    if schema_shape(conn)? != schema_shape(&expected)? {
346        return Err(schema_error(
347            "legacy export schema does not match its recorded version; complete the export before migration",
348        ));
349    }
350    Ok(())
351}
352
353type ColumnShape = (String, String, bool, Option<String>, i64);
354type SchemaShape = Vec<(String, String, String, Vec<ColumnShape>)>;
355
356fn schema_shape(conn: &Connection) -> Result<SchemaShape, StateError> {
357    let mut objects = conn.prepare(
358        "SELECT type, name, tbl_name FROM sqlite_schema
359         WHERE name NOT LIKE 'sqlite_%' AND name != '_stackless_schema_version'
360         ORDER BY type, name",
361    )?;
362    let objects: Vec<(String, String, String)> = objects
363        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))?
364        .collect::<Result<_, _>>()?;
365    let mut shape = Vec::new();
366    for (kind, name, table) in objects {
367        let columns = if kind == "table" {
368            conn.prepare(r#"SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info(?1) ORDER BY cid"#)?
369                .query_map([&name], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)))?
370                .collect::<Result<_, _>>()?
371        } else {
372            Vec::new()
373        };
374        shape.push((kind, name, table, columns));
375    }
376    Ok(shape)
377}
378
379// ── local driver bridges ──────────────────────────────────────────────
380
381fn to_rusqlite(v: &Value) -> Box<dyn rusqlite::types::ToSql> {
382    match v {
383        Value::Text(s) => Box::new(s.clone()),
384        Value::Int(i) => Box::new(*i),
385        Value::Null => Box::new(rusqlite::types::Null),
386    }
387}
388
389fn from_rusqlite(row: &rusqlite::Row<'_>, idx: usize) -> Result<Value, StateError> {
390    use rusqlite::types::ValueRef;
391    Ok(match row.get_ref(idx)? {
392        ValueRef::Null => Value::Null,
393        ValueRef::Integer(i) => Value::Int(i),
394        ValueRef::Text(t) => Value::Text(String::from_utf8_lossy(t).into_owned()),
395        ValueRef::Real(_) => {
396            return Err(StateError::row_type(idx, "int|text|null (got real)"));
397        }
398        ValueRef::Blob(_) => {
399            return Err(StateError::row_type(idx, "int|text|null (got blob)"));
400        }
401    })
402}