diff --git a/.env.example b/.env.example index 9d7a636..ee50c6f 100644 --- a/.env.example +++ b/.env.example @@ -1,10 +1,17 @@ # Synapse server configuration (names only; never commit real values). -# Address the sync server listens on, e.g. 127.0.0.1:7878 +# Address the sync server listens on, e.g. 127.0.0.1:7878 (default if empty) SYNAPSE_BIND= -# Directory holding server-side graphs and blobs +# Directory holding server-side graphs and blobs (required) SYNAPSE_DATA_DIR= -# Bearer token clients must present (generate a long random string) +# Bearer token(s) clients must present, comma separated, each >= 16 chars +# (generate with `openssl rand -hex 32`; required) SYNAPSE_AUTH_TOKEN= +# Token that authorises POST /admin/update (self-update). Endpoint disabled if empty. +SYNAPSE_UPDATE_TOKEN= +# Update script run by the endpoint (default /opt/synapse/scripts/update.sh) +SYNAPSE_UPDATE_SCRIPT= +# Log format: text (default) or json +SYNAPSE_LOG_FORMAT= # Log filter, e.g. info,synapse_server=debug RUST_LOG= diff --git a/CLAUDE.md b/CLAUDE.md index d7d427a..4448420 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client - Lint: `cargo clippy --workspace --all-targets -- -D warnings`, `cd app && dart analyze` (`flutter analyze` crashes on non-ASCII paths like `Darío/`) - Test: `cargo test --workspace`, `cd app && flutter test` -- Run server: `cargo run -p synapse-server` +- Run server: `SYNAPSE_DATA_DIR=/tmp/syn SYNAPSE_AUTH_TOKEN=<16+ chars> cargo run -p synapse-server` - Run app: `cd app && flutter run -d linux` (or `-d windows`, an Android device); Flutter SDK in `~/development/flutter/bin`. Graph dir override: `SYNAPSE_GRAPH=/path`. See `docs/app.md`. - Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` (frb 2.13.0; commit @@ -26,7 +26,7 @@ roadmap in `docs/plan.md`. - `synapse-ai`: provider-agnostic LLM/embeddings clients (user-supplied API keys). - `synapse-history`: automatic git-like snapshots of the graph. - `synapse-caldav`: CalDAV calendar + VTODO tasks. -- `synapse-sync` / `synapse-server`: client-server protocol and axum server. +- `synapse-sync` / `synapse-server`: client-server protocol and axum server (`docs/sync.md`). - `synapse-ffi`: the only API surface exposed to Flutter. ## Conventions diff --git a/Cargo.lock b/Cargo.lock index d79aaf3..a68d9a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -129,6 +129,58 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "backtrace" version = "0.3.76" @@ -285,6 +337,23 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -883,8 +952,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -894,8 +965,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1721,6 +1795,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -2106,12 +2181,33 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "lz4_flex" version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "md-5" version = "0.10.6" @@ -2146,6 +2242,12 @@ dependencies = [ "libc", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2210,6 +2312,15 @@ version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9737e026353e5cd0736f98eddae28665118eb6f6600902a7f50db585621fecb6" +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2418,6 +2529,62 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -2441,7 +2608,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -2451,7 +2629,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -2463,6 +2641,12 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_distr" version = "0.4.3" @@ -2470,7 +2654,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand", + "rand 0.8.8", +] + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", ] [[package]] @@ -2531,6 +2724,47 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.4.2", + "web-sys", + "webpki-roots", +] + [[package]] name = "reqwest" version = "0.13.5" @@ -2567,7 +2801,7 @@ dependencies = [ "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams", + "wasm-streams 0.5.0", "web-sys", ] @@ -2689,6 +2923,7 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ + "web-time", "zeroize", ] @@ -2736,6 +2971,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2832,6 +3073,29 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -2844,12 +3108,31 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5b0ebf6537e3e8db8bb7d21ecb6d7399738c953c757945c6b95e46c4e95df7b" +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -2962,7 +3245,7 @@ dependencies = [ "async-trait", "chrono", "futures-util", - "reqwest", + "reqwest 0.13.5", "rustls", "serde", "serde_json", @@ -2983,7 +3266,7 @@ dependencies = [ "chrono", "chrono-tz", "quick-xml", - "reqwest", + "reqwest 0.13.5", "rrule", "rusqlite", "rustls", @@ -3066,6 +3349,46 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-server" +version = "0.1.0" +dependencies = [ + "axum", + "blake3", + "chrono", + "futures-util", + "reqwest 0.12.28", + "serde", + "serde_json", + "synapse-core", + "synapse-sync", + "tempfile", + "tokio", + "tokio-util", + "tower-http", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "synapse-sync" +version = "0.1.0" +dependencies = [ + "blake3", + "chrono", + "futures-util", + "reqwest 0.12.28", + "rusqlite", + "serde", + "serde_json", + "synapse-core", + "tempfile", + "thiserror", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -3264,6 +3587,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "threadpool" version = "1.8.1" @@ -3329,6 +3661,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -3382,6 +3715,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3399,6 +3733,7 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", "url", ] @@ -3420,10 +3755,23 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -3431,6 +3779,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -3543,6 +3934,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -3636,6 +4033,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wasm-streams" version = "0.5.0" @@ -3659,6 +4069,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" diff --git a/crates/synapse-server/Cargo.toml b/crates/synapse-server/Cargo.toml new file mode 100644 index 0000000..a3336fb --- /dev/null +++ b/crates/synapse-server/Cargo.toml @@ -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"] } diff --git a/crates/synapse-server/deploy/synapse-server.service b/crates/synapse-server/deploy/synapse-server.service new file mode 100644 index 0000000..9edfe0f --- /dev/null +++ b/crates/synapse-server/deploy/synapse-server.service @@ -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 diff --git a/crates/synapse-server/src/admin.rs b/crates/synapse-server/src/admin.rs new file mode 100644 index 0000000..ded03ca --- /dev/null +++ b/crates/synapse-server/src/admin.rs @@ -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, + pub finished_at_ms: Option, + pub exit_code: Option, + /// Last bytes of the script output. + pub log_tail: String, +} + +pub struct Updater { + status: Mutex, + last_trigger: Mutex>, + hits: Mutex>, +} + +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, + req: Request, + next: Next, +) -> Result { + 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) -> Json { + Json( + state + .updater + .status + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(), + ) +} + +pub async fn trigger( + State(state): State, +) -> Result<(StatusCode, Json), 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(); + } +} diff --git a/crates/synapse-server/src/api.rs b/crates/synapse-server/src/api.rs new file mode 100644 index 0000000..d8b5fe0 --- /dev/null +++ b/crates/synapse-server/src/api.rs @@ -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> { + 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, + Extension(who): Extension, + Path(id): Path, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path(id): Path, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path(id): Path, + Json(req): Json, +) -> ApiResult> { + 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, + exclude_actor: Option, +} + +pub async fn pull_ops( + State(s): State, + Extension(who): Extension, + Path(id): Path, + Query(q): Query, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path(id): Path, +) -> ApiResult>>> { + 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, + #[serde(default)] + offset: u32, +} + +pub async fn list_pages( + State(s): State, + Extension(who): Extension, + Path(id): Path, + Query(q): Query, +) -> ApiResult>> { + 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 { + 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, + Extension(who): Extension, + Path(id): Path, + Query(q): Query, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path((id, page)): Path<(String, uuid_str::Id)>, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path((id, page)): Path<(String, uuid_str::Id)>, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path((id, date)): Path<(String, String)>, +) -> ApiResult> { + 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, + Extension(who): Extension, + Path(id): Path, + Query(q): Query, +) -> ApiResult>> { + 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: D) -> Result { + let s = String::deserialize(d)?; + s.parse().map(Id).map_err(serde::de::Error::custom) + } + } +} diff --git a/crates/synapse-server/src/auth.rs b/crates/synapse-server/src/auth.rs new file mode 100644 index 0000000..87529a4 --- /dev/null +++ b/crates/synapse-server/src/auth.rs @@ -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>, +} + +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 { + 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, + mut req: Request, + next: Next, +) -> Result { + 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) +} diff --git a/crates/synapse-server/src/blobs.rs b/crates/synapse-server/src/blobs.rs new file mode 100644 index 0000000..01fbd40 --- /dev/null +++ b/crates/synapse-server/src/blobs.rs @@ -0,0 +1,243 @@ +//! Blob endpoints: HEAD (existence / partial-upload offset), GET (Range, streamed) and PUT +//! (streamed to `/uploads/.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 { + 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, + Extension(who): Extension, + Path((id, hash)): Path<(String, String)>, +) -> ApiResult { + 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::().ok()?.min(size.checked_sub(1)?) + }; + (start <= end).then_some((start, end)) +} + +pub async fn get_blob( + State(s): State, + Extension(who): Extension, + Path((id, hash)): Path<(String, String)>, + headers: HeaderMap, +) -> ApiResult { + 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, + 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, + Extension(who): Extension, + Path((id, hash)): Path<(String, String)>, + headers: HeaderMap, + body: Body, +) -> ApiResult { + 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 { + 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()) +} diff --git a/crates/synapse-server/src/config.rs b/crates/synapse-server/src/config.rs new file mode 100644 index 0000000..b76e95f --- /dev/null +++ b/crates/synapse-server/src/config.rs @@ -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, + /// Token for `/admin/update`; the endpoint is disabled when unset. + pub update_token: Option, + pub update_script: PathBuf, +} + +pub const MIN_TOKEN_LEN: usize = 16; + +impl Config { + pub fn from_env() -> Result { + 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 = 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(()) + } +} diff --git a/crates/synapse-server/src/error.rs b/crates/synapse-server/src/error.rs new file mode 100644 index 0000000..191f401 --- /dev/null +++ b/crates/synapse-server/src/error.rs @@ -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) -> Self { + Self { + status, + message: message.into(), + } + } + pub fn bad_request(m: impl Into) -> Self { + Self::new(StatusCode::BAD_REQUEST, m) + } + pub fn not_found(m: impl Into) -> 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 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 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 = Result; diff --git a/crates/synapse-server/src/graphs.rs b/crates/synapse-server/src/graphs.rs new file mode 100644 index 0000000..b13485a --- /dev/null +++ b/crates/synapse-server/src/graphs.rs @@ -0,0 +1,105 @@ +//! Server-side graphs: one `synapse_core::Graph` per `SYNAPSE_DATA_DIR//`. + +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, + /// Latest op seq; subscribers (SSE) are woken when it changes. + pub seq: watch::Sender, + /// Hashes with an upload in flight. + pub uploads: Mutex>, +} + +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( + self: &Arc, + f: impl FnOnce(&Graph) -> synapse_core::Result + Send + 'static, + ) -> ApiResult { + 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>>, +} + +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>> { + self.open(id, false).await + } + + /// Returns the graph, creating it on first use. + pub async fn get_or_create(&self, id: &str) -> ApiResult> { + Ok(self.open(id, true).await?.expect("created")) + } + + async fn open(&self, id: &str, create: bool) -> ApiResult>> { + 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 { + 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)) + } +} diff --git a/crates/synapse-server/src/lib.rs b/crates/synapse-server/src/lib.rs new file mode 100644 index 0000000..4ccca9f --- /dev/null +++ b/crates/synapse-server/src/lib.rs @@ -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, + pub(crate) auth: Arc, + pub(crate) update_token: Option, + pub(crate) update_script: Arc, + pub(crate) data_dir: Arc, + pub(crate) updater: Arc, + pub(crate) shutdown: Arc, +} + +impl AppState { + pub fn new(cfg: &Config) -> std::io::Result { + 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 { + 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>, + shutdown: Arc, +} + +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 { + 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; + } +} diff --git a/crates/synapse-server/src/main.rs b/crates/synapse-server/src/main.rs new file mode 100644 index 0000000..52cfd02 --- /dev/null +++ b/crates/synapse-server/src/main.rs @@ -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); + } +} diff --git a/crates/synapse-server/tests/e2e.rs b/crates/synapse-server/tests/e2e.rs new file mode 100644 index 0000000..8d50ff5 --- /dev/null +++ b/crates/synapse-server/tests/e2e.rs @@ -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>, + 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 { + 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 = (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 = (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; + } +} diff --git a/crates/synapse-sync/Cargo.toml b/crates/synapse-sync/Cargo.toml new file mode 100644 index 0000000..d4a987c --- /dev/null +++ b/crates/synapse-sync/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "synapse-sync" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "Synapse sync protocol types and client (op-log push/pull, blobs, realtime)" + +[dependencies] +synapse-core.workspace = true +rusqlite.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +chrono.workspace = true +# Async runtime for the client and its background loop. +tokio = { version = "1", features = ["rt", "sync", "time", "fs", "io-util", "macros"] } +# HTTP client. 0.12 + rustls-tls-webpki-roots = rustls with the `ring` provider and bundled +# roots: no OpenSSL/aws-lc/platform verifier, so it builds for Android and Windows. +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-webpki-roots", "json", "stream"] } +# Stream large blobs from/to disk (ReaderStream) without buffering them. +tokio-util = { version = "0.7", features = ["io"] } +futures-util = "0.3" +# Verify downloaded blobs (same hash as the core blob store). +blake3 = "1" +tracing = "0.1" + +[dev-dependencies] +tempfile = "3" diff --git a/crates/synapse-sync/src/client.rs b/crates/synapse-sync/src/client.rs new file mode 100644 index 0000000..ac1c3db --- /dev/null +++ b/crates/synapse-sync/src/client.rs @@ -0,0 +1,472 @@ +use crate::error::{Error, Result}; +use crate::protocol::{SyncEvent, WireOp, hlc_actor}; +use crate::remote::{Remote, RemoteConfig}; +use crate::state::{self, Cursors, SyncState, SyncStatus}; +use futures_util::StreamExt; +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use synapse_core::{Graph, Op}; +use tokio::sync::{Notify, watch}; +use tokio::task::JoinHandle; +use tracing::{debug, info, warn}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BlobPolicy { + /// Download blobs of synced assets right after pulling their ops. + Eager, + /// Only download when asked via [`SyncClient::ensure_blob`] (e.g. metered connections). + OnDemand, +} + +#[derive(Debug, Clone)] +pub struct SyncConfig { + pub remote: RemoteConfig, + /// Ops per push/pull request. + pub batch_size: u32, + pub blob_policy: BlobPolicy, + /// Background loop: how often to check for unpushed local ops. + pub poll_interval: Duration, + /// Background loop: full sync at least this often even without notifications. + pub full_sync_interval: Duration, + pub max_backoff: Duration, +} + +impl SyncConfig { + pub fn new(remote: RemoteConfig) -> Self { + Self { + remote, + batch_size: 500, + blob_policy: BlobPolicy::Eager, + poll_interval: Duration::from_secs(5), + full_sync_interval: Duration::from_secs(120), + max_backoff: Duration::from_secs(300), + } + } +} + +struct Inner { + graph: Arc>, + cfg: SyncConfig, + remote: Remote, + state: watch::Sender, + /// Serialises sync cycles (manual `sync_once` vs the background loop). + cycle: tokio::sync::Mutex<()>, + /// Remote changed (SSE) or caller asked for a sync. + dirty: AtomicBool, + wake: Notify, + /// Some synced assets may lack their blob locally. + blobs_dirty: AtomicBool, +} + +/// Replicates a local [`Graph`] with a Synapse server. Cheap to clone. +/// +/// The graph is shared as `Arc>` (the core `Graph` is not `Sync`); the client only +/// holds the lock for short database steps, never across network calls. +#[derive(Clone)] +pub struct SyncClient { + inner: Arc, +} + +impl SyncClient { + pub fn new(graph: Arc>, cfg: SyncConfig) -> Result { + let remote = Remote::new(cfg.remote.clone())?; + let (state, _) = watch::channel(SyncState::default()); + let inner = Arc::new(Inner { + graph, + cfg, + remote, + state, + cycle: tokio::sync::Mutex::new(()), + dirty: AtomicBool::new(true), + wake: Notify::new(), + blobs_dirty: AtomicBool::new(true), + }); + Ok(Self { inner }) + } + + pub fn remote(&self) -> &Remote { + &self.inner.remote + } + + /// Current state for the UI. + pub fn state(&self) -> SyncState { + self.inner.state.borrow().clone() + } + + /// Receiver that fires on every state change. + pub fn subscribe(&self) -> watch::Receiver { + self.inner.state.subscribe() + } + + /// Recomputes the pending-ops count (call after local edits to update the UI badge). + pub async fn refresh_pending(&self) -> Result { + let n = self.with_graph(|g| Ok(state::pending_now(g)?)).await?; + self.inner.state.send_modify(|s| s.pending_ops = n); + Ok(n) + } + + /// Asks the background loop to sync soon (call after local edits). + pub fn trigger(&self) { + self.inner.dirty.store(true, Ordering::SeqCst); + self.inner.wake.notify_one(); + } + + async fn with_graph( + &self, + f: impl FnOnce(&Graph) -> Result + Send + 'static, + ) -> Result { + let graph = self.inner.graph.clone(); + tokio::task::spawn_blocking(move || { + let g = graph.lock().unwrap_or_else(PoisonError::into_inner); + f(&g) + }) + .await + .map_err(|e| Error::Task(e.to_string()))? + } + + /// One full cycle: push local ops (+ their blobs), pull remote ops, fetch blobs. + pub async fn sync_once(&self) -> Result<()> { + let _cycle = self.inner.cycle.lock().await; + self.inner.dirty.store(false, Ordering::SeqCst); + self.inner.state.send_modify(|s| { + s.status = SyncStatus::Syncing; + s.message = None; + }); + let res = self.run_cycle().await; + let pending = self + .with_graph(|g| Ok(state::pending_now(g)?)) + .await + .unwrap_or(0); + match &res { + Ok((pushed, pulled)) => { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0); + self.inner.state.send_modify(|s| { + s.status = SyncStatus::Idle; + s.message = None; + s.pending_ops = pending; + s.last_sync_ms = Some(now); + s.last_pushed = *pushed; + s.last_pulled = *pulled; + }); + } + Err(e) => { + let status = if e.is_offline() { + SyncStatus::Offline + } else { + SyncStatus::Error + }; + warn!(error = %e, ?status, "sync cycle failed"); + self.inner.state.send_modify(|s| { + s.status = status; + s.message = Some(e.to_string()); + s.pending_ops = pending; + }); + } + } + res.map(|_| ()) + } + + async fn run_cycle(&self) -> Result<(u64, u64)> { + let remote = &self.inner.remote; + let info = remote.ensure_graph().await?; + let key = remote.key(); + let server_id = info.server_id.clone(); + let mut cur = self + .with_graph(move |g| Ok(state::load(g, &key, &server_id)?)) + .await?; + + let pushed = self.push_all(&mut cur).await?; + let (pulled, got_assets) = self.pull_all(&mut cur, &info.server_id).await?; + if got_assets { + self.inner.blobs_dirty.store(true, Ordering::SeqCst); + } + if self.inner.cfg.blob_policy == BlobPolicy::Eager + && self.inner.blobs_dirty.load(Ordering::SeqCst) + { + self.fetch_missing_blobs().await?; + self.inner.blobs_dirty.store(false, Ordering::SeqCst); + } + Ok((pushed, pulled)) + } + + /// Pushes ops originated by this replica. Ops that were *applied from the server* are + /// re-logged locally by the core, but carry another actor in their HLC, so they are skipped + /// here: that is what prevents echoing them back. + async fn push_all(&self, cur: &mut Cursors) -> Result { + let limit = self.inner.cfg.batch_size; + let mut total = 0; + loop { + let after = cur.pushed_seq; + let (batch, scanned_to, scanned) = self + .with_graph(move |g| { + let recs = g.ops_since(after, limit)?; + let n = recs.len(); + let last = recs.last().map_or(after, |r| r.seq); + let me = g.actor().to_string(); + let ops: Vec = recs + .into_iter() + .filter(|r| hlc_actor(&r.hlc) == Some(me.as_str())) + .map(|r| WireOp { + hlc: r.hlc, + op: r.op, + }) + .collect(); + Ok((ops, last, n)) + }) + .await?; + if scanned == 0 { + return Ok(total); + } + if !batch.is_empty() { + // Blobs first, so the server never knows an asset it cannot serve. + let hashes: BTreeSet = batch + .iter() + .filter_map(|w| match &w.op { + Op::PutAsset { asset } => Some(asset.hash.clone()), + _ => None, + }) + .collect(); + for h in hashes { + self.upload_blob(&h).await?; + } + total += batch.len() as u64; + self.inner.remote.push(batch).await?; + } + self.with_graph(move |g| Ok(state::save_pushed(g, scanned_to)?)) + .await?; + cur.pushed_seq = scanned_to; + if (scanned as u32) < limit { + return Ok(total); + } + } + } + + async fn pull_all(&self, cur: &mut Cursors, server_id: &str) -> Result<(u64, bool)> { + let limit = self.inner.cfg.batch_size; + let me = self.with_graph(|g| Ok(g.actor().to_string())).await?; + let mut applied_total = 0; + let mut got_assets = false; + loop { + let resp = self + .inner + .remote + .pull(cur.pull_cursor, limit, Some(&me)) + .await?; + if resp.server_id != server_id { + return Err(Error::Protocol("server graph changed mid-sync".into())); + } + let next = resp.next_cursor.max(cur.pull_cursor); + let me2 = me.clone(); + let (applied, assets) = self + .with_graph(move |g| { + let (mut applied, mut assets) = (0u64, false); + for rec in resp.ops { + // Defence in depth: never re-apply our own ops. + if hlc_actor(&rec.hlc) == Some(me2.as_str()) { + continue; + } + if g.apply_remote(&rec.hlc, &rec.op)? { + applied += 1; + assets |= matches!(rec.op, Op::PutAsset { .. }); + } + } + state::save_pulled(g, next)?; + Ok((applied, assets)) + }) + .await?; + cur.pull_cursor = next; + applied_total += applied; + got_assets |= assets; + if !resp.has_more { + return Ok((applied_total, got_assets)); + } + } + } + + // ----------------------------------------------------------------- blobs + + async fn upload_blob(&self, hash: &str) -> Result<()> { + let h = hash.to_string(); + let path = self.with_graph(move |g| Ok(g.blobs().path_of(&h))).await?; + if !path.exists() { + return Err(Error::Protocol(format!( + "asset {hash} is registered but its blob is missing locally" + ))); + } + self.inner.remote.upload_blob(hash, &path).await + } + + /// Downloads blob `hash` if it is not stored locally yet (resumes partial downloads). + pub async fn ensure_blob(&self, hash: &str) -> Result<()> { + if !synapse_core_hash_ok(hash) { + return Err(Error::Protocol(format!("invalid blob hash {hash:?}"))); + } + let h = hash.to_string(); + let (dest, part, have) = self + .with_graph(move |g| { + let dest = g.blobs().path_of(&h); + let part = g + .dir() + .join("blobs") + .join("tmp") + .join(format!("sync-{h}.part")); + Ok((dest.clone(), part, dest.exists())) + }) + .await?; + if have { + return Ok(()); + } + let mut last = None; + for _ in 0..2 { + match self.inner.remote.download_blob(hash, &part, &dest).await { + Ok(()) => return Ok(()), + Err(e @ Error::Protocol(_)) => last = Some(e), // retry from scratch + Err(e) => return Err(e), + } + } + Err(last.unwrap()) + } + + async fn fetch_missing_blobs(&self) -> Result<()> { + let missing = self + .with_graph(|g| { + let mut st = g.conn().prepare("SELECT hash FROM assets")?; + let hashes = st + .query_map([], |r| r.get::<_, String>(0))? + .collect::, _>>()?; + Ok(hashes + .into_iter() + .filter(|h| h.len() > 2 && !g.blobs().contains(h)) + .collect::>()) + }) + .await?; + for h in missing { + debug!(hash = %h, "downloading blob"); + self.ensure_blob(&h).await?; + } + Ok(()) + } + + // ------------------------------------------------------------ background + + /// Starts the background loop on the current tokio runtime: syncs on server notifications + /// (SSE), when local ops are pending, and periodically; backs off exponentially on errors + /// and keeps working offline. Stop it with [`SyncHandle::stop`] or by dropping the handle. + pub fn start(&self) -> SyncHandle { + let me = self.clone(); + let loop_task = tokio::spawn(async move { me.run_loop().await }); + let me = self.clone(); + let events_task = tokio::spawn(async move { me.run_events().await }); + SyncHandle { + client: self.clone(), + tasks: vec![loop_task, events_task], + } + } + + async fn run_loop(self) { + let cfg = &self.inner.cfg; + let mut backoff = Duration::from_secs(1); + let mut last_full: Option = None; + loop { + let pending = self.refresh_pending().await.unwrap_or(0); + let due = last_full.is_none_or(|t| t.elapsed() >= cfg.full_sync_interval); + if self.inner.dirty.load(Ordering::SeqCst) || pending > 0 || due { + match self.sync_once().await { + Ok(()) => { + backoff = Duration::from_secs(1); + last_full = Some(tokio::time::Instant::now()); + } + Err(e) => { + let wait = jitter(backoff); + debug!(error = %e, ?wait, "sync failed; backing off"); + // Keep `dirty` so we retry as soon as the backoff elapses. + self.inner.dirty.store(true, Ordering::SeqCst); + backoff = (backoff * 2).min(cfg.max_backoff); + tokio::time::sleep(wait).await; + continue; + } + } + } + tokio::select! { + _ = self.inner.wake.notified() => {} + _ = tokio::time::sleep(cfg.poll_interval) => {} + } + } + } + + async fn run_events(self) { + let mut backoff = Duration::from_secs(1); + loop { + match self.inner.remote.open_events().await { + Ok(resp) => { + backoff = Duration::from_secs(1); + info!("realtime stream connected"); + // We may have missed events while disconnected. + self.trigger(); + let mut buf = String::new(); + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + let Ok(chunk) = chunk else { break }; + buf.push_str(&String::from_utf8_lossy(&chunk)); + while let Some(i) = buf.find("\n\n") { + let event: String = buf.drain(..i + 2).collect(); + let notified = event + .lines() + .filter_map(|l| l.strip_prefix("data:")) + .any(|d| serde_json::from_str::(d.trim()).is_ok()); + if notified { + self.trigger(); + } + } + } + } + Err(e) => debug!(error = %e, "realtime stream unavailable"), + } + tokio::time::sleep(jitter(backoff)).await; + backoff = (backoff * 2).min(Duration::from_secs(60)); + } + } +} + +/// Handle of the background sync loop. Dropping it stops the loop. +pub struct SyncHandle { + client: SyncClient, + tasks: Vec>, +} + +impl SyncHandle { + pub fn client(&self) -> &SyncClient { + &self.client + } + + pub fn trigger(&self) { + self.client.trigger(); + } + + pub fn stop(self) {} +} + +impl Drop for SyncHandle { + fn drop(&mut self) { + for t in &self.tasks { + t.abort(); + } + } +} + +fn jitter(d: Duration) -> Duration { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + d + d.mul_f64((nanos % 1000) as f64 / 4000.0) +} + +fn synapse_core_hash_ok(h: &str) -> bool { + crate::protocol::is_valid_hash(h) +} diff --git a/crates/synapse-sync/src/error.rs b/crates/synapse-sync/src/error.rs new file mode 100644 index 0000000..e29db4d --- /dev/null +++ b/crates/synapse-sync/src/error.rs @@ -0,0 +1,40 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("graph: {0}")] + Core(#[from] synapse_core::Error), + #[error("sqlite: {0}")] + Sqlite(#[from] rusqlite::Error), + #[error("http: {0}")] + Http(#[from] reqwest::Error), + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("unauthorized: check the auth token")] + Unauthorized, + #[error("server returned {status}: {message}")] + Status { status: u16, message: String }, + #[error("protocol: {0}")] + Protocol(String), + #[error("background task failed: {0}")] + Task(String), +} + +impl Error { + /// True when the server could not be reached (as opposed to rejecting a request). + pub fn is_offline(&self) -> bool { + match self { + Error::Http(e) => e.is_connect() || e.is_timeout() || e.is_request() && !e.is_status(), + Error::Io(e) => matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused + | std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::TimedOut + | std::io::ErrorKind::UnexpectedEof + ), + _ => false, + } + } +} + +pub type Result = std::result::Result; diff --git a/crates/synapse-sync/src/lib.rs b/crates/synapse-sync/src/lib.rs new file mode 100644 index 0000000..65393ae --- /dev/null +++ b/crates/synapse-sync/src/lib.rs @@ -0,0 +1,13 @@ +//! Synapse sync: wire protocol (`protocol`), HTTP transport and thin-client read API +//! (`Remote`), and the replicating `SyncClient` with a background loop. See `docs/sync.md`. + +mod client; +mod error; +pub mod protocol; +mod remote; +mod state; + +pub use client::{BlobPolicy, SyncClient, SyncConfig, SyncHandle}; +pub use error::{Error, Result}; +pub use remote::{Remote, RemoteConfig}; +pub use state::{Cursors, SyncState, SyncStatus}; diff --git a/crates/synapse-sync/src/protocol.rs b/crates/synapse-sync/src/protocol.rs new file mode 100644 index 0000000..f78162f --- /dev/null +++ b/crates/synapse-sync/src/protocol.rs @@ -0,0 +1,120 @@ +//! Wire types shared by `synapse-sync` (client) and `synapse-server`. See `docs/sync.md`. + +use serde::{Deserialize, Serialize}; +use synapse_core::{Backlink, Block, Op, OpRecord, Page}; + +/// Bumped on incompatible changes. Sent as `X-Synapse-Protocol` by clients. +pub const PROTOCOL_VERSION: u32 = 1; +pub const HEADER_PROTOCOL: &str = "x-synapse-protocol"; +/// Bytes already stored of a partially uploaded blob (response header). +pub const HEADER_UPLOAD_OFFSET: &str = "upload-offset"; +/// Total size of the blob being uploaded (request header). +pub const HEADER_UPLOAD_LENGTH: &str = "upload-length"; + +/// `GET/PUT /v1/graphs/{id}` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Info { + pub protocol: u32, + /// Stable identity of the server-side graph (its actor id). A change means the graph was + /// recreated and clients must restart their cursors. + pub server_id: String, + pub last_seq: i64, +} + +/// An op to push: the local HLC plus the payload. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WireOp { + pub hlc: String, + pub op: Op, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PushRequest { + pub ops: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PushResponse { + /// Ops that changed server state (the rest lost LWW or were already known). + pub applied: u32, + pub last_seq: i64, +} + +/// `GET /v1/graphs/{id}/ops?since=&limit=&exclude_actor=` +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PullResponse { + pub server_id: String, + /// Ops after `since`, minus those from `exclude_actor`. + pub ops: Vec, + /// Cursor to use for the next pull: the seq of the last op *scanned* (even if filtered). + pub next_cursor: i64, + pub last_seq: i64, + pub has_more: bool, +} + +/// Payload of each `data:` line of the SSE stream `GET /v1/graphs/{id}/events`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SyncEvent { + pub last_seq: i64, +} + +// ---- read API (thin clients) ---- + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TreeEntry { + pub depth: usize, + pub block: Block, +} + +/// A page with its aliases and block tree. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PageView { + pub page: Page, + pub aliases: Vec, + pub tree: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BacklinksView { + pub backlinks: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ErrorBody { + pub error: String, +} + +/// Actor part of an HLC (`{millis:013}-{counter:05}-{actor}`). +pub fn hlc_actor(hlc: &str) -> Option<&str> { + hlc.splitn(3, '-').nth(2).filter(|a| !a.is_empty()) +} + +/// Graph ids are directory names on the server: restrict them to a safe alphabet. +pub fn is_valid_graph_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 64 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// blake3 hex digest (64 lowercase hex chars). +pub fn is_valid_hash(h: &str) -> bool { + h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn actor_and_validation() { + assert_eq!(hlc_actor("0000000000001-00000-abc123"), Some("abc123")); + assert_eq!(hlc_actor("garbage"), None); + assert!(is_valid_graph_id("my-graph_1")); + assert!(!is_valid_graph_id("../x")); + assert!(!is_valid_graph_id("")); + assert!(is_valid_hash(&"a".repeat(64))); + assert!(!is_valid_hash("ab/../")); + } +} diff --git a/crates/synapse-sync/src/remote.rs b/crates/synapse-sync/src/remote.rs new file mode 100644 index 0000000..e858f9c --- /dev/null +++ b/crates/synapse-sync/src/remote.rs @@ -0,0 +1,340 @@ +//! HTTP transport to a Synapse server. Usable on its own as a thin client (read API, no local +//! replica) and as the transport of [`crate::SyncClient`]. + +use crate::error::{Error, Result}; +use crate::protocol::*; +use futures_util::StreamExt; +use reqwest::{Method, RequestBuilder, Response, StatusCode, header}; +use serde::de::DeserializeOwned; +use std::path::Path; +use std::time::Duration; +use synapse_core::{Backlink, Page}; +use tokio::io::{AsyncSeekExt, AsyncWriteExt}; + +#[derive(Debug, Clone)] +pub struct RemoteConfig { + /// Base URL, e.g. `https://notes.example.com` (no trailing path). + pub server_url: String, + pub graph_id: String, + pub token: String, + pub connect_timeout: Duration, + /// Timeout for JSON requests; blob transfers only use an idle (read) timeout. + pub request_timeout: Duration, +} + +impl RemoteConfig { + pub fn new( + server_url: impl Into, + graph_id: impl Into, + token: impl Into, + ) -> Self { + Self { + server_url: server_url.into(), + graph_id: graph_id.into(), + token: token.into(), + connect_timeout: Duration::from_secs(10), + request_timeout: Duration::from_secs(30), + } + } +} + +#[derive(Debug, Clone)] +pub struct Remote { + http: reqwest::Client, + cfg: RemoteConfig, +} + +impl Remote { + pub fn new(cfg: RemoteConfig) -> Result { + if !is_valid_graph_id(&cfg.graph_id) { + return Err(Error::Protocol(format!( + "invalid graph id {:?}", + cfg.graph_id + ))); + } + let http = reqwest::Client::builder() + .connect_timeout(cfg.connect_timeout) + .read_timeout(Duration::from_secs(60)) + .user_agent(concat!("synapse-sync/", env!("CARGO_PKG_VERSION"))) + .build()?; + Ok(Self { http, cfg }) + } + + pub fn config(&self) -> &RemoteConfig { + &self.cfg + } + + /// Identifies this remote graph; sync cursors are only valid for the same key. + pub fn key(&self) -> String { + format!( + "{}|{}", + self.cfg.server_url.trim_end_matches('/'), + self.cfg.graph_id + ) + } + + fn url(&self, path: &str) -> String { + format!( + "{}/v1/graphs/{}{}", + self.cfg.server_url.trim_end_matches('/'), + self.cfg.graph_id, + path + ) + } + + fn req(&self, method: Method, path: &str) -> RequestBuilder { + self.http + .request(method, self.url(path)) + .bearer_auth(&self.cfg.token) + .header(HEADER_PROTOCOL, PROTOCOL_VERSION) + } + + fn json_req(&self, method: Method, path: &str) -> RequestBuilder { + self.req(method, path).timeout(self.cfg.request_timeout) + } + + async fn check(resp: Response) -> Result { + let status = resp.status(); + if status.is_success() { + return Ok(resp); + } + if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN { + return Err(Error::Unauthorized); + } + let message = match resp.json::().await { + Ok(b) => b.error, + Err(_) => status.canonical_reason().unwrap_or("error").to_string(), + }; + Err(Error::Status { + status: status.as_u16(), + message, + }) + } + + async fn json(rb: RequestBuilder) -> Result { + Ok(Self::check(rb.send().await?).await?.json().await?) + } + + // ------------------------------------------------------------------ sync + + /// Creates the graph on the server if needed (idempotent) and returns its identity. + pub async fn ensure_graph(&self) -> Result { + let info: Info = Self::json(self.json_req(Method::PUT, "")).await?; + if info.protocol != PROTOCOL_VERSION { + return Err(Error::Protocol(format!( + "server speaks protocol {}, client {}", + info.protocol, PROTOCOL_VERSION + ))); + } + Ok(info) + } + + pub async fn push(&self, ops: Vec) -> Result { + Self::json( + self.json_req(Method::POST, "/ops") + .json(&PushRequest { ops }), + ) + .await + } + + pub async fn pull( + &self, + since: i64, + limit: u32, + exclude_actor: Option<&str>, + ) -> Result { + let mut rb = self + .json_req(Method::GET, "/ops") + .query(&[("since", since.to_string()), ("limit", limit.to_string())]); + if let Some(a) = exclude_actor { + rb = rb.query(&[("exclude_actor", a)]); + } + Self::json(rb).await + } + + /// Opens the realtime stream (Server-Sent Events). Each `data:` line is a [`SyncEvent`]. + pub async fn open_events(&self) -> Result { + let rb = self + .req(Method::GET, "/events") + .header(header::ACCEPT, "text/event-stream"); + Self::check(rb.send().await?).await + } + + // ----------------------------------------------------------------- blobs + + /// `Ok(None)` if the server has the blob; otherwise how many bytes of a partial upload it + /// already holds (0 if none). + pub async fn blob_upload_offset(&self, hash: &str) -> Result> { + let resp = self + .json_req(Method::HEAD, &format!("/blobs/{hash}")) + .send() + .await?; + match resp.status() { + s if s.is_success() => Ok(None), + StatusCode::NOT_FOUND => Ok(Some( + resp.headers() + .get(HEADER_UPLOAD_OFFSET) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0), + )), + _ => Err(Self::check(resp).await.unwrap_err()), + } + } + + /// Uploads the file at `path` (whose blake3 is `hash`), skipping it if the server already + /// has it and resuming a partial upload. The file is streamed, never loaded in memory. + pub async fn upload_blob(&self, hash: &str, path: &Path) -> Result<()> { + let size = tokio::fs::metadata(path).await?.len(); + for _ in 0..3 { + let Some(offset) = self.blob_upload_offset(hash).await? else { + return Ok(()); + }; + let offset = if offset > size { 0 } else { offset }; + let mut file = tokio::fs::File::open(path).await?; + file.seek(std::io::SeekFrom::Start(offset)).await?; + let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::with_capacity( + file, + 256 * 1024, + )); + let resp = self + .req(Method::PUT, &format!("/blobs/{hash}")) + .header(HEADER_UPLOAD_OFFSET, offset) + .header(HEADER_UPLOAD_LENGTH, size) + .header(header::CONTENT_LENGTH, size - offset) + .body(body) + .send() + .await?; + if resp.status() == StatusCode::CONFLICT { + continue; // offset out of date: HEAD again + } + Self::check(resp).await?; + return Ok(()); + } + Err(Error::Protocol(format!( + "blob {hash}: upload offset keeps changing" + ))) + } + + /// Downloads blob `hash` into `dest`, streaming through `part` (resumed if it exists), and + /// verifies the hash. `part` and `dest` must be on the same filesystem. + pub async fn download_blob(&self, hash: &str, part: &Path, dest: &Path) -> Result<()> { + if let Some(dir) = part.parent() { + tokio::fs::create_dir_all(dir).await?; + } + if let Some(dir) = dest.parent() { + tokio::fs::create_dir_all(dir).await?; + } + let have = match tokio::fs::metadata(part).await { + Ok(m) => m.len(), + Err(_) => 0, + }; + let mut rb = self.req(Method::GET, &format!("/blobs/{hash}")); + if have > 0 { + rb = rb.header(header::RANGE, format!("bytes={have}-")); + } + let resp = rb.send().await?; + let mut out = match resp.status() { + StatusCode::PARTIAL_CONTENT => { + tokio::fs::OpenOptions::new() + .append(true) + .open(part) + .await? + } + StatusCode::RANGE_NOT_SATISFIABLE => { + // Stale partial file: drop it; the next attempt starts from scratch. + let _ = tokio::fs::remove_file(part).await; + return Err(Error::Protocol(format!("blob {hash}: stale partial file"))); + } + _ => tokio::fs::File::create(part).await?, + }; + let resp = Self::check(resp).await?; + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + out.write_all(&chunk?).await?; + } + out.flush().await?; + drop(out); + let part_owned = part.to_path_buf(); + let actual = tokio::task::spawn_blocking(move || hash_file(&part_owned)) + .await + .map_err(|e| Error::Task(e.to_string()))??; + if actual != hash { + let _ = tokio::fs::remove_file(part).await; + return Err(Error::Protocol(format!( + "blob {hash}: downloaded content hashes to {actual}" + ))); + } + tokio::fs::rename(part, dest).await?; + Ok(()) + } + + // -------------------------------------------------------------- read API + + pub async fn list_pages( + &self, + include_journals: bool, + limit: u32, + offset: u32, + ) -> Result> { + Self::json(self.json_req(Method::GET, "/pages").query(&[ + ("journals", include_journals.to_string()), + ("limit", limit.to_string()), + ("offset", offset.to_string()), + ])) + .await + } + + /// Page (with aliases and block tree) by title or alias; `None` if it does not exist. + pub async fn page_by_title(&self, title: &str) -> Result> { + self.optional( + self.json_req(Method::GET, "/pages/by-title") + .query(&[("title", title)]), + ) + .await + } + + pub async fn page(&self, id: synapse_core::PageId) -> Result> { + self.optional(self.json_req(Method::GET, &format!("/pages/{id}"))) + .await + } + + pub async fn backlinks(&self, id: synapse_core::PageId) -> Result> { + let v: BacklinksView = + Self::json(self.json_req(Method::GET, &format!("/pages/{id}/backlinks"))).await?; + Ok(v.backlinks) + } + + /// The journal of `date` (`None` if that day has no journal; reads never create it). + pub async fn journal(&self, date: chrono::NaiveDate) -> Result> { + self.optional(self.json_req(Method::GET, &format!("/journals/{date}"))) + .await + } + + pub async fn journals_between( + &self, + from: chrono::NaiveDate, + to: chrono::NaiveDate, + ) -> Result> { + Self::json( + self.json_req(Method::GET, "/journals") + .query(&[("from", from.to_string()), ("to", to.to_string())]), + ) + .await + } + + async fn optional(&self, rb: RequestBuilder) -> Result> { + let resp = rb.send().await?; + if resp.status() == StatusCode::NOT_FOUND { + return Ok(None); + } + Ok(Some(Self::check(resp).await?.json().await?)) + } +} + +pub(crate) fn hash_file(path: &Path) -> Result { + let mut f = std::fs::File::open(path)?; + let mut h = blake3::Hasher::new(); + std::io::copy(&mut f, &mut h)?; + Ok(h.finalize().to_hex().to_string()) +} diff --git a/crates/synapse-sync/src/state.rs b/crates/synapse-sync/src/state.rs new file mode 100644 index 0000000..29f9bc1 --- /dev/null +++ b/crates/synapse-sync/src/state.rs @@ -0,0 +1,125 @@ +//! Persistent sync cursors (table `sync_state`) and the UI-facing state. + +use rusqlite::{Connection, OptionalExtension, params}; +use serde::Serialize; +use synapse_core::Graph; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SyncStatus { + Idle, + Syncing, + /// Server unreachable; local edits are kept and pushed once it is back. + Offline, + /// The server answered but something failed (auth, protocol, disk...). See `message`. + Error, +} + +/// What the UI shows about sync. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SyncState { + pub status: SyncStatus, + pub message: Option, + /// Local ops not yet pushed to the server. + pub pending_ops: u64, + /// Wall-clock millis of the last fully successful cycle. + pub last_sync_ms: Option, + /// Ops pushed / pulled(applied) in the last successful cycle. + pub last_pushed: u64, + pub last_pulled: u64, +} + +impl Default for SyncState { + fn default() -> Self { + Self { + status: SyncStatus::Idle, + message: None, + pending_ops: 0, + last_sync_ms: None, + last_pushed: 0, + last_pulled: 0, + } + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Cursors { + /// Highest local op seq already pushed (or skipped because it came from the server). + pub pushed_seq: i64, + /// Highest server op seq already pulled. + pub pull_cursor: i64, +} + +pub(crate) fn init(conn: &Connection) -> rusqlite::Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS sync_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);", + ) +} + +fn get(conn: &Connection, key: &str) -> rusqlite::Result> { + conn.query_row("SELECT value FROM sync_state WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional() +} + +fn set(conn: &Connection, key: &str, value: &str) -> rusqlite::Result<()> { + conn.execute( + "INSERT INTO sync_state(key, value) VALUES (?1, ?2) + ON CONFLICT(key) DO UPDATE SET value=?2", + params![key, value], + )?; + Ok(()) +} + +/// Loads the cursors for `(remote_key, server_id)`. If the graph is now synced with another +/// server/graph, or the server graph was recreated, cursors restart from zero (re-pushing is +/// safe: the server merges with last-writer-wins and ignores what it already has). +pub(crate) fn load(g: &Graph, remote_key: &str, server_id: &str) -> rusqlite::Result { + let c = g.conn(); + init(c)?; + let same = get(c, "remote_key")?.as_deref() == Some(remote_key) + && get(c, "server_id")?.as_deref() == Some(server_id); + if !same { + set(c, "remote_key", remote_key)?; + set(c, "server_id", server_id)?; + set(c, "pushed_seq", "0")?; + set(c, "pull_cursor", "0")?; + return Ok(Cursors::default()); + } + let num = + |k| -> rusqlite::Result { Ok(get(c, k)?.and_then(|v| v.parse().ok()).unwrap_or(0)) }; + Ok(Cursors { + pushed_seq: num("pushed_seq")?, + pull_cursor: num("pull_cursor")?, + }) +} + +pub(crate) fn save_pushed(g: &Graph, seq: i64) -> rusqlite::Result<()> { + set(g.conn(), "pushed_seq", &seq.to_string()) +} + +pub(crate) fn save_pulled(g: &Graph, cursor: i64) -> rusqlite::Result<()> { + set(g.conn(), "pull_cursor", &cursor.to_string()) +} + +/// Number of local-origin ops after `pushed_seq`. +pub(crate) fn pending(g: &Graph, pushed_seq: i64) -> rusqlite::Result { + let pattern = format!("%-{}", g.actor()); + g.conn() + .query_row( + "SELECT count(*) FROM ops WHERE seq > ?1 AND hlc LIKE ?2", + params![pushed_seq, pattern], + |r| r.get::<_, i64>(0), + ) + .map(|n| n as u64) +} + +/// Pending count using the persisted cursor (works before the first successful sync too). +pub(crate) fn pending_now(g: &Graph) -> rusqlite::Result { + init(g.conn())?; + let pushed = get(g.conn(), "pushed_seq")? + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + pending(g, pushed) +} diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 0000000..856b67c --- /dev/null +++ b/docs/server.md @@ -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 `//` (`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 /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}`. diff --git a/docs/sync.md b/docs/sync.md new file mode 100644 index 0000000..ec32a98 --- /dev/null +++ b/docs/sync.md @@ -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 `. `/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=` (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: ` (required) and `Upload-Offset: N` (omit/0 to start). + The body (rest of the file) is appended to `/uploads/.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-.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>`; 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. diff --git a/scripts/update.sh b/scripts/update.sh new file mode 100755 index 0000000..4e07b72 --- /dev/null +++ b/scripts/update.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Idempotent update of a Synapse server install: pull, build, install the binary atomically. +# Run as the service user (by hand or via POST /admin/update). Exit codes: +# 0 updated; the caller (the server) exits so systemd restarts the new binary +# 10 already up to date, nothing to restart +# other: failed; the running binary is left untouched +set -euo pipefail + +REPO_DIR="${SYNAPSE_REPO_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +BIN_DIR="${SYNAPSE_BIN_DIR:-/opt/synapse/bin}" +BRANCH="${SYNAPSE_UPDATE_BRANCH:-main}" +export PATH="$HOME/.cargo/bin:$PATH" + +log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*"; } +trap 'log "update FAILED (line $LINENO)"' ERR + +cd "$REPO_DIR" +log "fetching $BRANCH" +git fetch --quiet origin "$BRANCH" +local_rev=$(git rev-parse HEAD) +remote_rev=$(git rev-parse "origin/$BRANCH") +if [ "$local_rev" = "$remote_rev" ] && [ -x "$BIN_DIR/synapse-server" ]; then + log "already up to date ($local_rev)" + exit 10 +fi + +log "updating $local_rev -> $remote_rev" +git merge --ff-only "origin/$BRANCH" +log "building (release)" +cargo build --release --locked -p synapse-server + +# Schema migrations run in synapse-core when each graph is opened; nothing to do here. +mkdir -p "$BIN_DIR" +install -m 0755 target/release/synapse-server "$BIN_DIR/synapse-server.new" +mv -f "$BIN_DIR/synapse-server.new" "$BIN_DIR/synapse-server" # atomic replace +log "installed $remote_rev"