mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 15:56:43 +00:00
feat(history): git-based snapshots, page history and restore
Deterministic Logseq-compatible Markdown export committed to a bare gix repository, incremental snapshots driven by the op log, snapshot policy, page history/diff, restore through the Graph API and pure-Rust HTTP push. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fbcfcf678f
commit
3ab03777ea
13 files changed
+3535
-9
No files matched your search
@@ -0,0 +1,299 @@
|
||||
use std::time::Duration;
|
||||
use synapse_core::{Graph, NewPage, Placement};
|
||||
use synapse_history::{History, HistoryOptions, SnapshotPolicy, export};
|
||||
|
||||
const T0: i64 = 1_700_000_000_000;
|
||||
|
||||
fn setup() -> (tempfile::TempDir, Graph, History) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
g.set_now(Some(T0));
|
||||
let h = History::open(dir.path(), HistoryOptions::default()).unwrap();
|
||||
(dir, g, h)
|
||||
}
|
||||
|
||||
fn add(g: &Graph, title: &str, blocks: &[&str]) -> synapse_core::Page {
|
||||
let p = g.ensure_page(title, None).unwrap();
|
||||
for b in blocks {
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), b)
|
||||
.unwrap();
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn at(g: &Graph, ms: i64) {
|
||||
g.set_now(Some(ms));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_is_deterministic_and_logseq_shaped() {
|
||||
let (_d, g, _h) = setup();
|
||||
let p = add(&g, "Project/Alpha", &["first", "second"]);
|
||||
let first = g.page_tree(p.id).unwrap()[0].1.clone();
|
||||
g.insert_block(p.id, Placement::LastChildOf(Some(first.id)), "child\nmore")
|
||||
.unwrap();
|
||||
let t = add(&g, "Target", &["target block"]);
|
||||
let tb = g.page_tree(t.id).unwrap()[0].1.id;
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), &format!("see (({tb}))"))
|
||||
.unwrap();
|
||||
g.set_alias("Alpha", Some(p.id)).unwrap();
|
||||
let refs = export::referenced_blocks(g.conn()).unwrap();
|
||||
assert!(refs.contains(&tb));
|
||||
|
||||
let a = export::render_page(&g, &p, &refs).unwrap();
|
||||
let b = export::render_page(&g, &p, &refs).unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert!(
|
||||
a.starts_with("alias:: Alpha\n\n- first\n\t- child\n\t more\n- second\n"),
|
||||
"{a}"
|
||||
);
|
||||
let tt = export::render_page(&g, &g.get_page(t.id).unwrap().unwrap(), &refs).unwrap();
|
||||
assert!(tt.contains(&format!("id:: {tb}")), "{tt}");
|
||||
assert_eq!(export::page_path(&p), "pages/Project___Alpha.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_snapshot_only_rewrites_touched_pages() {
|
||||
let (_d, g, mut h) = setup();
|
||||
add(&g, "A", &["a1"]);
|
||||
add(&g, "B", &["b1"]);
|
||||
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
|
||||
assert!(s1.summary.contains("created"), "{}", s1.summary);
|
||||
assert!(
|
||||
h.snapshot(&g, T0 + 1000).unwrap().is_none(),
|
||||
"nothing changed"
|
||||
);
|
||||
|
||||
at(&g, T0 + 10_000);
|
||||
let a = g.page_by_title("A").unwrap().unwrap();
|
||||
g.insert_block(a.id, Placement::LastChildOf(None), "a2")
|
||||
.unwrap();
|
||||
let s2 = h.snapshot(&g, T0 + 20_000).unwrap().unwrap();
|
||||
assert_eq!(s2.summary, "1 page edited: A");
|
||||
// B's blob is unchanged between snapshots.
|
||||
assert_eq!(
|
||||
h.page_at(&s1.id, "B").unwrap(),
|
||||
h.page_at(&s2.id, "B").unwrap()
|
||||
);
|
||||
assert_eq!(h.snapshots(10).unwrap().len(), 2);
|
||||
|
||||
// Deleting a block (no page op) is still noticed.
|
||||
at(&g, T0 + 30_000);
|
||||
let b = g.page_by_title("B").unwrap().unwrap();
|
||||
let blk = g.page_tree(b.id).unwrap()[0].1.id;
|
||||
g.delete_block(blk).unwrap();
|
||||
let s3 = h.snapshot(&g, T0 + 40_000).unwrap().unwrap();
|
||||
assert_eq!(s3.summary, "1 page edited: B");
|
||||
assert_eq!(h.page_at(&s3.id, "B").unwrap().unwrap(), "");
|
||||
|
||||
// Deleting and renaming pages updates the tree.
|
||||
at(&g, T0 + 50_000);
|
||||
g.rename_page(a.id, "A2").unwrap();
|
||||
g.delete_page(b.id).unwrap();
|
||||
let s4 = h.snapshot(&g, T0 + 60_000).unwrap().unwrap();
|
||||
assert!(s4.summary.contains("2 deleted"), "{}", s4.summary);
|
||||
assert!(h.page_at(&s4.id, "A").unwrap().is_none());
|
||||
assert!(h.page_at(&s4.id, "A2").unwrap().unwrap().contains("a2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_equals_full_export() {
|
||||
let (_d, g, mut h) = setup();
|
||||
let a = add(&g, "A", &["a1"]);
|
||||
let t = add(&g, "T", &["t1"]);
|
||||
h.snapshot(&g, T0).unwrap();
|
||||
at(&g, T0 + 1000);
|
||||
let tb = g.page_tree(t.id).unwrap()[0].1.id;
|
||||
g.insert_block(a.id, Placement::LastChildOf(None), &format!("(({tb}))"))
|
||||
.unwrap();
|
||||
let s = h.snapshot(&g, T0 + 2000).unwrap().unwrap();
|
||||
// Page T (untouched by ops) gained an `id::` because it is now referenced.
|
||||
assert!(
|
||||
h.page_at(&s.id, "T")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.contains(&format!("id:: {tb}"))
|
||||
);
|
||||
|
||||
// A fresh history over the same graph produces identical files.
|
||||
let dir2 = tempfile::tempdir().unwrap();
|
||||
let mut h2 = History::open_at(dir2.path(), HistoryOptions::default()).unwrap();
|
||||
let s2 = h2.snapshot(&g, T0 + 2000).unwrap().unwrap();
|
||||
for title in ["A", "T"] {
|
||||
assert_eq!(
|
||||
h.page_at("HEAD", title).unwrap(),
|
||||
h2.page_at(&s2.id, title).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_controls_maybe_snapshot() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
g.set_now(Some(T0));
|
||||
let opts = HistoryOptions {
|
||||
policy: SnapshotPolicy {
|
||||
min_interval: Duration::from_secs(60),
|
||||
max_interval: Duration::from_secs(600),
|
||||
on_idle: Some(Duration::from_secs(30)),
|
||||
},
|
||||
include_blobs: false,
|
||||
};
|
||||
let mut h = History::open(dir.path(), opts).unwrap();
|
||||
add(&g, "A", &["x"]);
|
||||
let first = h.maybe_snapshot(&g, T0).unwrap();
|
||||
assert!(first.is_some(), "first snapshot is immediate");
|
||||
|
||||
let a = g.page_by_title("A").unwrap().unwrap();
|
||||
g.insert_block(a.id, Placement::LastChildOf(None), "y")
|
||||
.unwrap();
|
||||
// Too soon (min_interval).
|
||||
assert!(h.maybe_snapshot(&g, T0 + 10_000).unwrap().is_none());
|
||||
// Past min_interval and idle for 60s (>= 30s) since the change was first observed.
|
||||
assert!(h.maybe_snapshot(&g, T0 + 70_000).unwrap().is_some());
|
||||
assert!(
|
||||
h.maybe_snapshot(&g, T0 + 80_000).unwrap().is_none(),
|
||||
"nothing pending"
|
||||
);
|
||||
|
||||
// Continuous editing still snapshots at max_interval.
|
||||
for i in 0..30 {
|
||||
g.insert_block(a.id, Placement::LastChildOf(None), "z")
|
||||
.unwrap();
|
||||
let t = T0 + 120_000 + i * 20_000;
|
||||
let r = h.maybe_snapshot(&g, t).unwrap();
|
||||
if r.is_some() {
|
||||
assert!(t - (T0 + 70_000) >= 600_000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("max_interval never fired");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_history_and_diff() {
|
||||
let (_d, g, mut h) = setup();
|
||||
let p = add(&g, "Notes", &["one"]);
|
||||
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
|
||||
add(&g, "Other", &["noise"]);
|
||||
h.snapshot(&g, T0 + 1000).unwrap();
|
||||
at(&g, T0 + 5000);
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), "two")
|
||||
.unwrap();
|
||||
let s3 = h.snapshot(&g, T0 + 6000).unwrap().unwrap();
|
||||
|
||||
let versions = h.page_history("Notes").unwrap();
|
||||
assert_eq!(versions.len(), 2, "only snapshots that changed the page");
|
||||
assert_eq!(versions[0].snapshot.id, s3.id);
|
||||
assert_eq!(versions[1].snapshot.id, s1.id);
|
||||
let d = h.diff_page("Notes", &s1.id, &s3.id).unwrap();
|
||||
assert!(d.contains("+- two"), "{d}");
|
||||
assert!(!d.contains("noise"));
|
||||
// Abbreviated ids work.
|
||||
assert_eq!(h.page_at(&s1.id[..8], "Notes").unwrap().unwrap(), "- one\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_page_and_graph_keep_block_ids_and_never_rewrite_history() {
|
||||
let (_d, g, mut h) = setup();
|
||||
let p = add(&g, "Doc", &["keep me", "will change"]);
|
||||
let tree = g.page_tree(p.id).unwrap();
|
||||
let (keep, change) = (tree[0].1.id, tree[1].1.id);
|
||||
let other = add(&g, "Gone", &["bye"]);
|
||||
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
|
||||
let n_snaps = h.snapshots(100).unwrap().len();
|
||||
|
||||
at(&g, T0 + 1000);
|
||||
g.update_block(change, "changed!").unwrap();
|
||||
g.insert_block(p.id, Placement::LastChildOf(Some(keep)), "extra child")
|
||||
.unwrap();
|
||||
g.delete_page(other.id).unwrap();
|
||||
add(&g, "New page", &["fresh"]);
|
||||
|
||||
let r = h.restore_page(&g, "Doc", &s1.id, T0 + 2000).unwrap();
|
||||
assert_eq!(r.restored, 1);
|
||||
assert!(r.safety_snapshot.is_some());
|
||||
let texts: Vec<_> = g
|
||||
.page_tree(p.id)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(d, b)| (d, b.content, b.id))
|
||||
.collect();
|
||||
assert_eq!(texts.len(), 2);
|
||||
assert_eq!(texts[0].1, "keep me");
|
||||
assert_eq!(texts[0].2, keep, "unchanged block keeps its id");
|
||||
assert_eq!(texts[1].1, "will change");
|
||||
// History only grew.
|
||||
assert!(h.snapshots(100).unwrap().len() > n_snaps);
|
||||
|
||||
// Whole graph: deleted page returns, new page disappears.
|
||||
let r = h.restore_graph(&g, &s1.id, T0 + 3000).unwrap();
|
||||
assert!(r.removed >= 1);
|
||||
let gone = g.page_by_title("Gone").unwrap().expect("page restored");
|
||||
assert_eq!(g.page_tree(gone.id).unwrap()[0].1.content, "bye");
|
||||
assert!(g.page_by_title("New page").unwrap().is_none());
|
||||
|
||||
// After restoring, the next snapshot has the same page content as s1.
|
||||
let s = h
|
||||
.snapshot(&g, T0 + 4000)
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| h.snapshots(1).unwrap().remove(0));
|
||||
assert_eq!(
|
||||
h.page_at(&s.id, "Doc").unwrap(),
|
||||
h.page_at(&s1.id, "Doc").unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
h.page_at(&s.id, "Gone").unwrap(),
|
||||
h.page_at(&s1.id, "Gone").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_preserves_referenced_block_ids_and_aliases() {
|
||||
let (_d, g, mut h) = setup();
|
||||
let t = add(&g, "Target", &["answer"]);
|
||||
let tb = g.page_tree(t.id).unwrap()[0].1.id;
|
||||
let r = add(&g, "Ref", &[&format!("(({tb}))")]);
|
||||
g.set_alias("Tgt", Some(t.id)).unwrap();
|
||||
g.set_page_properties(
|
||||
t.id,
|
||||
serde_json::from_str(r#"{"type":"note","n":3,"done":true,"s":"true"}"#).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
|
||||
at(&g, T0 + 10);
|
||||
g.delete_block(tb).unwrap();
|
||||
g.set_alias("Tgt", None).unwrap();
|
||||
g.set_page_properties(t.id, Default::default()).unwrap();
|
||||
h.restore_page(&g, "Target", &s1.id, T0 + 20).unwrap();
|
||||
assert_eq!(g.get_block(tb).unwrap().unwrap().content, "answer");
|
||||
assert_eq!(g.aliases_of(t.id).unwrap(), ["Tgt"]);
|
||||
let props = g.get_page(t.id).unwrap().unwrap().properties;
|
||||
assert_eq!(props["n"], 3);
|
||||
assert_eq!(props["done"], true);
|
||||
assert_eq!(props["s"], "true");
|
||||
assert_eq!(g.block_backrefs(tb).unwrap()[0].page_id, r.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journals_and_assets() {
|
||||
let (dir, g, mut h) = setup();
|
||||
let day = chrono::NaiveDate::from_ymd_opt(2024, 3, 9).unwrap();
|
||||
let j = g.journal(day).unwrap();
|
||||
g.insert_block(j.id, Placement::LastChildOf(None), "met [[Someone]]")
|
||||
.unwrap();
|
||||
let src = dir.path().join("pic.png");
|
||||
std::fs::write(&src, b"not really a png").unwrap();
|
||||
let asset = g.put_asset_file(&src, Some("image/png")).unwrap();
|
||||
let s = h.snapshot(&g, T0).unwrap().unwrap();
|
||||
assert!(
|
||||
h.page_at(&s.id, "2024-03-09")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.contains("met [[Someone]]")
|
||||
);
|
||||
let files = h.file(&s.id, "assets.json").unwrap().unwrap();
|
||||
assert!(files.contains(&asset.hash) && files.contains("image/png"));
|
||||
let _ = NewPage::default();
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Pushes to a real `git receive-pack` behind a tiny smart-HTTP shim.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use synapse_core::{Graph, Placement};
|
||||
use synapse_history::{History, HistoryOptions, PushAuth};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
fn serve(
|
||||
remote: std::path::PathBuf,
|
||||
requests: usize,
|
||||
) -> (String, std::thread::JoinHandle<Vec<String>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}/repo.git", listener.local_addr().unwrap());
|
||||
let h = std::thread::spawn(move || {
|
||||
let mut auths = Vec::new();
|
||||
for _ in 0..requests {
|
||||
let (mut s, _) = listener.accept().unwrap();
|
||||
let mut r = BufReader::new(s.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let is_get = line.starts_with("GET");
|
||||
let mut len = 0usize;
|
||||
loop {
|
||||
let mut h = String::new();
|
||||
r.read_line(&mut h).unwrap();
|
||||
let h = h.trim_end().to_string();
|
||||
if h.is_empty() {
|
||||
break;
|
||||
}
|
||||
let lower = h.to_lowercase();
|
||||
if let Some(v) = lower.strip_prefix("content-length:") {
|
||||
len = v.trim().parse().unwrap();
|
||||
}
|
||||
if lower.starts_with("authorization:") {
|
||||
auths.push(h.clone());
|
||||
}
|
||||
}
|
||||
let mut body = vec![0; len];
|
||||
r.read_exact(&mut body).unwrap();
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("receive-pack").arg("--stateless-rpc");
|
||||
if is_get {
|
||||
cmd.arg("--advertise-refs");
|
||||
}
|
||||
let mut child = cmd
|
||||
.arg(&remote)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
child.stdin.take().unwrap().write_all(&body).unwrap();
|
||||
let out = child.wait_with_output().unwrap().stdout;
|
||||
let mut payload = Vec::new();
|
||||
let ct = if is_get {
|
||||
payload.extend_from_slice(b"001f# service=git-receive-pack\n0000");
|
||||
"application/x-git-receive-pack-advertisement"
|
||||
} else {
|
||||
"application/x-git-receive-pack-result"
|
||||
};
|
||||
payload.extend_from_slice(&out);
|
||||
write!(s, "HTTP/1.1 200 OK\r\nContent-Type: {ct}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", payload.len()).unwrap();
|
||||
s.write_all(&payload).unwrap();
|
||||
}
|
||||
auths
|
||||
});
|
||||
(url, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_incrementally_to_a_real_git_remote() {
|
||||
if Command::new("git").arg("--version").output().is_err() {
|
||||
eprintln!("git not installed, skipping");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
g.set_now(Some(1_700_000_000_000));
|
||||
let mut h = History::open(dir.path(), HistoryOptions::default()).unwrap();
|
||||
let p = g.ensure_page("Pushed", None).unwrap();
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), "hello remote")
|
||||
.unwrap();
|
||||
h.snapshot(&g, 1_700_000_000_000).unwrap();
|
||||
|
||||
let remote = tempfile::tempdir().unwrap();
|
||||
git(remote.path(), &["init", "--bare", "-q", "."]);
|
||||
let auth = PushAuth {
|
||||
username: "u".into(),
|
||||
secret: "tok".into(),
|
||||
};
|
||||
|
||||
let (url, srv) = serve(remote.path().into(), 2);
|
||||
let r = h.push(&url, "main", Some(&auth), false).unwrap();
|
||||
assert!(r.updated && r.objects > 3);
|
||||
assert_eq!(
|
||||
git(remote.path(), &["show", "main:pages/Pushed.md"]),
|
||||
"- hello remote\n"
|
||||
);
|
||||
git(remote.path(), &["fsck", "--strict"]);
|
||||
let auths = srv.join().unwrap();
|
||||
assert!(
|
||||
auths.iter().all(|a| a.contains("Basic dTp0b2s=")),
|
||||
"{auths:?}"
|
||||
);
|
||||
|
||||
// Second push: new snapshot only sends the delta; unchanged tip is a no-op.
|
||||
g.set_now(Some(1_700_000_100_000));
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), "more")
|
||||
.unwrap();
|
||||
h.snapshot(&g, 1_700_000_100_000).unwrap();
|
||||
let (url, srv) = serve(remote.path().into(), 2);
|
||||
let r = h.push(&url, "main", Some(&auth), false).unwrap();
|
||||
assert!(r.updated && r.objects < 8, "{r:?}");
|
||||
srv.join().unwrap();
|
||||
assert_eq!(
|
||||
git(remote.path(), &["rev-list", "--count", "main"]).trim(),
|
||||
"2"
|
||||
);
|
||||
git(remote.path(), &["fsck", "--strict"]);
|
||||
|
||||
let (url, srv) = serve(remote.path().into(), 1);
|
||||
assert!(!h.push(&url, "main", Some(&auth), false).unwrap().updated);
|
||||
srv.join().unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user