Files
loki/bridge/README.md
T
Mao NakamotoandClaude Opus 4.7 e3541e2374 feat(v0.6): Phase A — event bus foundation (Postgres NOTIFY → SSE bridge)
The end-to-end push pipeline that replaces /api/control polling. This
commit ships the foundation; phases B-E light it up across the web,
desktop, and daemon. Read the architectural narrative in
/thoughts/from-polling-to-listening-fleetcrown-v0-6.

drizzle/0022_notify_triggers.sql
  - Generic fc_emit_change() plpgsql function: receives (user_col,
    key_col) via TG_ARGV, emits NOTIFY 'fc:state' with a compact
    {t, u, k, op, ts} JSON payload. IDs only — no row content — so
    the bus stays under Postgres's 8 KB NOTIFY limit even on bursts.
  - AFTER INSERT/UPDATE/DELETE triggers on the five UI-relevant
    tables: project_states, runtime_snapshots, pending_commands,
    orchestration_runs, beacon_settings.
  - Adding more tables in the future is two lines: drop + create
    trigger pointing at the same fc_emit_change function.

bridge/  (new ~300-line Node service)
  - src/server.ts — HTTP server with /sse (SSE endpoint, ?token=ck_*
    auth, Last-Event-ID replay) and /healthz. CORS open; the bridge
    sits on a different origin than Vercel and the desktop app.
  - src/listen.ts — single dedicated pg Client running LISTEN
    "fc:state" forever, with exponential-backoff reconnect on
    disconnect. Notifications fan out to subscriptions.
  - src/subscriptions.ts — in-memory Map<userId, Set<connection>>.
    Per-user routing; fanout writes SSE frames; idempotent remove
    on disconnect.
  - src/auth.ts — validates ck_* tokens against agent_tokens using
    the same plaintext lookup the cloud API uses (mirrors src/db/
    queries/agent-tokens.ts validateAgentToken).
  - src/types.ts — ChangeEvent and Subscription shapes.
  - In-memory ring buffer (1000 events) for Last-Event-ID replay so
    a brief disconnect doesn't drop state.
  - Heartbeat (SSE comment) every 25s to keep proxies happy.
  - Graceful SIGINT/SIGTERM shutdown with 5s hard-fail timeout.
  - .env.example, .gitignore, README with the Oracle systemd deploy
    runbook.

next.config.ts
  - Exclude ./bridge/** from output: standalone tracing. Same lesson
    as ./desktop/** — bridge has its own node_modules and is
    deployed separately. Don't let Vercel bundle it into every
    serverless function.

Verified end-to-end locally:
  - psql UPDATE on project_states → fc_emit_change fires →
    pg_notify reaches the bridge's LISTEN client → fanout to the
    subscribed curl SSE connection in ~milliseconds.
  - Per-user routing: a token bound to user A only receives events
    for user A's rows; tested by minting under two different users.
  - Last-Event-ID replay: reconnect with header skips already-
    delivered events, then live events arrive immediately.

Next: Phase B (web client subscribes to the bridge instead of polling
/api/control). Phases C-E follow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 10:59:06 +02:00

132 lines
5.2 KiB
Markdown

# FleetCrown event bridge
A ~300-line Node service that takes Postgres `NOTIFY` events on the `fc:state`
channel and fans them out to subscribed browsers, desktop apps, and phones
over Server-Sent Events. The piece that lets v0.6 replace polling with push.
## What runs where
```
┌───────────────────┐
│ this service │
Browser ─────── /sse?token=ck_* ──────┤ (bridge/) │
│ │
Fleet Runner ── /sse?token=ck_* ──────┤ one HTTP+SSE │
│ server, one │
│ pg LISTEN │
│ │
└────────┬──────────┘
│ LISTEN "fc:state"
↓
┌───────────────────┐
│ Postgres │
│ triggers in │
│ drizzle/0022 │
└───────────────────┘
↑
│ INSERT/UPDATE/DELETE
┌────────┴──────────┐
│ Vercel API │
│ /api/control, │
│ /api/control/ │
│ runtime-state, │
│ etc. │
└───────────────────┘
```
Read the architectural narrative in
[/thoughts/from-polling-to-listening-fleetcrown-v0-6](../content/thoughts/from-polling-to-listening-fleetcrown-v0-6.md)
for the why.
## Run locally
```bash
cd bridge
cp .env.example .env
# edit .env — point DATABASE_URL at the same db that has the v0.6 triggers
npm install
npm run dev # tsx — fast iteration
# or
npm run build && npm start
```
Health: `curl http://localhost:4001/healthz` → `{ok:true, users, connections, eventLogSize}`
SSE: `curl -N "http://localhost:4001/sse?token=ck_..."` (replace with a real
ck_* token from your `agent_tokens` table). Watch as `event: change`
frames arrive whenever a row owned by that user changes.
## Auth model
Tokens are looked up in the same `agent_tokens` table the cloud API uses.
Plaintext lookup (matches the existing scheme; see `src/db/queries/agent-tokens.ts`).
The token is passed as `?token=ck_...` in the SSE URL because EventSource
does not let JavaScript set custom request headers. Mitigated by HTTPS-only
deploy + scrubbing query strings from access logs.
## Last-Event-ID replay
Clients that disconnect briefly (sleep, wifi drop, deploy) reconnect with
`Last-Event-ID: <last_id>` in their headers. The bridge replays any
buffered events with a higher id, filtered to the user's scope. Buffer
size is 1000 events — anything older requires a full re-fetch from the
cloud snapshot endpoint.
## Deploy (Oracle / Hetzner)
The bridge lives on the same box as Postgres. Both processes plus a small
backup cron fit comfortably on Oracle Always Free or a Hetzner CX22.
See `scripts/db/SETUP_ORACLE_FREE.md` and `scripts/db/BOTH_PRODUCTS_ONE_HOST.md`
for the host setup. Once Postgres is up:
```bash
# On the box
git clone git@github.com:maonakamoto/fleetcrown.git /opt/fleetcrown
cd /opt/fleetcrown/bridge
npm ci
npm run build
# /etc/systemd/system/fleetcrown-bridge.service
sudo tee /etc/systemd/system/fleetcrown-bridge.service <<'UNIT'
[Unit]
Description=FleetCrown event bridge (Postgres LISTEN → SSE)
After=postgresql.service network-online.target
Wants=network-online.target
[Service]
Type=simple
User=fleetcrown
WorkingDirectory=/opt/fleetcrown/bridge
EnvironmentFile=/opt/fleetcrown/bridge/.env
ExecStart=/usr/bin/node /opt/fleetcrown/bridge/dist/server.js
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
UNIT
sudo systemctl daemon-reload
sudo systemctl enable --now fleetcrown-bridge
sudo journalctl -u fleetcrown-bridge -f
```
Then reverse-proxy 443 → 4001 via nginx/caddy with a TLS cert. Point Vercel
env `FLEETCROWN_BRIDGE_URL` at `https://your-host/sse` and the web client
will subscribe instead of polling.
## Connection limits
Default Linux file descriptor limit (1024) caps connections per process.
Bump in the systemd unit before going to scale:
```
[Service]
LimitNOFILE=65536
```
One process easily handles ~50,000 concurrent SSE connections on the
Oracle Free shape (4 OCPU / 24 GB). Past that, run multiple bridge
processes behind a load balancer; they share state via the Postgres
LISTEN channel automatically (NOTIFY fans out to every LISTEN'er).