diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 77d1947..f5d4437 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -9,6 +9,7 @@ pub mod embed; pub mod error; pub mod hlc; pub mod model; +pub mod module_data; pub mod parse; pub mod position; mod schema; @@ -20,6 +21,7 @@ pub mod types; pub use error::{Error, Result}; pub use model::*; +pub use module_data::{MAX_MODULE_KEY, MAX_MODULE_VALUE, is_valid_module_id}; pub use store::Graph; pub use structure::{ HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent, diff --git a/crates/synapse-core/src/model.rs b/crates/synapse-core/src/model.rs index e3aab4b..fdeac62 100644 --- a/crates/synapse-core/src/model.rs +++ b/crates/synapse-core/src/model.rs @@ -206,6 +206,14 @@ pub enum Op { PutTypeDef { def: TypeDef, }, + /// An entry of a module's key-value store (`value: None` deletes it), last writer wins + /// per (module, key). + PutModuleData { + module: String, + key: String, + #[serde(default)] + value: Option, + }, } /// Graph-wide metadata of a type name: types are names, not pages, so this is where their diff --git a/crates/synapse-core/src/module_data.rs b/crates/synapse-core/src/module_data.rs new file mode 100644 index 0000000..1427c0d --- /dev/null +++ b/crates/synapse-core/src/module_data.rs @@ -0,0 +1,135 @@ +//! Module data: a small key-value store per installed module (`module_data` table, schema v9). +//! +//! Each entry is keyed by (module id, key) and synced with its own op +//! ([`Op::PutModuleData`], last writer wins per entry). A deleted entry is kept as a tombstone +//! (`value` NULL) so the delete wins over older writes from other replicas. The core never +//! interprets values: modules store their own encoding (the secrets module stores ciphertext). + +use crate::error::{Error, Result}; +use crate::model::Op; +use crate::store::Graph; +use rusqlite::{OptionalExtension, params}; + +/// Longest module id, in bytes. +pub const MAX_MODULE_ID: usize = 64; +/// Longest key, in bytes. +pub const MAX_MODULE_KEY: usize = 256; +/// Largest value, in bytes. +pub const MAX_MODULE_VALUE: usize = 1 << 20; + +/// Module ids are lowercase ASCII letters, digits, `.`, `-` and `_` (e.g. `synapse.secrets`). +pub fn is_valid_module_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= MAX_MODULE_ID + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b)) + && !id.starts_with('.') +} + +fn check(module: &str, key: &str, value: Option<&str>) -> Result<()> { + if !is_valid_module_id(module) { + return Err(Error::Invalid(format!("invalid module id {module:?}"))); + } + if key.is_empty() || key.len() > MAX_MODULE_KEY || key.chars().any(char::is_control) { + return Err(Error::Invalid(format!("invalid module key {key:?}"))); + } + if value.is_some_and(|v| v.len() > MAX_MODULE_VALUE) { + return Err(Error::Invalid(format!("value of {key:?} is too large"))); + } + Ok(()) +} + +impl Graph { + /// The value of `key` for `module`, `None` when unset or deleted. + pub fn module_data(&self, module: &str, key: &str) -> Result> { + Ok(self + .row( + "SELECT value FROM module_data WHERE module=?1 AND key=?2", + params![module, key], + |r| r.get::<_, Option>(0), + ) + .optional()? + .flatten()) + } + + /// Live entries of `module` whose key starts with `prefix`, sorted by key. + pub fn module_data_list(&self, module: &str, prefix: &str) -> Result> { + let mut st = self.conn().prepare_cached( + "SELECT key, value FROM module_data + WHERE module=?1 AND value IS NOT NULL AND substr(key, 1, length(?2))=?2 + ORDER BY key", + )?; + let rows = st + .query_map(params![module, prefix], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::>>()?; + Ok(rows) + } + + /// Sets (`Some`) or deletes (`None`) an entry, logged as [`Op::PutModuleData`]. Deleting an + /// unset key is a no-op. + pub fn set_module_data(&self, module: &str, key: &str, value: Option<&str>) -> Result<()> { + check(module, key, value)?; + let tx = self.tx()?; + if value.is_none() && self.module_data(module, key)?.is_none() { + tx.commit()?; + return Ok(()); + } + let hlc = self.tick(); + self.write_module_data_row(module, key, value, &hlc)?; + self.log( + &hlc, + &Op::PutModuleData { + module: module.to_string(), + key: key.to_string(), + value: value.map(str::to_string), + }, + )?; + tx.commit()?; + Ok(()) + } + + /// Deletes every live entry of `module` (one op each). Returns how many were deleted. + pub fn clear_module_data(&self, module: &str) -> Result { + let tx = self.tx()?; + let keys: Vec = self + .module_data_list(module, "")? + .into_iter() + .map(|(k, _)| k) + .collect(); + for k in &keys { + self.set_module_data(module, k, None)?; + } + tx.commit()?; + Ok(keys.len()) + } + + pub(crate) fn module_data_hlc(&self, module: &str, key: &str) -> Result> { + Ok(self + .row( + "SELECT hlc FROM module_data WHERE module=?1 AND key=?2", + params![module, key], + |r| r.get(0), + ) + .optional()?) + } + + pub(crate) fn write_module_data_row( + &self, + module: &str, + key: &str, + value: Option<&str>, + hlc: &str, + ) -> Result<()> { + self.exec( + "INSERT OR REPLACE INTO module_data(module, key, value, hlc) VALUES (?1, ?2, ?3, ?4)", + params![module, key, value, hlc], + )?; + Ok(()) + } +} + +/// Validates a remote [`Op::PutModuleData`] (same rules as local writes). +pub(crate) fn check_remote(module: &str, key: &str, value: Option<&str>) -> bool { + check(module, key, value).is_ok() +} diff --git a/crates/synapse-core/src/schema.rs b/crates/synapse-core/src/schema.rs index 9caee63..0127650 100644 --- a/crates/synapse-core/src/schema.rs +++ b/crates/synapse-core/src/schema.rs @@ -1,6 +1,6 @@ use rusqlite::OptionalExtension; -pub const VERSION: i64 = 8; +pub const VERSION: i64 = 9; pub const SCHEMA: &str = r#" CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); @@ -116,6 +116,15 @@ CREATE TABLE IF NOT EXISTS type_defs ( hlc TEXT NOT NULL ); +-- v9: per-module key-value data; a NULL value is a tombstone. +CREATE TABLE IF NOT EXISTS module_data ( + module TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT, + hlc TEXT NOT NULL, + PRIMARY KEY (module, key) +); + CREATE TABLE IF NOT EXISTS tombstones (id TEXT PRIMARY KEY, hlc TEXT NOT NULL); CREATE TABLE IF NOT EXISTS ops ( @@ -281,7 +290,8 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> { // v7: a page's hub title is an implicit tag, so the index changes. rebuild_page_tags(conn)?; } - // v8: `type_defs` (type icons) is created empty by `SCHEMA`; nothing to convert. + // v8: `type_defs` (type icons) and v9: `module_data` are created empty by `SCHEMA`; + // nothing to convert. conn.execute( "INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)", [VERSION.to_string()], diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs index 269e7cc..0a04455 100644 --- a/crates/synapse-core/src/store.rs +++ b/crates/synapse-core/src/store.rs @@ -1174,6 +1174,16 @@ impl Graph { true } } + Op::PutModuleData { module, key, value } => { + crate::module_data::check_remote(module, key, value.as_deref()) + && self + .module_data_hlc(module, key)? + .is_none_or(|l| hlc > l.as_str()) + && { + self.write_module_data_row(module, key, value.as_deref(), hlc)?; + true + } + } }; if applied { self.log(hlc, op)?; diff --git a/crates/synapse-core/tests/module_data.rs b/crates/synapse-core/tests/module_data.rs new file mode 100644 index 0000000..6e8877f --- /dev/null +++ b/crates/synapse-core/tests/module_data.rs @@ -0,0 +1,82 @@ +use synapse_core::{Graph, Op}; + +fn graph() -> (tempfile::TempDir, Graph) { + let dir = tempfile::tempdir().unwrap(); + let g = Graph::open(dir.path()).unwrap(); + (dir, g) +} + +fn module_ops(g: &Graph) -> Vec<(String, Op)> { + g.ops_since(0, 10_000) + .unwrap() + .into_iter() + .filter(|r| matches!(r.op, Op::PutModuleData { .. })) + .map(|r| (r.hlc, r.op)) + .collect() +} + +#[test] +fn module_data_is_namespaced_listed_and_deleted() { + let (_d, g) = graph(); + g.set_module_data("a.mod", "entry/1", Some("x")).unwrap(); + g.set_module_data("a.mod", "entry/2", Some("y")).unwrap(); + g.set_module_data("a.mod", "vault", Some("h")).unwrap(); + g.set_module_data("b.mod", "entry/1", Some("other")).unwrap(); + assert_eq!(g.module_data("a.mod", "entry/1").unwrap().as_deref(), Some("x")); + let keys: Vec<_> = g + .module_data_list("a.mod", "entry/") + .unwrap() + .into_iter() + .map(|(k, _)| k) + .collect(); + assert_eq!(keys, ["entry/1", "entry/2"]); + g.set_module_data("a.mod", "entry/1", None).unwrap(); + assert_eq!(g.module_data("a.mod", "entry/1").unwrap(), None); + assert_eq!(g.module_data_list("a.mod", "").unwrap().len(), 2); + // Deleting a missing key logs nothing. + let before = module_ops(&g).len(); + g.set_module_data("a.mod", "missing", None).unwrap(); + assert_eq!(module_ops(&g).len(), before); + assert_eq!(g.clear_module_data("a.mod").unwrap(), 2); + assert!(g.module_data_list("a.mod", "").unwrap().is_empty()); + assert_eq!(g.module_data_list("b.mod", "").unwrap().len(), 1); +} + +#[test] +fn module_data_validates_ids_keys_and_sizes() { + let (_d, g) = graph(); + assert!(g.set_module_data("Bad Id", "k", Some("v")).is_err()); + assert!(g.set_module_data("ok", "", Some("v")).is_err()); + assert!(g.set_module_data("ok", "a\nb", Some("v")).is_err()); + let big = "x".repeat(synapse_core::MAX_MODULE_VALUE + 1); + assert!(g.set_module_data("ok", "k", Some(&big)).is_err()); +} + +#[test] +fn module_data_syncs_last_writer_wins_with_tombstones() { + let (_a, a) = graph(); + let (_b, b) = graph(); + a.set_module_data("m", "k", Some("first")).unwrap(); + for (hlc, op) in module_ops(&a) { + assert!(b.apply_remote(&hlc, &op).unwrap()); + } + assert_eq!(b.module_data("m", "k").unwrap().as_deref(), Some("first")); + // A later delete on b wins over a's older write replayed again. + b.set_module_data("m", "k", None).unwrap(); + for (hlc, op) in module_ops(&a) { + assert!(!b.apply_remote(&hlc, &op).unwrap()); + } + assert_eq!(b.module_data("m", "k").unwrap(), None); + // ...and reaches a. + let ops = module_ops(&b); + let (hlc, op) = ops.last().unwrap(); + assert!(a.apply_remote(hlc, op).unwrap()); + assert_eq!(a.module_data("m", "k").unwrap(), None); + // Invalid remote ops are ignored. + let bad = Op::PutModuleData { + module: "Bad Id".into(), + key: "k".into(), + value: Some("v".into()), + }; + assert!(!a.apply_remote("0000000000001-00000-x", &bad).unwrap()); +} diff --git a/crates/synapse-history/src/history.rs b/crates/synapse-history/src/history.rs index 9c2e172..774d815 100644 --- a/crates/synapse-history/src/history.rs +++ b/crates/synapse-history/src/history.rs @@ -202,7 +202,8 @@ impl History { Op::DeletePage { id } => touched.extend(graph.hub_members(id)?), // Deletions and moves do not say which page lost a block; those // pages are caught by the `updated_at` scan below. - Op::DeleteBlock { .. } | Op::PutAsset { .. } | Op::PutTypeDef { .. } => {} + Op::DeleteBlock { .. } | Op::PutAsset { .. } | Op::PutTypeDef { .. } + | Op::PutModuleData { .. } => {} // The previous owner of an alias is unknown. Op::SetAlias { .. } => everything = true, } diff --git a/crates/synapse-search/src/lib.rs b/crates/synapse-search/src/lib.rs index a8e9eb9..087f428 100644 --- a/crates/synapse-search/src/lib.rs +++ b/crates/synapse-search/src/lib.rs @@ -256,7 +256,7 @@ impl Search { } // The previous owner of an alias is not in the op, so refresh all pages. Op::SetAlias { .. } => all_pages = true, - Op::PutAsset { .. } | Op::PutTypeDef { .. } => {} + Op::PutAsset { .. } | Op::PutTypeDef { .. } | Op::PutModuleData { .. } => {} } } stats.ops_processed += ops.len();