Yokan / rebuild
Course 1 8624561

SYNC_SERVER_PLAN.md

docs/SYNC_SERVER_PLAN.md

documentation / design asset323 lines
1# Yokan Sync Server — Plan (v2, reinvented sync)23Self-hosted sync backend for the Yokan KMP app. Rust + Postgres + Next.js admin panel.4Separate repo (`yokan-hub`). This revision **replaces** the app's current snapshot-exchange protocol5(`HttpSyncService.kt`) with a new one; nothing here is constrained by the old wire format.67## 0. Why the old model can't be made efficient89| Today (`HttpSyncService.kt`) | Cost |10|---|---|11| Client posts *all* manga/chapters/tracks every round, server returns *all* of them | O(library) bandwidth and JSON work per sync on both sides, regardless of what changed |12| Row-level last-writer-wins on `updatedAt` | Reading a chapter on the phone clobbers a category change made on the desktop for the same title (same row, different fields) |13| Whole `DbSettings` blob (~200 fields incl. per-title lists) is one row | Any two devices touching settings clobber each other |14| Ids are local auto-increment (`YokanDatabase.kt:377`) | Two devices with existing libraries collide; same title added on two devices becomes two rows |15| Deletions via `changed_part` tombstones + `lastSync*` cutoffs | Fragile against clock skew between devices |1617The redesign: **stable content-derived ids, a coalescing per-field outbox on the client, hybrid logical clocks,18path-level LWW plus two commutative types on the server, and one round-trip that pushes and pulls a delta.**1920## 1. Sync model2122### 1.1 Identity — deterministic ids2324Ids stay `Long` (no schema type change) but become **derived from the natural key**, so the same title on two25devices is the same row and merging is automatic. No dedupe feature needed, ever.2627| Entity | Id source (FNV-1a 64 of the key string, masked positive — pure Kotlin, synchronous on every target; `database/sync/SyncIds.kt`) |28|---|---|29| manga (remote) | `"$itemType|$sourceId|$link"` |30| manga (local archive) | `LocalLibraryIdentity` string (`LocalLibraryService.kt:38`) |31| chapter | `"$mangaId|$url"` (`archivePath` for local) |32| track | `"$mangaId|$syncId"` |33| history | `"$mangaId"` (one history row per title; `chapterId` is a field) |34| update | `"$mangaId|$chapterId"` |35| category | random 63-bit (no natural key; user-created) |36| settings | fixed id, but see 1.3 — the blob is exploded |3738One-time Room migration (v1→v2) rewrites ids and every FK (`chapter.mangaId`, `history.*`, `track.mangaId`,39`update.*`, `manga.categories`, and the `mangaId`/`chapterId` keys inside `DbSettings` lists).4041### 1.2 Clock — HLC4243Every write gets a **hybrid logical clock** value: 64-bit = 48 bits wall ms + 16-bit counter, ties broken by44device id. Client rule: `hlc = max(now_ms, last_hlc.ms) . counter++`. On every server response the client45adopts `max(own, server_hlc)`, so a device with a wrong clock is pulled forward and can't "win the future".46Server clamps incoming clocks to `server_now + 60 s`.4748### 1.3 Granularity — paths4950A synced entity is a JSON object. Changes are tracked per **path**, not per row:5152- top-level field: `isRead`, `name`, `favorite`53- one level of map key for list-of-keyed-objects fields: `categories.<categoryId>` (value `true` / delete),54  `personalReaderModeList.<mangaId>`, `sortChapterList.<mangaId>`, `chapterPageIndexList.<chapterId>`,55  `sourcePreferences.<sourceId>:<key>`, …5657Kotlin lists like `List<DbPersonalReaderMode>` are marshalled to/from maps keyed by `mangaId` at the sync58boundary; the app's domain classes don't change. The settings blob becomes entity kind `settings` with ~20059paths (+ map entries) instead of one opaque value, so two devices changing different preferences never conflict.6061### 1.4 Merge — path LWW + two monotone types6263Default for every path: **last-writer-wins by HLC**. Registry of exceptions, tiny and shared by client and server64(same JSON test vectors, §6):6566| Path | Type | Why |67|---|---|---|68| `history.readingTimeSeconds.<device>` | **max** per device (a grow-only counter: the client stores its own running total under its device id and reads the sum of the map) | reading on two devices adds up, and re-sending the same op is a no-op — a plain delta counter would double-count on retry |69| `manga.dateAdded` | **min** | earliest add wins |70| `chapter.lastPageRead` | LWW (deliberate) | re-reading from page 0 is intent, not a conflict |71| `_deleted` | LWW path like any other | delete newer than every field → row gone; any field newer than the delete → row resurrected with its stored doc |7273Properties: commutative, associative, idempotent → replaying a batch is a no-op, order of arrival doesn't74matter, retries are free. There is no manual conflict UI: every conflict has a deterministic outcome. The server75reports which client ops *lost* so the app can show "n changes from another device took precedence" (optional).7677### 1.5 Client outbox7879Room table `outbox(kind, id, path, value_json, hlc, seq autoinc)`, PK `(kind, id, path)`.8081- Every write to a synced entity in `YokanDatabase` diffs old vs new row and **upserts one outbox row per changed82  path**. Writing the same path again overwrites value/hlc and takes a new `seq`. Page-by-page reading produces83  one row, not hundreds. Nothing is recorded while no hub is logged in: such epoch-0 ops are never accepted, and84  the first sync after login seeds the hub with full local state instead (see the phase notes below).85- Non-synced tables: `download`, `page_cache`, `track_search`, `track_preference` (OAuth), `sync_preference`.86  `manga.customCoverImage` (BLOB) syncs as base64, it's rare.87- `chapter.downloadSize`, and `chapter.archivePath` while `downloadSize` is set (a download folder on this device),88  stay device-local; local-library chapters keep syncing their virtual `archivePath` (`SyncPaths`).89- Push triggers: debounce 3 s after the last outbox write while foreground+online; on background90  (WorkManager / BGTaskScheduler / desktop timer); on a live hint (§2.3).9192### 1.6 Round trip9394One request does push and pull. Client-side, in order:95961. Read outbox rows with `seq ≤ N` (N = current max). Send them with `since` (last server head).972. Server (§3) merges ops, returns changed entities with `seq > since` as **full docs** (already merged), plus new `head`.983. Client, in one Room transaction: delete outbox rows with `seq ≤ N` (rows rewritten during flight have `seq > N`99   and survive); apply each incoming doc, **except paths that still have an outbox row** (local newer edit,100   will win next round by HLC anyway). Store `head`.101102Clocks never leave the server. The client only needs its unpushed ops to merge correctly, because everything it103has pushed is already inside the docs it receives.104105## 2. Wire protocol106107Single endpoint plus a hint channel. JSON via kotlinx.serialization (already used), gzip both ways108(Ktor `ContentEncoding` / tower-http). Field names are one letter because a steady-state sync is dominated109by op envelopes, not values.110111All API routes live under `/api/` so the admin SPA can own every other path. `GET /api/version` →112`{"supported": ["1"]}` (no auth) is checked by the client before it sends credentials.113114```115POST /api/v1/sync116Authorization: Bearer <token>117X-Device: <stable device id>118119{ "since": 18234, "epoch": 3, "hlc": 1756700000000_0007,120  "ops": [ {"k":3,"id":-812…,"p":"isRead","v":true,"t":1756700000000_0007},121           {"k":3,"id":-812…,"p":"lastPageRead","v":18,"t":1756700000000_0008},122           {"k":5,"id":4471…,"p":"readingTimeSeconds.<device>","v":5340,"t":…}, // per-device running total, merge = max123           {"k":2,"id":4471…,"p":"categories.77","v":null,"t":…},          // null = delete path124           {"k":2,"id":9912…,"p":"_deleted","v":true,"t":…} ] }125126200 { "epoch": 3, "head": 18291, "tip": 18291, "hlc": 1756700000210_0001, "more": false,127      "ents": [ {"k":3,"id":-812…,"doc":{…full merged chapter…}},128                {"k":2,"id":9912…,"del":true} ],129      "lost": 1 }130```131132- `k` = kind: 1 category, 2 manga, 3 chapter, 4 track, 5 history, 6 update, 7 settings.133- `more: true` → client repeats with `since = head` (page size 500 entities). Initial sync of a new device is134  the same loop from `since: 0`; no separate restore mode. `tip` is the user's newest seq, so135  `(head - since) / (tip - since)` is pull progress while `more` is true.136- `epoch` mismatch or `since < min_seq` (tombstones already purged) → `409 {"resync": true}` → client sets137  `since = 0` and keeps its outbox. Only two failure shapes exist.138- Idempotent: same ops re-sent after a network failure lose LWW to themselves (strict `>`) — no idempotency keys.139- Steady state: reading one chapter costs ~150 bytes up, ~400 bytes down. `ops: []` with `since == head`140  returns ~60 bytes.141142### 2.3 Live hint143144`WS /api/v1/events` (WebSockets are already wired on all five targets in the app). Server sends `{"head": 18291}`145whenever the user's head advances by a *different* device. Client does a round trip. Nothing else travels over146the socket. Reconnect with jittered backoff; the socket is a latency optimisation, never a correctness requirement.147148## 3. Server149150### 3.1 Data model151152```sql153create table entities (154  user_id  uuid not null references users on delete cascade,155  kind     smallint not null,156  id       bigint not null,157  doc      jsonb not null,               -- merged current value (kept on tombstones for resurrection)158  clocks   jsonb not null,               -- {"path": hlc, ...} incl. "_deleted"159  deleted  bool not null default false,160  seq      bigint not null,              -- per-user dense sequence161  primary key (user_id, kind, id)162);163create index entities_delta on entities (user_id, seq);164165alter table users add column head bigint not null default 0,      -- last assigned seq166                  add column min_seq bigint not null default 0,   -- oldest seq still fully represented167                  add column epoch int not null default 1;        -- bump only when history is rewritten168```169170No oplog table. The materialised row *is* the log entry: `seq` says "changed after X", the merged doc says what171it is now. Storage stays O(entities), never grows with activity. Tombstones are purged after 30 days (`min_seq`172advances; a device gone longer than that resyncs from zero).173174### 3.2 Request handling (one transaction)175176```177pg_advisory_xact_lock(hash(user_id))                 -- serialise devices of the same user178select … from entities where (kind,id) in unnest(touched) for update179merge in Rust: per op, compare t with clocks[path]; apply lww / counter / min; note losers180head += 1 per changed entity; upsert via unnest (doc, clocks, deleted, seq)181select … where user_id = $1 and seq > $2 order by seq limit 500182update users set head = …183notify live hub (in-process broadcast channel keyed by user_id; single-node server, no Redis)184```185186Cost per request is O(ops + delta rows). A 50k-chapter library that nobody touched costs one index probe.187Merge lives in one pure Rust module (`merge.rs`: `fn apply(doc, clocks, op) -> Outcome`) with no SQL in it.188189### 3.3 Snapshots, backups, rollback190191- **Infra**: `pg_dump` cron sidecar in `compose.yaml`. Not built into the binary.192- **Per-user snapshots** (`snapshots(user_id, reason, seq_at, blob zstd, created_at)`): nightly, before every193  rollback, on demand. Export renders as a Yokan `BackupSnapshot` (`schemaVersion 1`) so the app's existing194  importer reads it.195- **Rollback** to a snapshot: `pre_rollback` snapshot first; then in one transaction every live entity not in the196  snapshot is tombstoned and every snapshot entity is written with `clocks = {all paths: now_hlc}` and a fresh197  `seq`. That's the whole trick: rolled-back values carry the newest clocks, so **pending ops on offline devices198  lose by ordinary LWW** and every device converges through the normal delta pull. No generation counter, no199  special client state. `epoch` is bumped only when a Postgres restore moves `head` backwards.200- The panel shows a diff-count preview (`+n / −n` per kind) before confirming.201202### 3.4 Stack203204| | |205|---|---|206| HTTP/WS | `axum`, `tokio`, `tower-http` (compression, request-decompression, trace, `ServeDir`) |207| DB | `sqlx` postgres, compile-time checked, `sqlx migrate` |208| Auth | `argon2`, random 32-byte tokens hashed with SHA-256 in `sessions`; `subtle` compare |209| JSON | `serde_json` with `RawValue` for op values (never re-serialised) |210| Blobs | `zstd` |211| Admin UI | Next.js 15 App Router + Tailwind + **shadcn/ui**, `output: 'export'`, served by axum → no Node in prod |212| Deploy | `compose.yaml`: `postgres:17`, `yokan-hub` (distroless), `pg_dump` cron. TLS from the user's proxy |213| Config | env vars only. `tracing` JSON logs, `GET /healthz` |214215## 4. Users, permissions, invites216217Unchanged in spirit from the first draft, restated for completeness.218219- `users(id, email citext, password_hash, role 'admin'|'user', permissions text[], quota jsonb, disabled, …)`220- `sessions(token_hash, user_id, device_id, label, created_at, last_seen, expires_at)` — 30-day sliding; users221  revoke their own devices, admins anyone's. Bearer token for app and panel alike.222- `invites(code, grants jsonb {role, permissions, quota}, max_uses, uses, expires_at, revoked, created_by)`.223  `POST /api/v1/register {email,password,code?}`. Invite link `PUBLIC_URL/join/<code>` served by the SPA.224  The app only ever logs in (`POST /api/v1/login` → `{token}`).225- **Access mode** (`server_settings.access_mode`, toggled by admins in the panel, default `invite_only`):226227  | Mode | `register` | `login` / `sync` |228  |---|---|---|229  | `open` | no code needed (an optional code still applies its grants) | normal |230  | `invite_only` | valid code required | normal |231  | `maintenance` | `503` | `503` for role `user`; admins still log in and use the panel |232233  `503` responses carry `Retry-After` and `{"error":"maintenance"}`; the app shows the message and keeps its outbox.234- Permissions checked by an axum extractor:235  `sync:read:{library|progress|settings}`, `sync:write:{…}` (library = kinds 1,2,3,4; progress = 5,6; settings = 7),236  `backup:export`, `backup:restore`, `rollback:self`, `invite:create`, `devices:manage`,237  `admin:{users,invites,backups,audit,settings}`.238- Quota: `max_bytes` (sum of `pg_column_size(doc)`), `max_devices`, `snapshot_keep`. Enforced in the sync transaction.239- `audit_log(at, actor, action, target, meta)`; `server_settings` single jsonb row.240- `tower_governor` rate limit on `/login` and `/register` only.241242## 5. Admin panel (Next.js + shadcn/ui)243244| Route | Contents |245|---|---|246| `/login`, `/join/<code>` | sign in; redeem invite |247| `/` | tiles: users, live devices, entities, storage, syncs/24 h, ops lost to conflicts/24 h, last backup |248| `/users` | data-table; row sheet: permissions checklist, quota, devices (revoke), disable, reset password, **snapshot timeline + rollback** |249| `/invites` | create from template → grants, copy link, uses/expiry, revoke |250| `/backups` | per-user snapshots, create now, export, rollback-to (with diff preview); pg_dump status |251| `/audit` | filterable log |252| `/settings` | **access mode switch** (open / invite only / maintenance), snapshot schedule/retention, tombstone retention, session TTL |253| `/me` | own password, devices, snapshots, export, rollback (if permitted) |254255## 6. Testing the merge (the part that must not be wrong)256257- `merge.rs` gets a `proptest`: for random op sets, every permutation and every duplication yields the same doc.258- The same rules exist once in Kotlin (`SyncMerge.kt`, used for the "skip paths with pending outbox rows" step and259  for unit tests). **Shared JSON vectors** in `yokan-hub/test-vectors/*.json` (`ops → expected doc`) are run by260  `cargo test` and by `:composeApp:desktopTest` so the two implementations can't drift.261- `#[sqlx::test]` per handler; one integration test drives two simulated devices through offline edits, a262  delete/edit race, and a rollback, asserting convergence.263264## 7. Client work (this repo)265266| # | Change | Where |267|---|---|---|268| 1 | Deterministic ids + Room v2 migration rewriting ids/FKs/settings keys | `YokanDatabase.kt`, `YokanRoomDatabase.kt`, new `SyncIdentity.kt` |269| 2 | `outbox` table + path diff on every synced write | `YokanDatabase.kt` upsert/remove paths, `RowAdapters.kt` |270| 3 | List↔map marshalling for keyed list fields (`categories`, settings `*List`) | new `SyncPaths.kt` |271| 4 | New `HttpSyncService` (round trip, HLC, apply-with-outbox-mask, WS hint) replacing the current file | `services/HttpSyncService.kt` |272| 5 | `sync_preference`: replace `lastSync{Manga,History,Update}` with `head`, `epoch`, `hlc` | `DatabaseEntities.kt`, Room migration |273| 6 | Sync screen: server URL, login, devices link, "n changes from another device" note | `settings/sync/SyncSettingsScreen.kt` |274| 7 | Delete `changed_part` writes and `HybridSyncService`'s `cloud://` branch if cloud-backup sync is retired (decide; it's orthogonal) | `HybridSyncService.kt` |275276Web (wasm) target: no Room; the outbox lives in the same `localStorage` snapshot. Same protocol, no special case.277278## 8. Phases279280> **Status (2026-09-02):** server side complete in `../yokan-hub` (phases 1, 2, 4, 5). Client side281> (phase 3) implemented in this repo: `database/sync/SyncIds.kt` (stable ids), `database/sync/SyncClock.kt` (HLC),282> `database/sync/SyncPaths.kt` (wire docs, list↔map, path diff, masking), `database/sync/SyncIdentityMigration.kt`283> (one-time id rewrite, `DbSettings.syncIdentityVersion`), outbox in `InMemoryYokanDatabase` +284> Room v2 (`outbox` table, `sync_preference.hub*` columns, `MIGRATION_1_2`),285> `services/HubSyncService.kt` replacing `HttpSyncService`. Tests in `commonTest/.../database/sync/*` and286> `HubSyncServiceTest`. Deviation from the plan: no Kotlin `SyncMerge.kt` — the client never merges287> (the hub does; the client only masks pending paths), so the shared vectors stay a hub-only test and288> the client tests cover the list↔map conventions instead. Remaining: web (wasm) has no Room, so its289> outbox lives in the localStorage snapshot (already covered by the snapshot field); sync screen290> shows pending-change count. Full-state upload (2026-09-03): the outbox only covers edits made291> since it started recording, so `HubSyncService` also streams every synced entity as path ops, in292> `MAX_OPS` chunks with `since = NO_DELTA`, (a) on the first push from a device (`hubHead == 0`,293> i.e. after login) with clock `SEED_CLOCK` so the hub's existing values win and only gaps are294> filled, and (b) on "Upload only" with fresh clocks so local state wins. A backup restore records295> every path it changed (and every entity it removed) as ordinary outbox ops with fresh clocks, so296> restored values win on the hub instead of being undone by the next pull; it also resets `hubHead`297> to 0 so the next round re-pulls everything else.298299| Phase | Scope | Rough size |300|---|---|---|301| 1 | `merge.rs` + proptest + test vectors; Kotlin `SyncMerge`/`SyncPaths` against the same vectors | 3 days |302| 2 | Server: schema, auth/register/invites, `/v1/sync`, `/v1/events`, compose, first-boot admin | 1 week |303| 3 | Client: deterministic ids + migration, outbox, new `HttpSyncService`, sync screen | 1.5 weeks |304| 4 | Snapshots, export, rollback; permissions/quotas; audit | 4 days |305| 5 | Admin SPA | 1 week |306307Phase 1 is deliberately first: if the merge rules are right, everything else is plumbing.308309## 9. Deliberately skipped (and when to add)310311- **Manual conflict resolution UI.** Path LWW + counter/min gives a deterministic answer for every case in this312  data model. Add only if users report a specific field where "last write" is the wrong answer; that becomes a313  new merge type in the registry, not a UI.314- **Binary encoding (CBOR/protobuf).** Gzip'd single-letter JSON is within ~30 % of it. Add when a profile shows315  serialisation on the client's hot path.316- **Snapshot-served initial sync.** `since: 0` paging is the same code; serve the zstd snapshot blob instead when317  first sync of a huge library is measurably slow.318- **Multi-node server / Redis pub-sub.** In-process broadcast; personal-scale server.319- **Per-path clocks compaction.** `clocks` jsonb per row is small; collapse to a single row clock when all paths320  share it if storage ever matters.321- **End-to-end encryption.** Server must read paths and clocks to merge; values could be opaque later without a322  schema change, but not now.323- **OAuth/SSO, TOTP, Prometheus.** Invite-gated personal server; `tracing` + `/healthz` first.324

Search chapters, reference and source filenames.