feat(core): per-module key-value data synced as PutModuleData (schema v9)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:08:33 +01:00
1 parent 6c11d851f2
commit c9ebb4fd30
8 files changed
+252 -4

No files matched your search

+2
View File
@@ -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,
+8
View File
@@ -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<String>,
},
}
/// Graph-wide metadata of a type name: types are names, not pages, so this is where their
+135
View File
@@ -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<Option<String>> {
Ok(self
.row(
"SELECT value FROM module_data WHERE module=?1 AND key=?2",
params![module, key],
|r| r.get::<_, Option<String>>(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<Vec<(String, String)>> {
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::<rusqlite::Result<Vec<_>>>()?;
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<usize> {
let tx = self.tx()?;
let keys: Vec<String> = 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<Option<String>> {
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()
}
+12 -2
View File
@@ -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()],
+10
View File
@@ -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)?;