369 行
12 KiB
Rust
369 行
12 KiB
Rust
mod profiles;
|
|
|
|
use std::{path::Path, sync::Mutex, time::Duration};
|
|
|
|
use rusqlite::{Connection, OptionalExtension, params};
|
|
use thiserror::Error;
|
|
|
|
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
|
|
|
|
pub struct ApplicationDatabase {
|
|
store: Mutex<ProfileMessageStore>,
|
|
}
|
|
|
|
impl ApplicationDatabase {
|
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
|
|
Ok(Self {
|
|
store: Mutex::new(ProfileMessageStore::open(path)?),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn in_memory() -> Result<Self, DatabaseError> {
|
|
Ok(Self {
|
|
store: Mutex::new(ProfileMessageStore::in_memory()?),
|
|
})
|
|
}
|
|
|
|
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
|
|
self.store
|
|
.lock()
|
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
|
.schema_version()
|
|
}
|
|
}
|
|
|
|
pub struct ProfileMessageStore {
|
|
connection: Connection,
|
|
}
|
|
|
|
impl ProfileMessageStore {
|
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
|
|
Self::from_connection(Connection::open(path)?, true)
|
|
}
|
|
|
|
pub fn in_memory() -> Result<Self, DatabaseError> {
|
|
Self::from_connection(Connection::open_in_memory()?, false)
|
|
}
|
|
|
|
fn from_connection(
|
|
mut connection: Connection,
|
|
persistent: bool,
|
|
) -> Result<Self, DatabaseError> {
|
|
configure_connection(&connection, persistent)?;
|
|
migrate(&mut connection)?;
|
|
Ok(Self { connection })
|
|
}
|
|
|
|
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
|
|
Ok(self
|
|
.connection
|
|
.pragma_query_value(None, "user_version", |row| row.get(0))?)
|
|
}
|
|
|
|
pub fn insert_message(
|
|
&self,
|
|
profile_id: &str,
|
|
server_instance_id: &str,
|
|
conversation_id: &str,
|
|
message_id: &str,
|
|
content: &str,
|
|
) -> Result<(), DatabaseError> {
|
|
self.connection.execute(
|
|
"
|
|
INSERT INTO messages (
|
|
profile_id,
|
|
server_instance_id,
|
|
conversation_id,
|
|
message_id,
|
|
content
|
|
) VALUES (?1, ?2, ?3, ?4, ?5)
|
|
",
|
|
params![
|
|
profile_id,
|
|
server_instance_id,
|
|
conversation_id,
|
|
message_id,
|
|
content
|
|
],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn message_content(
|
|
&self,
|
|
profile_id: &str,
|
|
server_instance_id: &str,
|
|
conversation_id: &str,
|
|
message_id: &str,
|
|
) -> Result<Option<String>, DatabaseError> {
|
|
Ok(self
|
|
.connection
|
|
.query_row(
|
|
"
|
|
SELECT content
|
|
FROM messages
|
|
WHERE profile_id = ?1
|
|
AND server_instance_id = ?2
|
|
AND conversation_id = ?3
|
|
AND message_id = ?4
|
|
",
|
|
params![profile_id, server_instance_id, conversation_id, message_id],
|
|
|row| row.get(0),
|
|
)
|
|
.optional()?)
|
|
}
|
|
}
|
|
|
|
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
|
|
connection.pragma_update(None, "foreign_keys", "ON")?;
|
|
connection.busy_timeout(Duration::from_secs(5))?;
|
|
if persistent {
|
|
connection.pragma_update(None, "journal_mode", "WAL")?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
|
let found: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?;
|
|
|
|
if found > CURRENT_SCHEMA_VERSION {
|
|
return Err(DatabaseError::UnsupportedSchemaVersion {
|
|
found,
|
|
supported: CURRENT_SCHEMA_VERSION,
|
|
});
|
|
}
|
|
|
|
if found == 0 {
|
|
let transaction = connection.transaction()?;
|
|
transaction.execute_batch(
|
|
"
|
|
CREATE TABLE messages (
|
|
profile_id TEXT NOT NULL,
|
|
server_instance_id TEXT NOT NULL,
|
|
conversation_id TEXT NOT NULL,
|
|
message_id TEXT NOT NULL,
|
|
content TEXT NOT NULL,
|
|
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
|
);
|
|
PRAGMA user_version = 1;
|
|
",
|
|
)?;
|
|
transaction.commit()?;
|
|
}
|
|
|
|
if found <= 1 {
|
|
let transaction = connection.transaction()?;
|
|
transaction.execute_batch(
|
|
"
|
|
CREATE TABLE connection_profiles (
|
|
id TEXT PRIMARY KEY NOT NULL,
|
|
display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80),
|
|
role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')),
|
|
base_url TEXT NOT NULL,
|
|
event_stream_url TEXT,
|
|
authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')),
|
|
credential_reference TEXT,
|
|
allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)),
|
|
pinned_certificate_fingerprint TEXT,
|
|
auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')),
|
|
auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)),
|
|
server_instance_id TEXT,
|
|
server_version TEXT,
|
|
protocol_version TEXT,
|
|
local_tool_policy_id TEXT,
|
|
last_connected_at TEXT,
|
|
created_at TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE INDEX connection_profiles_role_idx
|
|
ON connection_profiles(role);
|
|
PRAGMA user_version = 2;
|
|
",
|
|
)?;
|
|
transaction.commit()?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum DatabaseError {
|
|
#[error("SQLite operation failed")]
|
|
Sqlite(#[from] rusqlite::Error),
|
|
#[error("database schema version {found} is newer than supported version {supported}")]
|
|
UnsupportedSchemaVersion { found: u32, supported: u32 },
|
|
#[error("database state lock is unavailable")]
|
|
LockPoisoned,
|
|
#[error("database contains invalid profile data")]
|
|
InvalidStoredProfile,
|
|
#[error("connection profile was not found")]
|
|
ProfileNotFound,
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn creates_and_reopens_a_persistent_migrated_database() {
|
|
let directory = tempfile::tempdir().expect("temporary directory");
|
|
let path = directory.path().join("desktop.sqlite3");
|
|
|
|
{
|
|
let store = ProfileMessageStore::open(&path).expect("open database");
|
|
assert_eq!(
|
|
store.schema_version().expect("schema version"),
|
|
CURRENT_SCHEMA_VERSION
|
|
);
|
|
store
|
|
.insert_message(
|
|
"profile-a",
|
|
"server-a",
|
|
"conversation-a",
|
|
"message-a",
|
|
"persisted",
|
|
)
|
|
.expect("insert message");
|
|
}
|
|
|
|
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
|
assert_eq!(
|
|
reopened.schema_version().expect("schema version"),
|
|
CURRENT_SCHEMA_VERSION
|
|
);
|
|
assert_eq!(
|
|
reopened
|
|
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
|
.expect("query message")
|
|
.as_deref(),
|
|
Some("persisted")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn migrates_v1_to_v2_without_losing_messages() {
|
|
let directory = tempfile::tempdir().expect("temporary directory");
|
|
let path = directory.path().join("v1.sqlite3");
|
|
let connection = Connection::open(&path).expect("create v1 database");
|
|
connection
|
|
.execute_batch(
|
|
"
|
|
CREATE TABLE messages (
|
|
profile_id TEXT NOT NULL,
|
|
server_instance_id TEXT NOT NULL,
|
|
conversation_id TEXT NOT NULL,
|
|
message_id TEXT NOT NULL,
|
|
content TEXT NOT NULL,
|
|
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
|
);
|
|
INSERT INTO messages (
|
|
profile_id,
|
|
server_instance_id,
|
|
conversation_id,
|
|
message_id,
|
|
content
|
|
) VALUES (
|
|
'profile-a',
|
|
'server-a',
|
|
'conversation-a',
|
|
'message-a',
|
|
'preserved'
|
|
);
|
|
PRAGMA user_version = 1;
|
|
",
|
|
)
|
|
.expect("create v1 schema");
|
|
drop(connection);
|
|
|
|
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
|
assert_eq!(store.schema_version().expect("schema version"), 2);
|
|
assert_eq!(
|
|
store
|
|
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
|
.expect("query preserved message")
|
|
.as_deref(),
|
|
Some("preserved")
|
|
);
|
|
let profile_table_count: u32 = store
|
|
.connection
|
|
.query_row(
|
|
"SELECT COUNT(*) FROM sqlite_master
|
|
WHERE type = 'table' AND name = 'connection_profiles'",
|
|
[],
|
|
|row| row.get(0),
|
|
)
|
|
.expect("query profile table");
|
|
assert_eq!(profile_table_count, 1);
|
|
}
|
|
|
|
#[test]
|
|
fn refuses_a_database_from_a_newer_schema_version() {
|
|
let directory = tempfile::tempdir().expect("temporary directory");
|
|
let path = directory.path().join("future.sqlite3");
|
|
let connection = Connection::open(&path).expect("create database");
|
|
connection
|
|
.pragma_update(None, "user_version", CURRENT_SCHEMA_VERSION + 1)
|
|
.expect("set future version");
|
|
drop(connection);
|
|
|
|
assert!(matches!(
|
|
ProfileMessageStore::open(path),
|
|
Err(DatabaseError::UnsupportedSchemaVersion {
|
|
found: 3,
|
|
supported: CURRENT_SCHEMA_VERSION
|
|
})
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn repeated_migration_is_idempotent() {
|
|
let store = ProfileMessageStore::in_memory().expect("store");
|
|
assert_eq!(
|
|
store.schema_version().expect("schema version"),
|
|
CURRENT_SCHEMA_VERSION
|
|
);
|
|
assert_eq!(
|
|
store.schema_version().expect("schema version"),
|
|
CURRENT_SCHEMA_VERSION
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn identical_remote_ids_remain_isolated_by_profile_and_server() {
|
|
let store = ProfileMessageStore::in_memory().expect("store");
|
|
store
|
|
.insert_message(
|
|
"profile-a",
|
|
"server-a",
|
|
"same-conversation",
|
|
"same-message",
|
|
"A",
|
|
)
|
|
.expect("insert A");
|
|
store
|
|
.insert_message(
|
|
"profile-b",
|
|
"server-b",
|
|
"same-conversation",
|
|
"same-message",
|
|
"B",
|
|
)
|
|
.expect("insert B");
|
|
|
|
assert_eq!(
|
|
store
|
|
.message_content("profile-a", "server-a", "same-conversation", "same-message")
|
|
.expect("query A")
|
|
.as_deref(),
|
|
Some("A")
|
|
);
|
|
assert_eq!(
|
|
store
|
|
.message_content("profile-b", "server-b", "same-conversation", "same-message")
|
|
.expect("query B")
|
|
.as_deref(),
|
|
Some("B")
|
|
);
|
|
}
|
|
}
|