feat(sync): op-log sync protocol, client and axum server

Adds synapse-sync (protocol types, Remote transport and read API, SyncClient with
background loop, SSE realtime, resumable blobs) and synapse-server (multi-graph,
bearer auth, blob streaming, read API, authenticated update endpoint), with e2e
tests, docs/sync.md, docs/server.md, systemd unit and update script.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-21 04:25:00 +02:00
1 parent fbcfcf678f
commit 4aa3c01a7f
25 files changed
+4299 -10

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
[package]
name = "synapse-sync"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Synapse sync protocol types and client (op-log push/pull, blobs, realtime)"
[dependencies]
synapse-core.workspace = true
rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
chrono.workspace = true
# Async runtime for the client and its background loop.
tokio = { version = "1", features = ["rt", "sync", "time", "fs", "io-util", "macros"] }
# HTTP client. 0.12 + rustls-tls-webpki-roots = rustls with the `ring` provider and bundled
# roots: no OpenSSL/aws-lc/platform verifier, so it builds for Android and Windows.
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-webpki-roots", "json", "stream"] }
# Stream large blobs from/to disk (ReaderStream) without buffering them.
tokio-util = { version = "0.7", features = ["io"] }
futures-util = "0.3"
# Verify downloaded blobs (same hash as the core blob store).
blake3 = "1"
tracing = "0.1"
[dev-dependencies]
tempfile = "3"
+472
View File
@@ -0,0 +1,472 @@
use crate::error::{Error, Result};
use crate::protocol::{SyncEvent, WireOp, hlc_actor};
use crate::remote::{Remote, RemoteConfig};
use crate::state::{self, Cursors, SyncState, SyncStatus};
use futures_util::StreamExt;
use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use synapse_core::{Graph, Op};
use tokio::sync::{Notify, watch};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlobPolicy {
/// Download blobs of synced assets right after pulling their ops.
Eager,
/// Only download when asked via [`SyncClient::ensure_blob`] (e.g. metered connections).
OnDemand,
}
#[derive(Debug, Clone)]
pub struct SyncConfig {
pub remote: RemoteConfig,
/// Ops per push/pull request.
pub batch_size: u32,
pub blob_policy: BlobPolicy,
/// Background loop: how often to check for unpushed local ops.
pub poll_interval: Duration,
/// Background loop: full sync at least this often even without notifications.
pub full_sync_interval: Duration,
pub max_backoff: Duration,
}
impl SyncConfig {
pub fn new(remote: RemoteConfig) -> Self {
Self {
remote,
batch_size: 500,
blob_policy: BlobPolicy::Eager,
poll_interval: Duration::from_secs(5),
full_sync_interval: Duration::from_secs(120),
max_backoff: Duration::from_secs(300),
}
}
}
struct Inner {
graph: Arc<Mutex<Graph>>,
cfg: SyncConfig,
remote: Remote,
state: watch::Sender<SyncState>,
/// Serialises sync cycles (manual `sync_once` vs the background loop).
cycle: tokio::sync::Mutex<()>,
/// Remote changed (SSE) or caller asked for a sync.
dirty: AtomicBool,
wake: Notify,
/// Some synced assets may lack their blob locally.
blobs_dirty: AtomicBool,
}
/// Replicates a local [`Graph`] with a Synapse server. Cheap to clone.
///
/// The graph is shared as `Arc<Mutex<Graph>>` (the core `Graph` is not `Sync`); the client only
/// holds the lock for short database steps, never across network calls.
#[derive(Clone)]
pub struct SyncClient {
inner: Arc<Inner>,
}
impl SyncClient {
pub fn new(graph: Arc<Mutex<Graph>>, cfg: SyncConfig) -> Result<Self> {
let remote = Remote::new(cfg.remote.clone())?;
let (state, _) = watch::channel(SyncState::default());
let inner = Arc::new(Inner {
graph,
cfg,
remote,
state,
cycle: tokio::sync::Mutex::new(()),
dirty: AtomicBool::new(true),
wake: Notify::new(),
blobs_dirty: AtomicBool::new(true),
});
Ok(Self { inner })
}
pub fn remote(&self) -> &Remote {
&self.inner.remote
}
/// Current state for the UI.
pub fn state(&self) -> SyncState {
self.inner.state.borrow().clone()
}
/// Receiver that fires on every state change.
pub fn subscribe(&self) -> watch::Receiver<SyncState> {
self.inner.state.subscribe()
}
/// Recomputes the pending-ops count (call after local edits to update the UI badge).
pub async fn refresh_pending(&self) -> Result<u64> {
let n = self.with_graph(|g| Ok(state::pending_now(g)?)).await?;
self.inner.state.send_modify(|s| s.pending_ops = n);
Ok(n)
}
/// Asks the background loop to sync soon (call after local edits).
pub fn trigger(&self) {
self.inner.dirty.store(true, Ordering::SeqCst);
self.inner.wake.notify_one();
}
async fn with_graph<T: Send + 'static>(
&self,
f: impl FnOnce(&Graph) -> Result<T> + Send + 'static,
) -> Result<T> {
let graph = self.inner.graph.clone();
tokio::task::spawn_blocking(move || {
let g = graph.lock().unwrap_or_else(PoisonError::into_inner);
f(&g)
})
.await
.map_err(|e| Error::Task(e.to_string()))?
}
/// One full cycle: push local ops (+ their blobs), pull remote ops, fetch blobs.
pub async fn sync_once(&self) -> Result<()> {
let _cycle = self.inner.cycle.lock().await;
self.inner.dirty.store(false, Ordering::SeqCst);
self.inner.state.send_modify(|s| {
s.status = SyncStatus::Syncing;
s.message = None;
});
let res = self.run_cycle().await;
let pending = self
.with_graph(|g| Ok(state::pending_now(g)?))
.await
.unwrap_or(0);
match &res {
Ok((pushed, pulled)) => {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
self.inner.state.send_modify(|s| {
s.status = SyncStatus::Idle;
s.message = None;
s.pending_ops = pending;
s.last_sync_ms = Some(now);
s.last_pushed = *pushed;
s.last_pulled = *pulled;
});
}
Err(e) => {
let status = if e.is_offline() {
SyncStatus::Offline
} else {
SyncStatus::Error
};
warn!(error = %e, ?status, "sync cycle failed");
self.inner.state.send_modify(|s| {
s.status = status;
s.message = Some(e.to_string());
s.pending_ops = pending;
});
}
}
res.map(|_| ())
}
async fn run_cycle(&self) -> Result<(u64, u64)> {
let remote = &self.inner.remote;
let info = remote.ensure_graph().await?;
let key = remote.key();
let server_id = info.server_id.clone();
let mut cur = self
.with_graph(move |g| Ok(state::load(g, &key, &server_id)?))
.await?;
let pushed = self.push_all(&mut cur).await?;
let (pulled, got_assets) = self.pull_all(&mut cur, &info.server_id).await?;
if got_assets {
self.inner.blobs_dirty.store(true, Ordering::SeqCst);
}
if self.inner.cfg.blob_policy == BlobPolicy::Eager
&& self.inner.blobs_dirty.load(Ordering::SeqCst)
{
self.fetch_missing_blobs().await?;
self.inner.blobs_dirty.store(false, Ordering::SeqCst);
}
Ok((pushed, pulled))
}
/// Pushes ops originated by this replica. Ops that were *applied from the server* are
/// re-logged locally by the core, but carry another actor in their HLC, so they are skipped
/// here: that is what prevents echoing them back.
async fn push_all(&self, cur: &mut Cursors) -> Result<u64> {
let limit = self.inner.cfg.batch_size;
let mut total = 0;
loop {
let after = cur.pushed_seq;
let (batch, scanned_to, scanned) = self
.with_graph(move |g| {
let recs = g.ops_since(after, limit)?;
let n = recs.len();
let last = recs.last().map_or(after, |r| r.seq);
let me = g.actor().to_string();
let ops: Vec<WireOp> = recs
.into_iter()
.filter(|r| hlc_actor(&r.hlc) == Some(me.as_str()))
.map(|r| WireOp {
hlc: r.hlc,
op: r.op,
})
.collect();
Ok((ops, last, n))
})
.await?;
if scanned == 0 {
return Ok(total);
}
if !batch.is_empty() {
// Blobs first, so the server never knows an asset it cannot serve.
let hashes: BTreeSet<String> = batch
.iter()
.filter_map(|w| match &w.op {
Op::PutAsset { asset } => Some(asset.hash.clone()),
_ => None,
})
.collect();
for h in hashes {
self.upload_blob(&h).await?;
}
total += batch.len() as u64;
self.inner.remote.push(batch).await?;
}
self.with_graph(move |g| Ok(state::save_pushed(g, scanned_to)?))
.await?;
cur.pushed_seq = scanned_to;
if (scanned as u32) < limit {
return Ok(total);
}
}
}
async fn pull_all(&self, cur: &mut Cursors, server_id: &str) -> Result<(u64, bool)> {
let limit = self.inner.cfg.batch_size;
let me = self.with_graph(|g| Ok(g.actor().to_string())).await?;
let mut applied_total = 0;
let mut got_assets = false;
loop {
let resp = self
.inner
.remote
.pull(cur.pull_cursor, limit, Some(&me))
.await?;
if resp.server_id != server_id {
return Err(Error::Protocol("server graph changed mid-sync".into()));
}
let next = resp.next_cursor.max(cur.pull_cursor);
let me2 = me.clone();
let (applied, assets) = self
.with_graph(move |g| {
let (mut applied, mut assets) = (0u64, false);
for rec in resp.ops {
// Defence in depth: never re-apply our own ops.
if hlc_actor(&rec.hlc) == Some(me2.as_str()) {
continue;
}
if g.apply_remote(&rec.hlc, &rec.op)? {
applied += 1;
assets |= matches!(rec.op, Op::PutAsset { .. });
}
}
state::save_pulled(g, next)?;
Ok((applied, assets))
})
.await?;
cur.pull_cursor = next;
applied_total += applied;
got_assets |= assets;
if !resp.has_more {
return Ok((applied_total, got_assets));
}
}
}
// ----------------------------------------------------------------- blobs
async fn upload_blob(&self, hash: &str) -> Result<()> {
let h = hash.to_string();
let path = self.with_graph(move |g| Ok(g.blobs().path_of(&h))).await?;
if !path.exists() {
return Err(Error::Protocol(format!(
"asset {hash} is registered but its blob is missing locally"
)));
}
self.inner.remote.upload_blob(hash, &path).await
}
/// Downloads blob `hash` if it is not stored locally yet (resumes partial downloads).
pub async fn ensure_blob(&self, hash: &str) -> Result<()> {
if !synapse_core_hash_ok(hash) {
return Err(Error::Protocol(format!("invalid blob hash {hash:?}")));
}
let h = hash.to_string();
let (dest, part, have) = self
.with_graph(move |g| {
let dest = g.blobs().path_of(&h);
let part = g
.dir()
.join("blobs")
.join("tmp")
.join(format!("sync-{h}.part"));
Ok((dest.clone(), part, dest.exists()))
})
.await?;
if have {
return Ok(());
}
let mut last = None;
for _ in 0..2 {
match self.inner.remote.download_blob(hash, &part, &dest).await {
Ok(()) => return Ok(()),
Err(e @ Error::Protocol(_)) => last = Some(e), // retry from scratch
Err(e) => return Err(e),
}
}
Err(last.unwrap())
}
async fn fetch_missing_blobs(&self) -> Result<()> {
let missing = self
.with_graph(|g| {
let mut st = g.conn().prepare("SELECT hash FROM assets")?;
let hashes = st
.query_map([], |r| r.get::<_, String>(0))?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(hashes
.into_iter()
.filter(|h| h.len() > 2 && !g.blobs().contains(h))
.collect::<Vec<_>>())
})
.await?;
for h in missing {
debug!(hash = %h, "downloading blob");
self.ensure_blob(&h).await?;
}
Ok(())
}
// ------------------------------------------------------------ background
/// Starts the background loop on the current tokio runtime: syncs on server notifications
/// (SSE), when local ops are pending, and periodically; backs off exponentially on errors
/// and keeps working offline. Stop it with [`SyncHandle::stop`] or by dropping the handle.
pub fn start(&self) -> SyncHandle {
let me = self.clone();
let loop_task = tokio::spawn(async move { me.run_loop().await });
let me = self.clone();
let events_task = tokio::spawn(async move { me.run_events().await });
SyncHandle {
client: self.clone(),
tasks: vec![loop_task, events_task],
}
}
async fn run_loop(self) {
let cfg = &self.inner.cfg;
let mut backoff = Duration::from_secs(1);
let mut last_full: Option<tokio::time::Instant> = None;
loop {
let pending = self.refresh_pending().await.unwrap_or(0);
let due = last_full.is_none_or(|t| t.elapsed() >= cfg.full_sync_interval);
if self.inner.dirty.load(Ordering::SeqCst) || pending > 0 || due {
match self.sync_once().await {
Ok(()) => {
backoff = Duration::from_secs(1);
last_full = Some(tokio::time::Instant::now());
}
Err(e) => {
let wait = jitter(backoff);
debug!(error = %e, ?wait, "sync failed; backing off");
// Keep `dirty` so we retry as soon as the backoff elapses.
self.inner.dirty.store(true, Ordering::SeqCst);
backoff = (backoff * 2).min(cfg.max_backoff);
tokio::time::sleep(wait).await;
continue;
}
}
}
tokio::select! {
_ = self.inner.wake.notified() => {}
_ = tokio::time::sleep(cfg.poll_interval) => {}
}
}
}
async fn run_events(self) {
let mut backoff = Duration::from_secs(1);
loop {
match self.inner.remote.open_events().await {
Ok(resp) => {
backoff = Duration::from_secs(1);
info!("realtime stream connected");
// We may have missed events while disconnected.
self.trigger();
let mut buf = String::new();
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let Ok(chunk) = chunk else { break };
buf.push_str(&String::from_utf8_lossy(&chunk));
while let Some(i) = buf.find("\n\n") {
let event: String = buf.drain(..i + 2).collect();
let notified = event
.lines()
.filter_map(|l| l.strip_prefix("data:"))
.any(|d| serde_json::from_str::<SyncEvent>(d.trim()).is_ok());
if notified {
self.trigger();
}
}
}
}
Err(e) => debug!(error = %e, "realtime stream unavailable"),
}
tokio::time::sleep(jitter(backoff)).await;
backoff = (backoff * 2).min(Duration::from_secs(60));
}
}
}
/// Handle of the background sync loop. Dropping it stops the loop.
pub struct SyncHandle {
client: SyncClient,
tasks: Vec<JoinHandle<()>>,
}
impl SyncHandle {
pub fn client(&self) -> &SyncClient {
&self.client
}
pub fn trigger(&self) {
self.client.trigger();
}
pub fn stop(self) {}
}
impl Drop for SyncHandle {
fn drop(&mut self) {
for t in &self.tasks {
t.abort();
}
}
}
fn jitter(d: Duration) -> Duration {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
d + d.mul_f64((nanos % 1000) as f64 / 4000.0)
}
fn synapse_core_hash_ok(h: &str) -> bool {
crate::protocol::is_valid_hash(h)
}
+40
View File
@@ -0,0 +1,40 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("graph: {0}")]
Core(#[from] synapse_core::Error),
#[error("sqlite: {0}")]
Sqlite(#[from] rusqlite::Error),
#[error("http: {0}")]
Http(#[from] reqwest::Error),
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("unauthorized: check the auth token")]
Unauthorized,
#[error("server returned {status}: {message}")]
Status { status: u16, message: String },
#[error("protocol: {0}")]
Protocol(String),
#[error("background task failed: {0}")]
Task(String),
}
impl Error {
/// True when the server could not be reached (as opposed to rejecting a request).
pub fn is_offline(&self) -> bool {
match self {
Error::Http(e) => e.is_connect() || e.is_timeout() || e.is_request() && !e.is_status(),
Error::Io(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionRefused
| std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::TimedOut
| std::io::ErrorKind::UnexpectedEof
),
_ => false,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
+13
View File
@@ -0,0 +1,13 @@
//! Synapse sync: wire protocol (`protocol`), HTTP transport and thin-client read API
//! (`Remote`), and the replicating `SyncClient` with a background loop. See `docs/sync.md`.
mod client;
mod error;
pub mod protocol;
mod remote;
mod state;
pub use client::{BlobPolicy, SyncClient, SyncConfig, SyncHandle};
pub use error::{Error, Result};
pub use remote::{Remote, RemoteConfig};
pub use state::{Cursors, SyncState, SyncStatus};
+120
View File
@@ -0,0 +1,120 @@
//! Wire types shared by `synapse-sync` (client) and `synapse-server`. See `docs/sync.md`.
use serde::{Deserialize, Serialize};
use synapse_core::{Backlink, Block, Op, OpRecord, Page};
/// Bumped on incompatible changes. Sent as `X-Synapse-Protocol` by clients.
pub const PROTOCOL_VERSION: u32 = 1;
pub const HEADER_PROTOCOL: &str = "x-synapse-protocol";
/// Bytes already stored of a partially uploaded blob (response header).
pub const HEADER_UPLOAD_OFFSET: &str = "upload-offset";
/// Total size of the blob being uploaded (request header).
pub const HEADER_UPLOAD_LENGTH: &str = "upload-length";
/// `GET/PUT /v1/graphs/{id}`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Info {
pub protocol: u32,
/// Stable identity of the server-side graph (its actor id). A change means the graph was
/// recreated and clients must restart their cursors.
pub server_id: String,
pub last_seq: i64,
}
/// An op to push: the local HLC plus the payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WireOp {
pub hlc: String,
pub op: Op,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PushRequest {
pub ops: Vec<WireOp>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PushResponse {
/// Ops that changed server state (the rest lost LWW or were already known).
pub applied: u32,
pub last_seq: i64,
}
/// `GET /v1/graphs/{id}/ops?since=&limit=&exclude_actor=`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullResponse {
pub server_id: String,
/// Ops after `since`, minus those from `exclude_actor`.
pub ops: Vec<OpRecord>,
/// Cursor to use for the next pull: the seq of the last op *scanned* (even if filtered).
pub next_cursor: i64,
pub last_seq: i64,
pub has_more: bool,
}
/// Payload of each `data:` line of the SSE stream `GET /v1/graphs/{id}/events`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncEvent {
pub last_seq: i64,
}
// ---- read API (thin clients) ----
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TreeEntry {
pub depth: usize,
pub block: Block,
}
/// A page with its aliases and block tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PageView {
pub page: Page,
pub aliases: Vec<String>,
pub tree: Vec<TreeEntry>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BacklinksView {
pub backlinks: Vec<Backlink>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorBody {
pub error: String,
}
/// Actor part of an HLC (`{millis:013}-{counter:05}-{actor}`).
pub fn hlc_actor(hlc: &str) -> Option<&str> {
hlc.splitn(3, '-').nth(2).filter(|a| !a.is_empty())
}
/// Graph ids are directory names on the server: restrict them to a safe alphabet.
pub fn is_valid_graph_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 64
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// blake3 hex digest (64 lowercase hex chars).
pub fn is_valid_hash(h: &str) -> bool {
h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn actor_and_validation() {
assert_eq!(hlc_actor("0000000000001-00000-abc123"), Some("abc123"));
assert_eq!(hlc_actor("garbage"), None);
assert!(is_valid_graph_id("my-graph_1"));
assert!(!is_valid_graph_id("../x"));
assert!(!is_valid_graph_id(""));
assert!(is_valid_hash(&"a".repeat(64)));
assert!(!is_valid_hash("ab/../"));
}
}
+340
View File
@@ -0,0 +1,340 @@
//! HTTP transport to a Synapse server. Usable on its own as a thin client (read API, no local
//! replica) and as the transport of [`crate::SyncClient`].
use crate::error::{Error, Result};
use crate::protocol::*;
use futures_util::StreamExt;
use reqwest::{Method, RequestBuilder, Response, StatusCode, header};
use serde::de::DeserializeOwned;
use std::path::Path;
use std::time::Duration;
use synapse_core::{Backlink, Page};
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
#[derive(Debug, Clone)]
pub struct RemoteConfig {
/// Base URL, e.g. `https://notes.example.com` (no trailing path).
pub server_url: String,
pub graph_id: String,
pub token: String,
pub connect_timeout: Duration,
/// Timeout for JSON requests; blob transfers only use an idle (read) timeout.
pub request_timeout: Duration,
}
impl RemoteConfig {
pub fn new(
server_url: impl Into<String>,
graph_id: impl Into<String>,
token: impl Into<String>,
) -> Self {
Self {
server_url: server_url.into(),
graph_id: graph_id.into(),
token: token.into(),
connect_timeout: Duration::from_secs(10),
request_timeout: Duration::from_secs(30),
}
}
}
#[derive(Debug, Clone)]
pub struct Remote {
http: reqwest::Client,
cfg: RemoteConfig,
}
impl Remote {
pub fn new(cfg: RemoteConfig) -> Result<Self> {
if !is_valid_graph_id(&cfg.graph_id) {
return Err(Error::Protocol(format!(
"invalid graph id {:?}",
cfg.graph_id
)));
}
let http = reqwest::Client::builder()
.connect_timeout(cfg.connect_timeout)
.read_timeout(Duration::from_secs(60))
.user_agent(concat!("synapse-sync/", env!("CARGO_PKG_VERSION")))
.build()?;
Ok(Self { http, cfg })
}
pub fn config(&self) -> &RemoteConfig {
&self.cfg
}
/// Identifies this remote graph; sync cursors are only valid for the same key.
pub fn key(&self) -> String {
format!(
"{}|{}",
self.cfg.server_url.trim_end_matches('/'),
self.cfg.graph_id
)
}
fn url(&self, path: &str) -> String {
format!(
"{}/v1/graphs/{}{}",
self.cfg.server_url.trim_end_matches('/'),
self.cfg.graph_id,
path
)
}
fn req(&self, method: Method, path: &str) -> RequestBuilder {
self.http
.request(method, self.url(path))
.bearer_auth(&self.cfg.token)
.header(HEADER_PROTOCOL, PROTOCOL_VERSION)
}
fn json_req(&self, method: Method, path: &str) -> RequestBuilder {
self.req(method, path).timeout(self.cfg.request_timeout)
}
async fn check(resp: Response) -> Result<Response> {
let status = resp.status();
if status.is_success() {
return Ok(resp);
}
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
return Err(Error::Unauthorized);
}
let message = match resp.json::<ErrorBody>().await {
Ok(b) => b.error,
Err(_) => status.canonical_reason().unwrap_or("error").to_string(),
};
Err(Error::Status {
status: status.as_u16(),
message,
})
}
async fn json<T: DeserializeOwned>(rb: RequestBuilder) -> Result<T> {
Ok(Self::check(rb.send().await?).await?.json().await?)
}
// ------------------------------------------------------------------ sync
/// Creates the graph on the server if needed (idempotent) and returns its identity.
pub async fn ensure_graph(&self) -> Result<Info> {
let info: Info = Self::json(self.json_req(Method::PUT, "")).await?;
if info.protocol != PROTOCOL_VERSION {
return Err(Error::Protocol(format!(
"server speaks protocol {}, client {}",
info.protocol, PROTOCOL_VERSION
)));
}
Ok(info)
}
pub async fn push(&self, ops: Vec<WireOp>) -> Result<PushResponse> {
Self::json(
self.json_req(Method::POST, "/ops")
.json(&PushRequest { ops }),
)
.await
}
pub async fn pull(
&self,
since: i64,
limit: u32,
exclude_actor: Option<&str>,
) -> Result<PullResponse> {
let mut rb = self
.json_req(Method::GET, "/ops")
.query(&[("since", since.to_string()), ("limit", limit.to_string())]);
if let Some(a) = exclude_actor {
rb = rb.query(&[("exclude_actor", a)]);
}
Self::json(rb).await
}
/// Opens the realtime stream (Server-Sent Events). Each `data:` line is a [`SyncEvent`].
pub async fn open_events(&self) -> Result<Response> {
let rb = self
.req(Method::GET, "/events")
.header(header::ACCEPT, "text/event-stream");
Self::check(rb.send().await?).await
}
// ----------------------------------------------------------------- blobs
/// `Ok(None)` if the server has the blob; otherwise how many bytes of a partial upload it
/// already holds (0 if none).
pub async fn blob_upload_offset(&self, hash: &str) -> Result<Option<u64>> {
let resp = self
.json_req(Method::HEAD, &format!("/blobs/{hash}"))
.send()
.await?;
match resp.status() {
s if s.is_success() => Ok(None),
StatusCode::NOT_FOUND => Ok(Some(
resp.headers()
.get(HEADER_UPLOAD_OFFSET)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok())
.unwrap_or(0),
)),
_ => Err(Self::check(resp).await.unwrap_err()),
}
}
/// Uploads the file at `path` (whose blake3 is `hash`), skipping it if the server already
/// has it and resuming a partial upload. The file is streamed, never loaded in memory.
pub async fn upload_blob(&self, hash: &str, path: &Path) -> Result<()> {
let size = tokio::fs::metadata(path).await?.len();
for _ in 0..3 {
let Some(offset) = self.blob_upload_offset(hash).await? else {
return Ok(());
};
let offset = if offset > size { 0 } else { offset };
let mut file = tokio::fs::File::open(path).await?;
file.seek(std::io::SeekFrom::Start(offset)).await?;
let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::with_capacity(
file,
256 * 1024,
));
let resp = self
.req(Method::PUT, &format!("/blobs/{hash}"))
.header(HEADER_UPLOAD_OFFSET, offset)
.header(HEADER_UPLOAD_LENGTH, size)
.header(header::CONTENT_LENGTH, size - offset)
.body(body)
.send()
.await?;
if resp.status() == StatusCode::CONFLICT {
continue; // offset out of date: HEAD again
}
Self::check(resp).await?;
return Ok(());
}
Err(Error::Protocol(format!(
"blob {hash}: upload offset keeps changing"
)))
}
/// Downloads blob `hash` into `dest`, streaming through `part` (resumed if it exists), and
/// verifies the hash. `part` and `dest` must be on the same filesystem.
pub async fn download_blob(&self, hash: &str, part: &Path, dest: &Path) -> Result<()> {
if let Some(dir) = part.parent() {
tokio::fs::create_dir_all(dir).await?;
}
if let Some(dir) = dest.parent() {
tokio::fs::create_dir_all(dir).await?;
}
let have = match tokio::fs::metadata(part).await {
Ok(m) => m.len(),
Err(_) => 0,
};
let mut rb = self.req(Method::GET, &format!("/blobs/{hash}"));
if have > 0 {
rb = rb.header(header::RANGE, format!("bytes={have}-"));
}
let resp = rb.send().await?;
let mut out = match resp.status() {
StatusCode::PARTIAL_CONTENT => {
tokio::fs::OpenOptions::new()
.append(true)
.open(part)
.await?
}
StatusCode::RANGE_NOT_SATISFIABLE => {
// Stale partial file: drop it; the next attempt starts from scratch.
let _ = tokio::fs::remove_file(part).await;
return Err(Error::Protocol(format!("blob {hash}: stale partial file")));
}
_ => tokio::fs::File::create(part).await?,
};
let resp = Self::check(resp).await?;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
out.write_all(&chunk?).await?;
}
out.flush().await?;
drop(out);
let part_owned = part.to_path_buf();
let actual = tokio::task::spawn_blocking(move || hash_file(&part_owned))
.await
.map_err(|e| Error::Task(e.to_string()))??;
if actual != hash {
let _ = tokio::fs::remove_file(part).await;
return Err(Error::Protocol(format!(
"blob {hash}: downloaded content hashes to {actual}"
)));
}
tokio::fs::rename(part, dest).await?;
Ok(())
}
// -------------------------------------------------------------- read API
pub async fn list_pages(
&self,
include_journals: bool,
limit: u32,
offset: u32,
) -> Result<Vec<Page>> {
Self::json(self.json_req(Method::GET, "/pages").query(&[
("journals", include_journals.to_string()),
("limit", limit.to_string()),
("offset", offset.to_string()),
]))
.await
}
/// Page (with aliases and block tree) by title or alias; `None` if it does not exist.
pub async fn page_by_title(&self, title: &str) -> Result<Option<PageView>> {
self.optional(
self.json_req(Method::GET, "/pages/by-title")
.query(&[("title", title)]),
)
.await
}
pub async fn page(&self, id: synapse_core::PageId) -> Result<Option<PageView>> {
self.optional(self.json_req(Method::GET, &format!("/pages/{id}")))
.await
}
pub async fn backlinks(&self, id: synapse_core::PageId) -> Result<Vec<Backlink>> {
let v: BacklinksView =
Self::json(self.json_req(Method::GET, &format!("/pages/{id}/backlinks"))).await?;
Ok(v.backlinks)
}
/// The journal of `date` (`None` if that day has no journal; reads never create it).
pub async fn journal(&self, date: chrono::NaiveDate) -> Result<Option<PageView>> {
self.optional(self.json_req(Method::GET, &format!("/journals/{date}")))
.await
}
pub async fn journals_between(
&self,
from: chrono::NaiveDate,
to: chrono::NaiveDate,
) -> Result<Vec<Page>> {
Self::json(
self.json_req(Method::GET, "/journals")
.query(&[("from", from.to_string()), ("to", to.to_string())]),
)
.await
}
async fn optional<T: DeserializeOwned>(&self, rb: RequestBuilder) -> Result<Option<T>> {
let resp = rb.send().await?;
if resp.status() == StatusCode::NOT_FOUND {
return Ok(None);
}
Ok(Some(Self::check(resp).await?.json().await?))
}
}
pub(crate) fn hash_file(path: &Path) -> Result<String> {
let mut f = std::fs::File::open(path)?;
let mut h = blake3::Hasher::new();
std::io::copy(&mut f, &mut h)?;
Ok(h.finalize().to_hex().to_string())
}
+125
View File
@@ -0,0 +1,125 @@
//! Persistent sync cursors (table `sync_state`) and the UI-facing state.
use rusqlite::{Connection, OptionalExtension, params};
use serde::Serialize;
use synapse_core::Graph;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncStatus {
Idle,
Syncing,
/// Server unreachable; local edits are kept and pushed once it is back.
Offline,
/// The server answered but something failed (auth, protocol, disk...). See `message`.
Error,
}
/// What the UI shows about sync.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SyncState {
pub status: SyncStatus,
pub message: Option<String>,
/// Local ops not yet pushed to the server.
pub pending_ops: u64,
/// Wall-clock millis of the last fully successful cycle.
pub last_sync_ms: Option<i64>,
/// Ops pushed / pulled(applied) in the last successful cycle.
pub last_pushed: u64,
pub last_pulled: u64,
}
impl Default for SyncState {
fn default() -> Self {
Self {
status: SyncStatus::Idle,
message: None,
pending_ops: 0,
last_sync_ms: None,
last_pushed: 0,
last_pulled: 0,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Cursors {
/// Highest local op seq already pushed (or skipped because it came from the server).
pub pushed_seq: i64,
/// Highest server op seq already pulled.
pub pull_cursor: i64,
}
pub(crate) fn init(conn: &Connection) -> rusqlite::Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS sync_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);",
)
}
fn get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> {
conn.query_row("SELECT value FROM sync_state WHERE key=?1", [key], |r| {
r.get(0)
})
.optional()
}
fn set(conn: &Connection, key: &str, value: &str) -> rusqlite::Result<()> {
conn.execute(
"INSERT INTO sync_state(key, value) VALUES (?1, ?2)
ON CONFLICT(key) DO UPDATE SET value=?2",
params![key, value],
)?;
Ok(())
}
/// Loads the cursors for `(remote_key, server_id)`. If the graph is now synced with another
/// server/graph, or the server graph was recreated, cursors restart from zero (re-pushing is
/// safe: the server merges with last-writer-wins and ignores what it already has).
pub(crate) fn load(g: &Graph, remote_key: &str, server_id: &str) -> rusqlite::Result<Cursors> {
let c = g.conn();
init(c)?;
let same = get(c, "remote_key")?.as_deref() == Some(remote_key)
&& get(c, "server_id")?.as_deref() == Some(server_id);
if !same {
set(c, "remote_key", remote_key)?;
set(c, "server_id", server_id)?;
set(c, "pushed_seq", "0")?;
set(c, "pull_cursor", "0")?;
return Ok(Cursors::default());
}
let num =
|k| -> rusqlite::Result<i64> { Ok(get(c, k)?.and_then(|v| v.parse().ok()).unwrap_or(0)) };
Ok(Cursors {
pushed_seq: num("pushed_seq")?,
pull_cursor: num("pull_cursor")?,
})
}
pub(crate) fn save_pushed(g: &Graph, seq: i64) -> rusqlite::Result<()> {
set(g.conn(), "pushed_seq", &seq.to_string())
}
pub(crate) fn save_pulled(g: &Graph, cursor: i64) -> rusqlite::Result<()> {
set(g.conn(), "pull_cursor", &cursor.to_string())
}
/// Number of local-origin ops after `pushed_seq`.
pub(crate) fn pending(g: &Graph, pushed_seq: i64) -> rusqlite::Result<u64> {
let pattern = format!("%-{}", g.actor());
g.conn()
.query_row(
"SELECT count(*) FROM ops WHERE seq > ?1 AND hlc LIKE ?2",
params![pushed_seq, pattern],
|r| r.get::<_, i64>(0),
)
.map(|n| n as u64)
}
/// Pending count using the persisted cursor (works before the first successful sync too).
pub(crate) fn pending_now(g: &Graph) -> rusqlite::Result<u64> {
init(g.conn())?;
let pushed = get(g.conn(), "pushed_seq")?
.and_then(|v| v.parse().ok())
.unwrap_or(0);
pending(g, pushed)
}