Spike native shells and define local-first integrations
CI / rust (push) Successful in 1m40s

This commit is contained in:
2026-08-31 15:42:26 -07:00
parent a703b5a5ee
commit aaa1cb1fa9
28 changed files with 14809 additions and 14 deletions
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "lumbridge-storage"
description = "Local SQLite persistence for Lumbridge"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
lumbridge-core = { path = "../lumbridge-core" }
rusqlite = { version = "0.40.2", default-features = false, features = ["bundled"] }
[lints]
workspace = true
+284
View File
@@ -0,0 +1,284 @@
//! Local, device-owned persistence for Lumbridge.
//!
//! This database stores workspace metadata and remote routing profiles. API
//! keys, subscription credentials, SSH private keys, and Tailscale credentials
//! are intentionally outside its contract.
use std::path::Path;
use lumbridge_core::{RemoteHost, RemoteTransport};
use rusqlite::{Connection, OptionalExtension, params};
const SCHEMA: &str = r"
CREATE TABLE IF NOT EXISTS app_meta (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL
) STRICT;
INSERT INTO app_meta (key, value) VALUES ('schema_version', '2')
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
CREATE TABLE IF NOT EXISTS remote_hosts (
id TEXT PRIMARY KEY NOT NULL,
label TEXT NOT NULL,
hostname TEXT NOT NULL,
username TEXT,
port INTEGER CHECK (port IS NULL OR port BETWEEN 1 AND 65535),
transport TEXT NOT NULL CHECK (transport IN ('openssh', 'tailscale-ssh')),
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
) STRICT;
CREATE TABLE IF NOT EXISTS workspaces (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
repository_path TEXT,
remote_host_id TEXT REFERENCES remote_hosts(id) ON DELETE RESTRICT,
remote_path TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (
(remote_host_id IS NULL AND remote_path IS NULL)
OR (remote_host_id IS NOT NULL AND remote_path IS NOT NULL)
)
) STRICT;
CREATE TABLE IF NOT EXISTS panes (
id TEXT PRIMARY KEY NOT NULL,
workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
title TEXT NOT NULL,
position INTEGER NOT NULL,
remote_session_id TEXT,
state_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
) STRICT;
CREATE INDEX IF NOT EXISTS panes_workspace_position
ON panes(workspace_id, position);
CREATE TABLE IF NOT EXISTS buzz_accounts (
id TEXT PRIMARY KEY NOT NULL,
label TEXT NOT NULL,
relay_url TEXT NOT NULL,
public_key TEXT NOT NULL,
secret_store_handle TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
) STRICT;
CREATE TABLE IF NOT EXISTS workspace_buzz_channels (
workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
account_id TEXT NOT NULL REFERENCES buzz_accounts(id) ON DELETE CASCADE,
channel_id TEXT NOT NULL,
channel_name TEXT NOT NULL,
PRIMARY KEY (workspace_id, account_id, channel_id)
) STRICT;
";
#[derive(Debug)]
pub enum StorageError {
Database(rusqlite::Error),
UnknownTransport(String),
}
impl std::fmt::Display for StorageError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Database(error) => write!(formatter, "SQLite error: {error}"),
Self::UnknownTransport(value) => write!(formatter, "unknown remote transport: {value}"),
}
}
}
impl std::error::Error for StorageError {}
impl From<rusqlite::Error> for StorageError {
fn from(error: rusqlite::Error) -> Self {
Self::Database(error)
}
}
pub type Result<T> = std::result::Result<T, StorageError>;
/// The one `SQLite` connection owned by a runtime instance.
pub struct Store {
connection: Connection,
}
impl Store {
/// Open or create a local database and apply forward-compatible migrations.
///
/// # Errors
///
/// Returns an error when the file cannot be opened or its schema cannot be
/// initialized.
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::from_connection(Connection::open(path)?)
}
/// Create an isolated store for tests and short-lived tools.
///
/// # Errors
///
/// Returns an error when `SQLite` cannot initialize the in-memory database.
pub fn open_in_memory() -> Result<Self> {
Self::from_connection(Connection::open_in_memory()?)
}
fn from_connection(connection: Connection) -> Result<Self> {
connection.execute_batch("PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;")?;
let mode: String =
connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
if mode == "wal" {
connection.execute_batch("PRAGMA synchronous = NORMAL;")?;
}
connection.execute_batch(SCHEMA)?;
Ok(Self { connection })
}
/// Return the currently installed schema version.
///
/// # Errors
///
/// Returns an error if the metadata table cannot be read.
pub fn schema_version(&self) -> Result<u32> {
let raw: String = self.connection.query_row(
"SELECT value FROM app_meta WHERE key = 'schema_version'",
[],
|row| row.get(0),
)?;
raw.parse()
.map_err(|_| StorageError::Database(rusqlite::Error::InvalidQuery))
}
/// Insert or update a credential-free remote host profile.
///
/// # Errors
///
/// Returns an error if `SQLite` rejects the profile.
pub fn save_remote_host(&self, host: &RemoteHost) -> Result<()> {
self.connection.execute(
r"
INSERT INTO remote_hosts (id, label, hostname, username, port, transport)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(id) DO UPDATE SET
label = excluded.label,
hostname = excluded.hostname,
username = excluded.username,
port = excluded.port,
transport = excluded.transport,
updated_at = CURRENT_TIMESTAMP
",
params![
host.id,
host.label,
host.hostname,
host.username,
host.port,
host.transport.storage_name()
],
)?;
Ok(())
}
/// Load one remote host profile by stable identifier.
///
/// # Errors
///
/// Returns an error when the row is malformed or cannot be read.
pub fn remote_host(&self, id: &str) -> Result<Option<RemoteHost>> {
let row = self
.connection
.query_row(
"SELECT id, label, hostname, username, port, transport FROM remote_hosts WHERE id = ?1",
[id],
|row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, Option<String>>(3)?,
row.get::<_, Option<u16>>(4)?,
row.get::<_, String>(5)?,
))
},
)
.optional()?;
row.map(|(id, label, hostname, username, port, transport)| {
let transport = RemoteTransport::from_storage_name(&transport)
.ok_or_else(|| StorageError::UnknownTransport(transport.clone()))?;
Ok(RemoteHost {
id,
label,
hostname,
username,
port,
transport,
})
})
.transpose()
}
#[cfg(test)]
fn contains_column(&self, table: &str, column: &str) -> Result<bool> {
let mut statement = self
.connection
.prepare(&format!("PRAGMA table_info({table})"))?;
let names = statement.query_map([], |row| row.get::<_, String>(1))?;
for name in names {
if name? == column {
return Ok(true);
}
}
Ok(false)
}
}
#[cfg(test)]
mod tests {
use lumbridge_core::{RemoteHost, RemoteTransport};
use super::Store;
#[test]
fn initializes_schema_and_round_trips_remote_host() {
let store = Store::open_in_memory().expect("store should initialize");
assert_eq!(store.schema_version().expect("schema version"), 2);
let host = RemoteHost {
id: "metal".into(),
label: "metal · Jarvis".into(),
hostname: "desk-1-metal-jarvis.tail.example".into(),
username: Some("engineer".into()),
port: None,
transport: RemoteTransport::TailscaleSsh,
};
store.save_remote_host(&host).expect("host should save");
assert_eq!(
store.remote_host("metal").expect("host should load"),
Some(host)
);
}
#[test]
fn credential_columns_do_not_exist() {
let store = Store::open_in_memory().expect("store should initialize");
for forbidden in ["password", "private_key", "api_key", "auth_token"] {
assert!(
!store
.contains_column("remote_hosts", forbidden)
.expect("schema query")
);
}
for forbidden in ["private_key", "secret_key", "nsec", "auth_token"] {
assert!(
!store
.contains_column("buzz_accounts", forbidden)
.expect("schema query")
);
}
}
}