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 fc9c60f..31bc4cb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client - Format: `cargo fmt --all` (Rust), `dart format app/` (Flutter) - Lint: `cargo clippy --workspace --all-targets -- -D warnings`, `cd app && flutter analyze` - 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) - Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` @@ -23,7 +23,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 4da5ab4..eb351d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -17,12 +26,82 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" 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 = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" @@ -48,6 +127,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.9.0" @@ -64,6 +149,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", +] + [[package]] name = "chrono" version = "0.4.45" @@ -97,6 +199,17 @@ dependencies = [ "libc", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "errno" version = "0.3.14" @@ -104,7 +217,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -137,12 +250,53 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -156,11 +310,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -168,8 +339,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", + "rand_core", + "wasm-bindgen", ] [[package]] @@ -190,6 +364,111 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -214,6 +493,116 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.18" @@ -231,6 +620,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" @@ -254,18 +649,71 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "log" version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[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 = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[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-traits" version = "0.2.19" @@ -281,6 +729,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -293,6 +747,15 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -302,6 +765,62 @@ dependencies = [ "unicode-ident", ] +[[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", + "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" @@ -317,6 +836,104 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[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", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +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", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rusqlite" version = "0.37.0" @@ -331,6 +948,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" version = "1.1.5" @@ -341,7 +964,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -350,6 +1008,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 = "serde" version = "1.0.229" @@ -393,18 +1057,60 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" +[[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 = "slab" version = "0.4.12" @@ -417,6 +1123,28 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -453,6 +1181,66 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-server" +version = "0.1.0" +dependencies = [ + "axum", + "blake3", + "chrono", + "futures-util", + "reqwest", + "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", + "rusqlite", + "serde", + "serde_json", + "synapse-core", + "tempfile", + "thiserror", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -460,10 +1248,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -486,31 +1274,279 @@ 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 = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "tracing", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +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" +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]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ - "getrandom", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", "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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -524,6 +1560,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -556,6 +1603,48 @@ 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 = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "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-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -615,6 +1704,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -624,6 +1722,159 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zmij" version = "1.0.23" 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"