[Fix] Connectivity

This commit is contained in:
Alex Emmet 2026-08-29 12:49:10 +02:00
commit afc1832fb7
No known key found for this signature in database
14 changed files with 1462 additions and 188 deletions

View file

@ -1,8 +1,19 @@
use crate::storage_error::StorageError;
use crate::users::contact::Contact;
use crate::util::db;
use crate::util::sync::{self, EntityType, Operation};
use rusqlite::params;
pub fn has_user(storage_owner: i64, user_id: i64) -> Result<bool, StorageError> {
db::with_db(|conn| {
Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM contacts WHERE storage_owner = ?1 AND user_id = ?2)",
params![storage_owner, user_id],
|row| row.get(0),
)?)
})
}
pub fn mod_user(storage_owner: i64, contact: &Contact) {
if let Err(e) = db::with_db(|conn| {
let tx = conn.unchecked_transaction()?;

View file

@ -1,4 +1,6 @@
use crate::storage_error::StorageError;
use crate::util::db;
use crate::util::synced_settings::{self, SettingScope};
use rusqlite::params;
#[derive(Debug, Clone)]
@ -11,6 +13,16 @@ pub struct StoredCommunity {
pub struct CommunitiesUtil;
impl CommunitiesUtil {
pub fn has_community(storage_owner: i64, address: &str) -> Result<bool, StorageError> {
db::with_db(|conn| {
Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM communities WHERE storage_owner = ?1 AND address = ?2)",
params![storage_owner, address],
|row| row.get(0),
)?)
})
}
pub fn add_community(storage_owner: i64, address: String, title: String, position: String) {
if let Err(e) = db::with_db(|conn| {
conn.execute(
@ -29,16 +41,22 @@ impl CommunitiesUtil {
}
}
pub fn remove_community(storage_owner: i64, community_address: String) {
if let Err(e) = db::with_db(|conn| {
conn.execute(
pub fn remove_community(
storage_owner: i64,
community_address: String,
) -> Result<(), StorageError> {
db::with_immediate_transaction(|tx| {
tx.execute(
"DELETE FROM communities WHERE storage_owner = ?1 AND address = ?2",
params![storage_owner, community_address],
)?;
Ok(())
}) {
eprintln!("Failed to remove_community: {}", e);
}
synced_settings::delete_scope_in_tx(
tx,
storage_owner,
SettingScope::Community,
&community_address,
)
})
}
pub fn get_communities(storage_owner: i64) -> Vec<StoredCommunity> {

View file

@ -464,6 +464,31 @@ fn run_migrations_on_connection(conn: &Connection) -> Result<(), StorageError> {
)?;
}
if current_version < 12 {
conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS synced_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
scope_type TEXT NOT NULL
CHECK (scope_type IN ('user', 'contact', 'community')),
scope_key TEXT NOT NULL,
name TEXT NOT NULL,
payload TEXT NOT NULL,
revision INTEGER NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0
CHECK (deleted IN (0, 1)),
UNIQUE(user_id, scope_type, scope_key, name)
);
CREATE INDEX IF NOT EXISTS idx_synced_settings_owner
ON synced_settings (user_id, deleted);
CREATE INDEX IF NOT EXISTS idx_synced_settings_scope
ON synced_settings (user_id, scope_type, scope_key, deleted);
PRAGMA user_version = 12;
"#,
)?;
}
Ok(())
}
@ -533,7 +558,7 @@ mod tests {
run_migrations_on_connection(&conn)?;
let version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
assert_eq!(version, 11);
assert_eq!(version, 12);
for column in ["height", "reply_to", "edited_count", "deleted_by_external"] {
let mut statement =
conn.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = ?1")?;
@ -552,7 +577,7 @@ mod tests {
run_migrations_on_connection(&conn)?;
run_migrations_on_connection(&conn)?;
let version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
assert_eq!(version, 11);
assert_eq!(version, 12);
for table in [
"sync_heads",
"sync_events",
@ -561,6 +586,7 @@ mod tests {
"relay_replay",
"pending_relays",
"relay_inbox",
"synced_settings",
] {
let exists: i64 = conn.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1",
@ -576,4 +602,22 @@ mod tests {
}
Ok(())
}
#[test]
fn adds_synced_settings_to_a_version_eleven_schema() -> Result<(), StorageError> {
let conn = Connection::open_in_memory()?;
conn.execute_batch("PRAGMA user_version = 11;")?;
run_migrations_on_connection(&conn)?;
let version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
assert_eq!(version, 12);
for column in ["id", "user_id", "scope_type", "scope_key", "name", "payload", "revision", "deleted"] {
let mut statement =
conn.prepare("SELECT 1 FROM pragma_table_info('synced_settings') WHERE name = ?1")?;
assert!(statement.exists([column])?);
}
Ok(())
}
}

View file

@ -8,3 +8,4 @@ pub mod relay_queue;
pub mod relay_replay;
pub mod settings;
pub mod sync;
pub mod synced_settings;

View file

@ -1,21 +1,23 @@
//! Durable per-user state journal used by device cache synchronization.
/* Durable per-user state journal used by device cache synchronization. */
use crate::storage_error::StorageError;
use crate::util::db;
use rusqlite::{Transaction, params};
use std::collections::BTreeMap;
pub const CACHE_SCHEMA_VERSION: i64 = 2;
pub const CACHE_SCHEMA_VERSION: i64 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntityType {
Message,
Contact,
Setting,
}
impl EntityType {
fn as_str(self) -> &'static str {
match self {
Self::Message => "message",
Self::Contact => "contact",
Self::Setting => "setting",
}
}
}
@ -40,6 +42,8 @@ pub struct Delta {
pub deleted_message_ids: Vec<i64>,
pub contact_upserts: Vec<i64>,
pub deleted_contact_ids: Vec<i64>,
pub setting_upserts: Vec<i64>,
pub deleted_setting_ids: Vec<i64>,
}
pub fn now_millis() -> i64 {
@ -145,16 +149,174 @@ pub fn delta(user_id: i64, from_version: i64, captured_head: i64) -> Result<Delt
let (kind, id, operation) = row?;
final_events.insert((kind, id), operation);
}
let mut out = Delta::default();
for ((kind, id), operation) in final_events {
match (kind.as_str(), operation.as_str()) {
("message", "delete") => out.deleted_message_ids.push(id),
("message", _) => out.message_upserts.push(id),
("contact", "delete") => out.deleted_contact_ids.push(id),
("contact", _) => out.contact_upserts.push(id),
_ => {}
}
}
Ok(out)
Ok(reduce_events(final_events))
})
}
fn reduce_events(events: BTreeMap<(String, i64), String>) -> Delta {
let mut out = Delta::default();
for ((kind, id), operation) in events {
match (kind.as_str(), operation.as_str()) {
("message", "delete") => out.deleted_message_ids.push(id),
("message", _) => out.message_upserts.push(id),
("contact", "delete") => out.deleted_contact_ids.push(id),
("contact", _) => out.contact_upserts.push(id),
("setting", "delete") => out.deleted_setting_ids.push(id),
("setting", _) => out.setting_upserts.push(id),
_ => {}
}
}
out
}
#[cfg(test)]
fn reduce_event_sequence<I>(events: I) -> Delta
where
I: IntoIterator<Item = (String, i64, String)>,
{
let mut final_events = BTreeMap::new();
for (kind, id, operation) in events {
final_events.insert((kind, id), operation);
}
reduce_events(final_events)
}
#[cfg(test)]
mod tests {
use super::{EntityType, Operation, reduce_event_sequence, reduce_events};
use rusqlite::Connection;
use std::collections::BTreeMap;
#[test]
fn setting_upsert_is_included_in_delta() {
let mut events = BTreeMap::new();
events.insert(
(EntityType::Setting.as_str().to_string(), 7),
Operation::Upsert.as_str().to_string(),
);
let delta = reduce_events(events);
assert_eq!(delta.setting_upserts, vec![7]);
assert!(delta.deleted_setting_ids.is_empty());
}
#[test]
fn setting_delete_is_included_in_delta() {
let mut events = BTreeMap::new();
events.insert(
(EntityType::Setting.as_str().to_string(), 7),
Operation::Delete.as_str().to_string(),
);
let delta = reduce_events(events);
assert_eq!(delta.deleted_setting_ids, vec![7]);
assert!(delta.setting_upserts.is_empty());
}
#[test]
fn final_setting_operation_wins() {
let mut events = BTreeMap::new();
events.insert(
(EntityType::Setting.as_str().to_string(), 7),
Operation::Upsert.as_str().to_string(),
);
events.insert(
(EntityType::Setting.as_str().to_string(), 8),
Operation::Delete.as_str().to_string(),
);
let delta = reduce_events(events);
assert_eq!(delta.setting_upserts, vec![7]);
assert_eq!(delta.deleted_setting_ids, vec![8]);
}
#[test]
fn setting_upsert_then_delete_resolves_to_delete() {
let delta = reduce_event_sequence([
(
EntityType::Setting.as_str().to_string(),
7,
Operation::Upsert.as_str().to_string(),
),
(
EntityType::Setting.as_str().to_string(),
7,
Operation::Delete.as_str().to_string(),
),
]);
assert_eq!(delta.deleted_setting_ids, vec![7]);
assert!(delta.setting_upserts.is_empty());
}
#[test]
fn setting_delete_then_upsert_resolves_to_upsert() {
let delta = reduce_event_sequence([
(
EntityType::Setting.as_str().to_string(),
7,
Operation::Delete.as_str().to_string(),
),
(
EntityType::Setting.as_str().to_string(),
7,
Operation::Upsert.as_str().to_string(),
),
]);
assert_eq!(delta.setting_upserts, vec![7]);
assert!(delta.deleted_setting_ids.is_empty());
}
#[test]
fn setting_events_share_the_user_sync_head() {
let connection = Connection::open_in_memory().unwrap();
connection
.execute_batch(
"
CREATE TABLE sync_heads (user_id INTEGER PRIMARY KEY, version INTEGER NOT NULL);
CREATE TABLE sync_events (
user_id INTEGER NOT NULL,
version INTEGER NOT NULL,
entity_type TEXT NOT NULL,
entity_id INTEGER NOT NULL,
operation TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (user_id, version)
);
",
)
.unwrap();
let transaction = connection.unchecked_transaction().unwrap();
let message = super::record_event(
&transaction,
1,
EntityType::Message,
10,
Operation::Upsert,
)
.unwrap();
let setting = super::record_event(
&transaction,
1,
EntityType::Setting,
11,
Operation::Upsert,
)
.unwrap();
let contact = super::record_event(
&transaction,
1,
EntityType::Contact,
12,
Operation::Upsert,
)
.unwrap();
transaction.commit().unwrap();
assert_eq!((message, setting, contact), (1, 2, 3));
}
}

View file

@ -0,0 +1,659 @@
use crate::storage_error::StorageError;
use crate::util::db;
use crate::util::sync::{self, EntityType, Operation};
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingScope {
User,
Contact,
Community,
}
impl SettingScope {
pub fn as_str(self) -> &'static str {
match self {
Self::User => "user",
Self::Contact => "contact",
Self::Community => "community",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"user" => Some(Self::User),
"contact" => Some(Self::Contact),
"community" => Some(Self::Community),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncedSetting {
pub id: i64,
pub user_id: i64,
pub scope: SettingScope,
pub scope_key: String,
pub name: String,
pub payload: String,
pub revision: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeletedSetting {
pub id: i64,
pub revision: i64,
pub changed: bool,
}
pub fn is_valid_name(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.all(|character| character.is_alphanumeric() || "_-.".contains(character))
&& !name.contains("..")
}
fn validate_locator(scope: SettingScope, scope_key: &str, name: &str) -> Result<(), StorageError> {
if !is_valid_name(name) {
return Err(StorageError::Other(
"invalid synchronized setting name".into(),
));
}
match scope {
SettingScope::User if !scope_key.is_empty() => Err(StorageError::Other(
"user settings must not have a target".into(),
)),
SettingScope::Contact => {
let valid_contact = scope_key.parse::<i64>().is_ok_and(|id| id > 0);
if valid_contact {
Ok(())
} else {
Err(StorageError::Other("invalid contact setting target".into()))
}
}
SettingScope::Community if scope_key.is_empty() => Err(StorageError::Other(
"community settings require a target".into(),
)),
_ => Ok(()),
}
}
fn normalized_scope_key(scope: SettingScope, scope_key: &str) -> Result<String, StorageError> {
match scope {
SettingScope::Contact => scope_key
.parse::<i64>()
.map(|id| id.to_string())
.map_err(|_| StorageError::Other("invalid contact setting target".into())),
SettingScope::User | SettingScope::Community => Ok(scope_key.to_string()),
}
}
fn setting_from_parts(
id: i64,
user_id: i64,
scope_type: String,
scope_key: String,
name: String,
payload: String,
revision: i64,
) -> Result<SyncedSetting, StorageError> {
let scope = SettingScope::parse(&scope_type)
.ok_or_else(|| StorageError::Other("database contains an invalid setting scope".into()))?;
Ok(SyncedSetting {
id,
user_id,
scope,
scope_key,
name,
payload,
revision,
})
}
fn row_parts(row: &Row<'_>) -> rusqlite::Result<(i64, i64, String, String, String, String, i64)> {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
row.get(6)?,
))
}
fn load_setting_from_tx(
tx: &Transaction<'_>,
setting_id: i64,
) -> Result<SyncedSetting, StorageError> {
let parts = tx.query_row(
"SELECT id, user_id, scope_type, scope_key, name, payload, revision
FROM synced_settings
WHERE id = ?1 AND deleted = 0",
[setting_id],
row_parts,
)?;
setting_from_parts(
parts.0, parts.1, parts.2, parts.3, parts.4, parts.5, parts.6,
)
}
pub fn set(
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
payload: &str,
) -> Result<SyncedSetting, StorageError> {
if user_id <= 0 {
return Err(StorageError::Other("invalid setting owner".into()));
}
validate_locator(scope, scope_key, name)?;
let scope_key = normalized_scope_key(scope, scope_key)?;
db::with_immediate_transaction(|tx| set_in_tx(tx, user_id, scope, &scope_key, name, payload))
}
fn set_in_tx(
tx: &Transaction<'_>,
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
payload: &str,
) -> Result<SyncedSetting, StorageError> {
tx.execute(
"INSERT INTO synced_settings
(user_id, scope_type, scope_key, name, payload, revision, deleted)
VALUES (?1, ?2, ?3, ?4, ?5, 0, 0)
ON CONFLICT(user_id, scope_type, scope_key, name) DO NOTHING",
params![user_id, scope.as_str(), scope_key, name, payload],
)?;
let setting_id: i64 = tx.query_row(
"SELECT id FROM synced_settings
WHERE user_id = ?1 AND scope_type = ?2 AND scope_key = ?3 AND name = ?4",
params![user_id, scope.as_str(), scope_key, name],
|row| row.get(0),
)?;
let revision = sync::record_event(
tx,
user_id,
EntityType::Setting,
setting_id,
Operation::Upsert,
)?;
tx.execute(
"UPDATE synced_settings
SET payload = ?2, deleted = 0, revision = ?3
WHERE id = ?1",
params![setting_id, payload, revision],
)?;
load_setting_from_tx(tx, setting_id)
}
pub fn get(
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
) -> Result<Option<SyncedSetting>, StorageError> {
if user_id <= 0 {
return Err(StorageError::Other("invalid setting owner".into()));
}
validate_locator(scope, scope_key, name)?;
let scope_key = normalized_scope_key(scope, scope_key)?;
db::with_db(|conn| get_from_connection(conn, user_id, scope, &scope_key, name))
}
fn get_from_connection(
conn: &Connection,
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
) -> Result<Option<SyncedSetting>, StorageError> {
let parts = conn
.query_row(
"SELECT id, user_id, scope_type, scope_key, name, payload, revision
FROM synced_settings
WHERE user_id = ?1 AND scope_type = ?2 AND scope_key = ?3
AND name = ?4 AND deleted = 0",
params![user_id, scope.as_str(), scope_key, name],
row_parts,
)
.optional()?;
parts
.map(|parts| {
setting_from_parts(
parts.0, parts.1, parts.2, parts.3, parts.4, parts.5, parts.6,
)
})
.transpose()
}
pub fn list(user_id: i64) -> Result<Vec<SyncedSetting>, StorageError> {
if user_id <= 0 {
return Err(StorageError::Other("invalid setting owner".into()));
}
db::with_db(|conn| list_from_connection(conn, user_id))
}
fn list_from_connection(
conn: &Connection,
user_id: i64,
) -> Result<Vec<SyncedSetting>, StorageError> {
let mut statement = conn.prepare(
"SELECT id, user_id, scope_type, scope_key, name, payload, revision
FROM synced_settings
WHERE user_id = ?1 AND deleted = 0
ORDER BY id ASC",
)?;
let rows = statement.query_map([user_id], row_parts)?;
let mut settings = Vec::new();
for row in rows {
let parts = row?;
settings.push(setting_from_parts(
parts.0, parts.1, parts.2, parts.3, parts.4, parts.5, parts.6,
)?);
}
Ok(settings)
}
pub fn list_by_ids(user_id: i64, ids: &[i64]) -> Result<Vec<SyncedSetting>, StorageError> {
if user_id <= 0 {
return Err(StorageError::Other("invalid setting owner".into()));
}
if ids.is_empty() {
return Ok(Vec::new());
}
db::with_db(|conn| list_by_ids_from_connection(conn, user_id, ids))
}
fn list_by_ids_from_connection(
conn: &Connection,
user_id: i64,
ids: &[i64],
) -> Result<Vec<SyncedSetting>, StorageError> {
let placeholders = std::iter::repeat_n("?", ids.len())
.collect::<Vec<_>>()
.join(", ");
let query = format!(
"SELECT id, user_id, scope_type, scope_key, name, payload, revision
FROM synced_settings
WHERE user_id = ? AND deleted = 0 AND id IN ({placeholders})
ORDER BY id ASC"
);
let mut values = Vec::with_capacity(ids.len() + 1);
values.push(user_id);
values.extend_from_slice(ids);
let mut statement = conn.prepare(&query)?;
let rows = statement.query_map(rusqlite::params_from_iter(values), row_parts)?;
let mut settings = Vec::new();
for row in rows {
let parts = row?;
settings.push(setting_from_parts(
parts.0, parts.1, parts.2, parts.3, parts.4, parts.5, parts.6,
)?);
}
Ok(settings)
}
pub fn delete(
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
) -> Result<Option<DeletedSetting>, StorageError> {
if user_id <= 0 {
return Err(StorageError::Other("invalid setting owner".into()));
}
validate_locator(scope, scope_key, name)?;
let scope_key = normalized_scope_key(scope, scope_key)?;
db::with_immediate_transaction(|tx| delete_in_tx(tx, user_id, scope, &scope_key, name))
}
fn delete_in_tx(
tx: &Transaction<'_>,
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
) -> Result<Option<DeletedSetting>, StorageError> {
let existing = tx
.query_row(
"SELECT id, revision, deleted FROM synced_settings
WHERE user_id = ?1 AND scope_type = ?2 AND scope_key = ?3 AND name = ?4",
params![user_id, scope.as_str(), scope_key, name],
|row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, i64>(1)?,
row.get::<_, i64>(2)?,
))
},
)
.optional()?;
let Some((setting_id, current_revision, deleted)) = existing else {
return Ok(None);
};
if deleted != 0 {
return Ok(Some(DeletedSetting {
id: setting_id,
revision: current_revision,
changed: false,
}));
}
let revision = sync::record_event(
tx,
user_id,
EntityType::Setting,
setting_id,
Operation::Delete,
)?;
tx.execute(
"UPDATE synced_settings SET deleted = 1, revision = ?2 WHERE id = ?1",
params![setting_id, revision],
)?;
Ok(Some(DeletedSetting {
id: setting_id,
revision,
changed: true,
}))
}
pub(crate) fn delete_scope_in_tx(
tx: &Transaction<'_>,
user_id: i64,
scope: SettingScope,
scope_key: &str,
) -> Result<(), StorageError> {
let setting_ids = {
let mut statement = tx.prepare(
"SELECT id FROM synced_settings
WHERE user_id = ?1 AND scope_type = ?2 AND scope_key = ?3 AND deleted = 0",
)?;
let rows = statement.query_map(params![user_id, scope.as_str(), scope_key], |row| {
row.get::<_, i64>(0)
})?;
rows.collect::<Result<Vec<_>, _>>()?
};
for setting_id in setting_ids {
let revision = sync::record_event(
tx,
user_id,
EntityType::Setting,
setting_id,
Operation::Delete,
)?;
tx.execute(
"UPDATE synced_settings SET deleted = 1, revision = ?2 WHERE id = ?1",
params![setting_id, revision],
)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{
delete_in_tx, get_from_connection, is_valid_name, list_by_ids_from_connection,
list_from_connection, set_in_tx, SettingScope,
};
use rusqlite::Connection;
fn connection() -> Connection {
let connection = Connection::open_in_memory().unwrap();
connection
.execute_batch(
"
CREATE TABLE sync_heads (
user_id INTEGER PRIMARY KEY,
version INTEGER NOT NULL
);
CREATE TABLE sync_events (
user_id INTEGER NOT NULL,
version INTEGER NOT NULL,
entity_type TEXT NOT NULL,
entity_id INTEGER NOT NULL,
operation TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (user_id, version)
);
CREATE TABLE synced_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
scope_type TEXT NOT NULL,
scope_key TEXT NOT NULL,
name TEXT NOT NULL,
payload TEXT NOT NULL,
revision INTEGER NOT NULL,
deleted INTEGER NOT NULL DEFAULT 0,
UNIQUE(user_id, scope_type, scope_key, name)
);
",
)
.unwrap();
connection
}
fn set(
connection: &mut Connection,
user_id: i64,
scope: SettingScope,
scope_key: &str,
name: &str,
payload: &str,
) -> super::SyncedSetting {
let transaction = connection.transaction().unwrap();
let setting = set_in_tx(&transaction, user_id, scope, scope_key, name, payload).unwrap();
transaction.commit().unwrap();
setting
}
#[test]
fn parses_supported_setting_scopes() {
assert_eq!(SettingScope::parse("user"), Some(SettingScope::User));
assert_eq!(SettingScope::parse("contact"), Some(SettingScope::Contact));
assert_eq!(
SettingScope::parse("community"),
Some(SettingScope::Community)
);
}
#[test]
fn rejects_unknown_setting_scope() {
assert_eq!(SettingScope::parse("device"), None);
}
#[test]
fn validates_setting_name_syntax() {
assert!(is_valid_name("notifications.enabled"));
assert!(!is_valid_name("notifications..enabled"));
assert!(!is_valid_name(""));
assert!(!is_valid_name("notifications/enabled"));
}
#[test]
fn stores_and_loads_a_user_setting() {
let mut connection = connection();
let stored = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"true",
);
let loaded = get_from_connection(
&connection,
1,
SettingScope::User,
"",
"notifications.enabled",
)
.unwrap();
assert_eq!(loaded, Some(stored));
}
#[test]
fn contact_and_community_targets_are_distinct() {
let mut connection = connection();
set(
&mut connection,
1,
SettingScope::Contact,
"123",
"notifications.enabled",
"false",
);
set(
&mut connection,
1,
SettingScope::Community,
"community-a",
"notifications.enabled",
"true",
);
assert_eq!(list_from_connection(&connection, 1).unwrap().len(), 2);
}
#[test]
fn users_store_same_setting_independently() {
let mut connection = connection();
set(
&mut connection,
1,
SettingScope::User,
"",
"receipts.user_read",
"true",
);
set(
&mut connection,
2,
SettingScope::User,
"",
"receipts.user_read",
"false",
);
assert_eq!(
get_from_connection(&connection, 1, SettingScope::User, "", "receipts.user_read")
.unwrap()
.unwrap()
.payload,
"true"
);
assert_eq!(
get_from_connection(&connection, 2, SettingScope::User, "", "receipts.user_read")
.unwrap()
.unwrap()
.payload,
"false"
);
}
#[test]
fn update_retains_id_and_advances_revision() {
let mut connection = connection();
let first = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"true",
);
let second = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"false",
);
assert_eq!(second.id, first.id);
assert!(second.revision > first.revision);
}
#[test]
fn delete_tombstones_setting_and_records_delta_delete() {
let mut connection = connection();
let stored = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"true",
);
let transaction = connection.transaction().unwrap();
let deleted = delete_in_tx(
&transaction,
1,
SettingScope::User,
"",
"notifications.enabled",
)
.unwrap()
.unwrap();
transaction.commit().unwrap();
let journal_operation: String = connection
.query_row(
"SELECT operation FROM sync_events WHERE entity_id = ?1 ORDER BY version DESC LIMIT 1",
[stored.id],
|row| row.get(0),
)
.unwrap();
assert_eq!(deleted.id, stored.id);
assert!(deleted.changed);
assert_eq!(journal_operation, "delete");
assert!(list_from_connection(&connection, 1).unwrap().is_empty());
assert!(list_by_ids_from_connection(&connection, 1, &[stored.id])
.unwrap()
.is_empty());
}
#[test]
fn setting_can_be_recreated_with_the_same_id() {
let mut connection = connection();
let first = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"true",
);
let transaction = connection.transaction().unwrap();
delete_in_tx(
&transaction,
1,
SettingScope::User,
"",
"notifications.enabled",
)
.unwrap();
transaction.commit().unwrap();
let recreated = set(
&mut connection,
1,
SettingScope::User,
"",
"notifications.enabled",
"false",
);
assert_eq!(recreated.id, first.id);
assert_eq!(recreated.payload, "false");
}
}