Files
tessera/crates/tessera-hub/src/db.rs

423 lines
14 KiB
Rust

use anyhow::Result;
use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path;
use std::sync::{Arc, Mutex};
use tessera_core::decay::RetentionPolicy;
use uuid::Uuid;
#[derive(Clone)]
pub struct Db {
conn: Arc<Mutex<Connection>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct OrbitRow {
pub id: Uuid,
pub name: String,
pub provider: String,
pub provider_config: String,
pub schedule: Option<String>,
pub decay_preset: String,
#[serde(default)]
pub retention: Option<RetentionPolicy>,
pub dry_run: bool,
pub last_status: String,
}
impl Db {
pub async fn connect(path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let conn = Connection::open(path)?;
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
}
pub async fn migrate(&self) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS orbits (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
provider TEXT NOT NULL,
provider_config TEXT NOT NULL,
schedule TEXT,
decay_preset TEXT NOT NULL DEFAULT 'week-of-dailies',
dry_run INTEGER NOT NULL DEFAULT 0,
last_status TEXT NOT NULL DEFAULT 'idle'
);
CREATE TABLE IF NOT EXISTS outposts (
id TEXT PRIMARY KEY,
name TEXT,
last_seen TEXT,
pairing_state TEXT NOT NULL DEFAULT 'unpaired'
);
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
event TEXT NOT NULL,
detail TEXT
);
CREATE TABLE IF NOT EXISTS upload_sessions (
id TEXT PRIMARY KEY,
outpost_id TEXT,
orbit_id TEXT,
offset INTEGER NOT NULL DEFAULT 0,
total INTEGER,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS wormhole_tokens (
token TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
code TEXT NOT NULL,
state TEXT NOT NULL,
expires_at TEXT NOT NULL,
outpost_name TEXT
);
CREATE TABLE IF NOT EXISTS upload_ranges (
session_id TEXT NOT NULL,
start_off INTEGER NOT NULL,
end_off INTEGER NOT NULL
);
"#,
)?;
ensure_column(
&conn,
"upload_sessions",
"sealed",
"INTEGER NOT NULL DEFAULT 0",
)?;
ensure_column(&conn, "orbits", "retention", "TEXT")?;
Ok(())
}
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention FROM orbits ORDER BY name")?;
let rows = stmt.query_map([], |r| {
Ok(OrbitRow {
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
name: r.get(1)?,
provider: r.get(2)?,
provider_config: r.get(3)?,
schedule: r.get(4)?,
decay_preset: r.get(5)?,
retention: r
.get::<_, Option<String>>(8)?
.map(|json| {
serde_json::from_str(&json).map_err(|error| {
rusqlite::Error::FromSqlConversionFailure(
8,
rusqlite::types::Type::Text,
Box::new(error),
)
})
})
.transpose()?,
dry_run: r.get::<_, i64>(6)? != 0,
last_status: r.get(7)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name, provider=excluded.provider, provider_config=excluded.provider_config,
schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run,
retention=excluded.retention"#,
params![
row.id.to_string(),
row.name,
row.provider,
row.provider_config,
row.schedule,
row.decay_preset,
row.dry_run as i64,
row.last_status,
row.retention.as_ref().map(serde_json::to_string).transpose()?,
],
)?;
Ok(())
}
pub fn set_orbit_retention(
&self,
id: Uuid,
preset: &str,
policy: Option<&RetentionPolicy>,
) -> Result<bool> {
let json = policy.map(serde_json::to_string).transpose()?;
let changed = self.conn.lock().unwrap().execute(
"UPDATE orbits SET decay_preset = ?1, retention = ?2 WHERE id = ?3",
params![preset, json, id.to_string()],
)?;
Ok(changed > 0)
}
pub fn orbit_retention(&self, id: Uuid) -> Result<(String, Option<RetentionPolicy>)> {
let row: Option<(String, Option<String>)> = self
.conn
.lock()
.unwrap()
.query_row(
"SELECT decay_preset, retention FROM orbits WHERE id = ?1",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let (preset, json) = row.unwrap_or_else(|| ("week-of-dailies".into(), None));
Ok((
preset,
json.as_deref().map(serde_json::from_str).transpose()?,
))
}
pub async fn set_orbit_status(&self, id: Uuid, status: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE orbits SET last_status = ?1 WHERE id = ?2",
params![status, id.to_string()],
)?;
Ok(())
}
pub async fn audit(&self, event: &str, detail: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), ?1, ?2)",
params![event, detail],
)?;
Ok(())
}
pub fn insert_upload_session(
&self,
id: &str,
orbit_id: &str,
total: Option<i64>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))",
params![id, orbit_id, total],
)?;
Ok(())
}
pub fn insert_wormhole_token(
&self,
token: &str,
outpost_id: &str,
code: &str,
expires_at: &str,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)",
params![token, outpost_id, code, expires_at],
)?;
Ok(())
}
pub fn claim_wormhole_code(
&self,
code: &str,
outpost_name: &str,
now: &str,
) -> Result<Option<(String, String)>> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2 WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3",
params![code, outpost_name, now],
)?;
if changed != 1 {
return Ok(None);
}
let mut stmt = conn.prepare(
"SELECT token, outpost_id FROM wormhole_tokens WHERE code = ?1 AND state = 'active'",
)?;
let mut rows = stmt.query(params![code])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
Ok(Some((row.get(0)?, row.get(1)?)))
}
pub fn upload_token_active(&self, token: &str) -> Result<bool> {
Ok(self.upload_token_outpost(token)?.is_some())
}
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT outpost_id FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
params![token], |row| row.get(0),
).optional()?)
}
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT orbit_id, total, sealed FROM upload_sessions WHERE id = ?1",
)?;
let mut rows = stmt.query(params![id])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
let orbit_id: String = row.get(0)?;
let total: Option<i64> = row.get(1)?;
let sealed: i64 = row.get(2)?;
Ok(Some(UploadSession {
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
total: total.unwrap_or(0).max(0) as u64,
sealed: sealed != 0,
}))
}
/// Records a received range. Returns whether this call won the right to seal.
pub fn record_range(&self, session_id: &str, start: u64, end: u64, total: u64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute_batch("BEGIN IMMEDIATE")?;
let outcome = (|| -> Result<bool> {
let sealed: i64 = conn.query_row(
"SELECT sealed FROM upload_sessions WHERE id = ?1",
params![session_id],
|row| row.get(0),
)?;
if sealed != 0 {
return Ok(false);
}
conn.execute(
"INSERT INTO upload_ranges (session_id, start_off, end_off) VALUES (?1, ?2, ?3)",
params![session_id, start as i64, end as i64],
)?;
let mut stmt =
conn.prepare("SELECT start_off, end_off FROM upload_ranges WHERE session_id = ?1")?;
let ranges = stmt
.query_map(params![session_id], |row| {
Ok(crate::upload::ByteRange {
start: row.get::<_, i64>(0)? as u64,
end: row.get::<_, i64>(1)? as u64,
})
})?
.collect::<Result<Vec<_>, _>>()?;
let covered = crate::upload::contiguous_from_zero(&ranges);
conn.execute(
"UPDATE upload_sessions SET offset = ?2 WHERE id = ?1",
params![session_id, covered as i64],
)?;
if covered >= total {
conn.execute(
"UPDATE upload_sessions SET sealed = 1 WHERE id = ?1 AND sealed = 0",
params![session_id],
)?;
return Ok(true);
}
Ok(false)
})();
match outcome {
Ok(value) => {
conn.execute_batch("COMMIT")?;
Ok(value)
}
Err(error) => {
let _ = conn.execute_batch("ROLLBACK");
Err(error)
}
}
}
pub fn mark_upload_unsealed(&self, session_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE upload_sessions SET sealed = 0 WHERE id = ?1",
params![session_id],
)?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct UploadSession {
pub orbit_id: Uuid,
pub total: u64,
pub sealed: bool,
}
fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
for name in names {
if name? == column {
return Ok(());
}
}
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn existing_orbit_can_switch_between_preset_and_custom_retention() {
let conn = Connection::open_in_memory().unwrap();
let id = Uuid::new_v4();
conn.execute_batch(
"CREATE TABLE orbits (
id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT,
schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT
)",
)
.unwrap();
conn.execute(
"INSERT INTO orbits VALUES (?1, 'archive', 'filesystem', '{}', NULL,
'month-of-weeklies', 0, 'completed')",
[id.to_string()],
)
.unwrap();
let db = Db {
conn: Arc::new(Mutex::new(conn)),
};
db.migrate().await.unwrap();
assert_eq!(
db.orbit_retention(id).unwrap(),
("month-of-weeklies".into(), None)
);
let policy = RetentionPolicy {
keep_daily: 7,
keep_weekly: 2,
keep_monthly: 6,
keep_yearly: 3,
};
assert!(db
.set_orbit_retention(id, "week-of-dailies", Some(&policy))
.unwrap());
let orbit = db.list_orbits().await.unwrap().remove(0);
assert_eq!(orbit.retention, Some(policy));
assert_eq!(orbit.last_status, "completed");
assert_eq!(db.orbit_retention(id).unwrap().1, Some(policy));
assert!(db
.set_orbit_retention(id, "year-of-monthlies", None)
.unwrap());
assert_eq!(
db.orbit_retention(id).unwrap(),
("year-of-monthlies".into(), None)
);
assert!(!db
.set_orbit_retention(Uuid::new_v4(), "year-of-monthlies", None)
.unwrap());
}
}