use slabs_core::{SlabError, SlabResult};
use sqlx::{
migrate::Migrator,
postgres::PgPoolOptions,
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
PgPool, Postgres, Sqlite, SqlitePool, Transaction,
};
use std::fmt::Write as _;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
pub use sqlx::QueryBuilder;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DbEngine {
Sqlite,
Postgres,
}
impl DbEngine {
#[must_use]
pub fn detect(database_url: &str) -> Self {
let lower = database_url.trim().to_ascii_lowercase();
if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
Self::Postgres
} else {
Self::Sqlite
}
}
}
pub const SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
token_hash TEXT NOT NULL UNIQUE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
CREATE TABLE IF NOT EXISTS slabs_magic_links (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
purpose TEXT NOT NULL DEFAULT 'sign_in',
code_hash TEXT NOT NULL UNIQUE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
CREATE TABLE IF NOT EXISTS slabs_access_tokens (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
description TEXT NOT NULL DEFAULT '',
permission TEXT NOT NULL DEFAULT 'write',
token_hash TEXT NOT NULL UNIQUE,
last_used_at TEXT,
expires_at TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
CREATE TABLE IF NOT EXISTS slabs_jobs (
id TEXT PRIMARY KEY NOT NULL,
job_name TEXT NOT NULL,
queue TEXT NOT NULL DEFAULT 'default',
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
run_at TEXT NOT NULL,
locked_until TEXT,
last_error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
CREATE TABLE IF NOT EXISTS slabs_cache (
cache_key TEXT PRIMARY KEY NOT NULL,
value_text TEXT NOT NULL,
expires_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
id TEXT PRIMARY KEY NOT NULL,
from_addr TEXT NOT NULL,
to_addr TEXT NOT NULL,
subject TEXT NOT NULL,
text_body TEXT NOT NULL,
html_body TEXT,
sent_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS slabs_blobs (
id TEXT PRIMARY KEY NOT NULL,
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
byte_size INTEGER NOT NULL,
checksum_sha256 TEXT NOT NULL,
storage_key TEXT NOT NULL UNIQUE,
scope TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS slabs_webhooks (
id TEXT PRIMARY KEY NOT NULL,
scope_id TEXT NOT NULL,
name TEXT NOT NULL,
url TEXT NOT NULL,
signing_secret TEXT NOT NULL,
subscribed_actions_json TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
id TEXT PRIMARY KEY NOT NULL,
webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
action TEXT NOT NULL,
payload_json TEXT NOT NULL,
signature TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
response_status INTEGER,
last_error TEXT,
created_at TEXT NOT NULL,
delivered_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
scope TEXT NOT NULL,
key TEXT NOT NULL,
response_json TEXT,
expires_at TEXT,
created_at TEXT NOT NULL,
PRIMARY KEY (scope, key)
);
CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
CREATE TABLE IF NOT EXISTS slabs_audit_log (
id TEXT PRIMARY KEY NOT NULL,
actor_id TEXT,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id TEXT NOT NULL,
metadata_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
CREATE TABLE IF NOT EXISTS slabs_incidents (
id TEXT PRIMARY KEY,
fingerprint TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL,
source_file TEXT NOT NULL,
route_pattern TEXT,
status_code INTEGER,
error_message TEXT NOT NULL,
detail TEXT,
context_json TEXT NOT NULL,
git_sha TEXT,
occurrences INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL DEFAULT 'open',
resolved_in_sha TEXT,
recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
ON slabs_incidents (status, last_seen_at DESC);
";
pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
CREATE TABLE IF NOT EXISTS slabs_magic_links (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
purpose TEXT NOT NULL DEFAULT 'sign_in',
code_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
CREATE TABLE IF NOT EXISTS slabs_access_tokens (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
description TEXT NOT NULL DEFAULT '',
permission TEXT NOT NULL DEFAULT 'write',
token_hash TEXT NOT NULL UNIQUE,
last_used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
CREATE TABLE IF NOT EXISTS slabs_jobs (
id TEXT PRIMARY KEY NOT NULL,
job_name TEXT NOT NULL,
queue TEXT NOT NULL DEFAULT 'default',
payload_json JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
attempts BIGINT NOT NULL DEFAULT 0,
max_attempts BIGINT NOT NULL DEFAULT 5,
run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
locked_until TIMESTAMPTZ,
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
CREATE TABLE IF NOT EXISTS slabs_cache (
cache_key TEXT PRIMARY KEY NOT NULL,
value_text TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
id TEXT PRIMARY KEY NOT NULL,
from_addr TEXT NOT NULL,
to_addr TEXT NOT NULL,
subject TEXT NOT NULL,
text_body TEXT NOT NULL,
html_body TEXT,
sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS slabs_blobs (
id TEXT PRIMARY KEY NOT NULL,
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
byte_size BIGINT NOT NULL,
checksum_sha256 TEXT NOT NULL,
storage_key TEXT NOT NULL UNIQUE,
scope TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS slabs_webhooks (
id TEXT PRIMARY KEY NOT NULL,
scope_id TEXT NOT NULL,
name TEXT NOT NULL,
url TEXT NOT NULL,
signing_secret TEXT NOT NULL,
subscribed_actions_json JSONB NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
id TEXT PRIMARY KEY NOT NULL,
webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
action TEXT NOT NULL,
payload_json JSONB NOT NULL,
signature TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
response_status INTEGER,
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
delivered_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
scope TEXT NOT NULL,
key TEXT NOT NULL,
response_json TEXT,
expires_at TIMESTAMPTZ,
created_at TEXT NOT NULL,
PRIMARY KEY (scope, key)
);
CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
CREATE TABLE IF NOT EXISTS slabs_audit_log (
id TEXT PRIMARY KEY NOT NULL,
actor_id TEXT,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id TEXT NOT NULL,
metadata_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
CREATE TABLE IF NOT EXISTS slabs_incidents (
id TEXT PRIMARY KEY,
fingerprint TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL,
source_file TEXT NOT NULL,
route_pattern TEXT,
status_code INTEGER,
error_message TEXT NOT NULL,
detail TEXT,
context_json TEXT NOT NULL,
git_sha TEXT,
occurrences INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL DEFAULT 'open',
resolved_in_sha TEXT,
recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
ON slabs_incidents (status, last_seen_at DESC);
";
#[must_use]
pub fn fts5_query(raw: &str) -> Option<String> {
let terms: Vec<String> = raw
.split_whitespace()
.map(|tok| {
tok.chars()
.filter(|&ch| ch != '"' && !ch.is_ascii_control())
.take(64)
.collect::<String>()
})
.filter(|tok| !tok.is_empty())
.take(16)
.map(|tok| format!("\"{tok}\"*"))
.collect();
if terms.is_empty() {
None
} else {
Some(terms.join(" AND "))
}
}
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct Pagination {
pub limit: Option<u32>,
pub cursor: Option<String>,
}
impl Pagination {
#[must_use]
pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
let upper = max_limit.max(1);
let raw = self.limit.unwrap_or(default_limit);
i64::from(raw.clamp(1, upper))
}
#[must_use]
pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
self.clamped_limit(default_limit, max_limit) + 1
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CursorPage<T> {
pub items: Vec<T>,
pub next_cursor: Option<String>,
pub has_more: bool,
}
impl<T> CursorPage<T> {
#[must_use]
pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
let has_more = rows.len() > limit;
if has_more {
rows.truncate(limit);
}
let next_cursor = if has_more {
rows.last().map(cursor_fn)
} else {
None
};
Self {
items: rows,
next_cursor,
has_more,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct AuditEntry {
pub id: String,
pub actor_id: Option<String>,
pub action: String,
pub target_type: String,
pub target_id: String,
pub metadata_json: String,
pub created_at: String,
}
#[derive(Debug, Clone)]
pub struct AuditLog {
db: Db,
}
impl AuditLog {
#[must_use]
pub fn new(db: Db) -> Self {
Self { db }
}
pub async fn record_in_tx(
&self,
tx: &mut Transaction<'_, Sqlite>,
actor_id: Option<&str>,
action: &str,
target_type: &str,
target_id: &str,
metadata: &serde_json::Value,
) -> SlabResult<String> {
let id = slabs_core::id::new("aud");
let created_at = chrono::Utc::now().to_rfc3339();
let metadata_json = serde_json::to_string(metadata)
.map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;
sqlx::query(
"INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(actor_id)
.bind(action)
.bind(target_type)
.bind(target_id)
.bind(&metadata_json)
.bind(&created_at)
.execute(&mut **tx)
.await?;
Ok(id)
}
pub async fn list_for_target(
&self,
target_type: &str,
target_id: &str,
limit: i64,
) -> SlabResult<Vec<AuditEntry>> {
let limit = limit.clamp(1, 500);
let rows: Vec<AuditEntry> = sqlx::query_as(
"SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
FROM slabs_audit_log
WHERE target_type = ? AND target_id = ?
ORDER BY created_at DESC, id DESC
LIMIT ?",
)
.bind(target_type)
.bind(target_id)
.bind(limit)
.fetch_all(self.db.reader())
.await?;
Ok(rows)
}
pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
let limit = limit.clamp(1, 500);
let rows: Vec<AuditEntry> = sqlx::query_as(
"SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
FROM slabs_audit_log
ORDER BY created_at DESC, id DESC
LIMIT ?",
)
.bind(limit)
.fetch_all(self.db.reader())
.await?;
Ok(rows)
}
}
const MAX_INCIDENT_ERROR_BYTES: usize = 1024;
const MAX_INCIDENT_DETAIL_BYTES: usize = 4096;
const MAX_RECENT_OCCURRENCES: usize = 10;
fn append_recent_occurrence(existing_json: &str, snapshot: serde_json::Value) -> String {
let mut items =
serde_json::from_str::<Vec<serde_json::Value>>(existing_json).unwrap_or_default();
items.push(snapshot);
if items.len() > MAX_RECENT_OCCURRENCES {
let drain_count = items.len() - MAX_RECENT_OCCURRENCES;
items.drain(..drain_count);
}
serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_owned())
}
fn truncate_utf8(input: &str, max_bytes: usize) -> &str {
if input.len() <= max_bytes {
return input;
}
let mut end = max_bytes;
while end > 0 && !input.is_char_boundary(end) {
end -= 1;
}
&input[..end]
}
fn format_utc_micros(dt: chrono::DateTime<chrono::Utc>) -> String {
dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct IncidentRecord {
pub id: String,
pub fingerprint: String,
pub kind: String,
pub source_file: String,
pub route_pattern: Option<String>,
pub status_code: Option<i64>,
pub error_message: String,
pub detail: Option<String>,
pub context_json: String,
pub git_sha: Option<String>,
pub occurrences: i64,
pub status: String,
pub resolved_in_sha: Option<String>,
pub recent_occurrences_json: String,
pub first_seen_at: String,
pub last_seen_at: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IncidentOutcome {
Opened,
Reopened,
Incremented,
}
#[derive(Debug, Clone)]
pub struct IncidentInput {
pub kind: String,
pub source_file: String,
pub route_pattern: Option<String>,
pub status_code: Option<i64>,
pub error_message: String,
pub detail: Option<String>,
pub context_json: serde_json::Value,
pub git_sha: Option<String>,
pub custom_fingerprint: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Incidents {
db: Db,
}
impl Incidents {
#[must_use]
pub fn new(db: Db) -> Self {
Self { db }
}
pub async fn record_with_outcome(
&self,
input: IncidentInput,
) -> SlabResult<(IncidentRecord, IncidentOutcome)> {
let fingerprint = if let Some(custom) = input
.custom_fingerprint
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
slabs_core::fingerprint(&["custom", custom])
} else if input.kind == "user_bug_report" {
let nonce = slabs_core::id::new("bug");
slabs_core::fingerprint(&[
&input.kind,
&input.source_file,
input.route_pattern.as_deref().unwrap_or(""),
&input.error_message,
&nonce,
])
} else {
slabs_core::fingerprint(&[
&input.kind,
&input.source_file,
input.route_pattern.as_deref().unwrap_or(""),
&input.error_message,
])
};
let error_message =
truncate_utf8(&input.error_message, MAX_INCIDENT_ERROR_BYTES).to_owned();
let detail = input
.detail
.as_deref()
.map(|d| truncate_utf8(d, MAX_INCIDENT_DETAIL_BYTES).to_owned());
let context_json = serde_json::to_string(&input.context_json).map_err(|e| {
SlabError::internal(format!("failed to serialize incident context: {e}"))
})?;
let now = format_utc_micros(chrono::Utc::now());
let occurrence_snapshot = serde_json::json!({
"seen_at": now,
"git_sha": input.git_sha,
"request_id": input.context_json.get("request_id"),
"latency_ms": input.context_json.get("latency_ms"),
});
let mut tx = self.db.begin().await?;
let existing: Option<IncidentRecord> = sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
WHERE fingerprint = ?",
)
.bind(&fingerprint)
.fetch_optional(&mut *tx)
.await?;
let (record, outcome) = if let Some(prev) = existing {
let reopened = prev.status == "resolved";
let next_status = if reopened {
"reopened".to_owned()
} else {
prev.status.clone()
};
let next_resolved_in_sha = if reopened {
None
} else {
prev.resolved_in_sha.clone()
};
let next_occurrences = prev.occurrences + 1;
let next_recent_occurrences_json =
append_recent_occurrence(&prev.recent_occurrences_json, occurrence_snapshot);
sqlx::query(
"UPDATE slabs_incidents
SET occurrences = ?,
last_seen_at = ?,
detail = ?,
context_json = ?,
git_sha = ?,
status = ?,
resolved_in_sha = ?,
recent_occurrences_json = ?
WHERE id = ?",
)
.bind(next_occurrences)
.bind(&now)
.bind(&detail)
.bind(&context_json)
.bind(&input.git_sha)
.bind(&next_status)
.bind(&next_resolved_in_sha)
.bind(&next_recent_occurrences_json)
.bind(&prev.id)
.execute(&mut *tx)
.await?;
let updated = IncidentRecord {
id: prev.id,
fingerprint: prev.fingerprint,
kind: prev.kind,
source_file: prev.source_file,
route_pattern: prev.route_pattern,
status_code: prev.status_code,
error_message: prev.error_message,
detail,
context_json,
git_sha: input.git_sha,
occurrences: next_occurrences,
status: next_status,
resolved_in_sha: next_resolved_in_sha,
recent_occurrences_json: next_recent_occurrences_json,
first_seen_at: prev.first_seen_at,
last_seen_at: now,
};
let outcome = if reopened {
IncidentOutcome::Reopened
} else {
IncidentOutcome::Incremented
};
(updated, outcome)
} else {
let id = slabs_core::id::new("inc");
let recent_occurrences_json = append_recent_occurrence("[]", occurrence_snapshot);
sqlx::query(
"INSERT INTO slabs_incidents (
id, fingerprint, kind, source_file, route_pattern, status_code,
error_message, detail, context_json, git_sha, occurrences,
status, resolved_in_sha, recent_occurrences_json, first_seen_at, last_seen_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'open', NULL, ?, ?, ?)",
)
.bind(&id)
.bind(&fingerprint)
.bind(&input.kind)
.bind(&input.source_file)
.bind(&input.route_pattern)
.bind(input.status_code)
.bind(&error_message)
.bind(&detail)
.bind(&context_json)
.bind(&input.git_sha)
.bind(&recent_occurrences_json)
.bind(&now)
.bind(&now)
.execute(&mut *tx)
.await?;
let inserted = IncidentRecord {
id,
fingerprint,
kind: input.kind,
source_file: input.source_file,
route_pattern: input.route_pattern,
status_code: input.status_code,
error_message,
detail,
context_json,
git_sha: input.git_sha,
occurrences: 1,
status: "open".to_owned(),
resolved_in_sha: None,
recent_occurrences_json,
first_seen_at: now.clone(),
last_seen_at: now,
};
(inserted, IncidentOutcome::Opened)
};
tx.commit().await?;
Ok((record, outcome))
}
pub async fn record(&self, input: IncidentInput) -> SlabResult<(IncidentRecord, bool)> {
let (record, outcome) = self.record_with_outcome(input).await?;
Ok((
record,
matches!(outcome, IncidentOutcome::Opened | IncidentOutcome::Reopened),
))
}
pub async fn list(&self, status: Option<&str>, limit: i64) -> SlabResult<Vec<IncidentRecord>> {
let limit = limit.clamp(1, 500);
let filter = status.map(str::trim).filter(|s| !s.is_empty());
let rows: Vec<IncidentRecord> = match filter {
None => {
sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
WHERE status IN ('open', 'reopened')
ORDER BY last_seen_at DESC, id DESC
LIMIT ?",
)
.bind(limit)
.fetch_all(self.db.reader())
.await?
}
Some(st) if st.eq_ignore_ascii_case("active") => {
sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
WHERE status IN ('open', 'reopened')
ORDER BY last_seen_at DESC, id DESC
LIMIT ?",
)
.bind(limit)
.fetch_all(self.db.reader())
.await?
}
Some(st) if st.eq_ignore_ascii_case("all") => {
sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
ORDER BY last_seen_at DESC, id DESC
LIMIT ?",
)
.bind(limit)
.fetch_all(self.db.reader())
.await?
}
Some(st) => {
sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
WHERE status = ?
ORDER BY last_seen_at DESC, id DESC
LIMIT ?",
)
.bind(st)
.bind(limit)
.fetch_all(self.db.reader())
.await?
}
};
Ok(rows)
}
pub async fn get(&self, id: &str) -> SlabResult<Option<IncidentRecord>> {
let row: Option<IncidentRecord> = sqlx::query_as(
"SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
detail, context_json, git_sha, occurrences, status, resolved_in_sha,
recent_occurrences_json, first_seen_at, last_seen_at
FROM slabs_incidents
WHERE id = ?",
)
.bind(id)
.fetch_optional(self.db.reader())
.await?;
Ok(row)
}
pub async fn resolve(&self, id: &str, resolved_in_sha: Option<&str>) -> SlabResult<bool> {
let now = format_utc_micros(chrono::Utc::now());
let res = sqlx::query(
"UPDATE slabs_incidents
SET status = 'resolved',
resolved_in_sha = ?,
last_seen_at = ?
WHERE id = ?",
)
.bind(resolved_in_sha)
.bind(&now)
.bind(id)
.execute(self.db.writer())
.await?;
Ok(res.rows_affected() > 0)
}
pub async fn close_stale(&self, stale_days: u64) -> SlabResult<u64> {
if stale_days == 0 {
return Ok(0);
}
let days = i64::try_from(stale_days.min(3650)).unwrap_or(3650);
let now_dt = chrono::Utc::now();
let cutoff_dt = now_dt
.checked_sub_signed(chrono::Duration::days(days))
.ok_or_else(|| SlabError::internal("stale incident cutoff timestamp overflow"))?;
let now = format_utc_micros(now_dt);
let cutoff = format_utc_micros(cutoff_dt);
let res = sqlx::query(
"UPDATE slabs_incidents
SET status = 'resolved',
resolved_in_sha = COALESCE(resolved_in_sha, 'auto:stale'),
last_seen_at = ?
WHERE status IN ('open', 'reopened')
AND last_seen_at < ?",
)
.bind(&now)
.bind(&cutoff)
.execute(self.db.writer())
.await?;
Ok(res.rows_affected())
}
pub async fn count_open(&self) -> SlabResult<i64> {
let (count,): (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM slabs_incidents WHERE status IN ('open', 'reopened')",
)
.fetch_one(self.db.reader())
.await?;
Ok(count)
}
}
#[derive(Debug, Clone)]
pub struct Db {
read_pool: SqlitePool,
write_pool: SqlitePool,
}
impl Db {
pub async fn connect(database_url: &str) -> SlabResult<Self> {
let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");
let mut write_opts = SqliteConnectOptions::from_str(database_url)
.map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
.create_if_missing(true)
.foreign_keys(true)
.busy_timeout(Duration::from_secs(10))
.synchronous(SqliteSynchronous::Normal)
.pragma("cache_size", "-64000")
.pragma("temp_store", "MEMORY")
.pragma("trusted_schema", "OFF")
.pragma("secure_delete", "ON");
if !is_memory {
write_opts = write_opts
.journal_mode(SqliteJournalMode::Wal)
.pragma("mmap_size", "268435456");
}
let write_pool = SqlitePoolOptions::new()
.max_connections(1)
.acquire_timeout(Duration::from_secs(10))
.connect_with(write_opts)
.await?;
let read_pool = if is_memory {
write_pool.clone()
} else {
let read_opts = SqliteConnectOptions::from_str(database_url)
.map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
.read_only(true)
.foreign_keys(true)
.busy_timeout(Duration::from_secs(5))
.pragma("cache_size", "-64000")
.pragma("temp_store", "MEMORY")
.pragma("trusted_schema", "OFF")
.pragma("mmap_size", "268435456");
SqlitePoolOptions::new()
.max_connections(16)
.acquire_timeout(Duration::from_secs(5))
.connect_with(read_opts)
.await?
};
Ok(Self {
read_pool,
write_pool,
})
}
#[must_use]
pub fn pool(&self) -> &SqlitePool {
&self.write_pool
}
#[must_use]
pub fn reader(&self) -> &SqlitePool {
&self.read_pool
}
#[must_use]
pub fn writer(&self) -> &SqlitePool {
&self.write_pool
}
pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
}
async fn ensure_sqlite_column(
&self,
table: &str,
column: &str,
column_def: &str,
) -> SlabResult<()> {
let query = format!("SELECT name FROM pragma_table_info('{table}')");
let cols: Vec<(String,)> = sqlx::query_as(&query).fetch_all(&self.write_pool).await?;
if !cols.is_empty() && !cols.iter().any(|(name,)| name == column) {
let alter = format!("ALTER TABLE {table} ADD COLUMN {column} {column_def}");
sqlx::raw_sql(&alter).execute(&self.write_pool).await?;
}
Ok(())
}
pub async fn init_system_tables(&self) -> SlabResult<()> {
self.ensure_sqlite_column("slabs_jobs", "locked_until", "TEXT")
.await?;
self.ensure_sqlite_column("slabs_idempotency_keys", "expires_at", "TEXT")
.await?;
self.ensure_sqlite_column("slabs_blobs", "scope", "TEXT")
.await?;
self.ensure_sqlite_column(
"slabs_incidents",
"recent_occurrences_json",
"TEXT NOT NULL DEFAULT '[]'",
)
.await?;
sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
.execute(&self.write_pool)
.await?;
Ok(())
}
pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
self.init_system_tables().await?;
migrator
.run(&self.write_pool)
.await
.map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
Ok(())
}
pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
self.init_system_tables().await?;
let migrator = Migrator::new(dir)
.await
.map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
self.migrate(&migrator).await
}
pub async fn dump_schema_sql(&self) -> SlabResult<String> {
let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
"SELECT type, name, sql
FROM sqlite_master
WHERE sql IS NOT NULL
AND name NOT LIKE 'sqlite_%'
AND name NOT LIKE '_sqlx_%'
ORDER BY
CASE type
WHEN 'table' THEN 1
WHEN 'index' THEN 2
WHEN 'trigger' THEN 3
WHEN 'view' THEN 4
ELSE 5
END,
name ASC",
)
.fetch_all(&self.read_pool)
.await?;
let mut out = String::from(
"-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
);
for (_kind, _name, sql) in rows {
if let Some(stmt) = sql {
out.push_str(stmt.trim());
if !stmt.trim_end().ends_with(';') {
out.push(';');
}
out.push_str("\n\n");
}
}
Ok(out)
}
pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
let sql = std::fs::read_to_string(path).map_err(|e| {
SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
})?;
if sql.trim().is_empty() {
return Ok(());
}
let mut tx = self.begin().await?;
sqlx::raw_sql(&sql).execute(&mut *tx).await?;
tx.commit().await?;
Ok(())
}
pub async fn ping(&self) -> SlabResult<()> {
let _: (i64,) = sqlx::query_as("SELECT 1")
.fetch_one(&self.read_pool)
.await?;
Ok(())
}
pub async fn checkpoint_and_close(&self) {
if let Err(err) = sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
.execute(&self.write_pool)
.await
{
tracing::warn!(error = %err, "SQLite WAL checkpoint failed during shutdown");
}
self.read_pool.close().await;
self.write_pool.close().await;
}
pub async fn explain_query_plan(&self, sql: &str) -> SlabResult<Vec<String>> {
let trimmed = sql.trim();
if trimmed.is_empty() {
return Err(SlabError::bad_request("SQL query cannot be empty"));
}
if trimmed.contains(';') {
return Err(SlabError::bad_request(
"SQL query must be a single statement without semicolons",
));
}
let starts_select = trimmed.len() > 6
&& trimmed
.get(..6)
.is_some_and(|p| p.eq_ignore_ascii_case("SELECT"))
&& trimmed
.as_bytes()
.get(6)
.is_some_and(u8::is_ascii_whitespace);
let starts_with = trimmed.len() > 4
&& trimmed
.get(..4)
.is_some_and(|p| p.eq_ignore_ascii_case("WITH"))
&& trimmed
.as_bytes()
.get(4)
.is_some_and(u8::is_ascii_whitespace);
if !starts_select && !starts_with {
return Err(SlabError::bad_request(
"only read-only SELECT or WITH queries can be explained",
));
}
let explain_sql = format!("EXPLAIN QUERY PLAN {trimmed}");
let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&explain_sql)
.fetch_all(self.reader())
.await?;
Ok(rows.into_iter().map(|(_, _, _, detail)| detail).collect())
}
}
fn quote_pg_ident(ident: &str) -> String {
format!("\"{}\"", ident.replace('"', "\"\""))
}
#[derive(Debug, Clone)]
pub struct PgDb {
pool: PgPool,
}
impl PgDb {
pub async fn connect(database_url: &str) -> SlabResult<Self> {
let pool = PgPoolOptions::new()
.max_connections(20)
.acquire_timeout(Duration::from_secs(5))
.idle_timeout(Duration::from_secs(300))
.max_lifetime(Duration::from_secs(1800))
.connect(database_url)
.await?;
Ok(Self { pool })
}
#[must_use]
pub fn pool(&self) -> &PgPool {
&self.pool
}
pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
Ok(self.pool.begin().await?)
}
pub async fn init_system_tables(&self) -> SlabResult<()> {
sqlx::raw_sql(
"ALTER TABLE IF EXISTS slabs_jobs ADD COLUMN IF NOT EXISTS locked_until TIMESTAMPTZ;
ALTER TABLE IF EXISTS slabs_idempotency_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
ALTER TABLE IF EXISTS slabs_blobs ADD COLUMN IF NOT EXISTS scope TEXT;
ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS recent_occurrences_json TEXT NOT NULL DEFAULT '[]';",
)
.execute(&self.pool)
.await?;
sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
self.init_system_tables().await?;
migrator
.run(&self.pool)
.await
.map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
Ok(())
}
pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
self.init_system_tables().await?;
let migrator = Migrator::new(dir)
.await
.map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
self.migrate(&migrator).await
}
pub async fn dump_schema_sql(&self) -> SlabResult<String> {
let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
"SELECT table_name, column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name NOT LIKE '_sqlx_%'
ORDER BY table_name ASC, ordinal_position ASC",
)
.fetch_all(&self.pool)
.await?;
let indexes: Vec<(String,)> = sqlx::query_as(
"SELECT indexdef
FROM pg_indexes
WHERE schemaname = 'public'
AND tablename NOT LIKE '_sqlx_%'
ORDER BY tablename ASC, indexname ASC",
)
.fetch_all(&self.pool)
.await?;
let mut out = String::from(
"-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
);
let mut current_table: Option<String> = None;
for (table, col, dtype, nullable, default) in cols {
if current_table.as_deref() == Some(table.as_str()) {
out.push_str(",\n");
} else {
if current_table.is_some() {
out.push_str(");\n\n");
}
let quoted_table = quote_pg_ident(&table);
let _ = writeln!(out, "CREATE TABLE {quoted_table} (");
current_table = Some(table);
}
let quoted_col = quote_pg_ident(&col);
let _ = write!(out, " {quoted_col} {dtype}");
if nullable == "NO" {
out.push_str(" NOT NULL");
}
if let Some(def) = default {
let _ = write!(out, " DEFAULT {def}");
}
}
if current_table.is_some() {
out.push_str("\n);\n\n");
}
for (indexdef,) in indexes {
out.push_str(&indexdef);
if !indexdef.ends_with(';') {
out.push(';');
}
out.push_str("\n\n");
}
Ok(out)
}
pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
let sql = std::fs::read_to_string(path).map_err(|e| {
SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
})?;
if sql.trim().is_empty() {
return Ok(());
}
sqlx::raw_sql(&sql).execute(&self.pool).await?;
Ok(())
}
pub async fn ping(&self) -> SlabResult<()> {
let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_sqlite_and_postgres_urls() {
assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
assert_eq!(
DbEngine::detect("sqlite://app.db?mode=rwc"),
DbEngine::Sqlite
);
assert_eq!(
DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
DbEngine::Postgres
);
assert_eq!(
DbEngine::detect("postgresql://localhost/slabs"),
DbEngine::Postgres
);
}
#[test]
fn fts5_query_safely_quotes_user_input() {
assert_eq!(
fts5_query(r#"hello "world" fts5"#),
Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
);
assert_eq!(fts5_query(" "), None);
}
#[tokio::test]
async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
let path =
std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
let url = format!("sqlite://{}", path.display());
let db = Db::connect(&url).await.unwrap();
sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
.execute(db.writer())
.await
.unwrap();
let mut handles = Vec::new();
for i in 0..24 {
let db_w = db.clone();
handles.push(tokio::spawn(async move {
let mut tx = db_w.begin().await.unwrap();
sqlx::query("INSERT INTO items (val) VALUES (?)")
.bind(format!("item-{i}"))
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
}));
let db_r = db.clone();
handles.push(tokio::spawn(async move {
let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
.fetch_one(db_r.reader())
.await
.unwrap();
}));
}
for h in handles {
h.await.unwrap();
}
let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
.fetch_one(db.reader())
.await
.unwrap();
assert_eq!(total, 24);
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_file(format!("{}-wal", path.display()));
let _ = std::fs::remove_file(format!("{}-shm", path.display()));
}
#[test]
fn pagination_clamps_limits_and_computes_fetch_limit() {
let default_page = Pagination::default();
assert_eq!(default_page.clamped_limit(20, 100), 20);
assert_eq!(default_page.fetch_limit(20, 100), 21);
let zero_page = Pagination {
limit: Some(0),
cursor: None,
};
assert_eq!(zero_page.clamped_limit(20, 100), 1);
assert_eq!(zero_page.fetch_limit(20, 100), 2);
let huge_page = Pagination {
limit: Some(500),
cursor: Some("cur_1".into()),
};
assert_eq!(huge_page.clamped_limit(20, 100), 100);
assert_eq!(huge_page.fetch_limit(20, 100), 101);
assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
}
#[test]
fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
assert_eq!(page.items, vec![10, 20]);
assert!(page.has_more);
assert_eq!(page.next_cursor.as_deref(), Some("20"));
let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
assert_eq!(exact.items, vec![10, 20]);
assert!(!exact.has_more);
assert!(exact.next_cursor.is_none());
let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
assert_eq!(empty.items, Vec::<i32>::new());
assert!(!empty.has_more);
assert!(empty.next_cursor.is_none());
}
#[tokio::test]
async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let audit = AuditLog::new(db.clone());
let mut tx = db.begin().await.unwrap();
let entry_id = audit
.record_in_tx(
&mut tx,
Some("usr_1"),
"room.created",
"room",
"room_1",
&serde_json::json!({ "name": "Lobby" }),
)
.await
.unwrap();
assert!(entry_id.starts_with("aud_"));
tx.commit().await.unwrap();
let mut rollback_tx = db.begin().await.unwrap();
let _rolled_back_id = audit
.record_in_tx(
&mut rollback_tx,
Some("usr_2"),
"room.deleted",
"room",
"room_1",
&serde_json::json!({ "reason": "rolled back" }),
)
.await
.unwrap();
rollback_tx.rollback().await.unwrap();
let mut tx2 = db.begin().await.unwrap();
let _other_id = audit
.record_in_tx(
&mut tx2,
None,
"user.invited",
"user",
"usr_9",
&serde_json::json!({}),
)
.await
.unwrap();
tx2.commit().await.unwrap();
let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
assert_eq!(room_entries.len(), 1);
assert_eq!(room_entries[0].id, entry_id);
assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
assert_eq!(room_entries[0].action, "room.created");
assert_eq!(room_entries[0].target_type, "room");
assert_eq!(room_entries[0].target_id, "room_1");
assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);
let recent = audit.list_recent(10).await.unwrap();
assert_eq!(recent.len(), 2);
let recent_limited = audit.list_recent(1).await.unwrap();
assert_eq!(recent_limited.len(), 1);
}
#[tokio::test]
async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let seed_path = std::env::temp_dir().join(format!(
"slabs_seed_test_{}.sql",
slabs_core::id::new("sql")
));
std::fs::write(
&seed_path,
"CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
)
.unwrap();
db.execute_sql_file(&seed_path).await.unwrap();
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
.fetch_one(db.reader())
.await
.unwrap();
assert_eq!(count, 2);
std::fs::write(&seed_path, " \n\t ").unwrap();
db.execute_sql_file(&seed_path).await.unwrap();
let _ = std::fs::remove_file(&seed_path);
let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
assert!(db.execute_sql_file(&missing).await.is_err());
assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
}
#[test]
fn fts5_query_strips_control_chars_and_caps_tokens_and_lengths() {
assert_eq!(
fts5_query("hello\x00world \x07foo\x7fbar"),
Some("\"helloworld\"* AND \"foobar\"*".to_string())
);
assert_eq!(fts5_query("\0\x01\x1f\x7f"), None);
let many_tokens = (1..=25)
.map(|i| format!("tok{i}"))
.collect::<Vec<_>>()
.join(" ");
let rendered = fts5_query(&many_tokens).unwrap();
assert_eq!(rendered.split(" AND ").count(), 16);
assert!(rendered.contains("\"tok16\"*"));
assert!(!rendered.contains("\"tok17\"*"));
let huge_token = "a".repeat(100);
let rendered_long = fts5_query(&huge_token).unwrap();
assert_eq!(rendered_long, format!("\"{}\"*", "a".repeat(64)));
}
#[tokio::test]
async fn init_system_tables_adds_locked_until_and_expires_at_and_upgrades_legacy_tables() {
let db = Db::connect("sqlite::memory:").await.unwrap();
sqlx::raw_sql(
"CREATE TABLE slabs_jobs (
id TEXT PRIMARY KEY NOT NULL,
job_name TEXT NOT NULL,
queue TEXT NOT NULL DEFAULT 'default',
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
run_at TEXT NOT NULL,
last_error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE slabs_idempotency_keys (
scope TEXT NOT NULL,
key TEXT NOT NULL,
response_json TEXT,
created_at TEXT NOT NULL,
PRIMARY KEY (scope, key)
);
CREATE TABLE slabs_blobs (
id TEXT PRIMARY KEY NOT NULL,
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
byte_size INTEGER NOT NULL,
checksum_sha256 TEXT NOT NULL,
storage_key TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
);
CREATE TABLE slabs_incidents (
id TEXT PRIMARY KEY,
fingerprint TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL,
source_file TEXT NOT NULL,
route_pattern TEXT,
status_code INTEGER,
error_message TEXT NOT NULL,
detail TEXT,
context_json TEXT NOT NULL,
git_sha TEXT,
occurrences INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL DEFAULT 'open',
resolved_in_sha TEXT,
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
);",
)
.execute(db.writer())
.await
.unwrap();
db.init_system_tables().await.unwrap();
db.init_system_tables().await.unwrap();
let job_cols: Vec<(String,)> =
sqlx::query_as("SELECT name FROM pragma_table_info('slabs_jobs')")
.fetch_all(db.reader())
.await
.unwrap();
assert!(job_cols.iter().any(|(c,)| c == "locked_until"));
let idem_cols: Vec<(String,)> =
sqlx::query_as("SELECT name FROM pragma_table_info('slabs_idempotency_keys')")
.fetch_all(db.reader())
.await
.unwrap();
assert!(idem_cols.iter().any(|(c,)| c == "expires_at"));
let blob_cols: Vec<(String,)> =
sqlx::query_as("SELECT name FROM pragma_table_info('slabs_blobs')")
.fetch_all(db.reader())
.await
.unwrap();
assert!(blob_cols.iter().any(|(c,)| c == "scope"));
assert!(SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
let incident_cols: Vec<(String,)> =
sqlx::query_as("SELECT name FROM pragma_table_info('slabs_incidents')")
.fetch_all(db.reader())
.await
.unwrap();
assert!(
incident_cols
.iter()
.any(|(c,)| c == "recent_occurrences_json"),
"missing upgraded column recent_occurrences_json"
);
assert!(SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
for removed in ["assignee", "external_issue_key", "external_issue_url"] {
assert!(!SYSTEM_SCHEMA_SQL.contains(removed));
assert!(!POSTGRES_SYSTEM_SCHEMA_SQL.contains(removed));
}
let (trusted_schema,): (i64,) = sqlx::query_as("PRAGMA trusted_schema")
.fetch_one(db.writer())
.await
.unwrap();
assert_eq!(trusted_schema, 0);
let (secure_delete,): (i64,) = sqlx::query_as("PRAGMA secure_delete")
.fetch_one(db.writer())
.await
.unwrap();
assert_eq!(secure_delete, 1);
}
#[tokio::test]
async fn audit_log_clamps_limits_to_1_through_500() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let audit = AuditLog::new(db.clone());
let mut tx = db.begin().await.unwrap();
for i in 0..3 {
audit
.record_in_tx(
&mut tx,
Some("usr_1"),
"item.updated",
"item",
"item_1",
&serde_json::json!({ "n": i }),
)
.await
.unwrap();
}
tx.commit().await.unwrap();
assert_eq!(audit.list_recent(-1).await.unwrap().len(), 1);
assert_eq!(audit.list_recent(0).await.unwrap().len(), 1);
assert_eq!(
audit
.list_for_target("item", "item_1", -5)
.await
.unwrap()
.len(),
1
);
assert_eq!(
audit
.list_for_target("item", "item_1", 0)
.await
.unwrap()
.len(),
1
);
assert_eq!(audit.list_recent(10_000).await.unwrap().len(), 3);
}
#[tokio::test]
async fn execute_sql_file_rolls_back_on_error() {
let db = Db::connect("sqlite::memory:").await.unwrap();
sqlx::query("CREATE TABLE items (id TEXT PRIMARY KEY)")
.execute(db.writer())
.await
.unwrap();
let seed_path = std::env::temp_dir().join(format!(
"slabs_seed_rollback_{}.sql",
slabs_core::id::new("sql")
));
std::fs::write(
&seed_path,
"INSERT INTO items (id) VALUES ('ok_1');\n\
INSERT INTO items (id) VALUES ('ok_1');\n",
)
.unwrap();
assert!(db.execute_sql_file(&seed_path).await.is_err());
let _ = std::fs::remove_file(&seed_path);
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
.fetch_one(db.reader())
.await
.unwrap();
assert_eq!(count, 0);
}
#[test]
fn quote_pg_ident_escapes_double_quotes() {
assert_eq!(quote_pg_ident("users"), "\"users\"");
assert_eq!(quote_pg_ident("weird\"name"), "\"weird\"\"name\"");
}
#[tokio::test]
async fn incidents_record_deduplicate_list_get_resolve_and_reopen() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let incidents = Incidents::new(db.clone());
assert!(SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
let long_msg = "é".repeat(700); let long_detail = "€".repeat(2000);
let input = IncidentInput {
kind: "panic".into(),
source_file: "slabs/rooms/send_message.rs".into(),
route_pattern: Some("/api/rooms/{room_id}/messages".into()),
status_code: Some(500),
error_message: long_msg.clone(),
detail: Some(long_detail),
context_json: serde_json::json!({ "request_id": "req_1" }),
git_sha: Some("sha_aaa".into()),
custom_fingerprint: None,
};
let (first, is_new) = incidents.record(input.clone()).await.unwrap();
assert!(is_new);
assert!(first.id.starts_with("inc_"));
assert_eq!(first.occurrences, 1);
assert_eq!(first.status, "open");
assert!(first.error_message.len() <= MAX_INCIDENT_ERROR_BYTES);
assert!(first.detail.as_deref().unwrap().len() <= MAX_INCIDENT_DETAIL_BYTES);
assert_eq!(incidents.count_open().await.unwrap(), 1);
let mut second_input = input.clone();
second_input.detail = Some("updated detail".into());
second_input.git_sha = Some("sha_bbb".into());
let (second, is_new_second) = incidents.record(second_input).await.unwrap();
assert!(!is_new_second);
assert_eq!(second.id, first.id);
assert_eq!(second.occurrences, 2);
assert_eq!(second.status, "open");
assert_eq!(second.detail.as_deref(), Some("updated detail"));
assert_eq!(second.git_sha.as_deref(), Some("sha_bbb"));
let fetched = incidents.get(&first.id).await.unwrap().unwrap();
assert_eq!(fetched.id, first.id);
assert_eq!(fetched.occurrences, 2);
assert!(incidents.get("inc_missing").await.unwrap().is_none());
assert!(incidents.resolve(&first.id, Some("sha_fix")).await.unwrap());
assert!(!incidents.resolve("inc_missing", None).await.unwrap());
assert_eq!(incidents.count_open().await.unwrap(), 0);
assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
let resolved_list = incidents.list(Some("resolved"), 10).await.unwrap();
assert_eq!(resolved_list.len(), 1);
assert_eq!(resolved_list[0].resolved_in_sha.as_deref(), Some("sha_fix"));
let (reopened, is_reopened) = incidents.record(input.clone()).await.unwrap();
assert!(is_reopened);
assert_eq!(reopened.id, first.id);
assert_eq!(reopened.status, "reopened");
assert_eq!(reopened.occurrences, 3);
assert!(reopened.resolved_in_sha.is_none());
assert_eq!(incidents.count_open().await.unwrap(), 1);
let (still_reopened, is_new_again) = incidents.record(input).await.unwrap();
assert!(!is_new_again);
assert_eq!(still_reopened.status, "reopened");
assert_eq!(still_reopened.occurrences, 4);
assert_eq!(incidents.list(None, -1).await.unwrap().len(), 1);
assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 1);
assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);
assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
assert_eq!(incidents.list(Some("all"), 999).await.unwrap().len(), 1);
assert!(incidents
.resolve(&first.id, Some("sha_fix_2"))
.await
.unwrap());
assert_eq!(incidents.count_open().await.unwrap(), 0);
assert!(incidents.list(Some("active"), 10).await.unwrap().is_empty());
assert!(incidents.list(None, 10).await.unwrap().is_empty());
assert_eq!(incidents.list(Some("resolved"), 10).await.unwrap().len(), 1);
assert_eq!(incidents.list(Some("all"), 10).await.unwrap().len(), 1);
}
#[tokio::test]
async fn incidents_record_with_outcome_lifecycle_and_user_bug_reports() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let incidents = Incidents::new(db);
let base = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/rooms/show.rs".into(),
route_pattern: Some("/rooms/{id}".into()),
status_code: Some(500),
error_message: "boom".into(),
detail: None,
context_json: serde_json::json!({}),
git_sha: Some("sha_1".into()),
custom_fingerprint: None,
};
let (rec1, outcome1) = incidents.record_with_outcome(base.clone()).await.unwrap();
assert_eq!(outcome1, IncidentOutcome::Opened);
assert_eq!(rec1.status, "open");
assert_eq!(rec1.occurrences, 1);
let (rec2, outcome2) = incidents.record_with_outcome(base.clone()).await.unwrap();
assert_eq!(outcome2, IncidentOutcome::Incremented);
assert_eq!(rec2.id, rec1.id);
assert_eq!(rec2.status, "open");
assert_eq!(rec2.occurrences, 2);
assert!(incidents.resolve(&rec1.id, Some("sha_fix")).await.unwrap());
let (rec3, outcome3) = incidents.record_with_outcome(base.clone()).await.unwrap();
assert_eq!(outcome3, IncidentOutcome::Reopened);
assert_eq!(rec3.id, rec1.id);
assert_eq!(rec3.status, "reopened");
assert_eq!(rec3.occurrences, 3);
assert!(rec3.resolved_in_sha.is_none());
let (rec4, outcome4) = incidents.record_with_outcome(base).await.unwrap();
assert_eq!(outcome4, IncidentOutcome::Incremented);
assert_eq!(rec4.status, "reopened");
assert_eq!(rec4.occurrences, 4);
assert!(incidents.resolve(&rec1.id, Some("sha_fix2")).await.unwrap());
let resolved_row = incidents.get(&rec1.id).await.unwrap().unwrap();
assert_eq!(resolved_row.status, "resolved");
assert_eq!(resolved_row.resolved_in_sha.as_deref(), Some("sha_fix2"));
let bug = IncidentInput {
kind: "user_bug_report".into(),
source_file: "slabs/rooms/show.rs".into(),
route_pattern: Some("/rooms/1".into()),
status_code: None,
error_message: "Button does not respond".into(),
detail: Some("Button does not respond".into()),
context_json: serde_json::json!({ "reporter_user_id": "usr_1" }),
git_sha: None,
custom_fingerprint: None,
};
let (bug1, first_bug_outcome) = incidents.record_with_outcome(bug.clone()).await.unwrap();
let (bug2, second_bug_outcome) = incidents.record_with_outcome(bug).await.unwrap();
assert_eq!(first_bug_outcome, IncidentOutcome::Opened);
assert_eq!(second_bug_outcome, IncidentOutcome::Opened);
assert_ne!(bug1.id, bug2.id);
let mut custom = IncidentInput {
kind: "user_bug_report".into(),
source_file: "slabs/rooms/show.rs".into(),
route_pattern: None,
status_code: None,
error_message: "Grouped bug".into(),
detail: None,
context_json: serde_json::json!({}),
git_sha: None,
custom_fingerprint: Some("bug_group_key".into()),
};
let (c1, grouped_first) = incidents.record_with_outcome(custom.clone()).await.unwrap();
let (c2, grouped_second) = incidents.record_with_outcome(custom.clone()).await.unwrap();
assert_eq!(grouped_first, IncidentOutcome::Opened);
assert_eq!(grouped_second, IncidentOutcome::Incremented);
assert_eq!(c1.id, c2.id);
assert_eq!(c2.occurrences, 2);
custom.custom_fingerprint = Some(slabs_core::id::new("bug"));
let (c3, unique_custom) = incidents.record_with_outcome(custom).await.unwrap();
assert_eq!(unique_custom, IncidentOutcome::Opened);
assert_ne!(c3.id, c1.id);
}
#[tokio::test]
async fn explain_query_plan_detects_scan_vs_index_and_rejects_non_select_sql() {
let db = Db::connect("sqlite::memory:").await.unwrap();
sqlx::raw_sql(
"CREATE TABLE messages (
id TEXT PRIMARY KEY NOT NULL,
room_id TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE INDEX idx_messages_room ON messages(room_id);",
)
.execute(db.writer())
.await
.unwrap();
let scan_plan = db
.explain_query_plan("SELECT id FROM messages WHERE body = 'hello'")
.await
.unwrap();
assert!(
scan_plan.iter().any(|line| line.contains("SCAN messages")),
"expected SCAN in plan: {scan_plan:?}"
);
let index_plan = db
.explain_query_plan("SELECT id FROM messages WHERE room_id = 'room_1'")
.await
.unwrap();
assert!(
index_plan
.iter()
.any(|line| line.contains("USING INDEX idx_messages_room")
|| line.contains("USING COVERING INDEX idx_messages_room")),
"expected USING INDEX in plan: {index_plan:?}"
);
let cte_plan = db
.explain_query_plan(
"WITH r AS (SELECT id FROM messages WHERE room_id = 'r1') SELECT id FROM r",
)
.await
.unwrap();
assert!(
cte_plan
.iter()
.any(|line| line.contains("idx_messages_room")),
"expected idx_messages_room in CTE plan: {cte_plan:?}"
);
assert!(db.explain_query_plan(" ").await.is_err());
assert!(db
.explain_query_plan("SELECT 1; DROP TABLE messages")
.await
.is_err());
assert!(db.explain_query_plan("DELETE FROM messages").await.is_err());
assert!(db
.explain_query_plan("UPDATE messages SET body = 'x'")
.await
.is_err());
assert!(db
.explain_query_plan("INSERT INTO messages VALUES ('1','r','b')")
.await
.is_err());
assert!(db.explain_query_plan("DROP TABLE messages").await.is_err());
assert!(db
.explain_query_plan("PRAGMA table_info(messages)")
.await
.is_err());
}
#[tokio::test]
async fn incidents_ring_buffer_active_filtering_and_close_stale() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let incidents = Incidents::new(db.clone());
let mut inc_id = String::new();
for idx in 1..=12 {
let input = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/orders/charge.rs".into(),
route_pattern: Some("/api/orders/charge".into()),
status_code: Some(500),
error_message: "gateway timeout".into(),
detail: Some(format!("attempt {idx}")),
context_json: serde_json::json!({
"request_id": format!("req_{idx}"),
"latency_ms": idx * 100,
}),
git_sha: Some(format!("sha_{idx:02}")),
custom_fingerprint: None,
};
let (rec, outcome) = incidents.record_with_outcome(input).await.unwrap();
if idx == 1 {
assert_eq!(outcome, IncidentOutcome::Opened);
inc_id = rec.id.clone();
} else {
assert_eq!(outcome, IncidentOutcome::Incremented);
}
if idx == 12 {
let history: Vec<serde_json::Value> =
serde_json::from_str(&rec.recent_occurrences_json).unwrap();
assert_eq!(history.len(), 10);
assert_eq!(history[0]["git_sha"], "sha_03");
assert_eq!(history[0]["request_id"], "req_3");
assert_eq!(history[0]["latency_ms"], 300);
assert_eq!(history[9]["git_sha"], "sha_12");
assert_eq!(history[9]["request_id"], "req_12");
assert_eq!(history[9]["latency_ms"], 1200);
assert!(history[9]["seen_at"].as_str().is_some());
}
}
assert!(incidents.resolve(&inc_id, Some("sha_fix")).await.unwrap());
let recur_input = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/orders/charge.rs".into(),
route_pattern: Some("/api/orders/charge".into()),
status_code: Some(500),
error_message: "gateway timeout".into(),
detail: None,
context_json: serde_json::json!({ "request_id": "req_13", "latency_ms": 1300 }),
git_sha: Some("sha_13".into()),
custom_fingerprint: None,
};
let (reopened, outcome) = incidents
.record_with_outcome(recur_input.clone())
.await
.unwrap();
assert_eq!(outcome, IncidentOutcome::Reopened);
assert_eq!(reopened.status, "reopened");
assert!(reopened.resolved_in_sha.is_none());
let fresh_input = IncidentInput {
kind: "slow_request".into(),
source_file: "slabs/orders/list.rs".into(),
route_pattern: Some("/api/orders".into()),
status_code: Some(200),
error_message: "slow query".into(),
detail: None,
context_json: serde_json::json!({ "latency_ms": 900 }),
git_sha: Some("sha_13".into()),
custom_fingerprint: None,
};
let (fresh, fresh_outcome) = incidents.record_with_outcome(fresh_input).await.unwrap();
assert_eq!(fresh_outcome, IncidentOutcome::Opened);
assert_eq!(incidents.count_open().await.unwrap(), 2);
assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 2);
assert_eq!(incidents.list(None, 10).await.unwrap().len(), 2);
assert_eq!(incidents.list(Some("open"), 10).await.unwrap().len(), 1);
assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);
let old_ts = format_utc_micros(chrono::Utc::now() - chrono::Duration::days(45));
sqlx::query("UPDATE slabs_incidents SET last_seen_at = ? WHERE id = ?")
.bind(&old_ts)
.bind(&inc_id)
.execute(db.writer())
.await
.unwrap();
assert_eq!(incidents.close_stale(0).await.unwrap(), 0);
assert_eq!(incidents.count_open().await.unwrap(), 2);
assert_eq!(incidents.close_stale(30).await.unwrap(), 1);
assert_eq!(incidents.count_open().await.unwrap(), 1);
let stale_closed = incidents.get(&inc_id).await.unwrap().unwrap();
assert_eq!(stale_closed.status, "resolved");
assert_eq!(stale_closed.resolved_in_sha.as_deref(), Some("auto:stale"));
let still_fresh = incidents.get(&fresh.id).await.unwrap().unwrap();
assert_eq!(still_fresh.status, "open");
let (reopened_after_stale, outcome_after_stale) =
incidents.record_with_outcome(recur_input).await.unwrap();
assert_eq!(outcome_after_stale, IncidentOutcome::Reopened);
assert_eq!(reopened_after_stale.status, "reopened");
assert!(reopened_after_stale.resolved_in_sha.is_none());
assert_eq!(incidents.count_open().await.unwrap(), 2);
}
#[tokio::test]
async fn db_checkpoint_and_close_flushes_wal_and_closes_pools() {
let path = std::env::temp_dir().join(format!(
"slabs_checkpoint_close_{}.db",
slabs_core::id::new("db")
));
let url = format!("sqlite://{}", path.display());
let db = Db::connect(&url).await.unwrap();
db.init_system_tables().await.unwrap();
let mut tx = db.begin().await.unwrap();
sqlx::query("CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)")
.execute(&mut *tx)
.await
.unwrap();
sqlx::query("INSERT INTO notes (id, body) VALUES ('n_1', 'hello wal')")
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
let (before,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM notes")
.fetch_one(db.reader())
.await
.unwrap();
assert_eq!(before, 1);
db.checkpoint_and_close().await;
assert!(db.reader().is_closed());
assert!(db.pool().is_closed());
let reopened = Db::connect(&url).await.unwrap();
let (body,): (String,) = sqlx::query_as("SELECT body FROM notes WHERE id = 'n_1'")
.fetch_one(reopened.reader())
.await
.unwrap();
assert_eq!(body, "hello wal");
reopened.checkpoint_and_close().await;
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_file(format!("{}-wal", path.display()));
let _ = std::fs::remove_file(format!("{}-shm", path.display()));
}
}