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

+36
View File
@@ -0,0 +1,36 @@
[package]
name = "synapse-server"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Self-hosted Synapse sync server (axum): multi-graph op-log sync, blobs, read API"
[lib]
name = "synapse_server"
[[bin]]
name = "synapse-server"
path = "src/main.rs"
[dependencies]
synapse-core.workspace = true
# Shared wire types (single source of truth for the protocol).
synapse-sync = { path = "../synapse-sync" }
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
# HTTP framework (routing, SSE, streaming bodies).
axum = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "fs", "io-util", "signal", "process"] }
tokio-util = { version = "0.7", features = ["io"] }
futures-util = "0.3"
# Constant-time token comparison (blake3::Hash equality) and blob verification.
blake3 = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
# Per-request tracing spans.
tower-http = { version = "0.6", features = ["trace"] }
[dev-dependencies]
tempfile = "3"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-webpki-roots", "json"] }
@@ -0,0 +1,23 @@
[Unit]
Description=Synapse sync server
After=network-online.target
Wants=network-online.target
[Service]
User=synapse
Group=synapse
EnvironmentFile=/etc/synapse/server.env
ExecStart=/opt/synapse/bin/synapse-server
# Also how a successful POST /admin/update takes effect: the server exits, systemd restarts it.
Restart=always
RestartSec=2
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/synapse /opt/synapse
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
+206
View File
@@ -0,0 +1,206 @@
//! Authenticated self-update (web-deploy): `POST /admin/update` runs the update script
//! asynchronously (one at a time), `GET /admin/update` reports its status.
//!
//! Exit code 0 = updated: the server then exits gracefully so systemd (`Restart=always`)
//! starts the new binary. Exit code 10 = already up to date, no restart. Anything else = failed.
use crate::AppState;
use crate::auth::bearer;
use crate::error::ApiError;
use axum::Json;
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::Response;
use serde::Serialize;
use std::collections::VecDeque;
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const EXIT_UP_TO_DATE: i32 = 10;
const COOLDOWN: Duration = Duration::from_secs(60);
const RATE_WINDOW: Duration = Duration::from_secs(60);
const RATE_MAX: usize = 20;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdateState {
Idle,
Running,
UpToDate,
Succeeded,
Failed,
}
#[derive(Debug, Clone, Serialize)]
pub struct UpdateStatus {
pub state: UpdateState,
pub started_at_ms: Option<i64>,
pub finished_at_ms: Option<i64>,
pub exit_code: Option<i32>,
/// Last bytes of the script output.
pub log_tail: String,
}
pub struct Updater {
status: Mutex<UpdateStatus>,
last_trigger: Mutex<Option<Instant>>,
hits: Mutex<VecDeque<Instant>>,
}
impl Default for Updater {
fn default() -> Self {
Self {
status: Mutex::new(UpdateStatus {
state: UpdateState::Idle,
started_at_ms: None,
finished_at_ms: None,
exit_code: None,
log_tail: String::new(),
}),
last_trigger: Mutex::new(None),
hits: Mutex::new(VecDeque::new()),
}
}
}
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
impl Updater {
/// Sliding-window limit on all admin requests (also throttles token guessing).
fn rate_ok(&self) -> bool {
let mut hits = self.hits.lock().unwrap_or_else(|e| e.into_inner());
let now = Instant::now();
while hits
.front()
.is_some_and(|t| now.duration_since(*t) > RATE_WINDOW)
{
hits.pop_front();
}
if hits.len() >= RATE_MAX {
return false;
}
hits.push_back(now);
true
}
}
pub async fn admin_guard(
State(state): State<AppState>,
req: Request,
next: Next,
) -> Result<Response, ApiError> {
let Some(expected) = state.update_token.as_ref() else {
return Err(ApiError::not_found("update endpoint is disabled"));
};
if !state.updater.rate_ok() {
return Err(ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate limited"));
}
let given = blake3::hash(bearer(&req).unwrap_or("").as_bytes());
if given != *expected {
return Err(ApiError::new(
StatusCode::UNAUTHORIZED,
"invalid update token",
));
}
Ok(next.run(req).await)
}
pub async fn status(State(state): State<AppState>) -> Json<UpdateStatus> {
Json(
state
.updater
.status
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone(),
)
}
pub async fn trigger(
State(state): State<AppState>,
) -> Result<(StatusCode, Json<UpdateStatus>), ApiError> {
let up = &state.updater;
{
let mut st = up.status.lock().unwrap_or_else(|e| e.into_inner());
if matches!(st.state, UpdateState::Running) {
return Err(ApiError::new(
StatusCode::CONFLICT,
"an update is already running",
));
}
let mut last = up.last_trigger.lock().unwrap_or_else(|e| e.into_inner());
if last.is_some_and(|t| t.elapsed() < COOLDOWN) {
return Err(ApiError::new(
StatusCode::TOO_MANY_REQUESTS,
"updated too recently",
));
}
*last = Some(Instant::now());
*st = UpdateStatus {
state: UpdateState::Running,
started_at_ms: Some(now_ms()),
finished_at_ms: None,
exit_code: None,
log_tail: String::new(),
};
}
let snapshot = up.status.lock().unwrap_or_else(|e| e.into_inner()).clone();
let state2 = state.clone();
tokio::spawn(async move { run_script(state2).await });
Ok((StatusCode::ACCEPTED, Json(snapshot)))
}
async fn run_script(state: AppState) {
let log = state.data_dir.join("update.log");
let result = async {
let out = std::fs::File::create(&log)?;
let err = out.try_clone()?;
tokio::process::Command::new(state.update_script.as_path())
.stdin(std::process::Stdio::null())
.stdout(out)
.stderr(err)
.status()
.await
}
.await;
let tail = tokio::fs::read(&log)
.await
.map(|b| {
let start = b.len().saturating_sub(4096);
String::from_utf8_lossy(&b[start..]).into_owned()
})
.unwrap_or_default();
let (new_state, code) = match result {
Ok(s) if s.success() => (UpdateState::Succeeded, s.code()),
Ok(s) if s.code() == Some(EXIT_UP_TO_DATE) => (UpdateState::UpToDate, s.code()),
Ok(s) => (UpdateState::Failed, s.code()),
Err(e) => {
tracing::error!(error = %e, "could not run the update script");
(UpdateState::Failed, None)
}
};
{
let mut st = state
.updater
.status
.lock()
.unwrap_or_else(|e| e.into_inner());
st.state = new_state.clone();
st.exit_code = code;
st.finished_at_ms = Some(now_ms());
st.log_tail = tail;
}
tracing::info!(?new_state, ?code, "update finished");
if matches!(new_state, UpdateState::Succeeded) {
// Let clients poll the final status, then exit so systemd restarts the new binary.
tokio::time::sleep(Duration::from_secs(2)).await;
state.shutdown.notify_waiters();
state.shutdown.notify_one();
}
}
+301
View File
@@ -0,0 +1,301 @@
//! Op-log sync, realtime events and the read API.
use crate::AppState;
use crate::auth::Principal;
use crate::error::{ApiError, ApiResult};
use crate::graphs::GraphHandle;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::{Extension, Json};
use chrono::NaiveDate;
use futures_util::stream::{self, Stream};
use serde::Deserialize;
use std::convert::Infallible;
use std::sync::Arc;
use synapse_core::store::journal_id;
use synapse_sync::protocol::*;
const MAX_PUSH_OPS: usize = 5000;
const MAX_PULL_LIMIT: u32 = 2000;
/// Resolves and authorises the graph of a request.
pub async fn graph_for(
state: &AppState,
who: &Principal,
id: &str,
create: bool,
) -> ApiResult<Arc<GraphHandle>> {
if !who.can_access(id) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"no access to this graph",
));
}
let h = if create {
Some(state.graphs.get_or_create(id).await?)
} else {
state.graphs.get(id).await?
};
h.ok_or_else(|| ApiError::not_found("graph not found"))
}
fn info(h: &GraphHandle, last_seq: i64) -> Info {
Info {
protocol: PROTOCOL_VERSION,
server_id: h.server_id.clone(),
last_seq,
}
}
/// `PUT /graphs/{id}`: create if missing (idempotent).
pub async fn put_graph(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
) -> ApiResult<Json<Info>> {
let h = graph_for(&s, &who, &id, true).await?;
let seq = h.run(|g| g.last_seq()).await?;
Ok(Json(info(&h, seq)))
}
pub async fn get_graph(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
) -> ApiResult<Json<Info>> {
let h = graph_for(&s, &who, &id, false).await?;
let seq = h.run(|g| g.last_seq()).await?;
Ok(Json(info(&h, seq)))
}
pub async fn push_ops(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
Json(req): Json<PushRequest>,
) -> ApiResult<Json<PushResponse>> {
if req.ops.len() > MAX_PUSH_OPS {
return Err(ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
format!("at most {MAX_PUSH_OPS} ops per push"),
));
}
let h = graph_for(&s, &who, &id, false).await?;
let (applied, last_seq) = h
.run(move |g| {
let mut applied = 0u32;
for w in &req.ops {
if hlc_actor(&w.hlc).is_none() || synapse_core::hlc::decode(&w.hlc).is_none() {
return Err(synapse_core::Error::Invalid(format!("bad hlc {:?}", w.hlc)));
}
if g.apply_remote(&w.hlc, &w.op)? {
applied += 1;
}
}
Ok((applied, g.last_seq()?))
})
.await?;
if applied > 0 {
h.publish_seq(last_seq);
}
tracing::info!(graph = %id, principal = %who.name, applied, "push");
Ok(Json(PushResponse { applied, last_seq }))
}
#[derive(Deserialize)]
pub struct PullQuery {
#[serde(default)]
since: i64,
limit: Option<u32>,
exclude_actor: Option<String>,
}
pub async fn pull_ops(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
Query(q): Query<PullQuery>,
) -> ApiResult<Json<PullResponse>> {
let h = graph_for(&s, &who, &id, false).await?;
let limit = q.limit.unwrap_or(500).clamp(1, MAX_PULL_LIMIT);
let server_id = h.server_id.clone();
let resp = h
.run(move |g| {
let recs = g.ops_since(q.since, limit)?;
let scanned = recs.len() as u32;
let next_cursor = recs.last().map_or(q.since, |r| r.seq);
let ops = recs
.into_iter()
.filter(|r| {
q.exclude_actor
.as_deref()
.is_none_or(|a| hlc_actor(&r.hlc) != Some(a))
})
.collect();
let last_seq = g.last_seq()?;
Ok(PullResponse {
server_id,
ops,
next_cursor,
last_seq,
has_more: scanned == limit && next_cursor < last_seq,
})
})
.await?;
Ok(Json(resp))
}
/// `GET /graphs/{id}/events`: SSE, one `SyncEvent` on connect and on every change.
pub async fn events(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
let h = graph_for(&s, &who, &id, false).await?;
let mut rx = h.seq.subscribe();
let cur = *rx.borrow_and_update();
let stream = stream::unfold((cur, rx, true), |(cur, mut rx, first)| async move {
let seq = if first {
cur
} else {
rx.changed().await.ok()?;
*rx.borrow_and_update()
};
let ev = Event::default()
.event("seq")
.json_data(SyncEvent { last_seq: seq })
.expect("serialisable");
Some((Ok(ev), (seq, rx, false)))
});
Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
}
// ------------------------------------------------------------------ read API
#[derive(Deserialize)]
pub struct ListQuery {
#[serde(default)]
journals: bool,
limit: Option<u32>,
#[serde(default)]
offset: u32,
}
pub async fn list_pages(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
Query(q): Query<ListQuery>,
) -> ApiResult<Json<Vec<synapse_core::Page>>> {
let h = graph_for(&s, &who, &id, false).await?;
let limit = q.limit.unwrap_or(100).clamp(1, 1000);
Ok(Json(
h.run(move |g| g.list_pages(q.journals, limit, q.offset))
.await?,
))
}
fn view(g: &synapse_core::Graph, page: synapse_core::Page) -> synapse_core::Result<PageView> {
Ok(PageView {
aliases: g.aliases_of(page.id)?,
tree: g
.page_tree(page.id)?
.into_iter()
.map(|(depth, block)| TreeEntry { depth, block })
.collect(),
page,
})
}
#[derive(Deserialize)]
pub struct TitleQuery {
title: String,
}
pub async fn page_by_title(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
Query(q): Query<TitleQuery>,
) -> ApiResult<Json<PageView>> {
let h = graph_for(&s, &who, &id, false).await?;
h.run(move |g| g.page_by_title(&q.title)?.map(|p| view(g, p)).transpose())
.await?
.map(Json)
.ok_or_else(|| ApiError::not_found("page not found"))
}
pub async fn page_by_id(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, page)): Path<(String, uuid_str::Id)>,
) -> ApiResult<Json<PageView>> {
let h = graph_for(&s, &who, &id, false).await?;
h.run(move |g| g.get_page(page.0)?.map(|p| view(g, p)).transpose())
.await?
.map(Json)
.ok_or_else(|| ApiError::not_found("page not found"))
}
pub async fn backlinks(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, page)): Path<(String, uuid_str::Id)>,
) -> ApiResult<Json<BacklinksView>> {
let h = graph_for(&s, &who, &id, false).await?;
let backlinks = h.run(move |g| g.backlinks(page.0)).await?;
Ok(Json(BacklinksView { backlinks }))
}
pub async fn journal(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, date)): Path<(String, String)>,
) -> ApiResult<Json<PageView>> {
let date: NaiveDate = date
.parse()
.map_err(|_| ApiError::bad_request("date must be YYYY-MM-DD"))?;
let h = graph_for(&s, &who, &id, false).await?;
// Look up by deterministic id: `Graph::journal` would create (and log) the page.
h.run(move |g| {
g.get_page(journal_id(date))?
.map(|p| view(g, p))
.transpose()
})
.await?
.map(Json)
.ok_or_else(|| ApiError::not_found("no journal for that date"))
}
#[derive(Deserialize)]
pub struct RangeQuery {
from: NaiveDate,
to: NaiveDate,
}
pub async fn journals(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path(id): Path<String>,
Query(q): Query<RangeQuery>,
) -> ApiResult<Json<Vec<synapse_core::Page>>> {
let h = graph_for(&s, &who, &id, false).await?;
Ok(Json(
h.run(move |g| g.journals_between(q.from, q.to)).await?,
))
}
mod uuid_str {
use serde::{Deserialize, Deserializer};
/// Path segment holding a UUID (page id).
pub struct Id(pub synapse_core::PageId);
impl<'de> Deserialize<'de> for Id {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
s.parse().map(Id).map_err(serde::de::Error::custom)
}
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Bearer-token authentication. Tokens map to a [`Principal`] that may be restricted to some
//! graphs, so per-user tokens (loaded from a file or DB) can replace the env list later
//! without touching the handlers.
use crate::AppState;
use crate::error::ApiError;
use axum::extract::{Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::Response;
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct Principal {
pub name: String,
/// `None` = every graph.
pub graphs: Option<HashSet<String>>,
}
impl Principal {
pub fn can_access(&self, graph: &str) -> bool {
self.graphs.as_ref().is_none_or(|g| g.contains(graph))
}
}
/// Stores only hashes of the tokens; compares in constant time.
#[derive(Debug, Default)]
pub struct Authenticator {
entries: Vec<(blake3::Hash, Principal)>,
}
impl Authenticator {
pub fn from_shared_tokens(tokens: &[String]) -> Self {
let entries = tokens
.iter()
.enumerate()
.map(|(i, t)| {
(
blake3::hash(t.as_bytes()),
Principal {
name: format!("token-{}", i + 1),
graphs: None,
},
)
})
.collect();
Self { entries }
}
pub fn authenticate(&self, token: &str) -> Option<Principal> {
let h = blake3::hash(token.as_bytes());
let mut found = None;
// No early exit: the time taken does not depend on which token matched.
for (stored, p) in &self.entries {
if *stored == h {
found = Some(p.clone());
}
}
found
}
}
pub fn bearer(req: &Request) -> Option<&str> {
req.headers()
.get(header::AUTHORIZATION)?
.to_str()
.ok()?
.strip_prefix("Bearer ")
.map(str::trim)
}
pub async fn require_auth(
State(state): State<AppState>,
mut req: Request,
next: Next,
) -> Result<Response, ApiError> {
let principal = bearer(&req)
.and_then(|t| state.auth.authenticate(t))
.ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "missing or invalid token"))?;
req.extensions_mut().insert(principal);
Ok(next.run(req).await)
}
+243
View File
@@ -0,0 +1,243 @@
//! Blob endpoints: HEAD (existence / partial-upload offset), GET (Range, streamed) and PUT
//! (streamed to `<graph>/uploads/<hash>.part`, resumable, verified with blake3).
use crate::AppState;
use crate::api::graph_for;
use crate::auth::Principal;
use crate::error::{ApiError, ApiResult};
use crate::graphs::GraphHandle;
use axum::Extension;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use futures_util::StreamExt;
use std::sync::Arc;
use synapse_sync::protocol::{HEADER_UPLOAD_LENGTH, HEADER_UPLOAD_OFFSET, is_valid_hash};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
fn check_hash(h: &str) -> ApiResult<()> {
if is_valid_hash(h) {
Ok(())
} else {
Err(ApiError::bad_request(
"blob hash must be 64 lowercase hex chars",
))
}
}
fn header_u64(headers: &HeaderMap, name: &str) -> Option<u64> {
headers.get(name)?.to_str().ok()?.parse().ok()
}
fn part_path(h: &GraphHandle, hash: &str) -> std::path::PathBuf {
h.dir.join("uploads").join(format!("{hash}.part"))
}
pub async fn head_blob(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, hash)): Path<(String, String)>,
) -> ApiResult<Response> {
check_hash(&hash)?;
let h = graph_for(&s, &who, &id, false).await?;
if let Ok(meta) = tokio::fs::metadata(h.blobs.path_of(&hash)).await {
return Ok((
StatusCode::OK,
[(header::CONTENT_LENGTH, meta.len().to_string())],
)
.into_response());
}
let offset = tokio::fs::metadata(part_path(&h, &hash))
.await
.map(|m| m.len())
.unwrap_or(0);
Ok((
StatusCode::NOT_FOUND,
[(HEADER_UPLOAD_OFFSET, offset.to_string())],
)
.into_response())
}
/// Parses `bytes=START-[END]`.
fn parse_range(v: &str, size: u64) -> Option<(u64, u64)> {
let spec = v.strip_prefix("bytes=")?;
let (a, b) = spec.split_once('-')?;
let start: u64 = a.parse().ok()?;
let end = if b.is_empty() {
size.checked_sub(1)?
} else {
b.parse::<u64>().ok()?.min(size.checked_sub(1)?)
};
(start <= end).then_some((start, end))
}
pub async fn get_blob(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, hash)): Path<(String, String)>,
headers: HeaderMap,
) -> ApiResult<Response> {
check_hash(&hash)?;
let h = graph_for(&s, &who, &id, false).await?;
let mut file = tokio::fs::File::open(h.blobs.path_of(&hash))
.await
.map_err(|_| ApiError::not_found("blob not found"))?;
let size = file.metadata().await?.len();
let range = headers
.get(header::RANGE)
.and_then(|v| v.to_str().ok())
.map(|v| parse_range(v, size));
let (status, start, len) = match range {
None => (StatusCode::OK, 0, size),
Some(Some((a, b))) => (StatusCode::PARTIAL_CONTENT, a, b - a + 1),
Some(None) => {
return Ok((
StatusCode::RANGE_NOT_SATISFIABLE,
[(header::CONTENT_RANGE, format!("bytes */{size}"))],
)
.into_response());
}
};
file.seek(std::io::SeekFrom::Start(start)).await?;
let body = Body::from_stream(tokio_util::io::ReaderStream::with_capacity(
file.take(len),
256 * 1024,
));
let mut resp = Response::new(body);
*resp.status_mut() = status;
let hd = resp.headers_mut();
hd.insert(header::CONTENT_LENGTH, HeaderValue::from(len));
hd.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
hd.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
if status == StatusCode::PARTIAL_CONTENT {
hd.insert(
header::CONTENT_RANGE,
HeaderValue::from_str(&format!("bytes {start}-{}/{size}", start + len - 1)).unwrap(),
);
}
Ok(resp)
}
/// Removes the in-flight marker when the request ends (or is cancelled).
struct UploadGuard {
graph: Arc<GraphHandle>,
hash: String,
}
impl Drop for UploadGuard {
fn drop(&mut self) {
self.graph
.uploads
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&self.hash);
}
}
pub async fn put_blob(
State(s): State<AppState>,
Extension(who): Extension<Principal>,
Path((id, hash)): Path<(String, String)>,
headers: HeaderMap,
body: Body,
) -> ApiResult<Response> {
check_hash(&hash)?;
let h = graph_for(&s, &who, &id, false).await?;
if h.blobs.contains(&hash) {
return Ok(StatusCode::NO_CONTENT.into_response());
}
let offset = header_u64(&headers, HEADER_UPLOAD_OFFSET).unwrap_or(0);
let total = header_u64(&headers, HEADER_UPLOAD_LENGTH)
.ok_or_else(|| ApiError::bad_request("Upload-Length header is required"))?;
if !h
.uploads
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(hash.clone())
{
return Err(ApiError::new(
StatusCode::CONFLICT,
"upload already in progress",
));
}
let _guard = UploadGuard {
graph: h.clone(),
hash: hash.clone(),
};
let part = part_path(&h, &hash);
tokio::fs::create_dir_all(part.parent().unwrap()).await?;
let have = tokio::fs::metadata(&part)
.await
.map(|m| m.len())
.unwrap_or(0);
if offset > 0 && offset != have {
return Ok((
StatusCode::CONFLICT,
[(HEADER_UPLOAD_OFFSET, have.to_string())],
)
.into_response());
}
let mut out = if offset == 0 {
tokio::fs::File::create(&part).await?
} else {
tokio::fs::OpenOptions::new()
.append(true)
.open(&part)
.await?
};
let mut written = offset;
let mut stream = body.into_data_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| ApiError::bad_request(format!("upload interrupted: {e}")))?;
written += chunk.len() as u64;
if written > total {
drop(out);
let _ = tokio::fs::remove_file(&part).await;
return Err(ApiError::bad_request("body exceeds Upload-Length"));
}
out.write_all(&chunk).await?;
}
out.flush().await?;
drop(out);
if written < total {
// Partial upload stored; the client resumes from `Upload-Offset`.
return Ok((
StatusCode::ACCEPTED,
[(HEADER_UPLOAD_OFFSET, written.to_string())],
)
.into_response());
}
// Complete: verify the content hash before publishing it into the blob store.
let (part2, hash2) = (part.clone(), hash.clone());
let dest = h.blobs.path_of(&hash);
let ok = tokio::task::spawn_blocking(move || -> std::io::Result<bool> {
let mut f = std::fs::File::open(&part2)?;
let mut hasher = blake3::Hasher::new();
std::io::copy(&mut f, &mut hasher)?;
if hasher.finalize().to_hex().as_str() != hash2 {
std::fs::remove_file(&part2)?;
return Ok(false);
}
std::fs::create_dir_all(dest.parent().unwrap())?;
std::fs::rename(&part2, &dest)?;
Ok(true)
})
.await
.map_err(ApiError::internal)??;
if !ok {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"content does not match the blob hash",
));
}
tracing::info!(graph = %id, %hash, size = total, "blob stored");
Ok(StatusCode::CREATED.into_response())
}
+57
View File
@@ -0,0 +1,57 @@
use std::net::SocketAddr;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct Config {
pub bind: SocketAddr,
pub data_dir: PathBuf,
/// Accepted bearer tokens (`SYNAPSE_AUTH_TOKEN`, comma separated).
pub auth_tokens: Vec<String>,
/// Token for `/admin/update`; the endpoint is disabled when unset.
pub update_token: Option<String>,
pub update_script: PathBuf,
}
pub const MIN_TOKEN_LEN: usize = 16;
impl Config {
pub fn from_env() -> Result<Self, String> {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
let bind = var("SYNAPSE_BIND").unwrap_or_else(|| "127.0.0.1:7878".into());
let bind = bind
.parse()
.map_err(|e| format!("SYNAPSE_BIND={bind:?}: {e}"))?;
let data_dir = var("SYNAPSE_DATA_DIR").ok_or("SYNAPSE_DATA_DIR is required")?;
let tokens = var("SYNAPSE_AUTH_TOKEN").ok_or("SYNAPSE_AUTH_TOKEN is required")?;
let auth_tokens: Vec<String> = tokens
.split(',')
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.collect();
let cfg = Self {
bind,
data_dir: data_dir.into(),
auth_tokens,
update_token: var("SYNAPSE_UPDATE_TOKEN"),
update_script: var("SYNAPSE_UPDATE_SCRIPT")
.unwrap_or_else(|| "/opt/synapse/scripts/update.sh".into())
.into(),
};
cfg.validate()?;
Ok(cfg)
}
pub fn validate(&self) -> Result<(), String> {
if self.auth_tokens.is_empty() {
return Err("no auth token configured".into());
}
for t in self.auth_tokens.iter().chain(self.update_token.iter()) {
if t.len() < MIN_TOKEN_LEN {
return Err(format!(
"tokens must be at least {MIN_TOKEN_LEN} characters"
));
}
}
Ok(())
}
}
+61
View File
@@ -0,0 +1,61 @@
use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use synapse_sync::protocol::ErrorBody;
#[derive(Debug)]
pub struct ApiError {
pub status: StatusCode,
pub message: String,
}
impl ApiError {
pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
Self {
status,
message: message.into(),
}
}
pub fn bad_request(m: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, m)
}
pub fn not_found(m: impl Into<String>) -> Self {
Self::new(StatusCode::NOT_FOUND, m)
}
pub fn internal(e: impl std::fmt::Display) -> Self {
tracing::error!(error = %e, "internal error");
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
}
}
impl From<synapse_core::Error> for ApiError {
fn from(e: synapse_core::Error) -> Self {
use synapse_core::Error as E;
match e {
E::NotFound(m) => Self::not_found(m),
E::Invalid(m) => Self::bad_request(m),
E::Conflict(m) => Self::new(StatusCode::CONFLICT, m),
other => Self::internal(other),
}
}
}
impl From<std::io::Error> for ApiError {
fn from(e: std::io::Error) -> Self {
Self::internal(e)
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(
self.status,
Json(ErrorBody {
error: self.message,
}),
)
.into_response()
}
}
pub type ApiResult<T> = Result<T, ApiError>;
+105
View File
@@ -0,0 +1,105 @@
//! Server-side graphs: one `synapse_core::Graph` per `SYNAPSE_DATA_DIR/<graph_id>/`.
use crate::error::{ApiError, ApiResult};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, PoisonError};
use synapse_core::Graph;
use synapse_core::blob::BlobStore;
use synapse_sync::protocol::is_valid_graph_id;
use tokio::sync::{Mutex as AsyncMutex, watch};
pub struct GraphHandle {
pub dir: PathBuf,
pub server_id: String,
pub blobs: BlobStore,
graph: Mutex<Graph>,
/// Latest op seq; subscribers (SSE) are woken when it changes.
pub seq: watch::Sender<i64>,
/// Hashes with an upload in flight.
pub uploads: Mutex<HashSet<String>>,
}
impl GraphHandle {
/// Runs `f` on the blocking pool with the graph locked (the core `Graph` is `!Sync` and
/// SQLite is synchronous).
pub async fn run<T: Send + 'static>(
self: &Arc<Self>,
f: impl FnOnce(&Graph) -> synapse_core::Result<T> + Send + 'static,
) -> ApiResult<T> {
let me = self.clone();
tokio::task::spawn_blocking(move || {
let g = me.graph.lock().unwrap_or_else(PoisonError::into_inner);
f(&g)
})
.await
.map_err(ApiError::internal)?
.map_err(ApiError::from)
}
pub fn publish_seq(&self, seq: i64) {
self.seq.send_if_modified(|cur| {
if seq > *cur {
*cur = seq;
true
} else {
false
}
});
}
}
pub struct Graphs {
root: PathBuf,
map: AsyncMutex<HashMap<String, Arc<GraphHandle>>>,
}
impl Graphs {
pub fn new(root: PathBuf) -> Self {
Self {
root,
map: AsyncMutex::new(HashMap::new()),
}
}
/// Returns an existing graph (`None` if it was never created).
pub async fn get(&self, id: &str) -> ApiResult<Option<Arc<GraphHandle>>> {
self.open(id, false).await
}
/// Returns the graph, creating it on first use.
pub async fn get_or_create(&self, id: &str) -> ApiResult<Arc<GraphHandle>> {
Ok(self.open(id, true).await?.expect("created"))
}
async fn open(&self, id: &str, create: bool) -> ApiResult<Option<Arc<GraphHandle>>> {
if !is_valid_graph_id(id) {
return Err(ApiError::bad_request("invalid graph id"));
}
let mut map = self.map.lock().await;
if let Some(h) = map.get(id) {
return Ok(Some(h.clone()));
}
let dir = self.root.join(id);
if !create && !dir.join("synapse.db").exists() {
return Ok(None);
}
let handle = tokio::task::spawn_blocking(move || -> synapse_core::Result<GraphHandle> {
let graph = Graph::open(&dir)?;
let seq = graph.last_seq()?;
Ok(GraphHandle {
server_id: graph.actor().to_string(),
blobs: graph.blobs().clone(),
dir,
graph: Mutex::new(graph),
seq: watch::channel(seq).0,
uploads: Mutex::new(HashSet::new()),
})
})
.await
.map_err(ApiError::internal)??;
let handle = Arc::new(handle);
map.insert(id.to_string(), handle.clone());
Ok(Some(handle))
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Synapse sync server. See `docs/sync.md` (protocol) and `docs/server.md` (deployment).
mod admin;
mod api;
mod auth;
mod blobs;
pub mod config;
mod error;
mod graphs;
use axum::extract::DefaultBodyLimit;
use axum::routing::{get, head, post};
use axum::{Json, Router, middleware};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tower_http::trace::TraceLayer;
pub use config::Config;
#[derive(Clone)]
pub struct AppState {
pub(crate) graphs: Arc<graphs::Graphs>,
pub(crate) auth: Arc<auth::Authenticator>,
pub(crate) update_token: Option<blake3::Hash>,
pub(crate) update_script: Arc<std::path::PathBuf>,
pub(crate) data_dir: Arc<std::path::PathBuf>,
pub(crate) updater: Arc<admin::Updater>,
pub(crate) shutdown: Arc<Notify>,
}
impl AppState {
pub fn new(cfg: &Config) -> std::io::Result<Self> {
std::fs::create_dir_all(&cfg.data_dir)?;
Ok(Self {
graphs: Arc::new(graphs::Graphs::new(cfg.data_dir.clone())),
auth: Arc::new(auth::Authenticator::from_shared_tokens(&cfg.auth_tokens)),
update_token: cfg
.update_token
.as_ref()
.map(|t| blake3::hash(t.as_bytes())),
update_script: Arc::new(cfg.update_script.clone()),
data_dir: Arc::new(cfg.data_dir.clone()),
updater: Arc::new(admin::Updater::default()),
shutdown: Arc::new(Notify::new()),
})
}
}
async fn healthz() -> Json<serde_json::Value> {
Json(serde_json::json!({
"status": "ok",
"version": env!("CARGO_PKG_VERSION"),
"protocol": synapse_sync::protocol::PROTOCOL_VERSION,
}))
}
pub fn router(state: AppState) -> Router {
let graph_routes = Router::new()
.route("/graphs/{id}", get(api::get_graph).put(api::put_graph))
.route("/graphs/{id}/ops", get(api::pull_ops).post(api::push_ops))
.route("/graphs/{id}/events", get(api::events))
.route(
"/graphs/{id}/blobs/{hash}",
head(blobs::head_blob)
.get(blobs::get_blob)
.put(blobs::put_blob)
// Blobs can be multi-GB: no body limit, they are streamed to disk.
.layer(DefaultBodyLimit::disable()),
)
.route("/graphs/{id}/pages", get(api::list_pages))
.route("/graphs/{id}/pages/by-title", get(api::page_by_title))
.route("/graphs/{id}/pages/{page}", get(api::page_by_id))
.route("/graphs/{id}/pages/{page}/backlinks", get(api::backlinks))
.route("/graphs/{id}/journals", get(api::journals))
.route("/graphs/{id}/journals/{date}", get(api::journal))
// JSON bodies (op batches) are capped; see MAX_PUSH_OPS.
.layer(DefaultBodyLimit::max(64 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.clone(),
auth::require_auth,
));
let admin_routes = Router::new()
.route("/update", post(admin::trigger).get(admin::status))
.layer(middleware::from_fn_with_state(
state.clone(),
admin::admin_guard,
));
Router::new()
.route("/healthz", get(healthz))
.nest("/v1", graph_routes)
.nest("/admin", admin_routes)
.layer(TraceLayer::new_for_http())
.with_state(state)
}
pub struct RunningServer {
pub addr: SocketAddr,
pub task: tokio::task::JoinHandle<std::io::Result<()>>,
shutdown: Arc<Notify>,
}
impl RunningServer {
pub fn shutdown(&self) {
self.shutdown.notify_one();
}
}
/// Binds and serves in the background (used by tests and `serve`).
pub async fn start(cfg: &Config) -> std::io::Result<RunningServer> {
let state = AppState::new(cfg)?;
let shutdown = state.shutdown.clone();
let listener = TcpListener::bind(cfg.bind).await?;
let addr = listener.local_addr()?;
let sd = shutdown.clone();
let app = router(state);
let task = tokio::spawn(async move {
axum::serve(listener, app)
.with_graceful_shutdown(async move { sd.notified().await })
.await
});
Ok(RunningServer {
addr,
task,
shutdown,
})
}
/// Serves until SIGINT/SIGTERM or a successful self-update.
pub async fn serve(cfg: Config) -> std::io::Result<()> {
let server = start(&cfg).await?;
tracing::info!(addr = %server.addr, data_dir = %cfg.data_dir.display(), "synapse-server listening");
let sd = server.shutdown.clone();
tokio::spawn(async move {
wait_for_signal().await;
sd.notify_one();
});
server.task.await.map_err(std::io::Error::other)?
}
async fn wait_for_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
+25
View File
@@ -0,0 +1,25 @@
use synapse_server::Config;
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,tower_http=info"));
let builder = tracing_subscriber::fmt().with_env_filter(filter);
if std::env::var("SYNAPSE_LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json")) {
builder.json().init();
} else {
builder.init();
}
let cfg = match Config::from_env() {
Ok(c) => c,
Err(e) => {
tracing::error!("configuration error: {e}");
std::process::exit(2);
}
};
if let Err(e) = synapse_server::serve(cfg).await {
tracing::error!("server error: {e}");
std::process::exit(1);
}
}
+388
View File
@@ -0,0 +1,388 @@
//! End-to-end: a real server on a random local port and several client graphs.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use synapse_core::{Graph, NewPage, Placement};
use synapse_server::{Config, RunningServer};
use synapse_sync::{BlobPolicy, Error, Remote, RemoteConfig, SyncClient, SyncConfig, SyncStatus};
const TOKEN: &str = "test-token-0123456789abcdef";
struct TestServer {
server: RunningServer,
_dir: tempfile::TempDir,
}
impl TestServer {
async fn start() -> Self {
let dir = tempfile::tempdir().unwrap();
let cfg = Config {
bind: "127.0.0.1:0".parse().unwrap(),
data_dir: dir.path().join("data"),
auth_tokens: vec![TOKEN.into()],
update_token: None,
update_script: "/nonexistent".into(),
};
let server = synapse_server::start(&cfg).await.unwrap();
Self { server, _dir: dir }
}
fn url(&self) -> String {
format!("http://{}", self.server.addr)
}
fn remote_cfg(&self, graph: &str, token: &str) -> RemoteConfig {
RemoteConfig::new(self.url(), graph, token)
}
}
struct Device {
graph: Arc<Mutex<Graph>>,
client: SyncClient,
_dir: tempfile::TempDir,
}
fn device(srv: &TestServer, graph_id: &str) -> Device {
device_cfg(srv.remote_cfg(graph_id, TOKEN))
}
fn device_cfg(remote: RemoteConfig) -> Device {
let dir = tempfile::tempdir().unwrap();
let graph = Arc::new(Mutex::new(Graph::open(dir.path()).unwrap()));
let client = SyncClient::new(graph.clone(), SyncConfig::new(remote)).unwrap();
Device {
graph,
client,
_dir: dir,
}
}
impl Device {
fn g(&self) -> std::sync::MutexGuard<'_, Graph> {
self.graph.lock().unwrap()
}
}
fn texts(d: &Device, title: &str) -> Vec<String> {
let g = d.g();
let page = g.page_by_title(title).unwrap().expect("page exists");
g.page_tree(page.id)
.unwrap()
.into_iter()
.map(|(_, b)| b.content)
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn two_devices_converge_edits_deletes_and_assets() {
let srv = TestServer::start().await;
let a = device(&srv, "main");
let b = device(&srv, "main");
// A creates a page with two blocks and an asset (multi-chunk blob).
let (b1, b2, hash) = {
let g = a.g();
let p = g.create_page(NewPage::titled("Ideas")).unwrap();
let b1 = g
.insert_block(p.id, Placement::LastChildOf(None), "first")
.unwrap();
let b2 = g
.insert_block(p.id, Placement::LastChildOf(None), "second")
.unwrap();
let data: Vec<u8> = (0..3_000_000u32).map(|i| (i % 251) as u8).collect();
let asset = g
.put_asset_reader(
&data[..],
Some("blob.bin"),
Some("application/octet-stream"),
)
.unwrap();
(b1.id, b2.id, asset.hash)
};
a.client.sync_once().await.unwrap();
assert_eq!(a.client.state().pending_ops, 0);
b.client.sync_once().await.unwrap();
assert_eq!(texts(&b, "Ideas"), vec!["first", "second"]);
assert!(b.g().blobs().contains(&hash), "blob downloaded by B");
assert_eq!(b.g().asset(&hash).unwrap().unwrap().size, 3_000_000);
// B edits one block and deletes the other; A converges.
{
let g = b.g();
g.update_block(b1, "first (edited on B)").unwrap();
g.delete_block(b2).unwrap();
}
assert!(b.client.refresh_pending().await.unwrap() >= 2);
b.client.sync_once().await.unwrap();
a.client.sync_once().await.unwrap();
assert_eq!(texts(&a, "Ideas"), vec!["first (edited on B)"]);
assert_eq!(texts(&b, "Ideas"), texts(&a, "Ideas"));
// Echo avoidance: applied remote ops are never pushed back. A full extra round trip on
// both sides must not grow the server log.
let remote = Remote::new(srv.remote_cfg("main", TOKEN)).unwrap();
let before = remote.ensure_graph().await.unwrap().last_seq;
a.client.sync_once().await.unwrap();
b.client.sync_once().await.unwrap();
a.client.sync_once().await.unwrap();
assert_eq!(remote.ensure_graph().await.unwrap().last_seq, before);
assert_eq!(a.client.state().last_pushed, 0);
assert_eq!(b.client.state().last_pushed, 0);
assert_eq!(b.client.state().pending_ops, 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_edits_resolve_last_writer_wins() {
let srv = TestServer::start().await;
let a = device(&srv, "g");
let b = device(&srv, "g");
let blk = {
let g = a.g();
let p = g.create_page(NewPage::titled("Shared")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "base")
.unwrap()
.id
};
a.client.sync_once().await.unwrap();
b.client.sync_once().await.unwrap();
{
let g = a.g();
g.set_now(Some(g.now_ms() + 10_000));
g.update_block(blk, "from A").unwrap();
}
b.g().update_block(blk, "from B").unwrap();
// A's edit has the later timestamp regardless of sync order.
b.client.sync_once().await.unwrap();
a.client.sync_once().await.unwrap();
b.client.sync_once().await.unwrap();
assert_eq!(texts(&a, "Shared"), vec!["from A"]);
assert_eq!(texts(&b, "Shared"), vec!["from A"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_failures() {
let srv = TestServer::start().await;
let bad = device_cfg(srv.remote_cfg("main", "wrong-token-0123456789"));
let err = bad.client.sync_once().await.unwrap_err();
assert!(matches!(err, Error::Unauthorized), "{err:?}");
assert_eq!(bad.client.state().status, SyncStatus::Error);
let http = reqwest::Client::new();
let url = srv.url();
// Health is public; everything else needs the token.
assert_eq!(
http.get(format!("{url}/healthz"))
.send()
.await
.unwrap()
.status(),
200
);
for path in [
"/v1/graphs/main",
"/v1/graphs/main/ops",
"/v1/graphs/main/pages",
] {
let r = http.get(format!("{url}{path}")).send().await.unwrap();
assert_eq!(r.status(), 401, "{path}");
let r = http
.get(format!("{url}{path}"))
.bearer_auth("nope")
.send()
.await
.unwrap();
assert_eq!(r.status(), 401, "{path} with wrong token");
}
// Update endpoint is disabled unless SYNAPSE_UPDATE_TOKEN is set.
let r = http
.post(format!("{url}/admin/update"))
.bearer_auth(TOKEN)
.send()
.await
.unwrap();
assert_eq!(r.status(), 404);
// Bad graph id.
let r = http
.put(format!("{url}/v1/graphs/..%2Fetc"))
.bearer_auth(TOKEN)
.send()
.await
.unwrap();
assert!(r.status().is_client_error());
// Unknown graph on a read.
let r = http
.get(format!("{url}/v1/graphs/missing/ops"))
.bearer_auth(TOKEN)
.send()
.await
.unwrap();
assert_eq!(r.status(), 404);
}
#[tokio::test(flavor = "multi_thread")]
async fn blob_upload_resumes_and_verifies_hash() {
let srv = TestServer::start().await;
let remote = Remote::new(srv.remote_cfg("main", TOKEN)).unwrap();
remote.ensure_graph().await.unwrap();
let data: Vec<u8> = (0..1_000_000u32).map(|i| (i * 7 % 256) as u8).collect();
let hash = blake3::hash(&data).to_hex().to_string();
let url = format!("{}/v1/graphs/main/blobs/{hash}", srv.url());
let http = reqwest::Client::new();
// First half only.
let r = http
.put(&url)
.bearer_auth(TOKEN)
.header("upload-length", data.len())
.body(data[..400_000].to_vec())
.send()
.await
.unwrap();
assert_eq!(r.status(), 202);
assert_eq!(
remote.blob_upload_offset(&hash).await.unwrap(),
Some(400_000)
);
// Wrong offset is refused with the real one.
let r = http
.put(&url)
.bearer_auth(TOKEN)
.header("upload-length", data.len())
.header("upload-offset", 5)
.body(data[5..].to_vec())
.send()
.await
.unwrap();
assert_eq!(r.status(), 409);
assert_eq!(r.headers()["upload-offset"], "400000");
// Resume through the client helper.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("f.bin");
std::fs::write(&path, &data).unwrap();
remote.upload_blob(&hash, &path).await.unwrap();
assert_eq!(remote.blob_upload_offset(&hash).await.unwrap(), None);
// Ranged download resumes from a partial file.
let part = dir.path().join("f.part");
std::fs::write(&part, &data[..123_456]).unwrap();
let dest = dir.path().join("out.bin");
remote.download_blob(&hash, &part, &dest).await.unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), data);
// Content that does not match its hash is rejected and not stored.
let fake = "0".repeat(64);
let r = http
.put(format!("{}/v1/graphs/main/blobs/{fake}", srv.url()))
.bearer_auth(TOKEN)
.header("upload-length", 3)
.body("abc")
.send()
.await
.unwrap();
assert_eq!(r.status(), 422);
assert_eq!(remote.blob_upload_offset(&fake).await.unwrap(), Some(0));
}
#[tokio::test(flavor = "multi_thread")]
async fn thin_client_read_api() {
let srv = TestServer::start().await;
let a = device(&srv, "main");
let (target, date) = {
let g = a.g();
let t = g.create_page(NewPage::titled("Target")).unwrap();
g.insert_block(t.id, Placement::LastChildOf(None), "body")
.unwrap();
let j = g.today_journal().unwrap();
g.insert_block(j.id, Placement::LastChildOf(None), "see [[Target]]")
.unwrap();
(t, j.journal_date.unwrap())
};
a.client.sync_once().await.unwrap();
let thin = Remote::new(srv.remote_cfg("main", TOKEN)).unwrap();
let v = thin
.page_by_title("target")
.await
.unwrap()
.expect("case-insensitive");
assert_eq!(v.page.id, target.id);
assert_eq!(v.tree.len(), 1);
assert_eq!(v.tree[0].block.content, "body");
assert!(thin.page_by_title("Nope").await.unwrap().is_none());
let links = thin.backlinks(target.id).await.unwrap();
assert_eq!(links.len(), 1);
assert!(links[0].block.content.contains("Target"));
let j = thin.journal(date).await.unwrap().expect("journal");
assert_eq!(j.tree[0].block.content, "see [[Target]]");
assert!(
thin.journal(chrono::NaiveDate::from_ymd_opt(1999, 1, 1).unwrap())
.await
.unwrap()
.is_none()
);
assert!(thin.list_pages(true, 50, 0).await.unwrap().len() >= 2);
assert_eq!(thin.journals_between(date, date).await.unwrap().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn offline_keeps_edits_and_reports_state() {
// Nothing listens on this port.
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
drop(l);
let d = device_cfg(RemoteConfig::new(
format!("http://127.0.0.1:{port}"),
"main",
TOKEN,
));
{
let g = d.g();
let p = g.create_page(NewPage::titled("Offline note")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "kept")
.unwrap();
}
assert!(d.client.sync_once().await.is_err());
let st = d.client.state();
assert_eq!(st.status, SyncStatus::Offline);
assert!(st.pending_ops >= 2, "{st:?}");
assert_eq!(texts(&d, "Offline note"), vec!["kept"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn background_loop_delivers_realtime_via_sse() {
let srv = TestServer::start().await;
let mk = |id: &str| {
let dir = tempfile::tempdir().unwrap();
let graph = Arc::new(Mutex::new(Graph::open(dir.path()).unwrap()));
let mut cfg = SyncConfig::new(srv.remote_cfg(id, TOKEN));
// Polling is effectively off: B can only learn about A's edit through the stream.
cfg.poll_interval = Duration::from_secs(3600);
cfg.full_sync_interval = Duration::from_secs(3600);
cfg.blob_policy = BlobPolicy::OnDemand;
(SyncClient::new(graph.clone(), cfg).unwrap(), graph, dir)
};
let (ca, ga, _da) = mk("rt");
let (cb, gb, _db) = mk("rt");
let _ha = ca.start();
let _hb = cb.start();
tokio::time::sleep(Duration::from_millis(800)).await; // let both connect to the stream
{
let g = ga.lock().unwrap();
let p = g.create_page(NewPage::titled("Live")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "hello")
.unwrap();
}
ca.trigger();
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
loop {
if gb.lock().unwrap().page_by_title("Live").unwrap().is_some() {
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"B never received the page"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
+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)
}