diff --git a/LESSONS.md b/LESSONS.md index c01b51c..63babab 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -7,3 +7,7 @@ Recurring mistakes and how to avoid them. Add an entry when a mistake repeats. `dart analyze` locally; CI paths are ASCII so `flutter analyze` is fine there. - Generated FFI types share a namespace with Flutter widgets in Dart: avoid DTO names such as `PageView`, `Page`, `Route` in `synapse-ffi`. +- Fedora's packaged `cargo`/`rust` (in `/usr/bin`) shadows rustup's toolchain in some shells; + mixing them breaks `target/` with E0514 ("compiled by an incompatible version of rustc"). + Prefix commands with `PATH="$HOME/.cargo/bin:$PATH"` (the Stop hook already does) and check + `cargo --version` before building. diff --git a/crates/synapse-core/src/blob.rs b/crates/synapse-core/src/blob.rs index 6fea2b2..23f9162 100644 --- a/crates/synapse-core/src/blob.rs +++ b/crates/synapse-core/src/blob.rs @@ -6,6 +6,11 @@ use std::fs; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; +/// A blake3 hex digest: 64 lowercase hex chars. +pub fn is_valid_hash(hash: &str) -> bool { + hash.len() == 64 && hash.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) +} + #[derive(Debug, Clone)] pub struct BlobStore { root: PathBuf, @@ -18,12 +23,13 @@ impl BlobStore { Ok(Self { root }) } + /// Path of a blob. Callers must pass a valid hash (see [`is_valid_hash`]). pub fn path_of(&self, hash: &str) -> PathBuf { self.root.join(&hash[..2]).join(&hash[2..]) } pub fn contains(&self, hash: &str) -> bool { - hash.len() > 2 && self.path_of(hash).exists() + is_valid_hash(hash) && self.path_of(hash).exists() } /// Streams `reader` into the store. Returns `(hash, size)`. @@ -63,6 +69,9 @@ impl BlobStore { } pub fn open_blob(&self, hash: &str) -> Result { + if !is_valid_hash(hash) { + return Err(crate::Error::Invalid(format!("bad blob hash {hash:?}"))); + } Ok(fs::File::open(self.path_of(hash))?) } } diff --git a/crates/synapse-core/src/hlc.rs b/crates/synapse-core/src/hlc.rs index 11d423e..978fc7e 100644 --- a/crates/synapse-core/src/hlc.rs +++ b/crates/synapse-core/src/hlc.rs @@ -3,6 +3,8 @@ use std::sync::Mutex; +const MAX_COUNTER: u32 = 99_999; + #[derive(Debug)] pub struct HlcClock { actor: String, @@ -26,6 +28,9 @@ impl HlcClock { let mut s = self.state.lock().unwrap(); if now_ms > s.0 { *s = (now_ms, 0); + } else if s.1 >= MAX_COUNTER { + // Keep the fixed-width encoding sortable: borrow the next millisecond. + *s = (s.0 + 1, 0); } else { s.1 += 1; } @@ -63,7 +68,8 @@ mod tests { let t2 = c.tick(1000); let t3 = c.tick(999); assert!(t1 < t2 && t2 < t3); - c.observe(&encode(5000, 7, "b")); - assert!(c.tick(10) > encode(5000, 7, "b")); + c.observe(&encode(5000, MAX_COUNTER, "b")); + let next = c.tick(10); + assert!(next > encode(5000, MAX_COUNTER, "b") && next.starts_with("0000000005001-")); } } diff --git a/crates/synapse-core/src/schema.rs b/crates/synapse-core/src/schema.rs index d8f56a7..cbf1efb 100644 --- a/crates/synapse-core/src/schema.rs +++ b/crates/synapse-core/src/schema.rs @@ -1,4 +1,4 @@ -pub const VERSION: i64 = 1; +pub const VERSION: i64 = 2; pub const SCHEMA: &str = r#" CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); @@ -20,7 +20,8 @@ CREATE INDEX IF NOT EXISTS pages_origin ON pages(origin_journal); CREATE TABLE IF NOT EXISTS aliases ( alias_key TEXT PRIMARY KEY, alias TEXT NOT NULL, - page_id TEXT NOT NULL + page_id TEXT NOT NULL, + hlc TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS aliases_page ON aliases(page_id); @@ -90,3 +91,18 @@ CREATE TABLE IF NOT EXISTS ops ( payload TEXT NOT NULL ); "#; + +/// Upgrades databases created by older versions in place. +pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> { + let has_alias_hlc: bool = conn + .prepare("SELECT 1 FROM pragma_table_info('aliases') WHERE name='hlc'")? + .exists([])?; + if !has_alias_hlc { + conn.execute_batch("ALTER TABLE aliases ADD COLUMN hlc TEXT NOT NULL DEFAULT ''")?; + } + conn.execute( + "INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)", + [VERSION.to_string()], + )?; + Ok(()) +} diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs index 726cfd8..ccfeb8f 100644 --- a/crates/synapse-core/src/store.rs +++ b/crates/synapse-core/src/store.rs @@ -43,7 +43,9 @@ impl Graph { conn.pragma_update(None, "journal_mode", "WAL")?; conn.pragma_update(None, "synchronous", "NORMAL")?; conn.pragma_update(None, "foreign_keys", "OFF")?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; conn.execute_batch(schema::SCHEMA)?; + schema::migrate(&conn)?; let actor: String = match conn .query_row("SELECT value FROM meta WHERE key='actor'", [], |r| r.get(0)) .optional()? @@ -182,6 +184,11 @@ impl Graph { if title.is_empty() { return Err(Error::Invalid("empty page title".into())); } + if parse_day(&title).is_some() { + return Err(Error::Invalid(format!( + "{title:?} is a journal date; use journal()" + ))); + } if self.page_by_title(&title)?.is_some() { return Err(Error::Conflict(format!("page {title:?} already exists"))); } @@ -216,6 +223,9 @@ impl Graph { if let Some(p) = self.page_by_title(title)? { return Ok(p); } + if let Some(date) = parse_day(title) { + return self.journal(date); + } self.create_page(NewPage { title: title.into(), origin_journal: origin, @@ -254,9 +264,11 @@ impl Graph { let mut page = self .get_page(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; + let tx = self.tx()?; page.properties = properties; page.updated_at = self.now_ms(); self.write_page(&page, &self.tick())?; + tx.commit()?; Ok(page) } @@ -270,6 +282,12 @@ impl Graph { return Err(Error::Invalid("journal pages cannot be renamed".into())); } let new_title = new_title.trim(); + if new_title.is_empty() { + return Err(Error::Invalid("empty page title".into())); + } + if parse_day(new_title).is_some() { + return Err(Error::Invalid(format!("{new_title:?} is a journal date"))); + } if let Some(other) = self.page_by_title(new_title)? && other.id != id { @@ -291,7 +309,17 @@ impl Graph { for bid in referencing { if let Some(mut b) = self.get_block(parse_id(&bid)?)? { let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title); - if rewritten != b.content { + let mut props_changed = false; + for v in b.properties.values_mut() { + if let Some(text) = v.as_str() { + let r = parse::rewrite_refs(text, &old_key, new_title); + if r != text { + *v = serde_json::Value::String(r); + props_changed = true; + } + } + } + if rewritten != b.content || props_changed { b.content = rewritten; b.updated_at = self.now_ms(); self.write_block(&b, &self.tick())?; @@ -322,15 +350,17 @@ impl Graph { /// Points `alias` at `page` (or removes it with `None`). pub fn set_alias(&self, alias: &str, page: Option) -> Result<()> { + let tx = self.tx()?; let hlc = self.tick(); - self.write_alias(alias, page)?; + self.write_alias(alias, page, &hlc)?; self.log( &hlc, &Op::SetAlias { alias: alias.to_string(), page, }, - ) + )?; + tx.commit() } pub fn aliases_of(&self, page: PageId) -> Result> { @@ -508,6 +538,22 @@ impl Graph { } out.push((d, b)); } + // Blocks not reachable from the roots (parent missing after a concurrent delete, or a + // parent cycle from concurrent moves) are shown as roots, deterministically ordered. + let mut parents: Vec> = children.keys().copied().collect(); + parents.sort(); + for parent in parents { + let mut stack: Vec<(usize, Block)> = match children.remove(&parent) { + Some(blocks) => blocks.into_iter().rev().map(|b| (0, b)).collect(), + None => continue, + }; + while let Some((d, b)) = stack.pop() { + if let Some(kids) = children.remove(&Some(b.id)) { + stack.extend(kids.into_iter().rev().map(|k| (d + 1, k))); + } + out.push((d, b)); + } + } Ok(out) } @@ -573,7 +619,9 @@ impl Graph { .get_block(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; b.collapsed = collapsed; - self.write_block(&b, &self.tick()) + let tx = self.tx()?; + self.write_block(&b, &self.tick())?; + tx.commit() } /// Moves a block (with its subtree) to a new place, possibly on another page. @@ -584,7 +632,11 @@ impl Graph { .ok_or_else(|| Error::NotFound(id.to_string()))?; let (parent_id, position) = self.resolve_placement(page, at)?; let mut p = parent_id; + let mut seen = std::collections::HashSet::new(); while let Some(pid) = p { + if !seen.insert(pid) { + break; // pre-existing cycle (from concurrent moves); page_tree tolerates it + } if pid == id { return Err(Error::Invalid( "cannot move a block into its own subtree".into(), @@ -629,7 +681,7 @@ impl Graph { fn descendants(&self, id: BlockId) -> Result> { let mut st = self.conn.prepare_cached( "WITH RECURSIVE d(id) AS (SELECT id FROM blocks WHERE parent_id=?1 - UNION ALL SELECT b.id FROM blocks b JOIN d ON b.parent_id = d.id) + UNION SELECT b.id FROM blocks b JOIN d ON b.parent_id = d.id) SELECT id FROM d", )?; let rows = st.query_map([id.to_string()], |r| r.get::<_, String>(0))?; @@ -694,6 +746,9 @@ impl Graph { let parent_sql = "page_id=?1 AND parent_id IS ?2"; Ok(match at { Placement::LastChildOf(parent) => { + if let Some(p) = parent { + sib(p)?; + } let max: Option = self.conn.query_row( &format!("SELECT max(position) FROM blocks WHERE {parent_sql}"), params![page.to_string(), parent.map(|p| p.to_string())], @@ -841,6 +896,7 @@ impl Graph { original_name: name.map(str::to_string), created_at: self.now_ms(), }; + let tx = self.tx()?; let hlc = self.tick(); self.write_asset(&asset)?; self.log( @@ -849,6 +905,7 @@ impl Graph { asset: asset.clone(), }, )?; + tx.commit()?; Ok(asset) } @@ -948,17 +1005,30 @@ impl Graph { false } else { let mut page = page.clone(); - // Two replicas created the same title offline: the smaller id keeps it. - if let Some(other) = self.page_by_title(&page.title)? { - if other.id != page.id && other.id < page.id { - page.title = - format!("{} ~{}", page.title, &page.id.simple().to_string()[..6]); - } else if other.id != page.id { + // Two replicas created the same title offline. Journals always keep their + // date title; otherwise the smaller id keeps it. Every replica applies the + // same rule, so they converge. + if let Some(other) = self.page_by_exact_title(&page.title)? + && other.id != page.id + { + let incoming_wins = match (page.is_journal(), other.is_journal()) { + (true, false) => true, + (false, true) => false, + _ => page.id < other.id, + }; + if incoming_wins { let mut o = other.clone(); - o.title = format!("{} ~{}", o.title, &o.id.simple().to_string()[..6]); + o.title = self.conflict_title(&o.title, o.id)?; self.write_page(&o, &self.tick())?; + } else { + page.title = self.conflict_title(&page.title, page.id)?; } } + // A page title beats a colliding alias. + self.conn.execute( + "DELETE FROM aliases WHERE alias_key=?1 AND page_id != ?2", + params![title_key(&page.title), page.id.to_string()], + )?; self.write_page_row(&page, hlc)?; true } @@ -982,14 +1052,26 @@ impl Graph { } } Op::PutAsset { asset } => { - self.asset(&asset.hash)?.is_none() && { + crate::blob::is_valid_hash(&asset.hash) && self.asset(&asset.hash)?.is_none() && { self.write_asset(asset)?; true } } Op::SetAlias { alias, page } => { - self.write_alias(alias, *page)?; - true + let key = title_key(alias); + let local: Option = self + .conn + .query_row( + "SELECT hlc FROM aliases WHERE alias_key=?1 + UNION ALL SELECT hlc FROM tombstones WHERE id=?2", + params![key, format!("alias:{key}")], + |r| r.get(0), + ) + .optional()?; + local.is_none_or(|l| hlc > l.as_str()) && { + self.write_alias(alias, *page, hlc)?; + true + } } }; if applied { @@ -1046,6 +1128,21 @@ impl Graph { fn remove_page_row_raw(&self, id: PageId, hlc: &str) -> Result<()> { let s = id.to_string(); + // Cascade: blocks inserted concurrently on another replica must not linger orphaned. + self.conn.execute( + "INSERT OR REPLACE INTO tombstones(id, hlc) SELECT id, ?2 FROM blocks WHERE page_id=?1", + params![s, hlc], + )?; + self.conn.execute( + "DELETE FROM refs WHERE block_id IN (SELECT id FROM blocks WHERE page_id=?1)", + [&s], + )?; + self.conn.execute( + "DELETE FROM block_refs WHERE block_id IN (SELECT id FROM blocks WHERE page_id=?1)", + [&s], + )?; + self.conn + .execute("DELETE FROM blocks WHERE page_id=?1", [&s])?; self.conn.execute("DELETE FROM pages WHERE id=?1", [&s])?; self.conn .execute("DELETE FROM aliases WHERE page_id=?1", [&s])?; @@ -1153,18 +1250,56 @@ impl Graph { Ok(()) } - fn write_alias(&self, alias: &str, page: Option) -> Result<()> { + fn write_alias(&self, alias: &str, page: Option, hlc: &str) -> Result<()> { + let key = title_key(alias); match page { - Some(p) => self.conn.execute( - "INSERT OR REPLACE INTO aliases(alias_key, alias, page_id) VALUES (?1, ?2, ?3)", - params![title_key(alias), alias.trim(), p.to_string()], - )?, - None => self - .conn - .execute("DELETE FROM aliases WHERE alias_key=?1", [title_key(alias)])?, - }; + Some(p) => { + self.conn.execute( + "INSERT OR REPLACE INTO aliases(alias_key, alias, page_id, hlc) VALUES (?1, ?2, ?3, ?4)", + params![key, alias.trim(), p.to_string(), hlc], + )?; + self.conn.execute( + "DELETE FROM tombstones WHERE id=?1", + [format!("alias:{key}")], + )?; + } + None => { + self.conn + .execute("DELETE FROM aliases WHERE alias_key=?1", [&key])?; + self.conn.execute( + "INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)", + params![format!("alias:{key}"), hlc], + )?; + } + } Ok(()) } + + /// Page whose own title (not alias) matches, case-insensitively. + fn page_by_exact_title(&self, title: &str) -> Result> { + Ok(self + .conn + .query_row( + &format!("SELECT {PAGE_COLS} FROM pages WHERE title_key=?1"), + [title_key(title)], + page_row, + ) + .optional()?) + } + + /// A free title for the loser of a title conflict, using the random tail of its id. + fn conflict_title(&self, title: &str, id: PageId) -> Result { + let hex = id.simple().to_string(); + for n in [8, 16, 32] { + let t = format!("{title} ~{}", &hex[32 - n..]); + if self.page_by_exact_title(&t)?.is_none() { + return Ok(t); + } + } + Err(Error::Conflict(format!( + "no free conflict title for {title:?}" + ))) + } } /// Savepoint guard: rolled back on drop unless committed. diff --git a/crates/synapse-core/tests/review_regressions.rs b/crates/synapse-core/tests/review_regressions.rs new file mode 100644 index 0000000..3232d4c --- /dev/null +++ b/crates/synapse-core/tests/review_regressions.rs @@ -0,0 +1,163 @@ +//! Regressions for bugs found in the integration review. + +use synapse_core::{Asset, Graph, NewPage, Op, Placement}; + +fn graph() -> (tempfile::TempDir, Graph) { + let dir = tempfile::tempdir().unwrap(); + let g = Graph::open(dir.path()).unwrap(); + (dir, g) +} + +fn sync(from: &Graph, to: &Graph, after: i64) { + for r in from.ops_since(after, 100_000).unwrap() { + to.apply_remote(&r.hlc, &r.op).unwrap(); + } +} + +#[test] +fn concurrent_moves_creating_a_cycle_stay_visible_and_deletable() { + let (_a, a) = graph(); + let (_b, b) = graph(); + let p = a.create_page(NewPage::titled("P")).unwrap(); + let x = a + .insert_block(p.id, Placement::LastChildOf(None), "x") + .unwrap(); + let y = a + .insert_block(p.id, Placement::LastChildOf(None), "y") + .unwrap(); + sync(&a, &b, 0); + let (sa, sb) = (a.last_seq().unwrap(), b.last_seq().unwrap()); + a.move_block(x.id, p.id, Placement::LastChildOf(Some(y.id))) + .unwrap(); + b.move_block(y.id, p.id, Placement::LastChildOf(Some(x.id))) + .unwrap(); + sync(&a, &b, sa); + sync(&b, &a, sb); + for g in [&a, &b] { + assert_eq!(g.page_tree(p.id).unwrap().len(), 2); + g.move_block(x.id, p.id, Placement::LastChildOf(Some(y.id))) + .ok(); + } + a.delete_block(x.id).unwrap(); + assert!(a.page_tree(p.id).unwrap().is_empty()); +} + +#[test] +fn three_replicas_with_the_same_title_converge() { + let reps: Vec<_> = (0..3).map(|_| graph()).collect(); + for (_, g) in &reps { + g.create_page(NewPage::titled("T")).unwrap(); + } + for (i, (_, from)) in reps.iter().enumerate() { + for (j, (_, to)) in reps.iter().enumerate() { + if i != j { + sync(from, to, 0); + } + } + } + // A second round propagates the renames done while resolving. + for (i, (_, from)) in reps.iter().enumerate() { + for (j, (_, to)) in reps.iter().enumerate() { + if i != j { + sync(from, to, 0); + } + } + } + let titles = |g: &Graph| { + let mut t: Vec<_> = g + .list_pages(false, 100, 0) + .unwrap() + .into_iter() + .map(|p| (p.id, p.title)) + .collect(); + t.sort(); + t + }; + let t0 = titles(&reps[0].1); + assert_eq!(t0.len(), 3); + assert_eq!(t0, titles(&reps[1].1)); + assert_eq!(t0, titles(&reps[2].1)); + assert_eq!(t0.iter().filter(|(_, t)| t == "T").count(), 1); +} + +#[test] +fn alias_last_writer_wins() { + let (_a, a) = graph(); + let (_b, b) = graph(); + let pa = a.create_page(NewPage::titled("A")).unwrap(); + let pb = a.create_page(NewPage::titled("B")).unwrap(); + sync(&a, &b, 0); + let (sa, sb) = (a.last_seq().unwrap(), b.last_seq().unwrap()); + a.set_alias("X", Some(pa.id)).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(2)); + b.set_alias("X", Some(pb.id)).unwrap(); + sync(&a, &b, sa); + sync(&b, &a, sb); + for g in [&a, &b] { + assert_eq!(g.page_by_title("x").unwrap().unwrap().id, pb.id); + } +} + +#[test] +fn incoming_title_does_not_rename_a_page_with_that_alias() { + let (_a, a) = graph(); + let (_b, b) = graph(); + let zed = a.create_page(NewPage::titled("Zed")).unwrap(); + a.set_alias("Alpha", Some(zed.id)).unwrap(); + b.create_page(NewPage::titled("Alpha")).unwrap(); + sync(&b, &a, 0); + assert_eq!(a.get_page(zed.id).unwrap().unwrap().title, "Zed"); + assert_ne!(a.page_by_title("alpha").unwrap().unwrap().id, zed.id); +} + +#[test] +fn placement_and_title_validation() { + let (_d, g) = graph(); + let p = g.create_page(NewPage::titled("P")).unwrap(); + let q = g.create_page(NewPage::titled("Q")).unwrap(); + let on_q = g + .insert_block(q.id, Placement::LastChildOf(None), "q") + .unwrap(); + assert!( + g.insert_block(p.id, Placement::LastChildOf(Some(on_q.id)), "bad") + .is_err() + ); + assert!(g.rename_page(p.id, " ").is_err()); + assert!(g.rename_page(p.id, "2030-01-01").is_err()); + assert!(g.create_page(NewPage::titled("2030-01-01")).is_err()); + let j = g.ensure_page("2030-01-01", None).unwrap(); + assert!(j.is_journal()); +} + +#[test] +fn rename_rewrites_property_refs() { + let (_d, g) = graph(); + let p = g.create_page(NewPage::titled("P")).unwrap(); + let b = g + .insert_block(p.id, Placement::LastChildOf(None), "meeting") + .unwrap(); + let mut props = synapse_core::Properties::new(); + props.insert("type".into(), "[[Old]]".into()); + g.set_block_properties(b.id, props).unwrap(); + let old = g.ensure_page("Old", None).unwrap(); + g.rename_page(old.id, "New").unwrap(); + let b = g.get_block(b.id).unwrap().unwrap(); + assert_eq!(b.properties["type"], "[[New]]"); +} + +#[test] +fn invalid_remote_asset_hash_is_ignored() { + let (_d, g) = graph(); + let asset = Asset { + hash: "ñ/../x".into(), + size: 1, + mime: None, + original_name: None, + created_at: 0, + }; + assert!( + !g.apply_remote("0000000000001-00000-zz", &Op::PutAsset { asset }) + .unwrap() + ); + assert!(!g.blobs().contains("ñ/../x")); +}