fix(sync): robust blob handling, op validation and quarantine

- upload_blob resumes until the server confirms the blob (202/409 are not success)
- missing local blob skips its PutAsset instead of blocking all later ops
- failed blob downloads are counted and retried, not fatal to the cycle
- server validates pushed ops (hash, hlc, clock skew) and returns per-op rejections
- pulled ops that can never apply are quarantined; storage errors stay fatal
- SYNAPSE_MAX_CLOCK_SKEW_MINUTES; document Arc<Mutex<Graph>> handle for the FFI

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-21 14:38:58 +02:00
1 parent 3266ddda3a
commit 9ce35f90ff
11 files changed
+433 -52

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ SYNAPSE_AUTH_TOKEN=
SYNAPSE_UPDATE_TOKEN= SYNAPSE_UPDATE_TOKEN=
# Update script run by the endpoint (default /opt/synapse/scripts/update.sh) # Update script run by the endpoint (default /opt/synapse/scripts/update.sh)
SYNAPSE_UPDATE_SCRIPT= SYNAPSE_UPDATE_SCRIPT=
# Reject pushed ops whose clock is more than this many minutes ahead of the server (default 10)
SYNAPSE_MAX_CLOCK_SKEW_MINUTES=
# Log format: text (default) or json # Log format: text (default) or json
SYNAPSE_LOG_FORMAT= SYNAPSE_LOG_FORMAT=
# Log filter, e.g. info,synapse_server=debug # Log filter, e.g. info,synapse_server=debug
+27 -9
View File
@@ -82,25 +82,43 @@ pub async fn push_ops(
)); ));
} }
let h = graph_for(&s, &who, &id, false).await?; let h = graph_for(&s, &who, &id, false).await?;
let (applied, last_seq) = h let max_future_ms = s.max_clock_skew.as_millis() as i64;
let (applied, last_seq, rejected) = h
.run(move |g| { .run(move |g| {
let mut applied = 0u32; let (mut applied, mut rejected) = (0u32, Vec::new());
for w in &req.ops { let now = g.now_ms();
if hlc_actor(&w.hlc).is_none() || synapse_core::hlc::decode(&w.hlc).is_none() { for (i, w) in req.ops.iter().enumerate() {
return Err(synapse_core::Error::Invalid(format!("bad hlc {:?}", w.hlc))); let reject = |reason: String| Rejection {
index: i as u32,
reason,
};
if let Err(reason) = validate_op(&w.hlc, &w.op, now, max_future_ms) {
rejected.push(reject(reason));
continue;
} }
if g.apply_remote(&w.hlc, &w.op)? { match g.apply_remote(&w.hlc, &w.op) {
applied += 1; Ok(true) => applied += 1,
Ok(false) => {}
// Unappliable op: refuse it, keep the rest of the batch.
Err(e) if is_poison(&e) => rejected.push(reject(e.to_string())),
Err(e) => return Err(e),
} }
} }
Ok((applied, g.last_seq()?)) Ok((applied, g.last_seq()?, rejected))
}) })
.await?; .await?;
if applied > 0 { if applied > 0 {
h.publish_seq(last_seq); h.publish_seq(last_seq);
} }
if !rejected.is_empty() {
tracing::warn!(graph = %id, principal = %who.name, rejected = rejected.len(), first = %rejected[0].reason, "push: ops rejected");
}
tracing::info!(graph = %id, principal = %who.name, applied, "push"); tracing::info!(graph = %id, principal = %who.name, applied, "push");
Ok(Json(PushResponse { applied, last_seq })) Ok(Json(PushResponse {
applied,
last_seq,
rejected,
}))
} }
#[derive(Deserialize)] #[derive(Deserialize)]
+10
View File
@@ -1,5 +1,6 @@
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::Duration;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
@@ -10,6 +11,8 @@ pub struct Config {
/// Token for `/admin/update`; the endpoint is disabled when unset. /// Token for `/admin/update`; the endpoint is disabled when unset.
pub update_token: Option<String>, pub update_token: Option<String>,
pub update_script: PathBuf, pub update_script: PathBuf,
/// Ops whose HLC is further ahead of the server clock than this are rejected.
pub max_clock_skew: Duration,
} }
pub const MIN_TOKEN_LEN: usize = 16; pub const MIN_TOKEN_LEN: usize = 16;
@@ -36,6 +39,13 @@ impl Config {
update_script: var("SYNAPSE_UPDATE_SCRIPT") update_script: var("SYNAPSE_UPDATE_SCRIPT")
.unwrap_or_else(|| "/opt/synapse/scripts/update.sh".into()) .unwrap_or_else(|| "/opt/synapse/scripts/update.sh".into())
.into(), .into(),
max_clock_skew: Duration::from_secs(
60 * var("SYNAPSE_MAX_CLOCK_SKEW_MINUTES")
.map(|v| v.parse::<u64>())
.transpose()
.map_err(|e| format!("SYNAPSE_MAX_CLOCK_SKEW_MINUTES: {e}"))?
.unwrap_or(10),
),
}; };
cfg.validate()?; cfg.validate()?;
Ok(cfg) Ok(cfg)
+2
View File
@@ -28,6 +28,7 @@ pub struct AppState {
pub(crate) data_dir: Arc<std::path::PathBuf>, pub(crate) data_dir: Arc<std::path::PathBuf>,
pub(crate) updater: Arc<admin::Updater>, pub(crate) updater: Arc<admin::Updater>,
pub(crate) shutdown: Arc<Notify>, pub(crate) shutdown: Arc<Notify>,
pub(crate) max_clock_skew: std::time::Duration,
} }
impl AppState { impl AppState {
@@ -44,6 +45,7 @@ impl AppState {
data_dir: Arc::new(cfg.data_dir.clone()), data_dir: Arc::new(cfg.data_dir.clone()),
updater: Arc::new(admin::Updater::default()), updater: Arc::new(admin::Updater::default()),
shutdown: Arc::new(Notify::new()), shutdown: Arc::new(Notify::new()),
max_clock_skew: cfg.max_clock_skew,
}) })
} }
} }
+146
View File
@@ -22,6 +22,7 @@ impl TestServer {
auth_tokens: vec![TOKEN.into()], auth_tokens: vec![TOKEN.into()],
update_token: None, update_token: None,
update_script: "/nonexistent".into(), update_script: "/nonexistent".into(),
max_clock_skew: Duration::from_secs(600),
}; };
let server = synapse_server::start(&cfg).await.unwrap(); let server = synapse_server::start(&cfg).await.unwrap();
Self { server, _dir: dir } Self { server, _dir: dir }
@@ -29,6 +30,9 @@ impl TestServer {
fn url(&self) -> String { fn url(&self) -> String {
format!("http://{}", self.server.addr) format!("http://{}", self.server.addr)
} }
fn graph_dir(&self, graph: &str) -> std::path::PathBuf {
self._dir.path().join("data").join(graph)
}
fn remote_cfg(&self, graph: &str, token: &str) -> RemoteConfig { fn remote_cfg(&self, graph: &str, token: &str) -> RemoteConfig {
RemoteConfig::new(self.url(), graph, token) RemoteConfig::new(self.url(), graph, token)
} }
@@ -386,3 +390,145 @@ async fn background_loop_delivers_realtime_via_sse() {
tokio::time::sleep(Duration::from_millis(100)).await; tokio::time::sleep(Duration::from_millis(100)).await;
} }
} }
fn put_asset(d: &Device, len: u32) -> String {
let data: Vec<u8> = (0..len).map(|i| (i % 253) as u8).collect();
d.g()
.put_asset_reader(&data[..], Some("a.bin"), None)
.unwrap()
.hash
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_local_blob_does_not_block_later_ops() {
let srv = TestServer::start().await;
let a = device(&srv, "main");
let hash = put_asset(&a, 10_000);
std::fs::remove_file(a.g().blobs().path_of(&hash)).unwrap();
{
let g = a.g();
let p = g.create_page(NewPage::titled("After")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "still pushed")
.unwrap();
}
a.client.sync_once().await.expect("cycle succeeds");
let st = a.client.state();
assert_eq!(st.status, SyncStatus::Idle);
assert_eq!(st.skipped_assets, 1);
assert_eq!(st.pending_ops, 0);
let thin = Remote::new(srv.remote_cfg("main", TOKEN)).unwrap();
assert!(thin.page_by_title("After").await.unwrap().is_some());
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_remote_blob_does_not_wedge_the_cycle() {
let srv = TestServer::start().await;
let a = device(&srv, "main");
let b = device(&srv, "main");
let hash = put_asset(&a, 10_000);
{
let g = a.g();
let p = g.create_page(NewPage::titled("Doc")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "text")
.unwrap();
}
a.client.sync_once().await.unwrap();
// The server loses the blob (disk cleanup, manual deletion...).
let blob = srv
.graph_dir("main")
.join("blobs")
.join(&hash[..2])
.join(&hash[2..]);
std::fs::remove_file(blob).unwrap();
b.client
.sync_once()
.await
.expect("cycle succeeds despite the 404");
let st = b.client.state();
assert_eq!(st.status, SyncStatus::Idle);
assert_eq!(st.failed_blobs, 1);
assert_eq!(texts(&b, "Doc"), vec!["text"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn server_rejects_bad_ops_but_keeps_the_rest() {
use synapse_sync::protocol::WireOp;
let srv = TestServer::start().await;
let remote = Remote::new(srv.remote_cfg("main", TOKEN)).unwrap();
remote.ensure_graph().await.unwrap();
let id = synapse_core::new_id();
let op = synapse_core::Op::DeleteBlock { id };
let bad_asset = synapse_core::Op::PutAsset {
asset: synapse_core::Asset {
hash: "../../etc/passwd".into(),
size: 1,
mime: None,
original_name: None,
created_at: 0,
},
};
let ok_hlc = format!("{:013}-00000-peer", chrono::Utc::now().timestamp_millis());
let far = chrono::Utc::now().timestamp_millis() + 3_600_000;
let resp = remote
.push(vec![
WireOp {
hlc: ok_hlc.clone(),
op: op.clone(),
},
WireOp {
hlc: ok_hlc.clone(),
op: bad_asset,
},
WireOp {
hlc: format!("{far:013}-00000-peer"),
op: op.clone(),
},
WireOp {
hlc: "garbage".into(),
op,
},
])
.await
.unwrap();
assert_eq!(resp.applied, 1);
let idx: Vec<u32> = resp.rejected.iter().map(|r| r.index).collect();
assert_eq!(idx, vec![1, 2, 3], "{:?}", resp.rejected);
assert!(resp.rejected[1].reason.contains("future"));
}
#[tokio::test(flavor = "multi_thread")]
async fn poison_op_in_server_log_does_not_wedge_pull() {
let srv = TestServer::start().await;
let a = device(&srv, "main");
a.client.sync_once().await.unwrap(); // creates the server graph
// Plant ops straight into the server log, bypassing push validation: an asset with a
// hostile hash (core may reject it as `Invalid`, which the client quarantines; older core
// applies it, which the client must then ignore) followed by a normal page.
{
let g = Graph::open(srv.graph_dir("main")).unwrap();
let bad = serde_json::json!({"type": "put_asset", "asset": {
"hash": "../../evil", "size": 1, "mime": null, "original_name": null, "created_at": 0}});
let ms = chrono::Utc::now().timestamp_millis();
g.conn()
.execute(
"INSERT INTO ops(hlc, payload) VALUES (?1, ?2)",
[
format!("{ms:013}-00000-other").as_str(),
bad.to_string().as_str(),
],
)
.unwrap();
}
let c = device(&srv, "main");
{
let g = c.g();
let p = g.create_page(NewPage::titled("After poison")).unwrap();
g.insert_block(p.id, Placement::LastChildOf(None), "x")
.unwrap();
}
c.client.sync_once().await.unwrap();
let b = device(&srv, "main");
b.client.sync_once().await.expect("pull is not wedged");
assert_eq!(b.client.state().status, SyncStatus::Idle);
assert_eq!(texts(&b, "After poison"), vec!["x"]);
}
+110 -33
View File
@@ -1,10 +1,10 @@
use crate::error::{Error, Result}; use crate::error::{Error, Result};
use crate::protocol::{SyncEvent, WireOp, hlc_actor}; use crate::protocol::{SyncEvent, WireOp, hlc_actor, is_poison};
use crate::remote::{Remote, RemoteConfig}; use crate::remote::{Remote, RemoteConfig};
use crate::state::{self, Cursors, SyncState, SyncStatus}; use crate::state::{self, Cursors, SyncState, SyncStatus};
use futures_util::StreamExt; use futures_util::StreamExt;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError}; use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration; use std::time::Duration;
use synapse_core::{Graph, Op}; use synapse_core::{Graph, Op};
@@ -58,6 +58,16 @@ struct Inner {
wake: Notify, wake: Notify,
/// Some synced assets may lack their blob locally. /// Some synced assets may lack their blob locally.
blobs_dirty: AtomicBool, blobs_dirty: AtomicBool,
quarantined: AtomicU64,
}
/// Per-cycle counters.
#[derive(Debug, Default)]
struct Cycle {
pushed: u64,
pulled: u64,
skipped_assets: u64,
failed_blobs: u64,
} }
/// Replicates a local [`Graph`] with a Synapse server. Cheap to clone. /// Replicates a local [`Graph`] with a Synapse server. Cheap to clone.
@@ -82,6 +92,7 @@ impl SyncClient {
dirty: AtomicBool::new(true), dirty: AtomicBool::new(true),
wake: Notify::new(), wake: Notify::new(),
blobs_dirty: AtomicBool::new(true), blobs_dirty: AtomicBool::new(true),
quarantined: AtomicU64::new(0),
}); });
Ok(Self { inner }) Ok(Self { inner })
} }
@@ -140,7 +151,7 @@ impl SyncClient {
.await .await
.unwrap_or(0); .unwrap_or(0);
match &res { match &res {
Ok((pushed, pulled)) => { Ok(c) => {
let now = std::time::SystemTime::now() let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH) .duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64) .map(|d| d.as_millis() as i64)
@@ -150,8 +161,11 @@ impl SyncClient {
s.message = None; s.message = None;
s.pending_ops = pending; s.pending_ops = pending;
s.last_sync_ms = Some(now); s.last_sync_ms = Some(now);
s.last_pushed = *pushed; s.last_pushed = c.pushed;
s.last_pulled = *pulled; s.last_pulled = c.pulled;
s.skipped_assets = c.skipped_assets;
s.failed_blobs = c.failed_blobs;
s.quarantined_ops = self.inner.quarantined.load(Ordering::SeqCst);
}); });
} }
Err(e) => { Err(e) => {
@@ -165,13 +179,14 @@ impl SyncClient {
s.status = status; s.status = status;
s.message = Some(e.to_string()); s.message = Some(e.to_string());
s.pending_ops = pending; s.pending_ops = pending;
s.quarantined_ops = self.inner.quarantined.load(Ordering::SeqCst);
}); });
} }
} }
res.map(|_| ()) res.map(|_| ())
} }
async fn run_cycle(&self) -> Result<(u64, u64)> { async fn run_cycle(&self) -> Result<Cycle> {
let remote = &self.inner.remote; let remote = &self.inner.remote;
let info = remote.ensure_graph().await?; let info = remote.ensure_graph().await?;
let key = remote.key(); let key = remote.key();
@@ -180,26 +195,30 @@ impl SyncClient {
.with_graph(move |g| Ok(state::load(g, &key, &server_id)?)) .with_graph(move |g| Ok(state::load(g, &key, &server_id)?))
.await?; .await?;
let pushed = self.push_all(&mut cur).await?; let mut stats = Cycle::default();
self.push_all(&mut cur, &mut stats).await?;
let (pulled, got_assets) = self.pull_all(&mut cur, &info.server_id).await?; let (pulled, got_assets) = self.pull_all(&mut cur, &info.server_id).await?;
stats.pulled = pulled;
if got_assets { if got_assets {
self.inner.blobs_dirty.store(true, Ordering::SeqCst); self.inner.blobs_dirty.store(true, Ordering::SeqCst);
} }
if self.inner.cfg.blob_policy == BlobPolicy::Eager if self.inner.cfg.blob_policy == BlobPolicy::Eager
&& self.inner.blobs_dirty.load(Ordering::SeqCst) && self.inner.blobs_dirty.load(Ordering::SeqCst)
{ {
self.fetch_missing_blobs().await?; stats.failed_blobs = self.fetch_missing_blobs().await?;
self.inner.blobs_dirty.store(false, Ordering::SeqCst); // Failed blobs are retried on the next cycle.
self.inner
.blobs_dirty
.store(stats.failed_blobs > 0, Ordering::SeqCst);
} }
Ok((pushed, pulled)) Ok(stats)
} }
/// Pushes ops originated by this replica. Ops that were *applied from the server* are /// 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 /// 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. /// here: that is what prevents echoing them back.
async fn push_all(&self, cur: &mut Cursors) -> Result<u64> { async fn push_all(&self, cur: &mut Cursors, stats: &mut Cycle) -> Result<()> {
let limit = self.inner.cfg.batch_size; let limit = self.inner.cfg.batch_size;
let mut total = 0;
loop { loop {
let after = cur.pushed_seq; let after = cur.pushed_seq;
let (batch, scanned_to, scanned) = self let (batch, scanned_to, scanned) = self
@@ -220,10 +239,13 @@ impl SyncClient {
}) })
.await?; .await?;
if scanned == 0 { if scanned == 0 {
return Ok(total); return Ok(());
} }
let mut batch = batch;
if !batch.is_empty() { if !batch.is_empty() {
// Blobs first, so the server never knows an asset it cannot serve. // Blobs first, so the server never knows an asset it cannot serve. An asset
// whose blob is missing locally can never be uploaded: skip its op (and warn)
// instead of blocking every later op of this device.
let hashes: BTreeSet<String> = batch let hashes: BTreeSet<String> = batch
.iter() .iter()
.filter_map(|w| match &w.op { .filter_map(|w| match &w.op {
@@ -231,17 +253,38 @@ impl SyncClient {
_ => None, _ => None,
}) })
.collect(); .collect();
let mut missing = BTreeSet::new();
for h in hashes { for h in hashes {
self.upload_blob(&h).await?; if !self.upload_blob(&h).await? {
missing.insert(h);
}
}
if !missing.is_empty() {
let before = batch.len();
batch.retain(|w| match &w.op {
Op::PutAsset { asset } => !missing.contains(&asset.hash),
_ => true,
});
stats.skipped_assets += (before - batch.len()) as u64;
}
if !batch.is_empty() {
stats.pushed += batch.len() as u64;
let resp = self.inner.remote.push(batch).await?;
if !resp.rejected.is_empty() {
self.inner
.quarantined
.fetch_add(resp.rejected.len() as u64, Ordering::SeqCst);
for r in &resp.rejected {
warn!(index = r.index, reason = %r.reason, "server rejected a local op");
}
}
} }
total += batch.len() as u64;
self.inner.remote.push(batch).await?;
} }
self.with_graph(move |g| Ok(state::save_pushed(g, scanned_to)?)) self.with_graph(move |g| Ok(state::save_pushed(g, scanned_to)?))
.await?; .await?;
cur.pushed_seq = scanned_to; cur.pushed_seq = scanned_to;
if (scanned as u32) < limit { if (scanned as u32) < limit {
return Ok(total); return Ok(());
} }
} }
} }
@@ -262,23 +305,39 @@ impl SyncClient {
} }
let next = resp.next_cursor.max(cur.pull_cursor); let next = resp.next_cursor.max(cur.pull_cursor);
let me2 = me.clone(); let me2 = me.clone();
let (applied, assets) = self let (applied, assets, quarantined) = self
.with_graph(move |g| { .with_graph(move |g| {
let (mut applied, mut assets) = (0u64, false); let (mut applied, mut assets, mut quarantined) = (0u64, false, 0u64);
for rec in resp.ops { for rec in resp.ops {
// Defence in depth: never re-apply our own ops. // Defence in depth: never re-apply our own ops.
if hlc_actor(&rec.hlc) == Some(me2.as_str()) { if hlc_actor(&rec.hlc) == Some(me2.as_str()) {
continue; continue;
} }
if g.apply_remote(&rec.hlc, &rec.op)? { match g.apply_remote(&rec.hlc, &rec.op) {
applied += 1; Ok(true) => {
assets |= matches!(rec.op, Op::PutAsset { .. }); applied += 1;
assets |= matches!(rec.op, Op::PutAsset { .. });
}
Ok(false) => {}
// An op that can never apply must not wedge the pull forever:
// park it and move on. Storage errors stay fatal (retried).
Err(e) if is_poison(&e) => {
warn!(seq = rec.seq, hlc = %rec.hlc, error = %e, "quarantined remote op");
let payload = serde_json::to_string(&rec.op)
.map_err(synapse_core::Error::from)?;
state::quarantine(g, rec.seq, &rec.hlc, &payload, &e.to_string())?;
quarantined += 1;
}
Err(e) => return Err(e.into()),
} }
} }
state::save_pulled(g, next)?; state::save_pulled(g, next)?;
Ok((applied, assets)) Ok((applied, assets, quarantined))
}) })
.await?; .await?;
self.inner
.quarantined
.fetch_add(quarantined, Ordering::SeqCst);
cur.pull_cursor = next; cur.pull_cursor = next;
applied_total += applied; applied_total += applied;
got_assets |= assets; got_assets |= assets;
@@ -290,15 +349,16 @@ impl SyncClient {
// ----------------------------------------------------------------- blobs // ----------------------------------------------------------------- blobs
async fn upload_blob(&self, hash: &str) -> Result<()> { /// Uploads the blob of a local asset. `Ok(false)` if the blob is missing locally.
async fn upload_blob(&self, hash: &str) -> Result<bool> {
let h = hash.to_string(); let h = hash.to_string();
let path = self.with_graph(move |g| Ok(g.blobs().path_of(&h))).await?; let path = self.with_graph(move |g| Ok(g.blobs().path_of(&h))).await?;
if !path.exists() { if !path.exists() {
return Err(Error::Protocol(format!( warn!(%hash, "asset registered but its blob is missing locally; not pushing it");
"asset {hash} is registered but its blob is missing locally" return Ok(false);
)));
} }
self.inner.remote.upload_blob(hash, &path).await self.inner.remote.upload_blob(hash, &path).await?;
Ok(true)
} }
/// Downloads blob `hash` if it is not stored locally yet (resumes partial downloads). /// Downloads blob `hash` if it is not stored locally yet (resumes partial downloads).
@@ -332,7 +392,10 @@ impl SyncClient {
Err(last.unwrap()) Err(last.unwrap())
} }
async fn fetch_missing_blobs(&self) -> Result<()> { /// Downloads every asset blob we lack. A blob that fails (e.g. 404) is logged and left
/// for the next cycle; the others still download. Returns how many failed. Connectivity
/// errors abort the cycle since every other blob would fail too.
async fn fetch_missing_blobs(&self) -> Result<u64> {
let missing = self let missing = self
.with_graph(|g| { .with_graph(|g| {
let mut st = g.conn().prepare("SELECT hash FROM assets")?; let mut st = g.conn().prepare("SELECT hash FROM assets")?;
@@ -341,15 +404,29 @@ impl SyncClient {
.collect::<std::result::Result<Vec<_>, _>>()?; .collect::<std::result::Result<Vec<_>, _>>()?;
Ok(hashes Ok(hashes
.into_iter() .into_iter()
.filter(|h| h.len() > 2 && !g.blobs().contains(h)) .filter(|h| {
let valid = crate::protocol::is_valid_hash(h);
if !valid {
warn!(hash = %h, "ignoring asset with an invalid blob hash");
}
valid && !g.blobs().contains(h)
})
.collect::<Vec<_>>()) .collect::<Vec<_>>())
}) })
.await?; .await?;
let mut failed = 0;
for h in missing { for h in missing {
debug!(hash = %h, "downloading blob"); debug!(hash = %h, "downloading blob");
self.ensure_blob(&h).await?; match self.ensure_blob(&h).await {
Ok(()) => {}
Err(e) if e.is_offline() || matches!(e, Error::Unauthorized) => return Err(e),
Err(e) => {
warn!(hash = %h, error = %e, "blob download failed; will retry next cycle");
failed += 1;
}
}
} }
Ok(()) Ok(failed)
} }
// ------------------------------------------------------------ background // ------------------------------------------------------------ background
+58
View File
@@ -38,6 +38,17 @@ pub struct PushResponse {
/// Ops that changed server state (the rest lost LWW or were already known). /// Ops that changed server state (the rest lost LWW or were already known).
pub applied: u32, pub applied: u32,
pub last_seq: i64, pub last_seq: i64,
/// Ops refused (invalid, or failing to apply). They are skipped, never stored; the rest of
/// the batch is processed normally so one bad op cannot wedge a device.
#[serde(default)]
pub rejected: Vec<Rejection>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Rejection {
/// Index of the op in the pushed batch.
pub index: u32,
pub reason: String,
} }
/// `GET /v1/graphs/{id}/ops?since=&limit=&exclude_actor=` /// `GET /v1/graphs/{id}/ops?since=&limit=&exclude_actor=`
@@ -103,6 +114,37 @@ 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')) h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
} }
/// Structural checks for an op received from a peer, before it touches the graph.
/// `max_future_ms` bounds how far ahead of `now_ms` its HLC may be (clock-skew guard).
pub fn validate_op(hlc: &str, op: &Op, now_ms: i64, max_future_ms: i64) -> Result<(), String> {
let (ms, _) = synapse_core::hlc::decode(hlc).ok_or("malformed hlc")?;
if hlc_actor(hlc).is_none() {
return Err("hlc has no actor".into());
}
if ms > now_ms.saturating_add(max_future_ms) {
return Err(format!(
"hlc is {} s in the future (limit {} s)",
(ms - now_ms) / 1000,
max_future_ms / 1000
));
}
if let Op::PutAsset { asset } = op
&& !is_valid_hash(&asset.hash)
{
return Err("asset hash must be 64 lowercase hex chars".into());
}
Ok(())
}
/// Errors that make one op permanently unappliable (as opposed to transient storage errors).
pub fn is_poison(e: &synapse_core::Error) -> bool {
use synapse_core::Error as E;
matches!(
e,
E::Invalid(_) | E::Json(_) | E::Conflict(_) | E::NotFound(_)
)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -116,5 +158,21 @@ mod tests {
assert!(!is_valid_graph_id("")); assert!(!is_valid_graph_id(""));
assert!(is_valid_hash(&"a".repeat(64))); assert!(is_valid_hash(&"a".repeat(64)));
assert!(!is_valid_hash("ab/../")); assert!(!is_valid_hash("ab/../"));
let op = Op::DeleteBlock {
id: synapse_core::new_id(),
};
assert!(validate_op("0000000001000-00000-a", &op, 1000, 0).is_ok());
assert!(validate_op("0000000999000-00000-a", &op, 1000, 60_000).is_err());
assert!(validate_op("junk", &op, 1000, 0).is_err());
let bad = Op::PutAsset {
asset: synapse_core::Asset {
hash: "../x".into(),
size: 1,
mime: None,
original_name: None,
created_at: 0,
},
};
assert!(validate_op("0000000001000-00000-a", &bad, 1000, 0).is_err());
} }
} }
+19 -8
View File
@@ -186,10 +186,23 @@ impl Remote {
/// has it and resuming a partial upload. The file is streamed, never loaded in memory. /// 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<()> { pub async fn upload_blob(&self, hash: &str, path: &Path) -> Result<()> {
let size = tokio::fs::metadata(path).await?.len(); let size = tokio::fs::metadata(path).await?.len();
for _ in 0..3 { // Each round resumes from what the server holds; a 202 (body ended short) or a 409
// (stale offset) just means "ask again". Success is only a HEAD that finds the blob.
let mut stalled = 0;
let mut last_offset = None;
loop {
let Some(offset) = self.blob_upload_offset(hash).await? else { let Some(offset) = self.blob_upload_offset(hash).await? else {
return Ok(()); return Ok(());
}; };
if last_offset.is_some_and(|l| offset <= l) {
stalled += 1;
if stalled >= 3 {
return Err(Error::Protocol(format!(
"blob {hash}: upload makes no progress at offset {offset}"
)));
}
}
last_offset = Some(offset);
let offset = if offset > size { 0 } else { offset }; let offset = if offset > size { 0 } else { offset };
let mut file = tokio::fs::File::open(path).await?; let mut file = tokio::fs::File::open(path).await?;
file.seek(std::io::SeekFrom::Start(offset)).await?; file.seek(std::io::SeekFrom::Start(offset)).await?;
@@ -205,15 +218,13 @@ impl Remote {
.body(body) .body(body)
.send() .send()
.await?; .await?;
if resp.status() == StatusCode::CONFLICT { match resp.status() {
continue; // offset out of date: HEAD again StatusCode::CONFLICT | StatusCode::ACCEPTED => continue,
_ => {
Self::check(resp).await?;
}
} }
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 /// Downloads blob `hash` into `dest`, streaming through `part` (resumed if it exists), and
+33 -1
View File
@@ -27,6 +27,13 @@ pub struct SyncState {
/// Ops pushed / pulled(applied) in the last successful cycle. /// Ops pushed / pulled(applied) in the last successful cycle.
pub last_pushed: u64, pub last_pushed: u64,
pub last_pulled: u64, pub last_pulled: u64,
/// Ops refused by the server or skipped locally because they can never apply (this
/// session). Details are in the log and, for pulled ops, in table `sync_quarantine`.
pub quarantined_ops: u64,
/// Local assets whose blob is missing: their `PutAsset` op was not pushed.
pub skipped_assets: u64,
/// Blobs that could not be downloaded in the last cycle (retried next cycle).
pub failed_blobs: u64,
} }
impl Default for SyncState { impl Default for SyncState {
@@ -38,6 +45,9 @@ impl Default for SyncState {
last_sync_ms: None, last_sync_ms: None,
last_pushed: 0, last_pushed: 0,
last_pulled: 0, last_pulled: 0,
quarantined_ops: 0,
skipped_assets: 0,
failed_blobs: 0,
} }
} }
} }
@@ -52,10 +62,32 @@ pub struct Cursors {
pub(crate) fn init(conn: &Connection) -> rusqlite::Result<()> { pub(crate) fn init(conn: &Connection) -> rusqlite::Result<()> {
conn.execute_batch( conn.execute_batch(
"CREATE TABLE IF NOT EXISTS sync_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);", "CREATE TABLE IF NOT EXISTS sync_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sync_quarantine (
id INTEGER PRIMARY KEY AUTOINCREMENT,
server_seq INTEGER NOT NULL,
hlc TEXT NOT NULL,
payload TEXT NOT NULL,
reason TEXT NOT NULL
);",
) )
} }
/// Records a pulled op that can never be applied, so it is skipped instead of blocking sync.
pub(crate) fn quarantine(
g: &Graph,
server_seq: i64,
hlc: &str,
payload: &str,
reason: &str,
) -> rusqlite::Result<()> {
g.conn().execute(
"INSERT INTO sync_quarantine(server_seq, hlc, payload, reason) VALUES (?1, ?2, ?3, ?4)",
params![server_seq, hlc, payload, reason],
)?;
Ok(())
}
fn get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> { fn get(conn: &Connection, key: &str) -> rusqlite::Result<Option<String>> {
conn.query_row("SELECT value FROM sync_state WHERE key=?1", [key], |r| { conn.query_row("SELECT value FROM sync_state WHERE key=?1", [key], |r| {
r.get(0) r.get(0)
+1
View File
@@ -12,6 +12,7 @@ See `.env.example`.
| `SYNAPSE_DATA_DIR` | yes | Server graphs live in `<dir>/<graph_id>/` (`synapse.db` + `blobs/`) | | `SYNAPSE_DATA_DIR` | yes | Server graphs live in `<dir>/<graph_id>/` (`synapse.db` + `blobs/`) |
| `SYNAPSE_AUTH_TOKEN` | yes | Bearer token(s), comma separated, ≥ 16 chars. Compared in constant time | | `SYNAPSE_AUTH_TOKEN` | yes | Bearer token(s), comma separated, ≥ 16 chars. Compared in constant time |
| `SYNAPSE_BIND` | no | Listen address, default `127.0.0.1:7878` | | `SYNAPSE_BIND` | no | Listen address, default `127.0.0.1:7878` |
| `SYNAPSE_MAX_CLOCK_SKEW_MINUTES` | no | Reject pushed ops whose HLC is further ahead of the server clock (default 10) |
| `SYNAPSE_UPDATE_TOKEN` | no | Enables `/admin/update`; separate from the sync tokens | | `SYNAPSE_UPDATE_TOKEN` | no | Enables `/admin/update`; separate from the sync tokens |
| `SYNAPSE_UPDATE_SCRIPT` | no | Default `/opt/synapse/scripts/update.sh` | | `SYNAPSE_UPDATE_SCRIPT` | no | Default `/opt/synapse/scripts/update.sh` |
| `SYNAPSE_LOG_FORMAT` | no | `text` (default) or `json` | | `SYNAPSE_LOG_FORMAT` | no | `text` (default) or `json` |
+25 -1
View File
@@ -79,7 +79,31 @@ sync on SSE hint, when ops are pending or when due; on failure exponential backo
with jitter); "offline" (connect/timeout errors) never loses edits, they stay pending. Call with jitter); "offline" (connect/timeout errors) never loses edits, they stay pending. Call
`trigger()` after local edits to sync without waiting for the poll. `trigger()` after local edits to sync without waiting for the poll.
The graph is shared as `Arc<Mutex<Graph>>`; the client locks it only for short DB steps. ### Graph handle (FFI integration)
`SyncClient::new(graph: Arc<Mutex<Graph>>, cfg)` — the expected handle type is
`Arc<Mutex<synapse_core::Graph>>` (std `Mutex`). `synapse-ffi` must hold its graph as that
same `Arc` (today it holds a bare `Mutex<Graph>`) and pass a clone to the client, so UI edits
and sync share one HLC clock and one connection. The client locks it only for short database
steps (never across network calls) and runs them on `spawn_blocking`; it needs a tokio
runtime (`start()` spawns onto the current one). After local edits call `trigger()`.
### Robustness
- **Invalid ops**: the server validates every pushed op (`protocol::validate_op`: well-formed
HLC, `PutAsset.hash` = 64 lowercase hex) and rejects ops whose HLC is more than
`SYNAPSE_MAX_CLOCK_SKEW_MINUTES` (default 10) ahead of the server clock. Rejected ops are
not stored; they are listed in `PushResponse.rejected` (`{index, reason}`) and the rest of the
batch is still applied. Ops that fail to apply with a non-transient error (`Invalid`, `Json`,
`Conflict`, `NotFound`) are rejected the same way; storage errors fail the request (retry).
- **Quarantine (client)**: a pulled op that can never apply is logged, stored in table
`sync_quarantine` (`server_seq, hlc, payload, reason`) and skipped, so the cursor advances.
`SyncState.quarantined_ops` counts these plus ops the server rejected (per session).
- **Missing local blob**: the asset's `PutAsset` op is not pushed (warning,
`SyncState.skipped_assets`) and later ops still flow.
- **Failed blob downloads** (e.g. 404): logged, counted in `SyncState.failed_blobs`, retried
next cycle; other blobs and the op sync are unaffected. Connectivity/auth errors still abort
the cycle.
- **Uploads** only complete when the server reports the blob stored (`HEAD` 200); `202`/`409`
responses make the client resume until done.
## Limits / not in v1 ## Limits / not in v1
- Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list; - Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list;