Something went wrong. Try again.
The IoT platform Cloudflare didn't build. Telemetry, realtime dashboards, and automations on Workers + D1 + R2 + Durable Objects — in your… nodrix.live
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311import { DurableObject } from 'cloudflare:workers';import type { Env } from '../../env';import { projectStub } from './stubs';import { validateLayout, variablesFromLayout, chartVariablesFromLayout, type Layout } from '../lib/layout';import { newId } from '../lib/ids';import { userCanAccessProject } from '../lib/roles';import type { CompactSeries } from '../lib/series';
// Cap on points per chart series in the bootstrap snapshot (mirrors the public// /state full snapshot). Dense ingest is stride-sampled to this.const SNAPSHOT_SERIES_CAP = 300;
// Dashboard Durable Object (one per dashboard id). MUST use WebSocket Hibernation// (acceptWebSocket) — without it, idle tabs pin the DO in memory. First socket// subscribes to the owning Project DO; notifies broadcast to all live sockets;// last close unsubscribes.
type Snapshot = { type: 'snapshot'; dashboard: string; layout: Layout; variables: Record<string, { value: unknown; received_at: number }>; series: CompactSeries;};
type UpdatesMsg = { type: 'updates'; ts: number; points: Array<{ variable: string; value: unknown }>;};
type DeltaMsg = { type: 'delta'; dashboard: string; variables: Record<string, { value: unknown; received_at: number }>; series: CompactSeries;};
type AckMsg = { type: 'ack'; req: string; ok: boolean; reason?: string };
type ClientMsg = | { type: 'control'; req?: string; variable: string; value?: unknown };
type ViewerAttachment = { userId: string; sessionId: string; checkedAt: number };const REAUTH_INTERVAL_MS = 60_000;
export class DashboardDO extends DurableObject<Env> { private sql: SqlStorage;
constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; this.initSchema(); }
override async fetch(request: Request): Promise<Response> { const upgrade = request.headers.get('upgrade'); if (upgrade !== 'websocket') { return new Response('expected websocket', { status: 400 }); }
const pair = new WebSocketPair(); const client = pair[0]; const server = pair[1];
// Hibernation: this is the line that makes idle tabs cheap. this.ctx.acceptWebSocket(server);
// Stash the authenticated user + session (set by the WS route after auth) so // the socket can be re-authorized against current access while it stays open. const uid = request.headers.get('x-nodrix-uid'); const sid = request.headers.get('x-nodrix-sid'); if (uid && sid) server.serializeAttachment({ userId: uid, sessionId: sid, checkedAt: Date.now() } satisfies ViewerAttachment);
// Reconnecting clients pass ?since=<last applied ts> to resume with a delta. const rawSince = new URL(request.url).searchParams.get('since'); const since = rawSince != null && Number.isFinite(Number(rawSince)) ? Number(rawSince) : null;
// Bootstrap (load layout, subscribe, send snapshot/delta) runs in parallel with // the handshake completing. Any send is queued until the client is ready. this.ctx.waitUntil(this.bootstrapConnection(server, since));
return new Response(null, { status: 101, webSocket: client }); }
// Called by the admin DELETE handlers. Tells the subscribed Project DO to stop // pushing, then wipes our own storage. Open WebSockets get dropped on // storage.deleteAll() — clients will reconnect and fail with 404. async destroy(): Promise<void> { await this.unsubscribe(); await this.ctx.storage.deleteAll(); }
// One `updates` frame per socket carries the whole batch (not one frame per point). // Viewers are re-authorized at most once a minute; revoked ones are closed. async notifyBatch(points: Array<{ variable: string; value: unknown }>, ts: number): Promise<void> { const sockets = this.ctx.getWebSockets(); if (sockets.length === 0 || points.length === 0) return; const json = JSON.stringify({ type: 'updates', ts, points } satisfies UpdatesMsg); const allowed = await Promise.all(sockets.map((ws) => this.viewerAllowed(ws, REAUTH_INTERVAL_MS))); sockets.forEach((ws, i) => { try { if (allowed[i]) ws.send(json); else ws.close(1008, 'access revoked'); } catch { // Dead socket; will be cleaned up on webSocketClose. } }); }
// True while the socket's user still reaches the dashboard's project through // a live session. Cached per socket for maxAgeMs. private async viewerAllowed(ws: WebSocket, maxAgeMs: number): Promise<boolean> { const att = ws.deserializeAttachment() as ViewerAttachment | null; if (!att?.userId || !att.sessionId) return false; if (Date.now() - att.checkedAt < maxAgeMs) return true; const row = await this.env.DB .prepare( `SELECT d.project_id, s.id AS session_id FROM dashboards d LEFT JOIN sessions s ON s.id = ? AND s.user_id = ? WHERE d.id = ?` ) .bind(att.sessionId, att.userId, this.dashboardId()) .first<{ project_id: string; session_id: string | null }>(); const ok = !!row?.session_id && (await userCanAccessProject(this.env, att.userId, row.project_id)); if (ok) ws.serializeAttachment({ ...att, checkedAt: Date.now() }); return ok; }
override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> { if (typeof message !== 'string') return; // ignore binary in v1
let parsed: ClientMsg; try { parsed = JSON.parse(message) as ClientMsg; } catch { return; }
if (parsed.type === 'control') { await this.handleControl(ws, parsed); } }
override async webSocketClose(_ws: WebSocket, _code: number, _reason: string, _wasClean: boolean): Promise<void> { if (this.ctx.getWebSockets().length === 0) { await this.unsubscribe(); } }
override async webSocketError(_ws: WebSocket, _error: unknown): Promise<void> { if (this.ctx.getWebSockets().length === 0) { await this.unsubscribe(); } }
private dashboardId(): string { return this.ctx.id.name ?? this.ctx.id.toString(); }
private async bootstrapConnection(ws: WebSocket, since: number | null): Promise<void> { const dashId = this.dashboardId(); const row = await this.env.DB .prepare(`SELECT id, project_id, layout FROM dashboards WHERE id = ?`) .bind(dashId) .first<{ id: string; project_id: string; layout: string }>();
if (!row) { try { ws.send(JSON.stringify({ type: 'error', reason: 'dashboard_not_found' })); ws.close(1011, 'dashboard_not_found'); } catch {} return; }
let layout: Layout; try { const parsed = JSON.parse(row.layout) as unknown; const v = validateLayout(parsed); if (!v.ok) { ws.send(JSON.stringify({ type: 'error', reason: 'invalid_layout' })); ws.close(1011, 'invalid_layout'); return; } layout = v.value; } catch { ws.send(JSON.stringify({ type: 'error', reason: 'invalid_layout' })); ws.close(1011, 'invalid_layout'); return; }
// Subscribe the one Project DO that owns this dashboard. await this.subscribe(row.project_id).catch(() => undefined);
const stub = projectStub(this.env, row.project_id);
// Only ship what this dashboard renders: latest state for referenced // variables + 1h series for chart variables (not the whole project history). const shownVars = new Set(variablesFromLayout(layout)); const chartVars = chartVariablesFromLayout(layout);
// A `since` cursor only earns a delta if still within the ring's 1h window; // for a delta, fetch from the cursor without stride-sampling so no point drops. const now = Math.floor(Date.now() / 1000); const sinceTs: number | null = since != null && since >= now - 60 * 60 ? since : null; const fromTs = sinceTs ?? now - 60 * 60; const cap = sinceTs != null ? undefined : SNAPSHOT_SERIES_CAP;
// One DO round trip (chartVars=[] skips the series query inside the DO). const { latest, series, oldestTs } = await stub .getDashboardSnapshot(chartVars, fromTs, cap) .catch(() => ({ latest: [], series: {} as CompactSeries, oldestTs: null as number | null }));
const variables: Record<string, { value: unknown; received_at: number }> = {}; for (const r of latest) { if (shownVars.has(r.variable)) variables[r.variable] = { value: r.value, received_at: r.received_at }; }
// Delta is safe only if nothing at/after the cursor was evicted. The ring is one // time-ordered buffer, so oldestTs <= since means [since, now] is fully retained; // otherwise send a full snapshot so charts can't develop a hole. const isDelta = sinceTs != null && (oldestTs == null || oldestTs <= sinceTs); const msg: Snapshot | DeltaMsg = isDelta ? { type: 'delta', dashboard: dashId, variables, series } : { type: 'snapshot', dashboard: dashId, layout, variables, series };
try { ws.send(JSON.stringify(msg)); } catch { // Client disconnected during bootstrap. } }
private async handleControl(ws: WebSocket, msg: ClientMsg & { type: 'control' }): Promise<void> { const reqId = msg.req; const ack = (ok: boolean, reason?: string): void => { if (!reqId) return; try { const a: AckMsg = { type: 'ack', req: reqId, ok, ...(reason ? { reason } : {}) }; ws.send(JSON.stringify(a)); } catch {} };
const dashId = this.dashboardId(); // Resolve the dashboard's project and validate the variable in one round-trip. // LEFT JOIN keeps the two distinct ack reasons: no row → dashboard missing; // row with null variable_id → variable not in the dashboard's project. const row = await this.env.DB .prepare( `SELECT d.project_id, pv.id AS variable_id FROM dashboards d LEFT JOIN project_variables pv ON pv.project_id = d.project_id AND pv.key = ? WHERE d.id = ?` ) .bind(msg.variable, dashId) .first<{ project_id: string; variable_id: string | null }>(); if (!row) return ack(false, 'dashboard_not_found'); if (!row.variable_id) return ack(false, 'variable_not_in_project');
// Re-authorize the control write against the user's CURRENT access. Re-read // per frame so a removal from the project mid-session takes effect on this // already-open socket. if (!(await this.viewerAllowed(ws, 0))) return ack(false, 'forbidden');
const cmdId = newId('control'); const stub = projectStub(this.env, row.project_id); try { await stub.addControl(cmdId, msg.variable, msg.value ?? null); ack(true); } catch (e) { ack(false, 'enqueue_failed'); } }
private async subscribe(projectId: string): Promise<void> { this.sql.exec( `INSERT INTO subscribed_project (project_id) VALUES (?) ON CONFLICT(project_id) DO NOTHING`, projectId ); await projectStub(this.env, projectId).subscribeDashboard(this.dashboardId()); }
private async unsubscribe(): Promise<void> { const rows = this.sql .exec<{ project_id: string }>(`SELECT project_id FROM subscribed_project`) .toArray(); await Promise.all( rows.map(async (r) => { try { await projectStub(this.env, r.project_id).unsubscribeDashboard(this.dashboardId()); } catch { // best-effort } }) ); this.sql.exec(`DELETE FROM subscribed_project`); }
private initSchema(): void { this.sql.exec(` CREATE TABLE IF NOT EXISTS subscribed_project ( project_id TEXT PRIMARY KEY ); `); }}