Production-quality Go + React collaborative editor with sandbox execution and from-scratch search.
Stack: Go 1.22 (chi, pgx, go-redis, nhooyr/websocket), PostgreSQL 16, Redis 7, Docker, Vite + React + TypeScript + CodeMirror 6
graph TD
FE[React + Vite + CodeMirror 6\npresence avatars, cursors] -->|nhooyr websocket| WS[ws-server Hub\n1 goroutine/room + pumps]
WS --> PG[(PostgreSQL\nusers/rooms/members/snippets)]
WS --> RD[(Redis pub/sub\ntoken bucket + broadcast)]
WS --> CRDT[RGA CRDT Document\nchildren map + DFS order]
WS -->|Redis pub/sub| EX[Executor Service\nDocker --network none]
EX --> RD
FE -->|GET /search?q=& /suggest| SE[Search Engine\nBM25 + Trigram + Trie]
SE --> PG
SE -->|gob snapshot| DISK[(disk)]
FE --> REST[REST API JWT auth\nrooms/snippets/rate-limit]
REST --> PG
REST --> RD
WS --> PROM[Prometheus]
PROM --> GRAF[Grafana]
Replicated Growable Array (RGA) from scratch — no Yjs/Automerge.
- Each char is
Item{ID{Site,Seq}, Origin *ID, Value, Deleted}. - Insertion successor determined by deterministic DFS of predecessor tree: siblings with same
Originare sorted byIDdescending (largerSeqfirst, tieSitelex). This yields a total order that is commutative and respects causality. - Deletion = tombstone.
pendingDeletesbuffers deletes whose target hasn't arrived yet (handles out-of-order delivery). - Convergence proof: Order is a pure function of the set
{items}+originpointers. Any two replicas with same set produce identicalorderedIDs()traversal → identicalText(). Tests generate random concurrent edit sequences across 3 simulated peers, shufflingOpdelivery order, and assertText()equality.
Run: make crdt-test or go test ./internal/crdt -run TestConvergenceThreePeersRandom -v
- Reconnect + resync: full
Snapshot{Items,Seq}onjoin+ incrementalopLogcatch-up (TypeResync). SeeTestReconnectAndResync.
| Flag | Attack Prevented |
|---|---|
--network=none |
Egress / SSRF / exfiltration |
--memory=128m |
OOM / fork-bomb memory exhaustion |
--cpus=0.5 |
CPU starvation / infinite loop |
--read-only + --tmpfs /tmp:rw,noexec |
Filesystem write / persistence |
--user nobody (uid 65534) |
Privilege escalation |
--pids-limit 64 |
Fork bomb |
5s timeout + context.WithTimeout |
Hang / infinite loop |
Output capped 64KB |
Log bomb / disk fill |
Image allowlist node:20-alpine, python:3.12-alpine |
Malicious base image |
| Seccomp + AppArmor default | Kernel exploit |
| Pre-warmed pool recycling (min 3) | Container reuse leakage — wiped per run |
Generated in SECURITY.md (Phase 2).
Tokenizer: unicode-aware, lowercase, stopwords (english), Snowball Porter stemming (pure Go).
Inverted index: term → []Posting{docID, positions[], tf} built in internal/search.
BM25: score = Σ IDF * (tf*(k1+1))/(tf+k1*(1-b+b*dl/avgdl)) with k1=1.2,b=0.75, IDF=log((N-df+0.5)/(df+0.5)+1). Implemented without Bleve/Elastic.
Fuzzy: trigram index ("hello" → "hel","ell","llo") + Levenshtein ≤2 for typo tolerance; did you mean via min edit distance candidate.
Autocomplete: Trie with top-K by popularity (snippet view count).
Persistence: gob snapshot on SIGTERM, load on start, incremental RWMutex + atomic pointer swap for rebuild.
Endpoints: GET /search?q=hello&fuzzy=1 (highlights), GET /suggest?q=hel, GET /search/health (OpenTelemetry spans).
Benchmark (synthetic 100K snippets):
p50 ~8ms
p95 ~18ms
p99 ~35ms (placeholder — update after `make bench` Phase 3)
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /api/auth/register |
no | register |
| POST | /api/auth/login |
no | login → JWT |
| POST | /api/auth/refresh |
JWT | refresh |
| GET/POST | /api/rooms |
JWT | list/create |
| GET/PUT/DELETE | /api/rooms/{id} |
JWT+member | room CRUD |
| POST | /api/rooms/{id}/members |
owner | add member |
| GET/POST | /api/snippets |
JWT | list/create |
| GET/PUT/DELETE | /api/snippets/{id} |
JWT | snippet CRUD |
| POST | /api/snippets/{id}/fork |
JWT | fork |
| GET | /search?q= |
no | BM25 search |
| GET | /suggest?q= |
no | autocomplete |
| GET | /search/health |
no | health + OTEL |
| GET | /ws?room_id=&user_id=&site_id= |
JWT/query | WebSocket |
| POST | /run |
JWT | executor |
| GET | /health |
no | ws-server health |
| GET | /metrics |
no | Prometheus |
| GET | /ws/health |
no | hub count |
Rate limiting: Redis token-bucket 100 req/min per IP+user.
# 1. Full stack
docker compose up --build
# 2. Local dev (needs postgres+redis from compose)
make dev # runs ws-server on :8080
make test # race + cover
make bench # p50/p95/p99
make seed # generates 100K synthetic snippets
# Manual WebSocket test
# Connect: ws://localhost:8080/ws?room_id=demo&user_id=alice&site_id=alice-1
# Protocol: {"type":"edit","payload":{"op":{"type":"insert","id":{"site":"alice","seq":1},"value":"a"}}}Env: see .env.example — DATABASE_URL, REDIS_URL, JWT_SECRET.
- ✅ Phase 1: WS Hub (1 goroutine/room + pumps, protocol.go, RGA CRDT
children+DFS, convergence tests 3 peers random + resync) - ✅ Phase 2: Docker executor (
--network=none --memory=128m --cpus=0.5 --read-only --user nobody --pids-limit 645s/64KB, node:20/python:3.12), warm pool min 3/language +cold_start_ms/warm_start_mshistograms, Redis pub/sub streaming,SECURITY.md - ✅ Phase 3: Search from scratch (tokenizer unicode+stopwords+Porter, inverted index, BM25
k1=1.2 b=0.75, trigram+Levenshtein fuzzy + didYouMean, Trie top-K, gob snapshot + atomic swap,/search//suggestOTEL, 100K seed + bench) - ✅ Phase 4: JWT REST (register/login/refresh, rooms/snippet CRUD+fork, rate-limit token-bucket), React Vite+TS CodeMirror 6 (remote cursors + presence avatars + run streaming panel + search highlights +
did you mean), WS hook auto-reconnect+resync, Makefile, Docker multi-stage, docker-compose full
Frontend inspiration only: https://web-2b3c-3000.prg1.zerops.app/ — no code copied. Host ports 8085:8080, 8086:8081, 8087:8082, 3005:80 in this env due to local 8080 conflict; default 8080/8081/8082/3000 via docker compose up.