Something went wrong. Try again.
Demo comparing html-over-the-wire w/ WS and SSE.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802// One server, one session store, one renderer — two wires.//// GET /events text/event-stream (SSE read path)// POST /command application/json (CQRS write path)// WS /ws upgrade (both paths on one socket)//// TLS is on so the browser will negotiate h2 for the page and the SSE stream,// which is the configuration the whole argument is about. The WebSocket// necessarily opens its own HTTP/1.1 connection — browsers don't do RFC 8441 —// and the connection counter makes that visible.
import fs from 'node:fs'import http from 'node:http'import http2 from 'node:http2'import path from 'node:path'import zlib from 'node:zlib'import crypto from 'node:crypto'import { fileURLToPath } from 'node:url'import { WebSocketServer } from 'ws'import { getSession, serverStats, ROW_CAP, SESSION_CAP, MAX_SUBS_PER_SESSION } from './db.js'import { renderChat, renderGrid, renderChatRow } from './render.js'import { log, sessionTag, timer } from './log.js'
// The current view for a session, in whichever workload it is running. Both// transports get this exact string.function renderView(session) { if (session.workload === 'grid') { return renderGrid(session.issues(session.grid), session.grid, session.issueCount()) } return renderChat(session)}
// One command path for both transports and both workloads. Returns the patch// to broadcast, or null if the command was a no-op.function applyCommand(session, cmd, via) { const done = timer() const patch = buildPatch(session, cmd, via) if (patch) { log('command', { via, workload: session.workload, // What kind of interaction, never what the user typed. kind: session.workload === 'grid' ? (cmd.add != null ? 'add' : cmd.sort ? 'sort' : 'filter') : cmd.mode === 'narrow' ? 'append' : 'morph', queryLen: typeof cmd.q === 'string' ? cmd.q.length : undefined, bodyLen: typeof cmd.body === 'string' ? cmd.body.length : undefined, htmlBytes: Buffer.byteLength(patch.html, 'utf8'), renderMs: done(), session: sessionTag(session.id), }) } return patch}
function buildPatch(session, cmd, via) { if (session.workload === 'grid') { if (typeof cmd.add === 'string') { const title = cmd.add.trim().slice(0, 120) if (!title) return null session.addIssue(title) } if (typeof cmd.q === 'string') session.grid.q = cmd.q.slice(0, 60) if (cmd.sort) session.grid.sort = String(cmd.sort).slice(0, 20) if (cmd.dir) session.grid.dir = cmd.dir === 'desc' ? 'desc' : 'asc' // Always the whole table. That is the workload. return { target: 'morph', html: renderView(session) } } const text = String(cmd.body ?? '').slice(0, 400) if (!text.trim()) return null const row = session.append(via, text) return cmd.mode === 'narrow' ? { target: 'append', html: renderChatRow(row) } : { target: 'morph', html: renderView(session) }}
const __dirname = path.dirname(fileURLToPath(import.meta.url))const PUB = path.join(__dirname, 'public')
// TLS is opt-in. It buys HTTP/2 for the page, the SSE stream and the command// POSTs — but with a self-signed cert, browsers frequently refuse the wss://// upgrade even after you accept the interstitial for https:// (Safari always// does), which silently breaks half the demo. Plain HTTP costs us the h2// multiplexing story and nothing else: the compression divergence, which is// the actual headline, is identical on HTTP/1.1.const USE_TLS = process.argv.includes('--tls')// 8080 is claimed by a macOS system service on some machines; 8088 is quieter.const PORT = Number(process.env.PORT ?? (USE_TLS ? 8443 : 8088))// Behind a platform proxy (exe.dev, nginx, …) bind loopback only. Locally,// leaving this unset listens on all interfaces so phones on the LAN can QA.const HOST = process.env.HOST ?? undefined
let tcpConnections = 0let wsConnections = 0let openStreams = 0 // live SSE responses + WebSockets
const MAX_BODY = 8 * 1024// Each open SSE stream holds a brotli context — measured at ~900 KB of RSS per// connection in bench/compress-memory.js. That, not the SQLite rows, is what// actually bounds this box, so the connection cap is the load-bearing limit.const MAX_STREAMS = 250const MAX_WS_PAYLOAD = 16 * 1024
// ─────────────────────────────────────────────────── byte accounting helpers
// permessage-deflate is DEFLATE with context takeover and the 4-byte// Z_SYNC_FLUSH tail removed. We mirror `ws`'s exact settings so the counter// reports what the socket really carried, without re-implementing the send.class DeflateMirror { constructor() { this.z = zlib.createDeflateRaw({ level: 6, windowBits: 15 }) this.acc = 0 this.z.on('data', (c) => (this.acc += c.length)) this.z.on('error', () => {}) } async size(buf) { const before = this.acc this.z.write(buf) await new Promise((res) => this.z.flush(zlib.constants.Z_SYNC_FLUSH, res)) return Math.max(0, this.acc - before - 4) // strip the sync-flush tail } end() { try { this.z.end() } catch {} }}
// A WebSocket frame from a server is unmasked: 2 bytes, plus extended length.function wsFrameOverhead(len) { if (len < 126) return 2 if (len < 65536) return 4 return 10}
// `sink` returns the number of bytes it accounted for (payload + framing), so// write() can report the exact marginal cost of one patch. zlib's flush is// asynchronous, so this has to be awaited — a synchronous delta reads zero.function makeCompressor(kind, sink) { let out = 0 const tap = (chunk) => { out += sink(chunk) || 0 } if (kind === 'none') { return { async write(b) { const before = out tap(b) return out - before }, end() {}, } } const z = kind === 'br' ? zlib.createBrotliCompress({ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_LGWIN]: 22, [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, }, }) : zlib.createGzip({ level: 6 }) z.on('data', tap) z.on('error', () => {}) const FLUSH = kind === 'br' ? zlib.constants.BROTLI_OPERATION_FLUSH : zlib.constants.Z_SYNC_FLUSH return { async write(b) { const before = out z.write(b) await new Promise((res) => z.flush(FLUSH, res)) return out - before }, end() { try { z.end() } catch {} }, }}
const sseEvent = (html, id, target) => `event: patch\nid: ${id}\ndata: ${target}\ndata: ${html}\n\n`
const wsMessage = (html, id, target) => JSON.stringify({ t: 'patch', id, target, html })
// ──────────────────────────────────────────────────────────────── broadcast
async function broadcast(session, patch) { const fanoutTimer = timer() const raw = Buffer.byteLength(patch.html, 'utf8') const id = ++session.seq await Promise.all( [...session.subs].map(async (sub) => { try { await sub.send(patch, id, raw) } catch {} }), ) // Push after the sends, so lastPatch reflects this patch on both sides. pushMetrics(session) log('broadcast', { fanout: session.subs.size, watchers: session.watchers.size, htmlBytes: raw, wsWire: session.metrics.ws.lastPatch || undefined, sseWire: session.metrics.sse.lastPatch || undefined, totalMs: fanoutTimer(), session: sessionTag(session.id), })}
// ──────────────────────────────────────────────────────────────── SSE route
function handleEvents(req, res, session, compression, workload) { session.workload = workload if (openStreams >= MAX_STREAMS || !session.canSubscribe()) { log('reject', { reason: 'capacity', transport: 'sse', openStreams, subs: session.subs.size }, 'WARN') res.writeHead(503, { 'content-type': 'text/plain', 'retry-after': '30' }) return res.end('at capacity') } openStreams++ const liveSince = timer()
const m = session.metrics.sse m.connects++ m.open++
const headers = { 'content-type': 'text/event-stream', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no', } if (compression !== 'none') headers['content-encoding'] = compression res.writeHead(200, headers) res.flushHeaders?.()
// h2 DATA frame header is 9 bytes; h1 chunked framing is the hex length plus // two CRLFs. Counted so "wire bytes" means wire bytes. const isH2 = req.httpVersionMajor === 2 const framing = (n) => (isH2 ? 9 : n.toString(16).length + 4)
const comp = makeCompressor(compression, (chunk) => { const n = chunk.length + framing(chunk.length) m.wireDown += n if (!res.destroyed && res.writable) res.write(chunk) return n })
const sub = { transport: 'sse', protocol: isH2 ? 'h2' : 'http/1.1', async send(patch, id, raw) { m.patches++ m.rawDown += raw const done = timer() m.lastPatch = await comp.write(Buffer.from(sseEvent(patch.html, id, patch.target), 'utf8')) m.lastRaw = raw log('patch', { transport: 'sse', protocol: sub.protocol, compression, htmlBytes: raw, wireBytes: m.lastPatch, ratio: +(raw / Math.max(1, m.lastPatch)).toFixed(1), compressMs: done(), session: sessionTag(session.id), }) }, close() { try { res.end() } catch {} }, } session.subs.add(sub) session.sseProtocol = sub.protocol
// Initial render, counted like any other patch. const initial = renderView(session) m.patches++ m.rawDown += Buffer.byteLength(initial, 'utf8') comp.write(Buffer.from(sseEvent(initial, ++session.seq, 'morph'), 'utf8'))
// Keep-alive comments cost bytes too — count them honestly. const ka = setInterval(() => comp.write(Buffer.from(': ka\n\n', 'utf8')), 25000)
log('conn.open', { transport: 'sse', protocol: isH2 ? 'h2' : 'http/1.1', compression, workload, session: sessionTag(session.id), })
let closed = false const done = () => { if (closed) return closed = true clearInterval(ka) session.subs.delete(sub) comp.end() openStreams = Math.max(0, openStreams - 1) log('conn.close', { transport: 'sse', liveMs: liveSince(), patches: m.patches, wireDown: m.wireDown, session: sessionTag(session.id), }) m.open = Math.max(0, m.open - 1) m.disconnects++ } res.on('close', done) res.on('error', done)}
// ─────────────────────────────────────────────────────────── command route
async function handleCommand(req, res, session) { // Bounded read. Without a cap, one request can grow this string until the // process dies — a command is a few hundred bytes, so 8 KiB is generous. const body = await new Promise((resolve) => { let buf = '' let over = false req.on('data', (c) => { // Once over the limit we stop appending, so memory stays bounded even // if the client keeps streaming. Tearing the socket down here instead // would race the response and the client would see a reset, not a 413. if (over) return buf += c if (buf.length > MAX_BODY) { over = true resolve(null) } }) req.on('end', () => !over && resolve(buf)) req.on('error', () => !over && resolve(null)) }) if (body === null) { log('reject', { reason: 'body-too-large', limit: MAX_BODY }, 'WARN') if (!res.headersSent) res.writeHead(413, { 'content-type': 'text/plain' }) res.end('command body too large', () => { try { req.destroy() } catch {} }) return }
if (!session.takeToken()) { log('reject', { reason: 'rate-limit', transport: 'sse', session: sessionTag(session.id) }, 'WARN') res.writeHead(429, { 'retry-after': '1' }) return res.end() }
let cmd try { cmd = JSON.parse(body || '{}') } catch { res.writeHead(400) return res.end() }
const m = session.metrics.sse m.commands++ // Request line + HPACK-compressed headers on a warm h2 connection, plus the // JSON body. The header estimate is the honest part of the CQRS overhead. m.wireUp += Buffer.byteLength(body, 'utf8') + (req.httpVersionMajor === 2 ? 33 : 190)
const patch = applyCommand(session, cmd, 'sse') if (patch) await broadcast(session, patch)
res.writeHead(204) res.end()}
function metricsPayload(session) { return { ws: session.metrics.ws, sse: session.metrics.sse, db: session.stats(), server: { ...serverStats(), tcpConnections, wsConnections, openStreams, protocol: session.sseProtocol, }, limits: { rowCap: ROW_CAP, sessionCap: SESSION_CAP, maxStreams: MAX_STREAMS, maxSubsPerSession: MAX_SUBS_PER_SESSION, }, }}
// Metrics ride their own SSE stream. Polling a dashboard that exists to argue// for SSE would be a poor look, but the real reason is fidelity: at a 600 ms// poll the client only ever samples the LAST patch, so bursts are lost. Pushed,// every patch produces exactly one sample and the chart records rather than// samples. Watchers are kept out of `session.subs` so they never receive// patches and never inflate the numbers they report.function pushMetrics(session) { if (!session.watchers.size) return const frame = `event: metrics\ndata: ${JSON.stringify(metricsPayload(session))}\n\n` for (const w of session.watchers) { try { w.write(frame) } catch {} }}
function handleMetricsStream(req, res, session) { if (openStreams >= MAX_STREAMS || session.watchers.size >= 4) { res.writeHead(503, { 'retry-after': '30' }) return res.end() } openStreams++ // Identity encoding on purpose: these payloads are small, and a brotli // context here would cost ~900 KB of RSS per viewer for nothing. res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no', }) res.flushHeaders?.()
const w = { write: (t) => { if (!res.destroyed && res.writable) res.write(t) }, close: () => { try { res.end() } catch {} }, } session.watchers.add(w) w.write(`event: metrics\ndata: ${JSON.stringify(metricsPayload(session))}\n\n`)
// Server-level stats (sessions, streams, db size) drift without any patch // happening, so keep a slow heartbeat under the push. const hb = setInterval(() => pushMetrics(session), 2000) let closed = false const done = () => { if (closed) return closed = true clearInterval(hb) session.watchers.delete(w) openStreams = Math.max(0, openStreams - 1) } res.on('close', done) res.on('error', done)}
// ────────────────────────────────────────────────────────────── static files
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript' }
function serveStatic(res, file) { const p = path.join(PUB, file) if (!p.startsWith(PUB) || !fs.existsSync(p)) { res.writeHead(404) return res.end('not found') } const buf = fs.readFileSync(p) res.writeHead(200, { 'content-type': MIME[path.extname(p)] ?? 'application/octet-stream', 'cache-control': 'no-cache', }) res.end(buf)}
// ──────────────────────────────────────────────────────────────────── server
const server = USE_TLS ? http2.createSecureServer({ key: fs.readFileSync(path.join(__dirname, '../certs/key.pem')), cert: fs.readFileSync(path.join(__dirname, '../certs/cert.pem')), allowHTTP1: true, ALPNProtocols: ['h2', 'http/1.1'], settings: { maxConcurrentStreams: 200 }, }) : http.createServer()
server.on('connection', () => tcpConnections++)server.on('secureConnection', () => {})
// Session cookies are signed with a per-process key. Without this the sid is// whatever the client says it is, so anyone setting `Cookie: sid=test` joins// (and can write into) the session of everyone else who picked the same value.// The key is ephemeral by design: restarting the server invalidates old// sessions, which is the right lifetime for an in-memory demo.const SID_KEY = crypto.randomBytes(32)const sign = (id) => crypto.createHmac('sha256', SID_KEY).update(id).digest('base64url').slice(0, 16)
function parseSid(cookie) { const m = cookie.match(/(?:^|;\s*)sid=([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)/) if (!m) return null const [, id, mac] = m const expected = Buffer.from(sign(id)) const got = Buffer.from(mac) // Length check first: timingSafeEqual throws on a length mismatch. if (got.length !== expected.length || !crypto.timingSafeEqual(got, expected)) return null return `${id}.${mac}`}
function sidFrom(req, res) { const existing = parseSid(req.headers.cookie ?? '') if (existing) return existing const id = crypto.randomBytes(9).toString('base64url') const sid = `${id}.${sign(id)}` // No `Secure` — the demo may run over plain HTTP. HttpOnly regardless: // nothing client-side needs to read it. res.setHeader?.('set-cookie', `sid=${sid}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400`) return sid}
server.on('request', async (req, res) => { const url = new URL(req.url, 'http://localhost') const p = url.pathname
// The HTML entry points mint the session cookie, so a pane always has one // before it opens a socket. Static assets below stay cookie-free. if (p === '/' || p === '/pane') { sidFrom(req, res) return serveStatic(res, p === '/' ? 'shell.html' : 'pane.html') } if (p === '/app.css') return serveStatic(res, 'app.css') if (p === '/shell.css') return serveStatic(res, 'shell.css') if (p === '/pane.js') return serveStatic(res, 'pane.js') if (p === '/shell.js') return serveStatic(res, 'shell.js') if (p === '/idiomorph.js') return serveStatic(res, 'idiomorph.js') if (p === '/favicon.ico') { res.writeHead(204) return res.end() }
const sid = sidFrom(req, res) const session = getSession(sid) if (!session) { res.writeHead(503, { 'content-type': 'text/plain', 'retry-after': '60' }) return res.end('server is holding its maximum number of sessions') }
if (p === '/events') { const c = url.searchParams.get('c') ?? 'br' const w = url.searchParams.get('w') === 'grid' ? 'grid' : 'chat' return handleEvents(req, res, session, ['br', 'gzip', 'none'].includes(c) ? c : 'br', w) } if (p === '/command' && req.method === 'POST') return handleCommand(req, res, session)
// The number no server-side counter can see: submit -> patch painted, as // measured in the browser. Bounded and rate-limited like any other write. if (p === '/telemetry' && req.method === 'POST') { let body = '' let over = false req.on('data', (c) => { if (over) return body += c if (body.length > 1024) over = true }) await new Promise((r) => req.on('end', r)) if (!over && session.takeToken()) { try { const t = JSON.parse(body || '{}') log('rtt', { transport: t.t === 'ws' ? 'ws' : 'sse', workload: String(t.w ?? '').slice(0, 8), p50Ms: Number(t.p50) || undefined, lastMs: Number(t.last) || undefined, samples: Number(t.n) || undefined, session: sessionTag(session.id), }) } catch {} } res.writeHead(204) return res.end() }
if (p === '/metrics/stream') return handleMetricsStream(req, res, session)
if (p === '/metrics') { res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-cache' }) return res.end(JSON.stringify(metricsPayload(session))) }
// The divergence only appears once the document outgrows DEFLATE's window, // which is ~150 messages of typing. Seed the log server-side and send ONE // patch, so the metrics reflect the interesting regime immediately. if (p === '/seed') { // Top the log UP TO the cap rather than always appending a fixed batch. // Repeatedly appending 170 rows to a 300-row-capped log replaces most of // the content each time, so every other patch compresses cold — which // showed up as a sawtooth in the chart that was an artifact of this // button, not of either transport. Once full, this is a no-op. const room = ROW_CAP - session.stats().rows if (room <= 0) { res.writeHead(204) return res.end() } const n = Math.min(room, Math.max(1, Number(url.searchParams.get('n') ?? ROW_CAP))) const words = ['shipped', 'the', 'morph', 'patch', 'over', 'the', 'wire', 'again', 'today', 'nicely'] for (let i = 0; i < n; i++) { const len = 6 + (i % 7) const text = Array.from({ length: len }, (_, k) => words[(i + k) % words.length]).join(' ') session.append(i % 2 ? 'ws' : 'sse', `${text} (#${i + 1})`) } await broadcast(session, { target: 'morph', html: renderView(session) }) // That first patch is measured with a COLD dictionary — neither codec has // seen a document this size before, so it reads ~1x and looks like nothing // happened. Send a second so the panes settle on the steady-state cost. session.append('sse', 'log filled — this patch shows steady-state cost') await broadcast(session, { target: 'morph', html: renderView(session) }) res.writeHead(204) return res.end() }
if (p === '/reset') { session.db.exec('DELETE FROM msg') for (const k of ['ws', 'sse']) { const m = session.metrics[k] for (const f of ['patches', 'commands', 'rawDown', 'wireDown', 'wireUp']) m[f] = 0 } await broadcast(session, { target: 'morph', html: renderView(session) }) res.writeHead(204) return res.end() }
res.writeHead(404) res.end('not found')})
// ───────────────────────────────────────────────────────────────── WebSocket
const wss = new WebSocketServer({ server, path: '/ws', // Reject at the handshake, so an unauthenticated upgrade never gets a 101. verifyClient: ({ req }, done) => parseSid(req.headers.cookie ?? '') ? done(true) : done(false, 401, 'no session'), // `ws` defaults to a 100 MB frame limit; a command is a few hundred bytes. maxPayload: MAX_WS_PAYLOAD, perMessageDeflate: { zlibDeflateOptions: { level: 6, windowBits: 15 }, serverNoContextTakeover: false, clientNoContextTakeover: false, threshold: 0, },})
wss.on('connection', (socket, req) => { const url = new URL(req.url, 'http://localhost') const compress = url.searchParams.get('c') !== 'none' // verifyClient already rejected cookieless upgrades; a shared 'anon' bucket // used to put strangers into one another's session. const session = getSession(parseSid(req.headers.cookie ?? '')) // 1013 = "try again later". Same gates the SSE path enforces. if (!session || openStreams >= MAX_STREAMS || !session.canSubscribe()) { log('reject', { reason: session ? 'capacity' : 'no-session', transport: 'ws', openStreams }, 'WARN') try { socket.close(1013, 'at capacity') } catch {} return } openStreams++ const liveSince = timer()
const m = session.metrics.ws m.connects++ m.open++ wsConnections++
const mirror = compress ? new DeflateMirror() : null
const sub = { transport: 'ws', async send(patch, id, raw) { const msg = wsMessage(patch.html, id, patch.target) const bytes = Buffer.byteLength(msg, 'utf8') const done = timer() const payload = mirror ? await mirror.size(Buffer.from(msg, 'utf8')) : bytes m.patches++ m.rawDown += raw m.lastPatch = payload + wsFrameOverhead(payload) m.lastRaw = raw m.wireDown += m.lastPatch socket.send(msg) log('patch', { transport: 'ws', protocol: 'http/1.1', compression: mirror ? 'deflate' : 'none', htmlBytes: raw, wireBytes: m.lastPatch, ratio: +(raw / Math.max(1, m.lastPatch)).toFixed(1), compressMs: done(), session: sessionTag(session.id), }) }, close() { try { socket.close() } catch {} }, } session.subs.add(sub)
session.workload = url.searchParams.get('w') === 'grid' ? 'grid' : 'chat' const initial = renderView(session) sub.send({ target: 'morph', html: initial }, ++session.seq, Buffer.byteLength(initial, 'utf8'))
socket.on('message', async (data) => { let cmd try { cmd = JSON.parse(data) } catch { return } if (cmd.t !== 'cmd') return if (!session.takeToken()) { log('reject', { reason: 'rate-limit', transport: 'ws', session: sessionTag(session.id) }, 'WARN') return }
m.commands++ // Client frames are masked: +4 bytes over the server-side overhead. const up = Buffer.byteLength(String(data), 'utf8') m.wireUp += up + wsFrameOverhead(up) + 4
const patch = applyCommand(session, cmd, 'ws') if (patch) await broadcast(session, patch) })
log('conn.open', { transport: 'ws', protocol: 'http/1.1', compression: compress ? 'deflate' : 'none', workload: session.workload, session: sessionTag(session.id), })
let closed = false const done = () => { if (closed) return closed = true session.subs.delete(sub) mirror?.end() openStreams = Math.max(0, openStreams - 1) log('conn.close', { transport: 'ws', liveMs: liveSince(), patches: m.patches, wireDown: m.wireDown, session: sessionTag(session.id), }) m.open = Math.max(0, m.open - 1) m.disconnects++ } socket.on('close', done) socket.on('error', done)})
// A heartbeat of what the box is actually doing, so slow periods can be// correlated with memory and connection pressure after the fact.let cpuBase = process.cpuUsage()let cpuAt = Date.now()setInterval(() => { const mem = process.memoryUsage() const cpu = process.cpuUsage(cpuBase) const elapsed = Date.now() - cpuAt cpuBase = process.cpuUsage() cpuAt = Date.now() const st = serverStats() log('runtime', { rssMb: +(mem.rss / 1048576).toFixed(1), heapMb: +(mem.heapUsed / 1048576).toFixed(1), cpuPct: +(((cpu.user + cpu.system) / 1000 / Math.max(1, elapsed)) * 100).toFixed(1), openStreams, sessions: st.sessions, sqliteKb: +(st.bytes / 1024).toFixed(0), tcpConnections, })}, 30000).unref()
server.listen(PORT, HOST, () => { console.log(`\n transport bake-off demo`) console.log(` ${USE_TLS ? 'https' : 'http'}://${HOST ?? 'localhost'}:${PORT}\n`) if (USE_TLS) { console.log(` TLS on — page, SSE and POSTs negotiate HTTP/2.`) console.log(` Self-signed cert: accept the warning. If the WS pane stays`) console.log(` disconnected, your browser is refusing wss:// on an untrusted`) console.log(` cert — rerun without --tls.\n`) } else { console.log(` Plain HTTP/1.1 — no cert friction, both wires work everywhere.`) console.log(` Pass --tls to run the page and SSE over HTTP/2 instead.\n`) } console.log(` Session DB: in-memory SQLite, ${ROW_CAP} rows max, ${SESSION_CAP} sessions max.\n`)})