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

+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);
}
}