mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 07:46:25 +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
Generated
+1358
-9
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "synapse-history"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
description = "Automatic git-based backup and version history of a Synapse graph"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
synapse-core.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
rusqlite.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
# Pure-Rust git (no C toolchain: builds for Android/Windows). Local repo only; push is ours.
|
||||||
|
gix = { version = "0.89", default-features = false, features = ["sha1"] }
|
||||||
|
# Blocking HTTPS client (rustls) for pushing: gix cannot push yet.
|
||||||
|
ureq = { version = "3", default-features = false, features = ["rustls"] }
|
||||||
|
# zlib for the pack we send (already in the tree through gix/ureq).
|
||||||
|
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||||
|
# Unified text diffs for page versions.
|
||||||
|
similar = "2"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum Error {
|
||||||
|
#[error("core: {0}")]
|
||||||
|
Core(#[from] synapse_core::Error),
|
||||||
|
#[error("sqlite: {0}")]
|
||||||
|
Sqlite(#[from] rusqlite::Error),
|
||||||
|
#[error("io: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("json: {0}")]
|
||||||
|
Json(#[from] serde_json::Error),
|
||||||
|
#[error("git: {0}")]
|
||||||
|
Git(String),
|
||||||
|
#[error("not found: {0}")]
|
||||||
|
NotFound(String),
|
||||||
|
#[error("push: {0}")]
|
||||||
|
Push(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
pub(crate) fn git<E: std::fmt::Display>(e: E) -> Error {
|
||||||
|
Error::Git(e.to_string())
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
//! Deterministic Logseq-compatible Markdown export of pages.
|
||||||
|
//!
|
||||||
|
//! Layout: `pages/<encoded title>.md`, `journals/YYYY_MM_DD.md`, `assets.json`.
|
||||||
|
//! A page file starts with page properties (`key:: value`, aliases as `alias:: a, b`),
|
||||||
|
//! then one `- ` bullet per block, nested with tabs. Block properties follow the content;
|
||||||
|
//! blocks referenced by `((uuid))` carry an `id::` property.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::error::Error;
|
||||||
|
use rusqlite::Connection;
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use synapse_core::{Block, BlockId, Graph, Page, Properties};
|
||||||
|
|
||||||
|
pub const PAGES_DIR: &str = "pages";
|
||||||
|
pub const JOURNALS_DIR: &str = "journals";
|
||||||
|
pub const MANIFEST: &str = "assets.json";
|
||||||
|
|
||||||
|
/// Encodes a page title as a file name (Logseq "triple-lowbar" format: `/` becomes `___`,
|
||||||
|
/// characters illegal on Windows and `%` are percent-encoded).
|
||||||
|
pub fn encode_title(title: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(title.len());
|
||||||
|
let mut run = 0usize;
|
||||||
|
let mut prev_slash = false;
|
||||||
|
// Underscore runs next to a `/` or of 3+ would read back as `/`, so they are encoded.
|
||||||
|
let flush = |out: &mut String, run: &mut usize, prev_slash: bool, next_slash: bool| {
|
||||||
|
let enc = *run >= 3 || prev_slash || next_slash;
|
||||||
|
for _ in 0..*run {
|
||||||
|
out.push_str(if enc { "%5F" } else { "_" });
|
||||||
|
}
|
||||||
|
*run = 0;
|
||||||
|
};
|
||||||
|
for c in title.chars() {
|
||||||
|
if c == '_' {
|
||||||
|
run += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
flush(&mut out, &mut run, prev_slash, c == '/');
|
||||||
|
prev_slash = c == '/';
|
||||||
|
match c {
|
||||||
|
'/' => out.push_str("___"),
|
||||||
|
'%' | '<' | '>' | ':' | '"' | '\\' | '|' | '?' | '*' => {
|
||||||
|
out.push_str(&format!("%{:02X}", c as u32))
|
||||||
|
}
|
||||||
|
c if (c as u32) < 0x20 => out.push_str(&format!("%{:02X}", c as u32)),
|
||||||
|
c => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(&mut out, &mut run, prev_slash, false);
|
||||||
|
// Windows forbids trailing dots/spaces.
|
||||||
|
while out.ends_with('.') || out.ends_with(' ') {
|
||||||
|
let c = out.pop().unwrap();
|
||||||
|
out.push_str(&format!("%{:02X}", c as u32));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inverse of [`encode_title`].
|
||||||
|
pub fn decode_title(name: &str) -> String {
|
||||||
|
let s = name.replace("___", "/");
|
||||||
|
let bytes = s.as_bytes();
|
||||||
|
let mut raw = Vec::with_capacity(bytes.len());
|
||||||
|
let mut i = 0;
|
||||||
|
while i < bytes.len() {
|
||||||
|
let hex = (bytes[i] == b'%' && i + 2 < bytes.len())
|
||||||
|
.then(|| std::str::from_utf8(&bytes[i + 1..i + 3]).ok())
|
||||||
|
.flatten()
|
||||||
|
.and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||||
|
if let Some(v) = hex {
|
||||||
|
raw.push(v);
|
||||||
|
i += 3;
|
||||||
|
} else {
|
||||||
|
raw.push(bytes[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::from_utf8_lossy(&raw).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Repository-relative path of a page's Markdown file.
|
||||||
|
pub fn page_path(page: &Page) -> String {
|
||||||
|
match page.journal_date {
|
||||||
|
Some(d) => format!("{JOURNALS_DIR}/{}.md", d.format("%Y_%m_%d")),
|
||||||
|
None => format!("{PAGES_DIR}/{}.md", encode_title(&page.title)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Title (or journal date) from a repository path, if it is a page file.
|
||||||
|
pub fn title_from_path(path: &str) -> Option<String> {
|
||||||
|
if let Some(n) = path.strip_prefix("pages/") {
|
||||||
|
return n.strip_suffix(".md").map(decode_title);
|
||||||
|
}
|
||||||
|
let n = path.strip_prefix("journals/")?.strip_suffix(".md")?;
|
||||||
|
Some(n.replace('_', "-"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn render_value(v: &Value) -> String {
|
||||||
|
match v {
|
||||||
|
Value::String(s) => {
|
||||||
|
if !s.contains('\n') && parse_value(s) == Value::String(s.clone()) {
|
||||||
|
s.clone()
|
||||||
|
} else {
|
||||||
|
Value::String(s.clone()).to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a property value: JSON for non-strings and quoted strings, raw text otherwise.
|
||||||
|
pub(crate) fn parse_value(raw: &str) -> Value {
|
||||||
|
let t = raw.trim();
|
||||||
|
match serde_json::from_str::<Value>(t) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(_) => Value::String(t.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_props(out: &mut String, indent: &str, props: &[(String, String)]) {
|
||||||
|
for (k, v) in props {
|
||||||
|
out.push_str(indent);
|
||||||
|
out.push_str(k);
|
||||||
|
out.push_str(":: ");
|
||||||
|
out.push_str(v);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sorted_props(p: &Properties) -> Vec<(String, String)> {
|
||||||
|
let mut v: Vec<_> = p
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| (k.clone(), render_value(v)))
|
||||||
|
.collect();
|
||||||
|
v.sort();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders one block (without its children) at `depth`.
|
||||||
|
pub fn render_block(block: &Block, depth: usize, referenced: &HashSet<BlockId>) -> String {
|
||||||
|
let indent = "\t".repeat(depth);
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut lines = block.content.split('\n');
|
||||||
|
let first = lines.next().unwrap_or("");
|
||||||
|
out.push_str(&indent);
|
||||||
|
out.push('-');
|
||||||
|
if !first.is_empty() {
|
||||||
|
out.push(' ');
|
||||||
|
out.push_str(first);
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
let cont = format!("{indent} ");
|
||||||
|
for l in lines {
|
||||||
|
out.push_str(&cont);
|
||||||
|
out.push_str(l);
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
let mut props = block.properties.clone();
|
||||||
|
props.remove("id");
|
||||||
|
props.remove("collapsed");
|
||||||
|
let mut list = sorted_props(&props);
|
||||||
|
if block.collapsed {
|
||||||
|
list.push(("collapsed".into(), "true".into()));
|
||||||
|
}
|
||||||
|
if referenced.contains(&block.id) {
|
||||||
|
list.push(("id".into(), block.id.to_string()));
|
||||||
|
}
|
||||||
|
list.sort();
|
||||||
|
push_props(&mut out, &cont, &list);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the full Markdown file of a page.
|
||||||
|
pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet<BlockId>) -> Result<String> {
|
||||||
|
let mut props = page.properties.clone();
|
||||||
|
props.remove("alias");
|
||||||
|
let mut list = sorted_props(&props);
|
||||||
|
let aliases = graph.aliases_of(page.id)?;
|
||||||
|
if !aliases.is_empty() {
|
||||||
|
list.push(("alias".into(), aliases.join(", ")));
|
||||||
|
}
|
||||||
|
list.sort();
|
||||||
|
let mut out = String::new();
|
||||||
|
push_props(&mut out, "", &list);
|
||||||
|
if !list.is_empty() {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
for (depth, b) in graph.page_tree(page.id)? {
|
||||||
|
out.push_str(&render_block(&b, depth, referenced));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every block id that is the target of a `((uuid))` reference or embed.
|
||||||
|
pub fn referenced_blocks(conn: &Connection) -> Result<HashSet<BlockId>> {
|
||||||
|
let mut st = conn.prepare("SELECT DISTINCT target_block FROM block_refs")?;
|
||||||
|
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
|
||||||
|
let mut set = HashSet::new();
|
||||||
|
for r in rows {
|
||||||
|
if let Ok(id) = r?.parse() {
|
||||||
|
set.insert(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(set)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asset manifest (`assets.json`): sorted by hash, so it is deterministic.
|
||||||
|
pub fn render_manifest(conn: &Connection) -> Result<String> {
|
||||||
|
let mut st =
|
||||||
|
conn.prepare("SELECT hash, size, mime, original_name FROM assets ORDER BY hash")?;
|
||||||
|
let rows = st.query_map([], |r| {
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"hash": r.get::<_, String>(0)?,
|
||||||
|
"size": r.get::<_, i64>(1)?,
|
||||||
|
"mime": r.get::<_, Option<String>>(2)?,
|
||||||
|
"name": r.get::<_, Option<String>>(3)?,
|
||||||
|
}))
|
||||||
|
})?;
|
||||||
|
let list: Vec<Value> = rows.collect::<std::result::Result<_, _>>()?;
|
||||||
|
let mut s = serde_json::to_string_pretty(&list).map_err(Error::from)?;
|
||||||
|
s.push('\n');
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn title_encoding_roundtrips() {
|
||||||
|
for t in [
|
||||||
|
"Simple",
|
||||||
|
"a/b/c",
|
||||||
|
"100% sure?",
|
||||||
|
"snake_case",
|
||||||
|
"a___b",
|
||||||
|
"x____y/z",
|
||||||
|
"x_/_y",
|
||||||
|
"end.",
|
||||||
|
"q: \"w\" <e> |r| *t*",
|
||||||
|
"Ünï/cödé 日本",
|
||||||
|
"trail ",
|
||||||
|
] {
|
||||||
|
let e = encode_title(t);
|
||||||
|
assert!(!e.contains('/') && !e.contains(':'), "{e}");
|
||||||
|
assert_eq!(decode_title(&e), t, "{t} -> {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
//! Snapshot engine: incremental Markdown export committed to a bare git repository.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::export::{self, JOURNALS_DIR, MANIFEST, PAGES_DIR};
|
||||||
|
use crate::repo::{CommitInfo, Files, Repo};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::Duration;
|
||||||
|
use synapse_core::{BlockId, Graph, Op, Page, PageId};
|
||||||
|
|
||||||
|
const STATE_FILE: &str = "synapse-history.json";
|
||||||
|
const OPS_BATCH: u32 = 2000;
|
||||||
|
const TITLES_IN_MESSAGE: usize = 5;
|
||||||
|
|
||||||
|
/// When [`History::maybe_snapshot`] actually commits.
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SnapshotPolicy {
|
||||||
|
/// Never snapshot more often than this.
|
||||||
|
pub min_interval: Duration,
|
||||||
|
/// Snapshot at the latest this long after the previous one if anything changed.
|
||||||
|
pub max_interval: Duration,
|
||||||
|
/// Snapshot once the graph has been quiet this long (still respecting `min_interval`).
|
||||||
|
pub on_idle: Option<Duration>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SnapshotPolicy {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
min_interval: Duration::from_secs(5 * 60),
|
||||||
|
max_interval: Duration::from_secs(60 * 60),
|
||||||
|
on_idle: Some(Duration::from_secs(2 * 60)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct HistoryOptions {
|
||||||
|
pub policy: SnapshotPolicy,
|
||||||
|
/// Also commit asset bytes (`blobs/<hash>`). Off by default: blobs are already
|
||||||
|
/// content-addressed and only the manifest is versioned.
|
||||||
|
pub include_blobs: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SnapshotInfo {
|
||||||
|
/// Full commit id (hex).
|
||||||
|
pub id: String,
|
||||||
|
/// Seconds since epoch.
|
||||||
|
pub time: i64,
|
||||||
|
/// First line of the commit message.
|
||||||
|
pub summary: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CommitInfo> for SnapshotInfo {
|
||||||
|
fn from(c: CommitInfo) -> Self {
|
||||||
|
Self {
|
||||||
|
id: c.id,
|
||||||
|
time: c.time,
|
||||||
|
summary: c.message.lines().next().unwrap_or("").to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
struct State {
|
||||||
|
/// Last op seq covered by the newest snapshot.
|
||||||
|
last_seq: i64,
|
||||||
|
/// Graph clock (ms) when the newest snapshot was taken.
|
||||||
|
snapshot_ms: i64,
|
||||||
|
/// Blocks that carried an `id::` property in the newest snapshot.
|
||||||
|
referenced: BTreeSet<BlockId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct History {
|
||||||
|
pub(crate) repo: Repo,
|
||||||
|
dir: PathBuf,
|
||||||
|
opts: HistoryOptions,
|
||||||
|
/// `(last seen graph seq, time we saw it change)` for idle detection.
|
||||||
|
observed: Option<(i64, i64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl History {
|
||||||
|
/// Opens (creating if needed) `<graph_dir>/history/`.
|
||||||
|
pub fn open(graph_dir: impl AsRef<Path>, opts: HistoryOptions) -> Result<Self> {
|
||||||
|
Self::open_at(graph_dir.as_ref().join("history"), opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_at(dir: impl Into<PathBuf>, opts: HistoryOptions) -> Result<Self> {
|
||||||
|
let dir = dir.into();
|
||||||
|
let repo = Repo::open_or_init(&dir)?;
|
||||||
|
Ok(Self {
|
||||||
|
repo,
|
||||||
|
dir,
|
||||||
|
opts,
|
||||||
|
observed: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir(&self) -> &Path {
|
||||||
|
&self.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_state(&self) -> Option<State> {
|
||||||
|
serde_json::from_slice(&std::fs::read(self.dir.join(STATE_FILE)).ok()?).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_state(&self, s: &State) -> Result<()> {
|
||||||
|
let tmp = self.dir.join(format!("{STATE_FILE}.tmp"));
|
||||||
|
std::fs::write(&tmp, serde_json::to_vec(s)?)?;
|
||||||
|
std::fs::rename(tmp, self.dir.join(STATE_FILE))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the graph has changes not yet covered by a snapshot.
|
||||||
|
pub fn has_pending(&self, graph: &Graph) -> Result<bool> {
|
||||||
|
Ok(match self.load_state() {
|
||||||
|
Some(s) => graph.last_seq()? != s.last_seq,
|
||||||
|
None => true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called periodically by the app; snapshots when the policy says so.
|
||||||
|
/// `now_ms` is wall-clock milliseconds.
|
||||||
|
pub fn maybe_snapshot(&mut self, graph: &Graph, now_ms: i64) -> Result<Option<SnapshotInfo>> {
|
||||||
|
let seq = graph.last_seq()?;
|
||||||
|
let changed_at = match self.observed {
|
||||||
|
Some((s, t)) if s == seq => t,
|
||||||
|
_ => now_ms,
|
||||||
|
};
|
||||||
|
self.observed = Some((seq, changed_at));
|
||||||
|
let state = self.load_state();
|
||||||
|
if state.as_ref().is_some_and(|s| s.last_seq == seq) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let p = self.opts.policy;
|
||||||
|
let ms = |d: Duration| d.as_millis() as i64;
|
||||||
|
let since_last = match (&state, self.repo.head()?) {
|
||||||
|
(Some(_), Some(head)) => now_ms - self.repo.commit_info(head)?.time * 1000,
|
||||||
|
_ => i64::MAX, // first snapshot: take it as soon as there is something
|
||||||
|
};
|
||||||
|
if since_last < ms(p.min_interval) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let idle = p.on_idle.is_some_and(|d| now_ms - changed_at >= ms(d));
|
||||||
|
if since_last >= ms(p.max_interval) || idle {
|
||||||
|
return self.snapshot(graph, now_ms);
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes a snapshot now. Returns `None` when nothing changed.
|
||||||
|
pub fn snapshot(&mut self, graph: &Graph, now_ms: i64) -> Result<Option<SnapshotInfo>> {
|
||||||
|
let state = self.load_state();
|
||||||
|
let head = self.repo.head()?;
|
||||||
|
let seq_now = graph.last_seq()?;
|
||||||
|
let full = match (&state, head) {
|
||||||
|
(Some(s), Some(_)) => s.last_seq > seq_now,
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
if !full && state.as_ref().is_some_and(|s| s.last_seq == seq_now) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let old_state = state.unwrap_or_default();
|
||||||
|
let old_files = match head {
|
||||||
|
Some(h) => self.repo.files(h)?,
|
||||||
|
None => Files::new(),
|
||||||
|
};
|
||||||
|
let mut files = old_files.clone();
|
||||||
|
|
||||||
|
// 1. Which pages may have changed?
|
||||||
|
let mut touched: HashSet<PageId> = HashSet::new();
|
||||||
|
let mut everything = full;
|
||||||
|
if !full {
|
||||||
|
let mut after = old_state.last_seq;
|
||||||
|
loop {
|
||||||
|
let ops = graph.ops_since(after, OPS_BATCH)?;
|
||||||
|
let Some(last) = ops.last() else { break };
|
||||||
|
after = last.seq;
|
||||||
|
for rec in ops {
|
||||||
|
match rec.op {
|
||||||
|
Op::UpsertPage { page } => {
|
||||||
|
touched.insert(page.id);
|
||||||
|
}
|
||||||
|
Op::UpsertBlock { block } => {
|
||||||
|
touched.insert(block.page_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::DeletePage { .. } | Op::PutAsset { .. } => {}
|
||||||
|
// The previous owner of an alias is unknown.
|
||||||
|
Op::SetAlias { .. } => everything = true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut current: HashMap<String, Page> = HashMap::new();
|
||||||
|
let mut offset = 0;
|
||||||
|
loop {
|
||||||
|
let batch = graph.list_pages(true, 500, offset)?;
|
||||||
|
if batch.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset += batch.len() as u32;
|
||||||
|
for p in batch {
|
||||||
|
if p.updated_at >= old_state.snapshot_ms {
|
||||||
|
touched.insert(p.id);
|
||||||
|
}
|
||||||
|
current.insert(export::page_path(&p), p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let referenced = export::referenced_blocks(graph.conn())?;
|
||||||
|
let old_ref: HashSet<BlockId> = old_state.referenced.iter().copied().collect();
|
||||||
|
for id in referenced.symmetric_difference(&old_ref) {
|
||||||
|
if let Some(b) = graph.get_block(*id)? {
|
||||||
|
touched.insert(b.page_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Rewrite touched pages, drop vanished ones.
|
||||||
|
let (mut created, mut edited, mut deleted) =
|
||||||
|
(BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
|
||||||
|
let mut paths: Vec<&String> = current.keys().collect();
|
||||||
|
paths.sort();
|
||||||
|
for path in paths {
|
||||||
|
let page = ¤t[path];
|
||||||
|
if !everything && !touched.contains(&page.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let text = export::render_page(graph, page, &referenced)?;
|
||||||
|
let oid = self.repo.write_blob(text.as_bytes())?;
|
||||||
|
match old_files.get(path) {
|
||||||
|
Some(old) if *old == oid => {}
|
||||||
|
Some(_) => {
|
||||||
|
edited.insert(page.title.clone());
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
created.insert(page.title.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files.insert(path.clone(), oid);
|
||||||
|
}
|
||||||
|
for path in old_files.keys() {
|
||||||
|
let is_page = path.starts_with(&format!("{PAGES_DIR}/"))
|
||||||
|
|| path.starts_with(&format!("{JOURNALS_DIR}/"));
|
||||||
|
if is_page && !current.contains_key(path) {
|
||||||
|
files.remove(path);
|
||||||
|
deleted.insert(export::title_from_path(path).unwrap_or_else(|| path.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Assets.
|
||||||
|
let manifest = self
|
||||||
|
.repo
|
||||||
|
.write_blob(export::render_manifest(graph.conn())?.as_bytes())?;
|
||||||
|
let assets_changed = old_files.get(MANIFEST) != Some(&manifest);
|
||||||
|
files.insert(MANIFEST.to_string(), manifest);
|
||||||
|
if self.opts.include_blobs {
|
||||||
|
self.add_blobs(graph, &mut files)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Commit.
|
||||||
|
let new_state = State {
|
||||||
|
last_seq: seq_now,
|
||||||
|
snapshot_ms: graph.now_ms(),
|
||||||
|
referenced: referenced.into_iter().collect(),
|
||||||
|
};
|
||||||
|
if files == old_files && head.is_some() {
|
||||||
|
self.save_state(&new_state)?;
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let message = commit_message(&created, &edited, &deleted, assets_changed, seq_now);
|
||||||
|
let id = self.repo.commit(&files, &message, now_ms / 1000)?;
|
||||||
|
self.save_state(&new_state)?;
|
||||||
|
Ok(Some(self.repo.commit_info(id)?.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_blobs(&self, graph: &Graph, files: &mut Files) -> Result<()> {
|
||||||
|
let mut st = graph
|
||||||
|
.conn()
|
||||||
|
.prepare("SELECT hash FROM assets ORDER BY hash")?;
|
||||||
|
let hashes: Vec<String> = st
|
||||||
|
.query_map([], |r| r.get(0))?
|
||||||
|
.collect::<std::result::Result<_, _>>()?;
|
||||||
|
for h in hashes {
|
||||||
|
let path = format!("blobs/{h}");
|
||||||
|
if files.contains_key(&path) || !graph.blobs().contains(&h) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let bytes = std::fs::read(graph.blobs().path_of(&h))?;
|
||||||
|
files.insert(path, self.repo.write_blob(&bytes)?);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- queries
|
||||||
|
|
||||||
|
/// Snapshots, newest first.
|
||||||
|
pub fn snapshots(&self, limit: usize) -> Result<Vec<SnapshotInfo>> {
|
||||||
|
Ok(self.repo.log(limit)?.into_iter().map(Into::into).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a snapshot reference: full or abbreviated commit id, or `HEAD`.
|
||||||
|
pub fn resolve(&self, rev: &str) -> Result<gix::ObjectId> {
|
||||||
|
if rev == "HEAD" {
|
||||||
|
return self
|
||||||
|
.repo
|
||||||
|
.head()?
|
||||||
|
.ok_or_else(|| Self::not_found("empty history"));
|
||||||
|
}
|
||||||
|
if rev.len() >= 4 {
|
||||||
|
let hits: Vec<_> = self
|
||||||
|
.repo
|
||||||
|
.log(usize::MAX)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|c| c.id.starts_with(rev))
|
||||||
|
.collect();
|
||||||
|
if let [one] = hits.as_slice() {
|
||||||
|
return Repo::parse_id(&one.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(Self::not_found(&format!("snapshot {rev}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Path of a page's file for a title (journals are titled `YYYY-MM-DD`).
|
||||||
|
pub fn path_for_title(title: &str) -> String {
|
||||||
|
match chrono::NaiveDate::parse_from_str(title, "%Y-%m-%d") {
|
||||||
|
Ok(d) => format!("{JOURNALS_DIR}/{}.md", d.format("%Y_%m_%d")),
|
||||||
|
Err(_) => format!("{PAGES_DIR}/{}.md", export::encode_title(title)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File content at a snapshot, `None` if the page did not exist then.
|
||||||
|
pub fn page_at(&self, rev: &str, title: &str) -> Result<Option<String>> {
|
||||||
|
self.file_at(self.resolve(rev)?, &Self::path_for_title(title))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Any file of a snapshot by repository path (e.g. `assets.json`).
|
||||||
|
pub fn file(&self, rev: &str, path: &str) -> Result<Option<String>> {
|
||||||
|
self.file_at(self.resolve(rev)?, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn file_at(&self, commit: gix::ObjectId, path: &str) -> Result<Option<String>> {
|
||||||
|
match self.repo.files(commit)?.get(path) {
|
||||||
|
Some(oid) => Ok(Some(
|
||||||
|
String::from_utf8_lossy(&self.repo.read_blob(*oid)?).into_owned(),
|
||||||
|
)),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshots in which the page's file changed (newest first), including its creation and
|
||||||
|
/// deletion. `exists` tells whether the page was present after that snapshot.
|
||||||
|
pub fn page_history(&self, title: &str) -> Result<Vec<PageVersion>> {
|
||||||
|
let path = Self::path_for_title(title);
|
||||||
|
let mut commits = Vec::new();
|
||||||
|
let mut cur = self.repo.head()?;
|
||||||
|
while let Some(id) = cur {
|
||||||
|
let files = self.repo.files(id)?;
|
||||||
|
commits.push((id, files.get(&path).copied()));
|
||||||
|
cur = self.repo.parent(id)?;
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (i, (id, oid)) in commits.iter().enumerate() {
|
||||||
|
let prev = commits.get(i + 1).and_then(|(_, o)| *o);
|
||||||
|
if *oid != prev {
|
||||||
|
out.push(PageVersion {
|
||||||
|
snapshot: self.repo.commit_info(*id)?.into(),
|
||||||
|
exists: oid.is_some(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unified diff of a page between two snapshots (`from` may be `None` for "empty").
|
||||||
|
pub fn diff_page(&self, title: &str, from: &str, to: &str) -> Result<String> {
|
||||||
|
let a = self.page_at(from, title)?.unwrap_or_default();
|
||||||
|
let b = self.page_at(to, title)?.unwrap_or_default();
|
||||||
|
let diff = similar::TextDiff::from_lines(&a, &b);
|
||||||
|
Ok(diff
|
||||||
|
.unified_diff()
|
||||||
|
.context_radius(3)
|
||||||
|
.header(
|
||||||
|
&format!("{title}@{}", short(from)),
|
||||||
|
&format!("{title}@{}", short(to)),
|
||||||
|
)
|
||||||
|
.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn snapshot_files(&self, rev: &str) -> Result<Files> {
|
||||||
|
self.repo.files(self.resolve(rev)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn read_blob(&self, oid: gix::ObjectId) -> Result<String> {
|
||||||
|
Ok(String::from_utf8_lossy(&self.repo.read_blob(oid)?).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn not_found(what: &str) -> Error {
|
||||||
|
Error::NotFound(what.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct PageVersion {
|
||||||
|
pub snapshot: SnapshotInfo,
|
||||||
|
pub exists: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short(rev: &str) -> &str {
|
||||||
|
&rev[..rev.len().min(8)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_message(
|
||||||
|
created: &BTreeSet<String>,
|
||||||
|
edited: &BTreeSet<String>,
|
||||||
|
deleted: &BTreeSet<String>,
|
||||||
|
assets: bool,
|
||||||
|
seq: i64,
|
||||||
|
) -> String {
|
||||||
|
let plural = |n: usize| if n == 1 { "page" } else { "pages" };
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
if !edited.is_empty() {
|
||||||
|
parts.push(format!("{} {} edited", edited.len(), plural(edited.len())));
|
||||||
|
}
|
||||||
|
if !created.is_empty() {
|
||||||
|
parts.push(format!("{} created", created.len()));
|
||||||
|
}
|
||||||
|
if !deleted.is_empty() {
|
||||||
|
parts.push(format!("{} deleted", deleted.len()));
|
||||||
|
}
|
||||||
|
if parts.is_empty() {
|
||||||
|
parts.push(if assets { "assets updated" } else { "snapshot" }.to_string());
|
||||||
|
}
|
||||||
|
let mut titles: Vec<&String> = edited.iter().chain(created).chain(deleted).collect();
|
||||||
|
titles.sort();
|
||||||
|
titles.dedup();
|
||||||
|
let mut head = parts.join(", ");
|
||||||
|
if !titles.is_empty() {
|
||||||
|
let shown: Vec<&str> = titles
|
||||||
|
.iter()
|
||||||
|
.take(TITLES_IN_MESSAGE)
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
.collect();
|
||||||
|
head.push_str(": ");
|
||||||
|
head.push_str(&shown.join(", "));
|
||||||
|
if titles.len() > TITLES_IN_MESSAGE {
|
||||||
|
head.push_str(", …");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
format!("{head}\n\nSynapse-Seq: {seq}\n")
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
//! Automatic git-based backup and version history of a Synapse graph. See `docs/history.md`.
|
||||||
|
|
||||||
|
mod error;
|
||||||
|
pub mod export;
|
||||||
|
mod history;
|
||||||
|
pub mod parse;
|
||||||
|
mod push;
|
||||||
|
mod repo;
|
||||||
|
mod restore;
|
||||||
|
|
||||||
|
pub use error::{Error, Result};
|
||||||
|
pub use history::{History, HistoryOptions, PageVersion, SnapshotInfo, SnapshotPolicy};
|
||||||
|
pub use push::{PushAuth, PushReport};
|
||||||
|
pub use restore::RestoreReport;
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
//! Parser for the Markdown files produced by [`crate::export`] (and plain Logseq pages).
|
||||||
|
|
||||||
|
use crate::export::parse_value;
|
||||||
|
use serde_json::Value;
|
||||||
|
use synapse_core::{BlockId, Properties, parse::property_split};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct ParsedBlock {
|
||||||
|
pub depth: usize,
|
||||||
|
/// From an `id::` property.
|
||||||
|
pub id: Option<BlockId>,
|
||||||
|
pub content: String,
|
||||||
|
pub properties: Properties,
|
||||||
|
pub collapsed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
|
pub struct ParsedPage {
|
||||||
|
/// Page properties except `alias`.
|
||||||
|
pub properties: Properties,
|
||||||
|
pub aliases: Vec<String>,
|
||||||
|
pub blocks: Vec<ParsedBlock>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Visual width of leading whitespace (a tab counts as 2 columns) and its byte length.
|
||||||
|
fn indent_of(line: &str) -> (usize, usize) {
|
||||||
|
let mut cols = 0;
|
||||||
|
let mut bytes = 0;
|
||||||
|
for c in line.chars() {
|
||||||
|
match c {
|
||||||
|
'\t' => cols += 2,
|
||||||
|
' ' => cols += 1,
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
bytes += 1;
|
||||||
|
}
|
||||||
|
(cols, bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strip_cols(line: &str, cols: usize) -> &str {
|
||||||
|
let mut left = cols;
|
||||||
|
let mut bytes = 0;
|
||||||
|
for c in line.chars() {
|
||||||
|
let w = match c {
|
||||||
|
'\t' => 2,
|
||||||
|
' ' => 1,
|
||||||
|
_ => break,
|
||||||
|
};
|
||||||
|
if w > left {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
left -= w;
|
||||||
|
bytes += 1;
|
||||||
|
if left == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
&line[bytes..]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bullet_text(trimmed: &str) -> Option<&str> {
|
||||||
|
if trimmed == "-" {
|
||||||
|
Some("")
|
||||||
|
} else {
|
||||||
|
trimmed.strip_prefix("- ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Raw {
|
||||||
|
depth: usize,
|
||||||
|
lines: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_page(text: &str) -> ParsedPage {
|
||||||
|
let mut page = ParsedPage::default();
|
||||||
|
let mut raws: Vec<Raw> = Vec::new();
|
||||||
|
let mut stack: Vec<usize> = Vec::new(); // bullet columns of open ancestors
|
||||||
|
let mut col_of_current = 0usize;
|
||||||
|
|
||||||
|
for line in text.split('\n') {
|
||||||
|
let line = line.strip_suffix('\r').unwrap_or(line);
|
||||||
|
let (cols, bytes) = indent_of(line);
|
||||||
|
if let Some(rest) = bullet_text(&line[bytes..]) {
|
||||||
|
while stack.last().is_some_and(|&c| c >= cols) {
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
raws.push(Raw {
|
||||||
|
depth: stack.len(),
|
||||||
|
lines: vec![rest.to_string()],
|
||||||
|
});
|
||||||
|
stack.push(cols);
|
||||||
|
col_of_current = cols;
|
||||||
|
} else if let Some(cur) = raws.last_mut() {
|
||||||
|
cur.lines
|
||||||
|
.push(strip_cols(line, col_of_current + 2).to_string());
|
||||||
|
} else if let Some((k, v)) = property_split(line.trim()) {
|
||||||
|
if k == "alias" {
|
||||||
|
page.aliases.extend(
|
||||||
|
v.split(',')
|
||||||
|
.map(|a| a.trim().trim_matches(['[', ']']).to_string())
|
||||||
|
.filter(|a| !a.is_empty()),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
page.properties.insert(k.to_string(), parse_value(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for raw in raws {
|
||||||
|
let mut lines = raw.lines;
|
||||||
|
// Blank separator lines between blocks are not content.
|
||||||
|
while lines.len() > 1 && lines.last().is_some_and(|l| l.is_empty()) {
|
||||||
|
lines.pop();
|
||||||
|
}
|
||||||
|
let mut props = Properties::new();
|
||||||
|
let mut split = lines.len();
|
||||||
|
while split > 1 {
|
||||||
|
match property_split(&lines[split - 1]) {
|
||||||
|
Some(_) => split -= 1,
|
||||||
|
None => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for l in &lines[split..] {
|
||||||
|
if let Some((k, v)) = property_split(l) {
|
||||||
|
props.insert(k.to_string(), parse_value(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.truncate(split);
|
||||||
|
let id = match props.remove("id") {
|
||||||
|
Some(Value::String(s)) => s.parse().ok(),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let collapsed = matches!(props.remove("collapsed"), Some(Value::Bool(true)));
|
||||||
|
page.blocks.push(ParsedBlock {
|
||||||
|
depth: raw.depth,
|
||||||
|
id,
|
||||||
|
content: lines.join("\n"),
|
||||||
|
properties: props,
|
||||||
|
collapsed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
page
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_nesting_props_and_multiline() {
|
||||||
|
let text = "alias:: A, B\ntype:: note\n\n- root\n\tsecond line\n\tcolor:: red\n\t- child\n\t\t- deep\n- next\n";
|
||||||
|
let p = parse_page(text);
|
||||||
|
assert_eq!(p.aliases, ["A", "B"]);
|
||||||
|
assert_eq!(p.properties["type"], "note");
|
||||||
|
let d: Vec<_> = p
|
||||||
|
.blocks
|
||||||
|
.iter()
|
||||||
|
.map(|b| (b.depth, b.content.as_str()))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
d,
|
||||||
|
[
|
||||||
|
(0, "root\nsecond line"),
|
||||||
|
(1, "child"),
|
||||||
|
(2, "deep"),
|
||||||
|
(0, "next")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(p.blocks[0].properties["color"], "red");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn logseq_space_indent() {
|
||||||
|
let p = parse_page("- a\n - b\n - c\n - d\n");
|
||||||
|
let d: Vec<_> = p.blocks.iter().map(|b| b.depth).collect();
|
||||||
|
assert_eq!(d, [0, 1, 2, 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
//! Push the history branch to any Git smart-HTTP(S) remote.
|
||||||
|
//!
|
||||||
|
//! gix cannot push yet, so this speaks the `git-receive-pack` protocol directly: it advertises
|
||||||
|
//! refs, sends one un-deltified pack with the objects the remote lacks and reads the report.
|
||||||
|
//! Credentials are used for the HTTP `Authorization` header of this call only; nothing is
|
||||||
|
//! written to the repository or its config.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::error::{Error, git};
|
||||||
|
use crate::history::History;
|
||||||
|
use gix::ObjectId;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PushAuth {
|
||||||
|
pub username: String,
|
||||||
|
/// Password or access token.
|
||||||
|
pub secret: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for PushAuth {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("PushAuth")
|
||||||
|
.field("username", &self.username)
|
||||||
|
.field("secret", &"***")
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct PushReport {
|
||||||
|
/// Objects sent in the pack.
|
||||||
|
pub objects: usize,
|
||||||
|
/// False when the remote already had our tip.
|
||||||
|
pub updated: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_err(msg: impl Into<String>) -> Error {
|
||||||
|
Error::Push(msg.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pkt(out: &mut Vec<u8>, data: &[u8]) {
|
||||||
|
out.extend_from_slice(format!("{:04x}", data.len() + 4).as_bytes());
|
||||||
|
out.extend_from_slice(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits pkt-lines; `None` is a flush packet.
|
||||||
|
fn parse_pkts(mut b: &[u8]) -> Result<Vec<Option<Vec<u8>>>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while b.len() >= 4 {
|
||||||
|
let n = usize::from_str_radix(std::str::from_utf8(&b[..4]).map_err(git)?, 16)
|
||||||
|
.map_err(|_| push_err("bad pkt-line"))?;
|
||||||
|
if n == 0 {
|
||||||
|
out.push(None);
|
||||||
|
b = &b[4..];
|
||||||
|
} else {
|
||||||
|
if n < 4 || b.len() < n {
|
||||||
|
return Err(push_err("truncated pkt-line"));
|
||||||
|
}
|
||||||
|
out.push(Some(b[4..n].to_vec()));
|
||||||
|
b = &b[n..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn basic(auth: &PushAuth) -> String {
|
||||||
|
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
let raw = format!("{}:{}", auth.username, auth.secret);
|
||||||
|
let mut out = String::from("Basic ");
|
||||||
|
for c in raw.as_bytes().chunks(3) {
|
||||||
|
let n = (c[0] as u32) << 16
|
||||||
|
| (*c.get(1).unwrap_or(&0) as u32) << 8
|
||||||
|
| *c.get(2).unwrap_or(&0) as u32;
|
||||||
|
for i in 0..4 {
|
||||||
|
if i <= c.len() {
|
||||||
|
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||||
|
} else {
|
||||||
|
out.push('=');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
impl History {
|
||||||
|
/// Pushes the history branch to `url` (an `http(s)://` Git remote) as `branch`.
|
||||||
|
/// Fast-forward only unless `force`.
|
||||||
|
pub fn push(
|
||||||
|
&self,
|
||||||
|
url: &str,
|
||||||
|
branch: &str,
|
||||||
|
auth: Option<&PushAuth>,
|
||||||
|
force: bool,
|
||||||
|
) -> Result<PushReport> {
|
||||||
|
if !(url.starts_with("https://") || url.starts_with("http://")) {
|
||||||
|
return Err(push_err("only http(s) remotes are supported"));
|
||||||
|
}
|
||||||
|
let base = url.trim_end_matches('/');
|
||||||
|
let tip = self
|
||||||
|
.repo
|
||||||
|
.head()?
|
||||||
|
.ok_or_else(|| push_err("nothing to push: no snapshots yet"))?;
|
||||||
|
let target = format!("refs/heads/{branch}");
|
||||||
|
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||||
|
.http_status_as_error(false)
|
||||||
|
.build()
|
||||||
|
.into();
|
||||||
|
|
||||||
|
// 1. Ref advertisement.
|
||||||
|
let mut req = agent.get(&format!("{base}/info/refs?service=git-receive-pack"));
|
||||||
|
if let Some(a) = auth {
|
||||||
|
req = req.header("Authorization", &basic(a));
|
||||||
|
}
|
||||||
|
let mut resp = req.call().map_err(|e| push_err(e.to_string()))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(push_err(format!("remote answered {}", resp.status())));
|
||||||
|
}
|
||||||
|
let body = resp
|
||||||
|
.body_mut()
|
||||||
|
.read_to_vec()
|
||||||
|
.map_err(|e| push_err(e.to_string()))?;
|
||||||
|
let mut old = ObjectId::null(gix::hash::Kind::Sha1);
|
||||||
|
for line in parse_pkts(&body)?.into_iter().flatten() {
|
||||||
|
let text = String::from_utf8_lossy(&line);
|
||||||
|
let first = text.split('\0').next().unwrap_or("").trim_end();
|
||||||
|
if let Some((oid, name)) = first.split_once(' ')
|
||||||
|
&& name == target
|
||||||
|
{
|
||||||
|
old = ObjectId::from_hex(oid.as_bytes()).map_err(git)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if old == tip {
|
||||||
|
return Ok(PushReport {
|
||||||
|
objects: 0,
|
||||||
|
updated: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Objects the remote lacks.
|
||||||
|
let mut have = HashSet::new();
|
||||||
|
if !old.is_null() {
|
||||||
|
if self.repo.repo.find_object(old).is_ok() {
|
||||||
|
self.collect(old, &HashSet::new(), &mut have)?;
|
||||||
|
} else if !force {
|
||||||
|
return Err(push_err("remote has commits we do not have (diverged)"));
|
||||||
|
}
|
||||||
|
if !force && !self.is_ancestor(old, tip)? {
|
||||||
|
return Err(push_err("not a fast-forward (diverged)"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut send = HashSet::new();
|
||||||
|
self.collect(tip, &have, &mut send)?;
|
||||||
|
let pack = self.build_pack(&send)?;
|
||||||
|
|
||||||
|
// 3. Send commands + pack.
|
||||||
|
let mut payload = Vec::new();
|
||||||
|
pkt(
|
||||||
|
&mut payload,
|
||||||
|
format!("{old} {tip} {target}\0 report-status agent=synapse-history\n").as_bytes(),
|
||||||
|
);
|
||||||
|
payload.extend_from_slice(b"0000");
|
||||||
|
payload.extend_from_slice(&pack);
|
||||||
|
let mut req = agent
|
||||||
|
.post(&format!("{base}/git-receive-pack"))
|
||||||
|
.header("Content-Type", "application/x-git-receive-pack-request");
|
||||||
|
if let Some(a) = auth {
|
||||||
|
req = req.header("Authorization", &basic(a));
|
||||||
|
}
|
||||||
|
let mut resp = req.send(&payload).map_err(|e| push_err(e.to_string()))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(push_err(format!("remote answered {}", resp.status())));
|
||||||
|
}
|
||||||
|
let body = resp
|
||||||
|
.body_mut()
|
||||||
|
.read_to_vec()
|
||||||
|
.map_err(|e| push_err(e.to_string()))?;
|
||||||
|
let mut unpack_ok = false;
|
||||||
|
for line in parse_pkts(&body)?.into_iter().flatten() {
|
||||||
|
let t = String::from_utf8_lossy(&line);
|
||||||
|
let t = t.trim_end();
|
||||||
|
if t == "unpack ok" {
|
||||||
|
unpack_ok = true;
|
||||||
|
} else if t.starts_with("ng ") || t.starts_with("unpack ") {
|
||||||
|
return Err(push_err(format!("rejected: {t}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !unpack_ok {
|
||||||
|
return Err(push_err("remote did not confirm the push"));
|
||||||
|
}
|
||||||
|
Ok(PushReport {
|
||||||
|
objects: send.len(),
|
||||||
|
updated: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_ancestor(&self, ancestor: ObjectId, mut cur: ObjectId) -> Result<bool> {
|
||||||
|
loop {
|
||||||
|
if cur == ancestor {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
match self.repo.parent(cur)? {
|
||||||
|
Some(p) => cur = p,
|
||||||
|
None => return Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds every object reachable from `commit` (stopping at `skip`) to `out`.
|
||||||
|
fn collect(
|
||||||
|
&self,
|
||||||
|
commit: ObjectId,
|
||||||
|
skip: &HashSet<ObjectId>,
|
||||||
|
out: &mut HashSet<ObjectId>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut cur = Some(commit);
|
||||||
|
while let Some(id) = cur {
|
||||||
|
if skip.contains(&id) || !out.insert(id) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let c = self
|
||||||
|
.repo
|
||||||
|
.repo
|
||||||
|
.find_object(id)
|
||||||
|
.map_err(git)?
|
||||||
|
.try_into_commit()
|
||||||
|
.map_err(git)?;
|
||||||
|
self.collect_tree(c.tree_id().map_err(git)?.detach(), skip, out)?;
|
||||||
|
cur = c.parent_ids().next().map(|p| p.detach());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_tree(
|
||||||
|
&self,
|
||||||
|
tree: ObjectId,
|
||||||
|
skip: &HashSet<ObjectId>,
|
||||||
|
out: &mut HashSet<ObjectId>,
|
||||||
|
) -> Result<()> {
|
||||||
|
if skip.contains(&tree) || !out.insert(tree) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let obj = self.repo.repo.find_object(tree).map_err(git)?;
|
||||||
|
let t = obj.try_into_tree().map_err(git)?;
|
||||||
|
for e in t.decode().map_err(git)?.entries.iter() {
|
||||||
|
let oid = e.oid.to_owned();
|
||||||
|
if e.mode.is_tree() {
|
||||||
|
self.collect_tree(oid, skip, out)?;
|
||||||
|
} else if !skip.contains(&oid) {
|
||||||
|
out.insert(oid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_pack(&self, objects: &HashSet<ObjectId>) -> Result<Vec<u8>> {
|
||||||
|
let mut ids: Vec<_> = objects.iter().copied().collect();
|
||||||
|
ids.sort();
|
||||||
|
let mut pack = Vec::new();
|
||||||
|
pack.extend_from_slice(b"PACK");
|
||||||
|
pack.extend_from_slice(&2u32.to_be_bytes());
|
||||||
|
pack.extend_from_slice(&(ids.len() as u32).to_be_bytes());
|
||||||
|
for id in ids {
|
||||||
|
let obj = self.repo.repo.find_object(id).map_err(git)?;
|
||||||
|
let ty: u8 = match obj.kind {
|
||||||
|
gix::object::Kind::Commit => 1,
|
||||||
|
gix::object::Kind::Tree => 2,
|
||||||
|
gix::object::Kind::Blob => 3,
|
||||||
|
gix::object::Kind::Tag => 4,
|
||||||
|
};
|
||||||
|
let mut size = obj.data.len();
|
||||||
|
let mut first = (ty << 4) | (size & 0x0f) as u8;
|
||||||
|
size >>= 4;
|
||||||
|
if size > 0 {
|
||||||
|
first |= 0x80;
|
||||||
|
}
|
||||||
|
pack.push(first);
|
||||||
|
while size > 0 {
|
||||||
|
let mut b = (size & 0x7f) as u8;
|
||||||
|
size >>= 7;
|
||||||
|
if size > 0 {
|
||||||
|
b |= 0x80;
|
||||||
|
}
|
||||||
|
pack.push(b);
|
||||||
|
}
|
||||||
|
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||||
|
z.write_all(&obj.data)?;
|
||||||
|
pack.extend_from_slice(&z.finish()?);
|
||||||
|
}
|
||||||
|
let mut h = gix::hash::hasher(gix::hash::Kind::Sha1);
|
||||||
|
h.update(&pack);
|
||||||
|
let digest = h.try_finalize().map_err(git)?;
|
||||||
|
pack.extend_from_slice(digest.as_bytes());
|
||||||
|
Ok(pack)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
//! Thin wrapper over a bare gix repository: whole-tree commits from a `path → blob` map.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::error::git;
|
||||||
|
use gix::ObjectId;
|
||||||
|
use gix::objs::{Tree, tree};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub const BRANCH: &str = "refs/heads/main";
|
||||||
|
|
||||||
|
pub type Files = BTreeMap<String, ObjectId>;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CommitInfo {
|
||||||
|
pub id: String,
|
||||||
|
/// Seconds since epoch.
|
||||||
|
pub time: i64,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Repo {
|
||||||
|
pub(crate) repo: gix::Repository,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repo {
|
||||||
|
pub fn open_or_init(dir: &Path) -> Result<Self> {
|
||||||
|
let repo = if dir.join("HEAD").exists() {
|
||||||
|
gix::open(dir).map_err(git)?
|
||||||
|
} else {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
let repo = gix::init_bare(dir).map_err(git)?;
|
||||||
|
std::fs::write(dir.join("HEAD"), format!("ref: {BRANCH}\n"))?;
|
||||||
|
repo
|
||||||
|
};
|
||||||
|
Ok(Self { repo })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn head(&self) -> Result<Option<ObjectId>> {
|
||||||
|
self.repo
|
||||||
|
.try_find_reference(BRANCH)
|
||||||
|
.map_err(git)?
|
||||||
|
.map(|mut r| r.peel_to_id().map(|i| i.detach()))
|
||||||
|
.transpose()
|
||||||
|
.map_err(git)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All files of a commit's tree, as `path → blob id`.
|
||||||
|
pub fn files(&self, commit: ObjectId) -> Result<Files> {
|
||||||
|
let c = self
|
||||||
|
.repo
|
||||||
|
.find_object(commit)
|
||||||
|
.map_err(git)?
|
||||||
|
.try_into_commit()
|
||||||
|
.map_err(git)?;
|
||||||
|
let mut out = Files::new();
|
||||||
|
self.walk(c.tree_id().map_err(git)?.detach(), "", &mut out)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk(&self, tree: ObjectId, prefix: &str, out: &mut Files) -> Result<()> {
|
||||||
|
let obj = self.repo.find_object(tree).map_err(git)?;
|
||||||
|
let t = obj.try_into_tree().map_err(git)?;
|
||||||
|
let decoded = t.decode().map_err(git)?;
|
||||||
|
for e in decoded.entries.iter() {
|
||||||
|
let name = format!("{prefix}{}", e.filename);
|
||||||
|
if e.mode.is_tree() {
|
||||||
|
self.walk(e.oid.to_owned(), &format!("{name}/"), out)?;
|
||||||
|
} else {
|
||||||
|
out.insert(name, e.oid.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_blob(&self, bytes: &[u8]) -> Result<ObjectId> {
|
||||||
|
Ok(self.repo.write_blob(bytes).map_err(git)?.detach())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_blob(&self, id: ObjectId) -> Result<Vec<u8>> {
|
||||||
|
Ok(self.repo.find_object(id).map_err(git)?.detach().data)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_tree(&self, files: &Files, dir: &str) -> Result<ObjectId> {
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let mut subdirs: BTreeMap<&str, ()> = BTreeMap::new();
|
||||||
|
for (path, oid) in files.range(dir.to_string()..) {
|
||||||
|
let Some(rest) = path.strip_prefix(dir) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
match rest.split_once('/') {
|
||||||
|
None => entries.push(tree::Entry {
|
||||||
|
mode: tree::EntryKind::Blob.into(),
|
||||||
|
filename: rest.into(),
|
||||||
|
oid: *oid,
|
||||||
|
}),
|
||||||
|
Some((d, _)) => {
|
||||||
|
subdirs.insert(d, ());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for d in subdirs.keys() {
|
||||||
|
let oid = self.write_tree(files, &format!("{dir}{d}/"))?;
|
||||||
|
entries.push(tree::Entry {
|
||||||
|
mode: tree::EntryKind::Tree.into(),
|
||||||
|
filename: (*d).into(),
|
||||||
|
oid,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
entries.sort();
|
||||||
|
Ok(self
|
||||||
|
.repo
|
||||||
|
.write_object(Tree { entries })
|
||||||
|
.map_err(git)?
|
||||||
|
.detach())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits the full file set on top of the current branch tip. `time` is epoch seconds.
|
||||||
|
pub fn commit(&self, files: &Files, message: &str, time: i64) -> Result<ObjectId> {
|
||||||
|
let tree = self.write_tree(files, "")?;
|
||||||
|
let parents: Vec<ObjectId> = self.head()?.into_iter().collect();
|
||||||
|
let stamp = format!("{time} +0000");
|
||||||
|
let sig = gix::actor::SignatureRef {
|
||||||
|
name: "Synapse".into(),
|
||||||
|
email: "synapse@localhost".into(),
|
||||||
|
time: &stamp,
|
||||||
|
};
|
||||||
|
Ok(self
|
||||||
|
.repo
|
||||||
|
.commit_as(sig, sig, BRANCH, message, tree, parents)
|
||||||
|
.map_err(git)?
|
||||||
|
.detach())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn commit_info(&self, id: ObjectId) -> Result<CommitInfo> {
|
||||||
|
let c = self
|
||||||
|
.repo
|
||||||
|
.find_object(id)
|
||||||
|
.map_err(git)?
|
||||||
|
.try_into_commit()
|
||||||
|
.map_err(git)?;
|
||||||
|
Ok(CommitInfo {
|
||||||
|
id: id.to_string(),
|
||||||
|
time: c.time().map_err(git)?.seconds,
|
||||||
|
message: c.message_raw_sloppy().to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits from the branch tip backwards (newest first).
|
||||||
|
pub fn log(&self, limit: usize) -> Result<Vec<CommitInfo>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut cur = self.head()?;
|
||||||
|
while let Some(id) = cur {
|
||||||
|
if out.len() >= limit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let c = self
|
||||||
|
.repo
|
||||||
|
.find_object(id)
|
||||||
|
.map_err(git)?
|
||||||
|
.try_into_commit()
|
||||||
|
.map_err(git)?;
|
||||||
|
cur = c.parent_ids().next().map(|p| p.detach());
|
||||||
|
out.push(self.commit_info(id)?);
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parent(&self, id: ObjectId) -> Result<Option<ObjectId>> {
|
||||||
|
let c = self
|
||||||
|
.repo
|
||||||
|
.find_object(id)
|
||||||
|
.map_err(git)?
|
||||||
|
.try_into_commit()
|
||||||
|
.map_err(git)?;
|
||||||
|
Ok(c.parent_ids().next().map(|p| p.detach()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_id(s: &str) -> Result<ObjectId> {
|
||||||
|
ObjectId::from_hex(s.as_bytes()).map_err(git)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
//! Restore pages (or the whole graph) from a snapshot by re-importing the Markdown through the
|
||||||
|
//! `Graph` API. Restoring appends new ops; git history is never rewritten.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::export;
|
||||||
|
use crate::history::{History, SnapshotInfo};
|
||||||
|
use crate::parse::{ParsedPage, parse_page};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use synapse_core::position::between;
|
||||||
|
use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct RestoreReport {
|
||||||
|
/// Pages whose content was (re)written from the snapshot.
|
||||||
|
pub restored: usize,
|
||||||
|
/// Pages removed because they did not exist in the snapshot.
|
||||||
|
pub removed: usize,
|
||||||
|
/// Snapshot of the pre-restore state, taken so the restore itself is undoable.
|
||||||
|
pub safety_snapshot: Option<SnapshotInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Plan {
|
||||||
|
blocks: Vec<Block>,
|
||||||
|
delete: Vec<BlockId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_or_create(graph: &Graph, title: &str) -> Result<Page> {
|
||||||
|
if let Ok(d) = chrono::NaiveDate::parse_from_str(title, "%Y-%m-%d") {
|
||||||
|
return Ok(graph.journal(d)?);
|
||||||
|
}
|
||||||
|
match graph.page_by_title(title)? {
|
||||||
|
Some(p) => Ok(p),
|
||||||
|
None => Ok(graph.create_page(NewPage::titled(title))?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Matches parsed blocks to existing ones and decides what to write and delete.
|
||||||
|
fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<Plan> {
|
||||||
|
let page = find_or_create(graph, title)?;
|
||||||
|
let now = graph.now_ms();
|
||||||
|
|
||||||
|
if page.properties != parsed.properties {
|
||||||
|
graph.set_page_properties(page.id, parsed.properties.clone())?;
|
||||||
|
}
|
||||||
|
let current: HashSet<String> = graph.aliases_of(page.id)?.into_iter().collect();
|
||||||
|
let wanted: HashSet<String> = parsed.aliases.iter().cloned().collect();
|
||||||
|
for a in current.difference(&wanted) {
|
||||||
|
graph.set_alias(a, None)?;
|
||||||
|
}
|
||||||
|
for a in wanted.difference(¤t) {
|
||||||
|
graph.set_alias(a, Some(page.id))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let existing: Vec<Block> = graph
|
||||||
|
.page_tree(page.id)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, b)| b)
|
||||||
|
.collect();
|
||||||
|
let by_id: HashMap<BlockId, &Block> = existing.iter().map(|b| (b.id, b)).collect();
|
||||||
|
let mut claimed: HashSet<BlockId> = HashSet::new();
|
||||||
|
let mut ids: Vec<Option<BlockId>> = vec![None; parsed.blocks.len()];
|
||||||
|
|
||||||
|
for (i, pb) in parsed.blocks.iter().enumerate() {
|
||||||
|
let Some(id) = pb.id else { continue };
|
||||||
|
let usable = by_id.contains_key(&id)
|
||||||
|
|| match graph.get_block(id)? {
|
||||||
|
None => true,
|
||||||
|
Some(_) => steal,
|
||||||
|
};
|
||||||
|
if usable && claimed.insert(id) {
|
||||||
|
ids[i] = Some(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, pb) in parsed.blocks.iter().enumerate() {
|
||||||
|
if ids[i].is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let hit = existing
|
||||||
|
.iter()
|
||||||
|
.find(|b| !claimed.contains(&b.id) && b.content == pb.content);
|
||||||
|
let id = hit.map(|b| b.id).unwrap_or_else(new_id);
|
||||||
|
claimed.insert(id);
|
||||||
|
ids[i] = Some(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the tree: parents from depth, positions kept when still ordered.
|
||||||
|
let mut blocks: Vec<Block> = Vec::with_capacity(parsed.blocks.len());
|
||||||
|
let mut stack: Vec<BlockId> = Vec::new();
|
||||||
|
let mut last_pos: HashMap<Option<BlockId>, String> = HashMap::new();
|
||||||
|
for (i, pb) in parsed.blocks.iter().enumerate() {
|
||||||
|
let id = ids[i].unwrap();
|
||||||
|
stack.truncate(pb.depth);
|
||||||
|
let parent = stack.last().copied();
|
||||||
|
let prev = last_pos.get(&parent).cloned();
|
||||||
|
let old = by_id.get(&id);
|
||||||
|
let keep = old
|
||||||
|
.filter(|o| {
|
||||||
|
o.parent_id == parent && prev.as_deref().is_none_or(|p| o.position.as_str() > p)
|
||||||
|
})
|
||||||
|
.map(|o| o.position.clone());
|
||||||
|
let position = keep.unwrap_or_else(|| between(prev.as_deref(), None));
|
||||||
|
last_pos.insert(parent, position.clone());
|
||||||
|
blocks.push(Block {
|
||||||
|
id,
|
||||||
|
page_id: page.id,
|
||||||
|
parent_id: parent,
|
||||||
|
position,
|
||||||
|
content: pb.content.clone(),
|
||||||
|
properties: pb.properties.clone(),
|
||||||
|
collapsed: pb.collapsed,
|
||||||
|
created_at: old.map_or(now, |o| o.created_at),
|
||||||
|
updated_at: now,
|
||||||
|
});
|
||||||
|
stack.push(id);
|
||||||
|
}
|
||||||
|
let delete = existing
|
||||||
|
.iter()
|
||||||
|
.filter(|b| !claimed.contains(&b.id))
|
||||||
|
.map(|b| b.id)
|
||||||
|
.collect();
|
||||||
|
Ok(Plan { blocks, delete })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same(a: &Block, b: &Block) -> bool {
|
||||||
|
a.page_id == b.page_id
|
||||||
|
&& a.parent_id == b.parent_id
|
||||||
|
&& a.position == b.position
|
||||||
|
&& a.content == b.content
|
||||||
|
&& a.properties == b.properties
|
||||||
|
&& a.collapsed == b.collapsed
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_deletes(graph: &Graph, plan: &Plan) -> Result<()> {
|
||||||
|
for id in &plan.delete {
|
||||||
|
// Deleting a parent already removed its subtree.
|
||||||
|
if graph.get_block(*id)?.is_some() {
|
||||||
|
graph.delete_block(*id)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes changed blocks; returns whether anything was written.
|
||||||
|
fn apply_puts(graph: &Graph, plan: &Plan) -> Result<bool> {
|
||||||
|
let mut wrote = false;
|
||||||
|
for b in &plan.blocks {
|
||||||
|
if graph.get_block(b.id)?.is_some_and(|cur| same(&cur, b)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
graph.put_block(b)?;
|
||||||
|
wrote = true;
|
||||||
|
}
|
||||||
|
Ok(wrote || !plan.delete.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_or_delete(graph: &Graph, page: &Page) -> Result<bool> {
|
||||||
|
if page.is_journal() {
|
||||||
|
let roots: Vec<_> = graph
|
||||||
|
.page_tree(page.id)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(d, _)| *d == 0)
|
||||||
|
.map(|(_, b)| b.id)
|
||||||
|
.collect();
|
||||||
|
let had = !roots.is_empty();
|
||||||
|
for id in roots {
|
||||||
|
graph.delete_block(id)?;
|
||||||
|
}
|
||||||
|
Ok(had)
|
||||||
|
} else {
|
||||||
|
graph.delete_page(page.id)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl History {
|
||||||
|
/// Restores one page to its state at `rev`. A page that did not exist then is removed
|
||||||
|
/// (a journal is emptied instead).
|
||||||
|
pub fn restore_page(
|
||||||
|
&mut self,
|
||||||
|
graph: &Graph,
|
||||||
|
title: &str,
|
||||||
|
rev: &str,
|
||||||
|
now_ms: i64,
|
||||||
|
) -> Result<RestoreReport> {
|
||||||
|
let commit = self.resolve(rev)?;
|
||||||
|
let text = self.file_at(commit, &Self::path_for_title(title))?;
|
||||||
|
let safety = self.snapshot(graph, now_ms)?;
|
||||||
|
let mut report = RestoreReport {
|
||||||
|
safety_snapshot: safety,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
match text {
|
||||||
|
Some(text) => {
|
||||||
|
let p = plan(graph, title, &parse_page(&text), false)?;
|
||||||
|
apply_deletes(graph, &p)?;
|
||||||
|
apply_puts(graph, &p)?;
|
||||||
|
report.restored = 1;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let page = graph
|
||||||
|
.page_by_title(title)?
|
||||||
|
.ok_or_else(|| Self::not_found(title))?;
|
||||||
|
if clear_or_delete(graph, &page)? {
|
||||||
|
report.removed = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(report)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restores every page to its state at `rev`; pages created since are removed.
|
||||||
|
pub fn restore_graph(
|
||||||
|
&mut self,
|
||||||
|
graph: &Graph,
|
||||||
|
rev: &str,
|
||||||
|
now_ms: i64,
|
||||||
|
) -> Result<RestoreReport> {
|
||||||
|
let files = self.snapshot_files(rev)?;
|
||||||
|
let safety = self.snapshot(graph, now_ms)?;
|
||||||
|
let mut report = RestoreReport {
|
||||||
|
safety_snapshot: safety,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut plans = Vec::new();
|
||||||
|
let mut wanted: HashSet<String> = HashSet::new();
|
||||||
|
for (path, oid) in &files {
|
||||||
|
let Some(title) = export::title_from_path(path) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
wanted.insert(synapse_core::title_key(&title));
|
||||||
|
let text = self.read_blob(*oid)?;
|
||||||
|
plans.push(plan(graph, &title, &parse_page(&text), true)?);
|
||||||
|
}
|
||||||
|
// Delete first so blocks moved between pages can be re-created where they belong.
|
||||||
|
for p in &plans {
|
||||||
|
apply_deletes(graph, p)?;
|
||||||
|
}
|
||||||
|
for p in &plans {
|
||||||
|
if apply_puts(graph, p)? {
|
||||||
|
report.restored += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut offset = 0;
|
||||||
|
let mut extra = Vec::new();
|
||||||
|
loop {
|
||||||
|
let batch = graph.list_pages(true, 500, offset)?;
|
||||||
|
if batch.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset += batch.len() as u32;
|
||||||
|
extra.extend(
|
||||||
|
batch
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| !wanted.contains(&synapse_core::title_key(&p.title))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for page in extra {
|
||||||
|
if clear_or_delete(graph, &page)? {
|
||||||
|
report.removed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(report)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# History (`synapse-history`)
|
||||||
|
|
||||||
|
Automatic git-like backup of a graph. A bare git repository at `<graph>/history/` holds a
|
||||||
|
deterministic, Logseq-compatible Markdown export; every snapshot is a commit. Plain `git`
|
||||||
|
works on it (`git --git-dir=<graph>/history log`, `clone`, ...).
|
||||||
|
|
||||||
|
## Export format
|
||||||
|
- `pages/<title>.md`: title encoded Logseq-style (`/` → `___`, `% < > : " \ | ? *` and control
|
||||||
|
chars percent-encoded). `journals/YYYY_MM_DD.md` for journals.
|
||||||
|
- File = page properties (`key:: value`, aliases as `alias:: a, b`), then one `- ` bullet per
|
||||||
|
block, nested with tabs; extra content lines and block properties are indented under the
|
||||||
|
bullet. Blocks targeted by `((uuid))` get an `id::` property. `collapsed:: true` is kept.
|
||||||
|
- Property values: raw text, or JSON when the value is not a plain string (so numbers/bools
|
||||||
|
survive a restore). Keys are sorted, so output is byte-stable.
|
||||||
|
- `assets.json`: manifest `hash → name/size/mime`, sorted. Asset bytes are **not** committed
|
||||||
|
(the blob store is already content-addressed) unless `HistoryOptions::include_blobs`, which
|
||||||
|
adds `blobs/<hash>`.
|
||||||
|
|
||||||
|
## Snapshots
|
||||||
|
`History::snapshot(&graph, now_ms)` is incremental: it reads `ops_since(last_seq)` plus a scan
|
||||||
|
of pages whose `updated_at` moved (block deletes/moves do not log their page), rewrites only
|
||||||
|
those files and removes files of deleted/renamed pages. State (`last_seq`, referenced block
|
||||||
|
ids) lives in `history/synapse-history.json`; if it is missing or ahead of the graph a full
|
||||||
|
export is done (unchanged files still hash to the same blobs, so the commit stays small).
|
||||||
|
Commit messages look like `3 pages edited, 1 created: A, B, C` and end with `Synapse-Seq: n`.
|
||||||
|
|
||||||
|
`maybe_snapshot(&graph, now_ms)` is for the app's periodic timer, driven by `SnapshotPolicy`:
|
||||||
|
`min_interval` (floor between snapshots), `max_interval` (ceiling when changes are pending),
|
||||||
|
`on_idle` (snapshot after the graph has been quiet that long).
|
||||||
|
|
||||||
|
## Queries and restore
|
||||||
|
`snapshots(limit)`, `page_history(title)` (snapshots that changed the page), `page_at`, `file`,
|
||||||
|
`diff_page(title, from, to)` (unified diff). Revisions are commit ids, abbreviations or `HEAD`.
|
||||||
|
|
||||||
|
`restore_page` / `restore_graph` re-import the Markdown through the `Graph` API and so append
|
||||||
|
new ops; git history is never rewritten. They take a safety snapshot first. Blocks keep their
|
||||||
|
ids (`id::`, or matched by identical content) so references survive; pages absent from the
|
||||||
|
snapshot are deleted (journals are emptied).
|
||||||
|
|
||||||
|
## Push
|
||||||
|
`History::push(url, branch, Some(&PushAuth{..}), force)` pushes to any `http(s)` Git remote
|
||||||
|
with a pure-Rust smart-HTTP implementation (gix cannot push yet). Credentials are used for the
|
||||||
|
request only and never stored. SSH remotes are not supported.
|
||||||
|
|
||||||
|
## Why gix
|
||||||
|
gix is pure Rust: no C toolchain or OpenSSL/libssh needed for Android and Windows builds.
|
||||||
|
Fallback if gix ever blocks us: libgit2 via `git2` with vendored libgit2.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
- Block content lines that look like `key:: value` at the end of a block read back as block
|
||||||
|
properties on restore.
|
||||||
|
- Alias changes trigger a full re-export (the previous owner of an alias is not logged).
|
||||||
Reference in new issue
Block a user