mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
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:
1 parent
fbcfcf678f
commit
4aa3c01a7f
25 files changed
+4299
-10
No files matched your search
@@ -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
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user