Skip to content
Nirvanjha2004Public

About

CodeMesh — Real-Time Collaborative Code Playground + Search Engine (Go, RGA CRDT, Docker sandbox, BM25)

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CodeMesh — Real-Time Collaborative Code Playground + Search Engine

Hero GIF placeholder — Phase 4 will add live demo hero

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


Architecture

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]
Loading

CRDT Convergence

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 Origin are sorted by ID descending (larger Seq first, tie Site lex). This yields a total order that is commutative and respects causality.
  • Deletion = tombstone. pendingDeletes buffers deletes whose target hasn't arrived yet (handles out-of-order delivery).
  • Convergence proof: Order is a pure function of the set {items} + origin pointers. Any two replicas with same set produce identical orderedIDs() traversal → identical Text(). Tests generate random concurrent edit sequences across 3 simulated peers, shuffling Op delivery order, and assert Text() equality.

Run: make crdt-test or go test ./internal/crdt -run TestConvergenceThreePeersRandom -v

  • Reconnect + resync: full Snapshot{Items,Seq} on join + incremental opLog catch-up (TypeResync). See TestReconnectAndResync.

Sandbox Security Checklist

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).


Search Engine — BM25 from scratch

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)

API Endpoints

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.


Run Instructions

# 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.


Project Status

  • ✅ 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 64 5s/64KB, node:20/python:3.12), warm pool min 3/language + cold_start_ms/warm_start_ms histograms, 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//suggest OTEL, 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.

About

CodeMesh — Real-Time Collaborative Code Playground + Search Engine (Go, RGA CRDT, Docker sandbox, BM25)

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages