Merge branch 'refs/heads/claude/sync-server-edc467' into feat/integration

# Conflicts:
#	CLAUDE.md
#	Cargo.lock
This commit is contained in:
dasemu committed 2026-10-21 14:02:01 +02:00
commit 537d70bb55
25 files changed
+3469 -11

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
# Synapse server
Self-hosted sync server (`synapse-server`, axum). Protocol: `docs/sync.md`. Target: an LXC
container or VPS running Debian/Ubuntu (one of the last 3 releases), managed by systemd. No
Docker for deployment.
## Configuration (environment)
See `.env.example`.
| Variable | Required | Meaning |
|---|---|---|
| `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_BIND` | no | Listen address, default `127.0.0.1:7878` |
| `SYNAPSE_UPDATE_TOKEN` | no | Enables `/admin/update`; separate from the sync tokens |
| `SYNAPSE_UPDATE_SCRIPT` | no | Default `/opt/synapse/scripts/update.sh` |
| `SYNAPSE_LOG_FORMAT` | no | `text` (default) or `json` |
| `RUST_LOG` | no | Log filter, default `info` |
Graphs are created on first use by an authenticated client (`PUT /v1/graphs/{id}`). Each is a
normal `synapse_core::Graph`, so a backup is a copy of its directory (use `sqlite3 .backup`
or stop the service for a consistent copy of `synapse.db`).
## Install (Debian/Ubuntu, as root)
```bash
apt-get update && apt-get install -y git build-essential pkg-config curl caddy
useradd --system --create-home --home-dir /opt/synapse --shell /usr/sbin/nologin synapse
install -d -o synapse -g synapse /var/lib/synapse /etc/synapse
# Rust toolchain for the service user (the update script builds on the host)
su -s /bin/bash synapse -c 'curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal'
su -s /bin/bash synapse -c 'git clone <repo-url> /opt/synapse/src && /opt/synapse/src/scripts/update.sh' || true
```
`update.sh` installs the binary in `/opt/synapse/bin` (override with `SYNAPSE_BIN_DIR`); the
first run exits 0 once built. Point the unit's script path at the checkout:
```bash
install -d -o synapse -g synapse /opt/synapse/scripts
ln -sf /opt/synapse/src/scripts/update.sh /opt/synapse/scripts/update.sh
cp /opt/synapse/src/crates/synapse-server/deploy/synapse-server.service /etc/systemd/system/
```
Create `/etc/synapse/server.env` (mode `0600`, owner `synapse`) with the variables above, e.g.
`SYNAPSE_DATA_DIR=/var/lib/synapse`, `SYNAPSE_BIND=127.0.0.1:7878`, and tokens generated with
`openssl rand -hex 32`. Never commit this file. Then:
```bash
systemctl daemon-reload && systemctl enable --now synapse-server
curl -s http://127.0.0.1:7878/healthz
```
### TLS
The server speaks plain HTTP; put a reverse proxy in front for HTTPS. With Caddy
(`/etc/caddy/Caddyfile`):
```
notes.example.com {
reverse_proxy 127.0.0.1:7878 {
flush_interval -1 # keep the SSE stream (/events) unbuffered
}
}
```
Large blobs are streamed; do not set request-body limits or buffering in the proxy.
## Updating
`scripts/update.sh` is idempotent: `git fetch` + fast-forward, `cargo build --release --locked`,
atomic install of the binary; output goes to stdout (the endpoint logs it to
`$SYNAPSE_DATA_DIR/update.log`). It fails safely: on any error the running binary is untouched.
Exit codes: `0` updated, `10` already up to date, other = failed. SQLite schema migrations run
in `synapse-core` when a graph is opened, so a restart applies them.
By hand: `sudo -u synapse /opt/synapse/scripts/update.sh && systemctl restart synapse-server`.
### Authenticated update endpoint
Enabled only when `SYNAPSE_UPDATE_TOKEN` is set (otherwise 404).
```bash
curl -X POST -H "Authorization: Bearer $SYNAPSE_UPDATE_TOKEN" https://notes.example.com/admin/update # 202
curl -H "Authorization: Bearer $SYNAPSE_UPDATE_TOKEN" https://notes.example.com/admin/update # status
```
- Asynchronous, one update at a time (`409` while running), at least 60 s between runs (`429`),
and 20 admin requests/minute overall (`429`).
- Status: `{state: idle|running|up_to_date|succeeded|failed, started_at_ms, finished_at_ms,
exit_code, log_tail}`.
- After a successful update (script exit 0) the server exits about 2 s later and systemd
(`Restart=always`) starts the new binary, so no root privileges are needed.
## Operations
- Logs: `journalctl -u synapse-server -f`; set `SYNAPSE_LOG_FORMAT=json` for structured logs.
- Health: `GET /healthz` (public) → `{"status":"ok","version":...,"protocol":1}`.
+88
View File
@@ -0,0 +1,88 @@
# Sync protocol (v1)
Replication of a graph between devices through a self-hosted server. The unit of sync is the
**op log** of `synapse-core` (`Graph::ops_since` / `Graph::apply_remote`): each op carries a
hybrid logical clock (HLC) `{millis}-{counter}-{actor}`; replicas merge with last-writer-wins
per entity plus tombstones, so pushes and pulls are idempotent and order-insensitive.
Crates: `synapse-sync` (wire types in `protocol`, HTTP transport `Remote`, replicating
`SyncClient`) and `synapse-server` (axum). Clients send `X-Synapse-Protocol: 1`; `PUT
/v1/graphs/{id}` returns the server's `protocol` and the client refuses a mismatch.
## Auth
Every `/v1` request needs `Authorization: Bearer <token>`. `/healthz` is public. TLS is
terminated by a reverse proxy (see `docs/server.md`); the client uses rustls (no OpenSSL).
## Endpoints (`/v1/graphs/{id}`)
`{id}` is `[A-Za-z0-9_-]{1,64}` (a directory name on the server).
| Method | Path | Purpose |
|---|---|---|
| PUT | `/` | Create the graph if missing (idempotent). Returns `Info {protocol, server_id, last_seq}` |
| GET | `/` | Same, 404 if the graph does not exist |
| POST | `/ops` | Push `{ops:[{hlc, op}]}` (≤ 5000). Returns `{applied, last_seq}` |
| GET | `/ops?since=&limit=&exclude_actor=` | Pull ops with `seq > since` (limit ≤ 2000). Returns `{server_id, ops:[{seq,hlc,op}], next_cursor, last_seq, has_more}` |
| GET | `/events` | Server-Sent Events: `event: seq`, `data: {"last_seq":N}` on connect and after every change |
| HEAD | `/blobs/{hash}` | 200 if stored. Else 404 with `Upload-Offset` = bytes of a partial upload |
| GET | `/blobs/{hash}` | Streams the blob; supports `Range: bytes=N-[M]` (206) |
| PUT | `/blobs/{hash}` | Streamed upload, see below |
`{hash}` is the blake3 hex digest (64 lowercase hex chars) of the content.
### Read API (thin / online-mode clients, no replica needed)
`GET /pages?journals=&limit=&offset=`, `/pages/by-title?title=` (title or alias,
case-insensitive), `/pages/{uuid}` (page + aliases + block tree), `/pages/{uuid}/backlinks`,
`/journals/{YYYY-MM-DD}` (404 if the day has no journal; reads never create pages),
`/journals?from=&to=`. In Rust: `synapse_sync::Remote`.
## Push / pull and cursors
The client persists, in table `sync_state` of the local graph database: `pushed_seq` (highest
local seq already handled), `pull_cursor` (highest server seq already pulled), plus
`remote_key` (`url|graph_id`) and `server_id`. If either differs from the current remote, both
cursors reset to 0 (re-pushing is harmless: LWW ignores what the server already has).
A cycle (`SyncClient::sync_once`): 1) `PUT` graph; 2) push batches of local ops after
`pushed_seq`, uploading the blobs of `PutAsset` ops *first*; 3) pull batches after
`pull_cursor` and `apply_remote` each; 4) download blobs of assets that lack one (policy
`Eager`, or `OnDemand` via `ensure_blob`). Cursors are saved after each batch; a crash re-does
at most one batch.
### Avoiding echo
`apply_remote` re-logs applied ops locally (so they propagate to further replicas), which would
make them look like local edits. They are told apart by the HLC **actor**: local ops carry the
graph's own actor, applied ops keep the originating actor. The client pushes only ops whose
actor is its own, and the pull sends `exclude_actor=<own actor>` (and the client also skips them
when applying). The server's op log contains every actor's ops, so any other device receives
them through its pull.
## Blobs
Never fully in memory on either side. Upload is resumable:
1. `HEAD /blobs/{hash}` → 200 (done) or 404 + `Upload-Offset: N`.
2. `PUT` with `Upload-Length: <total>` (required) and `Upload-Offset: N` (omit/0 to start).
The body (rest of the file) is appended to `<graph>/uploads/<hash>.part`.
- offset ≠ stored length → `409` + the real `Upload-Offset`;
- body ended before `Upload-Length` → `202` + `Upload-Offset` (partial kept, resume later);
- complete → the content is hashed; match → moved into the blob store (`201`), mismatch →
`422` and the partial file is dropped.
Download resumes from a partial `blobs/tmp/sync-<hash>.part` with `Range`, verifies the hash
and renames atomically. A `PutAsset` op is only pushed after its blob is on the server.
## Realtime
After each change the server publishes the new `last_seq`; connected clients (SSE) trigger a
pull immediately. The stream is only a hint: the client also polls local pending ops
(`poll_interval`, default 5 s) and does a full cycle every `full_sync_interval` (default 120 s).
## Client state and the background loop
`SyncClient::state()` / `subscribe()` give `SyncState {status: idle|syncing|offline|error,
message, pending_ops, last_sync_ms, last_pushed, last_pulled}`. `start()` spawns the loop:
sync on SSE hint, when ops are pending or when due; on failure exponential backoff (1 s → 5 min,
with jitter); "offline" (connect/timeout errors) never loses edits, they stay pending. Call
`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.
## Limits / not in v1
- Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list;
only the token source (env list) is implemented.
- No blob quota, no garbage collection of unreferenced blobs, no op-log compaction.
- A client with a wrong clock can win LWW; HLCs are not validated against the server time.