Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
synapse docs architecture.md
13 kB · 222 lines
Markdown
at main

Architecture #

The one idea to hold onto is that the study data lives on the devices. Every device keeps a full replica of the workspace in CRDT documents and works on it locally, offline included. The server is an optional peer that stores accounts, files and an opaque sync log, and two devices can also converge with no server at all.

1. The big picture #

Server (optional peer)DevicesHTTP sync log + filesHTTP sync log + filesLAN sync (mDNS +WebSocket)file pack (.zip)generation + OCRoffline generationoffline generationBrowser SPA(Svelte 5, IndexedDB)Desktop app(Tauri shell, same SPA)Phone(same shell, iOS/Android)NestJS APISQLite or Postgresuploads/ + CASOllama or anyOpenAI-compatible runtimeAI providers(OpenAI / Anthropic)

Three deployment shapes fall out of this, all first-class:

Shape What syncs Auth
Browser + server HTTP sync log Session cookie or bearer token
Desktop standalone LAN peers and file packs only None (local mode)
Desktop + server HTTP log, plus LAN and packs Bearer token

2. Monorepo layout #

apps/
  web/        Svelte 5 SPA (Vite). All study features live here.
  api/        NestJS API (clean architecture, Drizzle ORM, sqlite/pg).
  shell/      Tauri 2 shell around the web build + LAN sync plumbing (Rust).
packages/
  ai-core/    Provider-agnostic AI calls (prompts, retries, generation, OCR).
  design-system/  Svelte UI components and tokens.
docs/         The MkDocs site: user guides, self-hosting, this file.

2.1 Inside the web app #

apps/web/src has three layers, and imports only flow one way (lib, then pages, then app). dependency-cruiser checks the rule as part of pnpm lint.

src/
  app/        The frame: boot, router, navigation chrome (TopBar, PageMain),
              the auth gate. The only layer that may import everything, since
              it wires the pages into routes.
  pages/      One folder per screen, nested like the navigation: course/
              contains viewer/, split-pdf/, exercises/ and settings/ because
              that is how you reach them. A page keeps its own component, its
              parts and its logic together, imports lib and the app shell
              freely, and never imports another top-level page.
  lib/        Shared infrastructure with no screen of its own: data/ (CRDT
              repos), documents/ (pdf pipeline), sync/, editor/ (Tiptap and
              markdown rendering), ai/, plus platform utilities. lib never
              imports app or pages, so everything in it stays reusable.

Placement follows use, not naming: LexiconDrawer lives in the viewer because only the viewer opens it, and workspaceExport lives in the course pages because the export button does. When a module gains a second consumer outside its page, it moves down into lib.

3. Client data layer #

Pages never talk to the network for study data. They call repositories, which read and write Loro CRDT documents; a persistence layer stores every change incrementally in IndexedDB and a sync engine ships it out later.

Pages + componentsrepos/ (courses,documents, links,exercises, annotations,attempts,progress, lexicon)workspace.tscommit() persists beforeresolvingloro.ts - doc registryopen, subscribe,importRemote, compactIndexedDB 'synapse'docs / doc_updates / blobs /sync_state / metasync/engine.tspull by cursor, push byversion vectortransports/http.ts(server log)p2p/tauri.ts(LAN exchange)sync/filePack.ts(.zip export/import)viewer (PDF)data/blobs.tscontent-addressed cache

The documents themselves:

Doc id Contents
workspace Registries of courses, topics, documents, links, exercises, lexicon (child maps keyed by uuid) plus ordering lists (course_order, per-course layout with topic_order and items:<topic> lists)
attempts Append-only, write-once map of exercise attempts (kept separate so its history never bloats workspace snapshots)
ann:<documentId> One doc per PDF: annotations keyed by uid, field-level last-writer-wins

Persistence is incremental: each local commit appends an update row; after 64 rows the doc is folded into a fresh snapshot (guarded by a web lock so two tabs never compact the same doc at once). Remote updates imported by the sync engine are persisted through the same path, so a reload never loses them.

4. How devices converge #

Loro updates are idempotent (operations deduplicate by peer and counter), so every channel below can replay or overlap safely. A device can use all three.

4.1 Server log (HTTP) #

The server stores base64 update blobs in an append-only log per user and doc. It never opens them, with one exception: a compaction job that folds long logs into snapshot rows.

GET /api/sync/manifest[{doc_id, latest_seq}]GET /api/sync/updates?doc_id=...&after_seq=cursor{updates: [snapshot?, blobs...], latest_seq}POST /api/sync/updates {doc_id, updates since last pushed vv}import + persist, cursor := latest_seqpush debounced 300 ms,sendBeacon on page hidecompaction job folds >=128 rowsinto one snapshot rowClient (sync engine)Server (sync log)Client (sync engine)Server (sync log)

4.2 LAN peers (desktop) #

The Rust side of the Tauri shell advertises _synapse-sync._tcp over mDNS and hosts a WebSocket listener that pipes every message to the webview; the whole protocol lives in the web code (sync/p2p/exchange.ts). Both sides run the same symmetric state machine:

hello {device_id, docs: [{doc_id, version_vector}]}hello {...}doc-update* (what A lacks, from A's vv)doc-update* (what B lacks, from B's vv)blob-have {hashes}blob-have {hashes}blob-want / B->>A: blob-data*byebyeDevice A (initiator)Device B (responder)Device A (initiator)Device B (responder)

4.3 File packs #

Settings > Backup exports the whole workspace (doc snapshots + file blobs) as one zip; importing it on any device merges it in. This is also the sneakernet path between two machines that share no network.

5. Server API surface #

The surface is deliberately small. The server holds what a device cannot do alone. There are no CRUD endpoints for courses, chapters, links, exercises, annotations, attempts or lexicon entries, because those exist only inside the Loro docs.

Area Endpoints Notes
Auth POST /api/auth/register|signup|login|login/local|logout|password, GET /api/auth/status|me, GET /api/auth/login/oidc|callback/oidc, GET/POST /api/auth/users, PUT /api/auth/users/:id/role, POST /api/auth/users/:id/password Passport local + OIDC single sign-on; sessions as cookie or bearer token
Sync log GET /api/sync/manifest, GET/POST /api/sync/updates Opaque base64 Loro blobs, per user + doc, cursor-based
Files POST /api/documents/upload, GET /api/documents/:id, GET /api/documents/:id/file, POST /api/documents/:id/ocr, DELETE /api/documents/:id Upload converts (LibreOffice/pandoc), extracts text, OCRs scans, stores bytes in the CAS
Blobs (CAS) GET/PUT /api/blobs/:hash, POST /api/blobs/diff Content-addressed by sha-256, deduplicated across users
AI POST /api/exercises/generate, GET/PUT /api/settings/ai Generation returns rows, stores nothing; course context travels with the request
SSO config GET/PUT /api/settings/sso Admin-only: the OIDC provider settings the login screen offers

There is no export endpoint: baking annotations into a PDF happens on the device, in apps/web/src/lib/documents/annotatedExport.ts.

Server-side tables mirror that surface: users, sessions, documents (file paths, extracted text, hashes), blob_owners, crdt_updates, crdt_snapshots, app_settings. Nothing else. Note that blob_owners only records which users hold a given hash, so the bytes drop when the last owner does. The metadata for an uploaded blob lives in a .json sidecar next to the bytes in the content store rather than in a table; sync payload blobs carry no sidecar at all.

6. AI routing #

yesno (offline / standalone)Generate exercisesServer reachable?POST/api/exercises/generateserver key, configuredprovider(OpenAI gpt-4o-mini bydefault)Device model viaOpenAI-compatible runtime(Ollama,http://localhost:11434/v1)Rows inserted into the localworkspace docSynced to other devices likeany other change

OCR of scanned PDFs runs server-side on upload (it follows the same provider settings). See AI.md for keys and provider setup.

7. Where to start reading #

Question File
How is an entity stored and listed? apps/web/src/lib/data/repos/courses.ts, .../containers.ts
How does a change reach the disk? apps/web/src/lib/data/loro.ts
How does a change reach other devices? apps/web/src/lib/sync/engine.ts, .../protocol.ts
What happens on first launch? apps/web/src/lib/data/bootstrap.ts
How do LAN peers talk? apps/web/src/lib/sync/p2p/exchange.ts, apps/shell/src-tauri/src/lib.rs
What does the server accept? apps/api/src/app.module.ts (controllers list)
How is the log kept small? apps/api/src/application/compaction.service.ts
How are files deduplicated? apps/api/src/infrastructure/external/cas.ts, apps/web/src/lib/data/blobs.ts