PEP-225: хаб с частями и строками задач, протокол WebSocket, свой сервер веба
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0b6a474c2b
commit
d3c29890f4
@ -8,6 +8,9 @@ export async function register() {
|
||||
installCrashReporting(db, "web");
|
||||
const { setRunnerClient } = await import("@peppa/runner");
|
||||
setRunnerClient(true, db);
|
||||
// PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process.
|
||||
const { registerLiveWs } = await import("@/lib/live-server");
|
||||
registerLiveWs();
|
||||
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
|
||||
const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`));
|
||||
void tick();
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { enterActor, getUiMode, getUser, isSuperadmin, isUserAllowed, sessionsValidAfter, sign, verify, type User } from "@peppa/core";
|
||||
import { enterActor, getUiMode, isSuperadmin, sign, type User } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { wording, type Words } from "@peppa/shared/wording";
|
||||
import { cookies, headers } from "next/headers";
|
||||
@ -6,31 +6,17 @@ import { redirect } from "next/navigation";
|
||||
import { cache } from "react";
|
||||
import { db } from "./db";
|
||||
import { getLocale } from "./i18n";
|
||||
import { SESSION_COOKIE, SESSION_DAYS, userFromSessionToken, type SessionPayload } from "./session-user";
|
||||
|
||||
export const SESSION_COOKIE = "peppa_session";
|
||||
export { SESSION_COOKIE };
|
||||
/** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */
|
||||
export const EGOV_COOKIE = "peppa_egov";
|
||||
|
||||
/** Only same-site relative paths are allowed as a post-login destination. */
|
||||
export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/");
|
||||
const SESSION_DAYS = 30;
|
||||
|
||||
interface SessionPayload {
|
||||
uid: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
/** Memoized per request: the layout, the page and the side panel all ask for the user. */
|
||||
export const currentUser = cache(async (): Promise<User | null> => {
|
||||
const p = verify<SessionPayload>((await cookies()).get(SESSION_COOKIE)?.value);
|
||||
if (!p || p.exp < Date.now()) return null;
|
||||
// PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid.
|
||||
const after = await sessionsValidAfter(db);
|
||||
if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null;
|
||||
const user = await getUser(db, p.uid);
|
||||
// Removed from the allowlist → the session stops working right away.
|
||||
return user && (await isUserAllowed(db, user)) ? user : null;
|
||||
});
|
||||
export const currentUser = cache(async (): Promise<User | null> => userFromSessionToken((await cookies()).get(SESSION_COOKIE)?.value));
|
||||
|
||||
/** For pages and server actions: the logged-in user, or a redirect to /login. */
|
||||
export async function requireUser(): Promise<User> {
|
||||
|
||||
27
apps/web/lib/live-server.ts
Normal file
27
apps/web/lib/live-server.ts
Normal file
@ -0,0 +1,27 @@
|
||||
// PEP-225: the tab's WebSocket, set up inside the Next process (instrumentation.ts) where the
|
||||
// web's modules live — the cookie check, navCounts, the boot id. apps/web/server.ts only hands
|
||||
// `upgrade` requests of /api/ws to what is registered here (globalThis: the custom server and
|
||||
// the Next bundle are different module graphs of one process).
|
||||
import { getNotifyPrefs } from "@peppa/core";
|
||||
import { setLiveProvider } from "@peppa/runner";
|
||||
import { createLiveWs, readCookie, type LiveWs } from "@peppa/runner/live-ws";
|
||||
import { bootId } from "./boot";
|
||||
import { db } from "./db";
|
||||
import { navCounts } from "./queries";
|
||||
import { SESSION_COOKIE, userFromSessionToken } from "./session-user";
|
||||
|
||||
const g = globalThis as { __peppaLiveWs?: LiveWs };
|
||||
|
||||
export function registerLiveWs(): void {
|
||||
setLiveProvider("attention", async (_db, userId) => {
|
||||
const [c, { sound }] = await Promise.all([navCounts(userId), getNotifyPrefs(db, userId)]);
|
||||
return { count: c.questions + c.waitingRunners, chats: c.chats, sound };
|
||||
});
|
||||
setLiveProvider("version", () => ({ boot: bootId() }));
|
||||
g.__peppaLiveWs?.close();
|
||||
g.__peppaLiveWs = createLiveWs({
|
||||
db,
|
||||
authenticate: (req) => userFromSessionToken(readCookie(req.headers.cookie, SESSION_COOKIE)),
|
||||
boot: bootId,
|
||||
});
|
||||
}
|
||||
23
apps/web/lib/session-user.ts
Normal file
23
apps/web/lib/session-user.ts
Normal file
@ -0,0 +1,23 @@
|
||||
// The signed-in user of a session cookie value (PEP-225): the same checks for pages
|
||||
// (lib/auth.ts currentUser) and for the tab's WebSocket, which has no `next/headers`.
|
||||
import { getUser, isUserAllowed, sessionsValidAfter, verify, type User } from "@peppa/core";
|
||||
import { db } from "./db";
|
||||
|
||||
export const SESSION_COOKIE = "peppa_session";
|
||||
export const SESSION_DAYS = 30;
|
||||
|
||||
export interface SessionPayload {
|
||||
uid: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
export async function userFromSessionToken(token: string | undefined): Promise<User | null> {
|
||||
const p = verify<SessionPayload>(token);
|
||||
if (!p || p.exp < Date.now()) return null;
|
||||
// PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid.
|
||||
const after = await sessionsValidAfter(db);
|
||||
if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null;
|
||||
const user = await getUser(db, p.uid);
|
||||
// Removed from the allowlist → the session stops working right away.
|
||||
return user && (await isUserAllowed(db, user)) ? user : null;
|
||||
}
|
||||
@ -48,7 +48,7 @@ const config: NextConfig = {
|
||||
return process.env.NODE_ENV === "development" ? [all, { source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }, sw] : [all, sw];
|
||||
},
|
||||
// PEP-212: the code-mode sandbox (QuickJS wasm) loads its .wasm file itself — it must not be bundled.
|
||||
serverExternalPackages: ["quickjs-emscripten"],
|
||||
serverExternalPackages: ["quickjs-emscripten", "ws"],
|
||||
transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"],
|
||||
env: {
|
||||
NEXT_PUBLIC_PEPPA_VERSION: version,
|
||||
|
||||
@ -4,10 +4,11 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3100",
|
||||
"dev": "node server.ts --dev -p 3100",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3100",
|
||||
"typecheck": "tsc -p ."
|
||||
"start": "node server.ts -p 3100",
|
||||
"typecheck": "tsc -p .",
|
||||
"dev:next": "next dev -p 3100"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.32.2",
|
||||
@ -29,7 +30,8 @@
|
||||
"quickjs-emscripten": "0.32.0",
|
||||
"react": "19.3.1",
|
||||
"react-dom": "19.3.1",
|
||||
"tailwind-merge": "3.7.0"
|
||||
"tailwind-merge": "3.7.0",
|
||||
"ws": "8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "4.3.5",
|
||||
|
||||
40
apps/web/server.ts
Normal file
40
apps/web/server.ts
Normal file
@ -0,0 +1,40 @@
|
||||
// The web's own server (PEP-225): Next.js 16 does not accept WebSockets, so this wraps it —
|
||||
// plain HTTP goes to Next, `upgrade` on /api/ws to the tab's live channel that
|
||||
// instrumentation.ts registered (lib/live-server.ts), other upgrades (dev HMR) to Next.
|
||||
// Usage: node server.ts [--dev] [-p 3100]
|
||||
import { createServer } from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
const dev = process.argv.includes("--dev");
|
||||
const pIdx = process.argv.indexOf("-p");
|
||||
const port = Number(pIdx > 0 ? process.argv[pIdx + 1] : (process.env.PORT ?? 3100));
|
||||
const env = process.env as Record<string, string | undefined>;
|
||||
env.NODE_ENV ??= dev ? "development" : "production";
|
||||
|
||||
const { default: next } = await import("next");
|
||||
const app = next({ dev, dir: import.meta.dirname, port, hostname: "localhost" });
|
||||
const handle = app.getRequestHandler();
|
||||
await app.prepare();
|
||||
const nextUpgrade = app.getUpgradeHandler();
|
||||
|
||||
type LiveWs = { handleUpgrade(req: import("node:http").IncomingMessage, socket: Duplex, head: Buffer): void };
|
||||
const live = () => (globalThis as { __peppaLiveWs?: LiveWs }).__peppaLiveWs;
|
||||
|
||||
const server = createServer((req, res) => void handle(req, res));
|
||||
server.on("upgrade", (req, socket: Duplex, head: Buffer) => {
|
||||
if (req.url?.split("?")[0] === "/api/ws") {
|
||||
const ws = live();
|
||||
if (ws) return ws.handleUpgrade(req, socket, head);
|
||||
socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
||||
return;
|
||||
}
|
||||
void nextUpgrade(req, socket, head);
|
||||
});
|
||||
server.listen(port, () => console.log(`peppa web: http://localhost:${port} (${dev ? "dev" : "production"}, WebSocket /api/ws)`));
|
||||
|
||||
const shutdown = () => {
|
||||
server.close();
|
||||
setTimeout(() => process.exit(0), 3000).unref();
|
||||
};
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
@ -4,7 +4,8 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
".": "./src/index.ts",
|
||||
"./live-ws": "./src/live-ws.ts"
|
||||
},
|
||||
"bin": {
|
||||
"peppa-hook": "./bin/peppa-hook"
|
||||
@ -17,6 +18,10 @@
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"drizzle-orm": "0.45.4"
|
||||
"drizzle-orm": "0.45.4",
|
||||
"ws": "8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/ws": "8.18.1"
|
||||
}
|
||||
}
|
||||
|
||||
268
packages/runner/src/live-ws.ts
Normal file
268
packages/runner/src/live-ws.ts
Normal file
@ -0,0 +1,268 @@
|
||||
// One WebSocket per browser tab (PEP-225): `GET /api/ws` carries every live scope of the tab —
|
||||
// the hub's scopes (live.ts) and the runner terminal (terminal.ts, output and input) — instead of
|
||||
// an SSE stream per page part. The web's own server (apps/web/server.ts) hands the upgrade here;
|
||||
// the protocol itself (LiveConnection) knows nothing of the transport, tests drive it directly.
|
||||
//
|
||||
// Client → server: {t:"sub", scope, since?} · {t:"unsub", scope} · {t:"in", scope:"terminal:<id>", keys?|paste?, id} · {t:"ping"}
|
||||
// Server → client: {t:"hello", boot} · {t:"ok", scope, v?} · {t:"err", scope?, status, error} · {t:"ev", scope, type, …} · {t:"ack", id, error?} · {t:"pong"}
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { PeppaError, projectSecretMasker, type User } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { checkScopeAccess, LIVE_MAX_SCOPES, LIVE_PING_MS, liveHub, LiveError, parseScope, type LiveScope } from "./live.ts";
|
||||
import { acquireViewer, terminalInput, terminalSession, watchTerminal } from "./terminal.ts";
|
||||
|
||||
/** Largest message from a client: a 64 KB paste in JSON with escapes. */
|
||||
export const LIVE_WS_MAX_PAYLOAD = 300_000;
|
||||
/** Client messages per window before the socket is closed (1008). */
|
||||
export const LIVE_WS_RATE_MAX = 60;
|
||||
export const LIVE_WS_RATE_WINDOW_MS = 5000;
|
||||
export const LIVE_WS_PATH = "/api/ws";
|
||||
|
||||
type Out = Record<string, unknown>;
|
||||
|
||||
/** One tab's connection: its subscriptions, input and limits. */
|
||||
export class LiveConnection {
|
||||
private subs = new Map<LiveScope, () => void>();
|
||||
private pending = new Set<LiveScope>();
|
||||
private window = { start: 0, n: 0 };
|
||||
private input: Promise<void> = Promise.resolve();
|
||||
private closed = false;
|
||||
private db: Db;
|
||||
private user: User;
|
||||
private out: (msg: Out) => void;
|
||||
private kill: (code: number, reason: string) => void;
|
||||
|
||||
constructor(db: Db, user: User, out: (msg: Out) => void, kill: (code: number, reason: string) => void) {
|
||||
this.db = db;
|
||||
this.user = user;
|
||||
this.out = out;
|
||||
this.kill = kill;
|
||||
}
|
||||
|
||||
private send(msg: Out) {
|
||||
if (!this.closed) this.out(msg);
|
||||
}
|
||||
|
||||
/** Handles one text message; returns once it is dealt with (tests await it). */
|
||||
async receive(raw: string, now = Date.now()): Promise<void> {
|
||||
if (this.closed) return;
|
||||
if (now - this.window.start >= LIVE_WS_RATE_WINDOW_MS) this.window = { start: now, n: 0 };
|
||||
if (++this.window.n > LIVE_WS_RATE_MAX) return this.kill(1008, "rate");
|
||||
let msg: { t?: unknown; scope?: unknown; since?: unknown; keys?: unknown; paste?: unknown; id?: unknown };
|
||||
try {
|
||||
msg = JSON.parse(raw);
|
||||
} catch {
|
||||
return this.send({ t: "err", status: 400, error: m("Неверный JSON") });
|
||||
}
|
||||
if (msg.t === "ping") return this.send({ t: "pong" });
|
||||
const scopeRaw = typeof msg.scope === "string" ? msg.scope : "";
|
||||
let scope: LiveScope;
|
||||
try {
|
||||
scope = parseScope(scopeRaw);
|
||||
} catch (e) {
|
||||
return this.send({ t: "err", scope: scopeRaw, status: 400, error: (e as Error).message });
|
||||
}
|
||||
if (msg.t === "sub") return this.subscribe(scope, typeof msg.since === "string" || typeof msg.since === "number" ? msg.since : undefined);
|
||||
if (msg.t === "unsub") return this.unsubscribe(scope);
|
||||
if (msg.t === "in") return this.terminalIn(scope, msg);
|
||||
this.send({ t: "err", scope, status: 400, error: m("Неизвестное сообщение") });
|
||||
}
|
||||
|
||||
private async subscribe(scope: LiveScope, since: string | number | undefined) {
|
||||
if (this.subs.has(scope) || this.pending.has(scope)) return this.send({ t: "ok", scope });
|
||||
if (this.subs.size + this.pending.size >= LIVE_MAX_SCOPES) return this.send({ t: "err", scope, status: 429, error: m("Слишком много областей") });
|
||||
this.pending.add(scope);
|
||||
try {
|
||||
await checkScopeAccess(this.db, this.user, scope);
|
||||
const stop = scope.startsWith("terminal:") ? await this.watchTerminal(scope) : this.watchHub(scope, since);
|
||||
// Unsubscribed (or closed) while access was checked.
|
||||
if (!this.pending.has(scope) || this.closed) return stop();
|
||||
this.subs.set(scope, stop);
|
||||
this.send({ t: "ok", scope, v: scope.startsWith("terminal:") ? undefined : liveHub(this.db).versionOf(scope, this.user.id) });
|
||||
} catch (e) {
|
||||
const status = e instanceof LiveError ? e.status : (e as { status?: number }).status ?? 500;
|
||||
if (status === 500) console.error(`live-ws: ${scope}`, e);
|
||||
this.send({ t: "err", scope, status, error: e instanceof LiveError || e instanceof PeppaError ? e.message : m("Ошибка потока") });
|
||||
} finally {
|
||||
this.pending.delete(scope);
|
||||
}
|
||||
}
|
||||
|
||||
private watchHub(scope: LiveScope, since: string | number | undefined): () => void {
|
||||
return liveHub(this.db).subscribe([scope], (e) => this.send({ t: "ev", ...e }), { userId: this.user.id, since: { [scope]: since } });
|
||||
}
|
||||
|
||||
/** The runner terminal (PEP-9): the shared TerminalFeed of the pane, secrets masked, viewers per user limited. */
|
||||
private async watchTerminal(scope: LiveScope): Promise<() => void> {
|
||||
const s = await terminalSession(this.db, this.user, Number(scope.slice(9)));
|
||||
const mask = await projectSecretMasker(this.db, s.projectId);
|
||||
const release = acquireViewer(this.user.id);
|
||||
let done = false;
|
||||
const stopFeed = watchTerminal(
|
||||
tmux.sessionPane(s),
|
||||
(e) => {
|
||||
this.send({ t: "ev", scope, ...e });
|
||||
if (e.type === "end") queueMicrotask(() => this.unsubscribe(scope));
|
||||
},
|
||||
{ mask },
|
||||
);
|
||||
return () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
stopFeed();
|
||||
release();
|
||||
};
|
||||
}
|
||||
|
||||
private unsubscribe(scope: LiveScope) {
|
||||
this.pending.delete(scope);
|
||||
const stop = this.subs.get(scope);
|
||||
this.subs.delete(scope);
|
||||
stop?.();
|
||||
}
|
||||
|
||||
/** Keyboard input / paste of the terminal: in order, with the PEP-9 checks and limits. */
|
||||
private terminalIn(scope: LiveScope, msg: { keys?: unknown; paste?: unknown; id?: unknown }) {
|
||||
const id = typeof msg.id === "number" || typeof msg.id === "string" ? msg.id : null;
|
||||
if (!scope.startsWith("terminal:")) return this.send({ t: "ack", id, error: m("Ввод — только в терминал") });
|
||||
const input = { keys: typeof msg.keys === "string" ? msg.keys : undefined, paste: typeof msg.paste === "string" ? msg.paste : undefined };
|
||||
const run = async () => {
|
||||
try {
|
||||
await terminalInput(this.db, this.user, Number(scope.slice(9)), input);
|
||||
this.send({ t: "ack", id });
|
||||
} catch (e) {
|
||||
this.send({ t: "ack", id, error: e instanceof PeppaError || e instanceof LiveError ? e.message : m("Ошибка терминала") });
|
||||
if (!(e instanceof PeppaError)) console.error("live-ws: terminal input", e);
|
||||
}
|
||||
};
|
||||
this.input = this.input.then(run);
|
||||
return this.input;
|
||||
}
|
||||
|
||||
get scopes(): LiveScope[] {
|
||||
return [...this.subs.keys()];
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
for (const stop of this.subs.values()) stop();
|
||||
this.subs.clear();
|
||||
this.pending.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Same-site only: the cookie is `lax`, a WebSocket from another site would carry it. */
|
||||
export function sameOriginUpgrade(req: IncomingMessage): boolean {
|
||||
const origin = req.headers.origin;
|
||||
if (!origin) return true; // not a browser
|
||||
const host = (req.headers["x-forwarded-host"] as string | undefined)?.split(",")[0]?.trim() || req.headers.host;
|
||||
try {
|
||||
return new URL(origin).host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface LiveWsOptions {
|
||||
db: Db;
|
||||
/** The signed-in user of the request (cookie `peppa_session`), or null. */
|
||||
authenticate: (req: IncomingMessage) => Promise<User | null>;
|
||||
/** Boot id of the web process (the client compares it after a reconnect). */
|
||||
boot?: () => string;
|
||||
pingMs?: number;
|
||||
}
|
||||
|
||||
export interface LiveWs {
|
||||
handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;
|
||||
readonly clients: number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function refuse(socket: Duplex, status: number, text: string) {
|
||||
try {
|
||||
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
} catch {}
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
/** The WebSocket endpoint: auth and origin before the upgrade, a ping every 15 s, one LiveConnection per socket. */
|
||||
export function createLiveWs(opts: LiveWsOptions): LiveWs {
|
||||
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: LIVE_WS_MAX_PAYLOAD });
|
||||
const alive = new WeakMap<WebSocket, number>();
|
||||
const pingMs = opts.pingMs ?? LIVE_PING_MS;
|
||||
// Two pings without a pong: the connection is dead (a sleeping phone, a dropped proxy).
|
||||
const pinger = setInterval(() => {
|
||||
for (const ws of wss.clients) {
|
||||
const missed = (alive.get(ws) ?? 0) + 1;
|
||||
if (missed > 2) {
|
||||
ws.terminate();
|
||||
continue;
|
||||
}
|
||||
alive.set(ws, missed);
|
||||
try {
|
||||
ws.ping();
|
||||
} catch {}
|
||||
}
|
||||
}, pingMs);
|
||||
pinger.unref?.();
|
||||
|
||||
wss.on("connection", (ws: WebSocket, _req: IncomingMessage, user: User) => {
|
||||
alive.set(ws, 0);
|
||||
const conn = new LiveConnection(
|
||||
opts.db,
|
||||
user,
|
||||
(msg) => {
|
||||
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg));
|
||||
},
|
||||
(code, reason) => ws.close(code, reason),
|
||||
);
|
||||
ws.on("pong", () => alive.set(ws, 0));
|
||||
ws.on("message", (data, isBinary) => {
|
||||
alive.set(ws, 0);
|
||||
if (isBinary) return ws.close(1003, "text only");
|
||||
void conn.receive(data.toString());
|
||||
});
|
||||
ws.on("close", () => conn.close());
|
||||
ws.on("error", () => conn.close());
|
||||
ws.send(JSON.stringify({ t: "hello", boot: opts.boot?.() ?? "" }));
|
||||
});
|
||||
|
||||
return {
|
||||
handleUpgrade(req, socket, head) {
|
||||
socket.on("error", () => socket.destroy());
|
||||
if (!sameOriginUpgrade(req)) return refuse(socket, 403, "Forbidden");
|
||||
opts
|
||||
.authenticate(req)
|
||||
.then((user) => {
|
||||
if (!user) return refuse(socket, 401, "Unauthorized");
|
||||
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req, user));
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error("live-ws: upgrade", e);
|
||||
refuse(socket, 500, "Internal Server Error");
|
||||
});
|
||||
},
|
||||
get clients() {
|
||||
return wss.clients.size;
|
||||
},
|
||||
close() {
|
||||
clearInterval(pinger);
|
||||
for (const ws of wss.clients) ws.terminate();
|
||||
wss.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads one cookie from a raw Cookie header. */
|
||||
export function readCookie(header: string | undefined, name: string): string | undefined {
|
||||
for (const part of (header ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i > 0 && part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim());
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@ -1,22 +1,52 @@
|
||||
// Live web (PEP-37): one change hub per web process. notify() pokes (the `web` subscriber
|
||||
// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks,
|
||||
// the watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody
|
||||
// watches and tells only the watchers whose scope changed. Steps of agents (PEP-33) go to
|
||||
// `steps:<sessionId>` watchers as data.
|
||||
// Live web (PEP-37, PEP-225): one change hub per web process. notify() pokes (the `web` subscriber
|
||||
// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks, the
|
||||
// watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody watches and
|
||||
// tells only the watchers whose scope changed — with what changed (`parts`, rows of tasks), so a
|
||||
// page can apply it in place. Steps of agents (PEP-33) go to `steps:<sessionId>` watchers as
|
||||
// data; value scopes (`attention`, `version`) send their value. The same events go out over the
|
||||
// tab's WebSocket (live-ws.ts) and over the SSE fallback (/api/live).
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
|
||||
import { events, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { findChangeDir, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
|
||||
import { events, sessions, subscriptions, tasks, type Db } from "@peppa/db";
|
||||
import { and, eq, gt } from "drizzle-orm";
|
||||
import { columnOf, type BoardColumn } from "./flow.ts";
|
||||
import { pollCodexLogin } from "./subscription-login.ts";
|
||||
import { terminalSession } from "./terminal.ts";
|
||||
|
||||
export type LiveScope = "home" | "runners" | "chats" | "team" | `project:${number}` | `task:${number}` | `steps:${number}`;
|
||||
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
|
||||
/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer). */
|
||||
export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me"] as const;
|
||||
const ID_KINDS = ["project", "task", "steps", "login", "terminal"] as const;
|
||||
type PlainScope = (typeof LIVE_PLAIN_SCOPES)[number];
|
||||
type IdKind = (typeof ID_KINDS)[number];
|
||||
export type LiveScope = PlainScope | `${IdKind}:${number}`;
|
||||
|
||||
/** A row of a task as a page shows it on the board and in the story header. */
|
||||
export interface LiveTaskRow {
|
||||
id: number;
|
||||
status: string;
|
||||
title: string;
|
||||
column: BoardColumn;
|
||||
/** Something else of the row changed (epic, order, «Предложено», importance): the page re-renders. */
|
||||
other?: boolean;
|
||||
}
|
||||
type Row = LiveTaskRow & { sig: string };
|
||||
|
||||
export type LiveEvent =
|
||||
/** The scope changed: `v` — its new version, `parts` — which parts of it, `tasks` — changed task rows, `chats` — chats with new messages. */
|
||||
| { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; chats?: number[] }
|
||||
| { type: "step"; scope: LiveScope; step: StepView }
|
||||
/** The current value of a value scope (`attention`, `version`). */
|
||||
| { type: "data"; scope: LiveScope; v: string; data: unknown };
|
||||
type Listener = (e: LiveEvent) => void;
|
||||
|
||||
export const LIVE_PING_MS = 15_000;
|
||||
/** Most scopes one SSE stream / one WebSocket may watch. */
|
||||
export const LIVE_MAX_SCOPES = 32;
|
||||
|
||||
/** Refusal of a live stream with its HTTP status. */
|
||||
/** Refusal of a live stream or a subscription with its HTTP status. */
|
||||
export class LiveError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
@ -25,38 +55,77 @@ export class LiveError extends Error {
|
||||
}
|
||||
}
|
||||
const WAKE_DEBOUNCE_MS = 250;
|
||||
/** Scopes read from outside the main database: re-checked on a timer while watched. */
|
||||
const OBSERVE_EVERY_MS = 2000;
|
||||
/** A pending ChatGPT sign-in is asked this often while somebody waits for it (PEP-148, server side since PEP-225). */
|
||||
export const LOGIN_POLL_MS = 3000;
|
||||
|
||||
/** Parses `?scope=a,b`; unknown parts are refused. */
|
||||
/** Checks one scope name; unknown ones are refused. */
|
||||
export function parseScope(part: string): LiveScope {
|
||||
if ((LIVE_PLAIN_SCOPES as readonly string[]).includes(part)) return part as LiveScope;
|
||||
if (/^(project|task|steps|login|terminal):[1-9]\d{0,9}$/.test(part)) return part as LiveScope;
|
||||
throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
|
||||
}
|
||||
|
||||
/** Parses `?scope=a,b` of the SSE fallback; the terminal has its own stream there. */
|
||||
export function parseScopes(raw: string | null): LiveScope[] {
|
||||
const out = new Set<LiveScope>();
|
||||
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
|
||||
if (part === "home" || part === "runners" || part === "chats" || part === "team") out.add(part);
|
||||
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
|
||||
else throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
|
||||
const s = parseScope(part);
|
||||
if (s.startsWith("terminal:")) throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
|
||||
out.add(s);
|
||||
}
|
||||
if (!out.size || out.size > 8) throw new LiveError(m("Нужна область (scope)"), 400);
|
||||
if (!out.size || out.size > LIVE_MAX_SCOPES) throw new LiveError(m("Нужна область (scope)"), 400);
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** Access: project/story/runner scopes need the project; home/runners only a user. */
|
||||
const notFound = () => new LiveError(m("Не найдено"), 404);
|
||||
|
||||
/**
|
||||
* Access, the same as the page's: project / story / steps / terminal need the project,
|
||||
* `observe` and `subs` a superadmin, `login:<id>` the author of that sign-in or a superadmin.
|
||||
*/
|
||||
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
|
||||
const [kind, raw] = scope.split(":") as [string, string?];
|
||||
const id = Number(raw);
|
||||
if (kind === "observe" || kind === "subs") {
|
||||
if (!(await isSuperadmin(db, user))) throw notFound();
|
||||
return;
|
||||
}
|
||||
if (kind === "login") {
|
||||
const row = (await db.select({ by: subscriptions.createdBy }).from(subscriptions).where(eq(subscriptions.id, id)))[0];
|
||||
if (!row || (row.by !== user.id && !(await isSuperadmin(db, user)))) throw notFound();
|
||||
return;
|
||||
}
|
||||
if (kind === "terminal") {
|
||||
await terminalSession(db, user, id).catch(() => {
|
||||
throw notFound();
|
||||
});
|
||||
return;
|
||||
}
|
||||
let projectId: number | undefined;
|
||||
if (kind === "project") projectId = id;
|
||||
else if (kind === "task") projectId = (await db.select({ p: tasks.projectId }).from(tasks).where(eq(tasks.id, id)))[0]?.p;
|
||||
else if (kind === "steps") projectId = (await db.select({ p: sessions.projectId }).from(sessions).where(eq(sessions.id, id)))[0]?.p;
|
||||
else return;
|
||||
if (projectId == null) throw new LiveError(m("Не найдено"), 404);
|
||||
if (projectId == null) throw notFound();
|
||||
await projectForUser(db, user.id, projectId).catch(() => {
|
||||
throw new LiveError(m("Не найдено"), 404);
|
||||
throw notFound();
|
||||
});
|
||||
}
|
||||
|
||||
const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
|
||||
/** Short version of a fingerprint: what a client sends back as `since`. */
|
||||
export const liveVersion = (fp: string) => createHash("sha1").update(fp).digest("base64url").slice(0, 12);
|
||||
|
||||
/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */
|
||||
function fingerprint(db: Db, scope: LiveScope): string {
|
||||
const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
|
||||
type Parts = Record<string, string>;
|
||||
const str = (row: Record<string, unknown> | undefined): Parts => Object.fromEntries(Object.entries(row ?? {}).map(([k, v]) => [k, String(v ?? "")]));
|
||||
|
||||
/**
|
||||
* One SQL per scope, split into named parts; frequent fields (last_activity_at, steps,
|
||||
* heartbeats) are left out. Part `t` is covered by the task rows sent along (see taskRows).
|
||||
*/
|
||||
function fingerprint(db: Db, scope: LiveScope, userId: number): Parts {
|
||||
const c = db.$client;
|
||||
const [kind, raw] = scope.split(":") as [string, string?];
|
||||
const id = Number(raw);
|
||||
@ -64,7 +133,8 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT json_array(status, title, coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS t,
|
||||
(SELECT json_array(status, title) FROM tasks WHERE id = ?1) AS t,
|
||||
(SELECT json_array(coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS d,
|
||||
(SELECT coalesce(max(id),0) FROM events WHERE task_id = ?1 AND type <> 'step') AS e,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE task_id = ?1) AS q,
|
||||
(SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(ended_at,'')),'') FROM sessions WHERE task_id = ?1) AS s,
|
||||
@ -74,7 +144,7 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
(SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`,
|
||||
)
|
||||
.get(id) as Record<string, string | number | null> | undefined;
|
||||
if (!row) return "";
|
||||
if (!row?.t) return {};
|
||||
// tasks.md of the working copy changes without a database write (agent ticks items).
|
||||
let tasksMtime = 0;
|
||||
if (row.ws && row.ch) {
|
||||
@ -82,13 +152,15 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
const file = found && join(found.dir, "tasks.md");
|
||||
if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs;
|
||||
}
|
||||
return [row.t, row.e, row.q, row.s, row.ci, row.r, tasksMtime].join("|");
|
||||
const { ws: _ws, ch: _ch, ...rest } = row;
|
||||
return { ...str(rest), md: String(tasksMtime) };
|
||||
}
|
||||
if (kind === "project") {
|
||||
// `t` — the board rows: what a page can't apply from `tasks` comes with `other: true`.
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks WHERE project_id = ?1) AS t,
|
||||
(SELECT coalesce(group_concat(id || ':' || status || ':' || title || ':' || position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,''), char(1)),'') FROM tasks WHERE project_id = ?1 AND archived_at IS NULL) AS t,
|
||||
(SELECT coalesce(max(id),0) FROM events WHERE project_id = ?1 AND type <> 'step') AS e,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = ?1) AS q,
|
||||
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions WHERE project_id = ?1) AS s,
|
||||
@ -98,7 +170,7 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
(SELECT updated_at FROM projects WHERE id = ?1) AS p`,
|
||||
)
|
||||
.get(id) as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
return str(row);
|
||||
}
|
||||
if (kind === "chats") {
|
||||
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
|
||||
@ -111,7 +183,41 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
(SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
return str(row);
|
||||
}
|
||||
if (kind === "subs") {
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(limited_until,'') || ':' || coalesce(checked_at,'') || ':' || coalesce(last_error,'')),'') FROM subscriptions) AS sub,
|
||||
(SELECT coalesce(group_concat(pool_id || ':' || subscription_id),'') FROM subscription_pool_members) AS pool,
|
||||
(SELECT coalesce(group_concat(key || '=' || value),'') FROM settings WHERE key >= 'subscription.' AND key < 'subscription/') AS st,
|
||||
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
return str(row);
|
||||
}
|
||||
if (kind === "login") {
|
||||
const row = c.prepare(`SELECT status || ':' || coalesce(last_error,'') AS sub FROM subscriptions WHERE id = ?`).get(id) as Record<string, unknown> | undefined;
|
||||
return { sub: String(row?.sub ?? "gone") };
|
||||
}
|
||||
if (kind === "me") {
|
||||
const row = c
|
||||
.prepare(`SELECT coalesce(telegram_chat_id,'') || ':' || coalesce(telegram_bot_username,'') || ':' || coalesce(egov_iin,'') || ':' || coalesce(google_sub,'') AS u FROM users WHERE id = ?`)
|
||||
.get(userId) as Record<string, unknown> | undefined;
|
||||
return { u: String(row?.u ?? "") };
|
||||
}
|
||||
if (kind === "observe") {
|
||||
const o = observeDb();
|
||||
const row = o
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(group_concat(id || ':' || state || ':' || paused || ':' || name || ':' || updated_at),'') FROM monitors) AS mon,
|
||||
(SELECT coalesce(max(id),0) || ':' || count(ended_at) FROM monitor_incidents) AS inc,
|
||||
(SELECT coalesce(substr(max(at),1,16),'') FROM monitor_checks) AS min`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
return str(row);
|
||||
}
|
||||
// home / runners / team: across projects (only wakes the page — data stays behind access checks).
|
||||
// team (PEP-179) also watches the team itself: a new agent, a renamed or removed one, and which
|
||||
@ -119,7 +225,7 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t,
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS tx,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
|
||||
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s,
|
||||
(SELECT count(*) FROM projects) AS p${
|
||||
@ -131,68 +237,178 @@ function fingerprint(db: Db, scope: LiveScope): string {
|
||||
}`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
return str(row);
|
||||
}
|
||||
|
||||
/** Board rows of a project / the story, keyed by id: «status|title». */
|
||||
function taskRows(db: Db, scope: LiveScope): Map<number, Row> {
|
||||
const [kind, raw] = scope.split(":");
|
||||
const cols = `id, status, title, position || ':' || coalesce(goal_id,0) || ':' || proposed || ':' || coalesce(severity,'') || ':' || coalesce(origin,'') AS sig`;
|
||||
const sql = kind === "project" ? `SELECT ${cols} FROM tasks WHERE project_id = ? AND archived_at IS NULL` : `SELECT ${cols} FROM tasks WHERE id = ?`;
|
||||
const rows = db.$client.prepare(sql).all(Number(raw)) as Array<{ id: number; status: string; title: string; sig: string }>;
|
||||
return new Map(rows.map((r) => [r.id, { id: r.id, status: r.status, title: r.title, column: columnOf(r.status), sig: String(r.sig) }]));
|
||||
}
|
||||
|
||||
/** Chats with a message newer than `after` (PEP-225: a chat page re-renders only for its own chat). */
|
||||
function chatsAfter(db: Db, after: number): number[] {
|
||||
const rows = db.$client.prepare(`SELECT DISTINCT chat_id AS id FROM chat_messages WHERE id > ? LIMIT 50`).all(after) as Array<{ id: number }>;
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
/** A value scope's provider: the web registers `attention` (it owns navCounts). */
|
||||
export type LiveProvider = (db: Db, userId: number) => Promise<unknown> | unknown;
|
||||
const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map<string, LiveProvider>; __peppaBoot?: string };
|
||||
const providers = (g.__peppaLiveProviders ??= new Map());
|
||||
const hubBoot = `boot-${Date.now().toString(36)}`;
|
||||
providers.set("version", () => ({ boot: g.__peppaBoot ?? hubBoot }));
|
||||
|
||||
/** Registers the value of a value scope (`attention`, `version`). */
|
||||
export function setLiveProvider(scope: "attention" | "version", fn: LiveProvider): void {
|
||||
providers.set(scope, fn);
|
||||
}
|
||||
|
||||
const VALUE_SCOPES = new Set(["attention", "version"]);
|
||||
const PER_USER = new Set(["attention", "me"]);
|
||||
/** Hub key of a scope: per-user scopes are watched per viewer. */
|
||||
const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) ? `${scope}@${userId}` : scope);
|
||||
|
||||
interface Watch {
|
||||
scope: LiveScope;
|
||||
userId: number;
|
||||
listeners: Set<Listener>;
|
||||
parts?: Parts;
|
||||
v?: string;
|
||||
rows?: Map<number, Row>;
|
||||
chatMax?: number;
|
||||
lastStep?: number;
|
||||
/** Value scopes: last value sent (JSON). */
|
||||
value?: string;
|
||||
}
|
||||
|
||||
class LiveHub {
|
||||
private listeners = new Map<LiveScope, Set<Listener>>();
|
||||
private prints = new Map<LiveScope, string>();
|
||||
private lastStep = new Map<LiveScope, number>();
|
||||
private watches = new Map<string, Watch>();
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private wakeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stopSocket: (() => Promise<void>) | null = null;
|
||||
private seen = "";
|
||||
private checking: Promise<void> | null = null;
|
||||
private again = false;
|
||||
private lastObserve = 0;
|
||||
private lastLoginPoll = 0;
|
||||
private db: Db;
|
||||
constructor(db: Db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
subscribe(scopes: LiveScope[], fn: Listener): () => void {
|
||||
for (const s of scopes) {
|
||||
let set = this.listeners.get(s);
|
||||
if (!set) {
|
||||
this.listeners.set(s, (set = new Set()));
|
||||
this.prime(s);
|
||||
/**
|
||||
* Watches `scopes` for the viewer `userId` (needed for `attention` / `me`). `since` — the
|
||||
* version (or the last step id for `steps:`) the client saw before a drop: whatever changed
|
||||
* since is sent right away. Value scopes always send their current value first.
|
||||
*/
|
||||
subscribe(scopes: LiveScope[], fn: Listener, opts: { userId?: number; since?: Record<string, string | number | undefined> } = {}): () => void {
|
||||
const userId = opts.userId ?? 0;
|
||||
const keys: string[] = [];
|
||||
for (const scope of scopes) {
|
||||
const key = keyOf(scope, userId);
|
||||
keys.push(key);
|
||||
let w = this.watches.get(key);
|
||||
if (!w) {
|
||||
this.watches.set(key, (w = { scope, userId, listeners: new Set() }));
|
||||
this.prime(w);
|
||||
}
|
||||
set.add(fn);
|
||||
w.listeners.add(fn);
|
||||
this.catchUp(w, fn, opts.since?.[scope]);
|
||||
}
|
||||
this.start();
|
||||
return () => {
|
||||
for (const s of scopes) {
|
||||
const set = this.listeners.get(s);
|
||||
set?.delete(fn);
|
||||
if (set && !set.size) {
|
||||
this.listeners.delete(s);
|
||||
this.prints.delete(s);
|
||||
this.lastStep.delete(s);
|
||||
}
|
||||
for (const key of keys) {
|
||||
const w = this.watches.get(key);
|
||||
w?.listeners.delete(fn);
|
||||
if (w && !w.listeners.size) this.watches.delete(key);
|
||||
}
|
||||
if (!this.listeners.size) this.stop();
|
||||
if (!this.watches.size) this.stop();
|
||||
};
|
||||
}
|
||||
|
||||
/** Remembers the current state, so only later changes are reported. */
|
||||
private prime(s: LiveScope) {
|
||||
private prime(w: Watch) {
|
||||
try {
|
||||
const s = w.scope;
|
||||
if (s.startsWith("steps:")) {
|
||||
const row = this.db.$client.prepare(`SELECT coalesce(max(id),0) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(Number(s.slice(6))) as { id: number };
|
||||
this.lastStep.set(s, row.id);
|
||||
} else this.prints.set(s, fingerprint(this.db, s));
|
||||
w.lastStep = row.id;
|
||||
} else if (!VALUE_SCOPES.has(s)) {
|
||||
w.parts = fingerprint(this.db, s, w.userId);
|
||||
w.v = liveVersion(JSON.stringify(w.parts));
|
||||
if (s.startsWith("project:") || s.startsWith("task:")) w.rows = taskRows(this.db, s);
|
||||
if (s === "chats") w.chatMax = Number(w.parts.m) || 0;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("live: prime failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** A new listener: the current value of a value scope, the version of others, missed steps. */
|
||||
private catchUp(w: Watch, fn: Listener, since: string | number | undefined) {
|
||||
const s = w.scope;
|
||||
if (VALUE_SCOPES.has(s)) {
|
||||
void this.value(w).then((data) => {
|
||||
if (data !== undefined && w.listeners.has(fn)) fn({ type: "data", scope: s, v: liveVersion(JSON.stringify(data)), data });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (s.startsWith("steps:")) {
|
||||
const after = Number(since);
|
||||
if (!after || after >= (w.lastStep ?? 0)) return;
|
||||
for (const r of this.stepsAfter(s, after, 200)) fn({ type: "step", scope: s, step: stepView(r) });
|
||||
return;
|
||||
}
|
||||
if (since !== undefined && w.v && since !== w.v) fn({ type: "change", scope: s, v: w.v, parts: ["*"] });
|
||||
}
|
||||
|
||||
private async value(w: Watch): Promise<unknown> {
|
||||
const fn = providers.get(w.scope);
|
||||
if (!fn) return undefined;
|
||||
try {
|
||||
const data = await fn(this.db, w.userId);
|
||||
w.value = JSON.stringify(data);
|
||||
return data;
|
||||
} catch (e) {
|
||||
console.error(`live: ${w.scope} value failed`, e);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private stepsAfter(scope: LiveScope, after: number, limit: number) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after)))
|
||||
.orderBy(events.id)
|
||||
.limit(limit)
|
||||
.all();
|
||||
}
|
||||
|
||||
private start() {
|
||||
if (this.timer) return;
|
||||
this.seen = this.version();
|
||||
// Writes of other processes (hooks, watchdog, bot, CLI) and of this one.
|
||||
// Writes of other processes (hooks, watchdog, bot, CLI) and of this one; the observe
|
||||
// database and a pending ChatGPT sign-in are looked at on a timer while somebody watches.
|
||||
this.timer = setInterval(() => {
|
||||
const v = this.version();
|
||||
if (v !== this.seen) {
|
||||
this.seen = v;
|
||||
this.wake();
|
||||
}
|
||||
const now = Date.now();
|
||||
if (this.watches.has("observe") && now - this.lastObserve >= OBSERVE_EVERY_MS) {
|
||||
this.lastObserve = now;
|
||||
this.wake();
|
||||
}
|
||||
if (now - this.lastLoginPoll >= LOGIN_POLL_MS) {
|
||||
this.lastLoginPoll = now;
|
||||
void this.pollLogins();
|
||||
}
|
||||
}, 1000);
|
||||
this.timer.unref?.();
|
||||
listenEvents("web", () => this.wake())
|
||||
@ -203,6 +419,17 @@ class LiveHub {
|
||||
.catch((e) => console.error("live: web.events.sock unavailable, data_version only:", (e as Error).message));
|
||||
}
|
||||
|
||||
/** One ChatGPT check per watched pending sign-in for all its viewers (it reads the sign-in's tmux pane). */
|
||||
private async pollLogins() {
|
||||
for (const w of [...this.watches.values()]) {
|
||||
if (!w.scope.startsWith("login:") || !w.parts?.sub?.startsWith("pending")) continue;
|
||||
const id = Number(w.scope.slice(6));
|
||||
const row = this.db.$client.prepare(`SELECT provider FROM subscriptions WHERE id = ?`).get(id) as { provider?: string } | undefined;
|
||||
if (row?.provider !== "codex") continue;
|
||||
await pollCodexLogin(this.db, id).catch(() => "pending");
|
||||
}
|
||||
}
|
||||
|
||||
private stop() {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
@ -227,51 +454,108 @@ class LiveHub {
|
||||
if (this.wakeTimer || !this.timer) return;
|
||||
this.wakeTimer = setTimeout(() => {
|
||||
this.wakeTimer = null;
|
||||
this.check();
|
||||
void this.check();
|
||||
}, WAKE_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/** Recomputes every watched scope now (tests call it directly). */
|
||||
check() {
|
||||
for (const [scope, set] of this.listeners) {
|
||||
/** Recomputes every watched scope now (tests call it directly). One check at a time. */
|
||||
check(): Promise<void> {
|
||||
if (this.checking) {
|
||||
this.again = true;
|
||||
return this.checking;
|
||||
}
|
||||
this.checking = (async () => {
|
||||
do {
|
||||
this.again = false;
|
||||
for (const w of [...this.watches.values()]) await this.checkOne(w);
|
||||
} while (this.again);
|
||||
})().finally(() => {
|
||||
this.checking = null;
|
||||
});
|
||||
return this.checking;
|
||||
}
|
||||
|
||||
private send(w: Watch, e: LiveEvent) {
|
||||
for (const fn of w.listeners) {
|
||||
try {
|
||||
if (scope.startsWith("steps:")) {
|
||||
const after = this.lastStep.get(scope) ?? 0;
|
||||
const rows = this.db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after)))
|
||||
.orderBy(events.id)
|
||||
.limit(50)
|
||||
.all();
|
||||
if (!rows.length) continue;
|
||||
this.lastStep.set(scope, rows.at(-1)!.id);
|
||||
for (const r of rows) for (const fn of set) fn({ type: "step", scope, step: stepView(r) });
|
||||
continue;
|
||||
}
|
||||
const fp = fingerprint(this.db, scope);
|
||||
if (fp === this.prints.get(scope)) continue;
|
||||
this.prints.set(scope, fp);
|
||||
for (const fn of set) fn({ type: "change", scope });
|
||||
} catch (e) {
|
||||
console.error(`live: ${scope} check failed`, e);
|
||||
fn(e);
|
||||
} catch (err) {
|
||||
console.error(`live: ${w.scope} listener failed`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async checkOne(w: Watch) {
|
||||
const scope = w.scope;
|
||||
try {
|
||||
if (scope.startsWith("steps:")) {
|
||||
const rows = this.stepsAfter(scope, w.lastStep ?? 0, 50);
|
||||
if (!rows.length) return;
|
||||
w.lastStep = rows.at(-1)!.id;
|
||||
for (const r of rows) this.send(w, { type: "step", scope, step: stepView(r) });
|
||||
return;
|
||||
}
|
||||
if (VALUE_SCOPES.has(scope)) {
|
||||
if (scope === "version") return; // changes only with the process: a reconnect brings it
|
||||
const before = w.value;
|
||||
const data = await this.value(w);
|
||||
if (data !== undefined && w.value !== before) this.send(w, { type: "data", scope, v: liveVersion(w.value!), data });
|
||||
return;
|
||||
}
|
||||
const parts = fingerprint(this.db, scope, w.userId);
|
||||
const old = w.parts ?? {};
|
||||
const changed = [...new Set([...Object.keys(parts), ...Object.keys(old)])].filter((k) => parts[k] !== old[k]);
|
||||
if (!changed.length) return;
|
||||
w.parts = parts;
|
||||
w.v = liveVersion(JSON.stringify(parts));
|
||||
const e: LiveEvent & { type: "change" } = { type: "change", scope, v: w.v, parts: changed };
|
||||
if (w.rows && (scope.startsWith("project:") || scope.startsWith("task:"))) {
|
||||
const rows = taskRows(this.db, scope);
|
||||
const diff: LiveTaskRow[] = [];
|
||||
for (const [id, { sig, ...r }] of rows) {
|
||||
const was = w.rows.get(id);
|
||||
if (!was) diff.push({ ...r, other: true });
|
||||
else if (was.sig !== sig) diff.push({ ...r, other: true });
|
||||
else if (was.status !== r.status || was.title !== r.title) diff.push(r);
|
||||
}
|
||||
// A story left the board (archived, deleted): the page can't apply that in place.
|
||||
if ([...w.rows.keys()].some((id) => !rows.has(id))) e.parts.push("gone");
|
||||
w.rows = rows;
|
||||
if (diff.length) e.tasks = diff.slice(0, 100);
|
||||
}
|
||||
if (scope === "chats") {
|
||||
const max = Number(parts.m) || 0;
|
||||
if (max > (w.chatMax ?? 0)) e.chats = chatsAfter(this.db, w.chatMax ?? 0);
|
||||
w.chatMax = max;
|
||||
}
|
||||
this.send(w, e);
|
||||
} catch (err) {
|
||||
console.error(`live: ${scope} check failed`, err);
|
||||
}
|
||||
}
|
||||
|
||||
get watched(): LiveScope[] {
|
||||
return [...this.listeners.keys()];
|
||||
return [...new Set([...this.watches.values()].map((w) => w.scope))];
|
||||
}
|
||||
|
||||
/** Current version of a watched scope (tests, `since`). */
|
||||
versionOf(scope: LiveScope, userId = 0): string | undefined {
|
||||
return this.watches.get(keyOf(scope, userId))?.v;
|
||||
}
|
||||
}
|
||||
|
||||
const g = globalThis as { __peppaLiveHub?: LiveHub };
|
||||
/** The process-wide hub (survives Next dev module reloads). */
|
||||
export type { LiveHub };
|
||||
|
||||
/** The process-wide hub (survives Next dev module reloads and is shared with the WebSocket server). */
|
||||
export function liveHub(db: Db): LiveHub {
|
||||
return (g.__peppaLiveHub ??= new LiveHub(db));
|
||||
}
|
||||
|
||||
/** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */
|
||||
export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise<Response> {
|
||||
/** Where the observe database lives (for a test that wants an observe scope). */
|
||||
export const liveObservePath = observeDbPath;
|
||||
|
||||
/** SSE response for /api/live (the fallback of the tab's WebSocket): `change` / `step` / `data` events, pings for Cloudflare. */
|
||||
export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number; since?: Record<string, string> } = {}): Promise<Response> {
|
||||
for (const s of scopes) await checkScopeAccess(db, user, s);
|
||||
const enc = new TextEncoder();
|
||||
let cleanup = () => {};
|
||||
@ -303,7 +587,7 @@ export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: A
|
||||
send("retry: 3000\n\n");
|
||||
send(`event: ready\ndata: ${JSON.stringify({ scopes })}\n\n`);
|
||||
if (signal.aborted) return close();
|
||||
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`));
|
||||
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`), { userId: user.id, since: opts.since });
|
||||
},
|
||||
cancel() {
|
||||
cleanup();
|
||||
|
||||
31
pnpm-lock.yaml
generated
31
pnpm-lock.yaml
generated
@ -265,6 +265,9 @@ importers:
|
||||
tailwind-merge:
|
||||
specifier: 3.7.0
|
||||
version: 3.7.0
|
||||
ws:
|
||||
specifier: 8.18.3
|
||||
version: 8.18.3
|
||||
devDependencies:
|
||||
'@tailwindcss/postcss':
|
||||
specifier: 4.3.5
|
||||
@ -374,6 +377,13 @@ importers:
|
||||
drizzle-orm:
|
||||
specifier: 0.45.4
|
||||
version: 0.45.4(postgres@4.1.1)
|
||||
ws:
|
||||
specifier: 8.18.3
|
||||
version: 8.18.3
|
||||
devDependencies:
|
||||
'@types/ws':
|
||||
specifier: 8.18.1
|
||||
version: 8.18.1
|
||||
|
||||
packages/shared:
|
||||
dependencies:
|
||||
@ -1272,6 +1282,9 @@ packages:
|
||||
'@types/react@19.3.0':
|
||||
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
|
||||
|
||||
'@xterm/headless@6.0.0':
|
||||
resolution: {integrity: sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==}
|
||||
|
||||
@ -2101,6 +2114,18 @@ packages:
|
||||
wrappy@1.0.2:
|
||||
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
|
||||
|
||||
ws@8.18.3:
|
||||
resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
peerDependencies:
|
||||
bufferutil: ^4.0.1
|
||||
utf-8-validate: '>=5.0.2'
|
||||
peerDependenciesMeta:
|
||||
bufferutil:
|
||||
optional: true
|
||||
utf-8-validate:
|
||||
optional: true
|
||||
|
||||
y18n@4.0.3:
|
||||
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
|
||||
|
||||
@ -2661,6 +2686,10 @@ snapshots:
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
dependencies:
|
||||
'@types/node': 26.6.6
|
||||
|
||||
'@xterm/headless@6.0.0': {}
|
||||
|
||||
'@xterm/xterm@6.0.0': {}
|
||||
@ -3441,6 +3470,8 @@ snapshots:
|
||||
|
||||
wrappy@1.0.2: {}
|
||||
|
||||
ws@8.18.3: {}
|
||||
|
||||
y18n@4.0.3: {}
|
||||
|
||||
yargs-parser@18.1.3:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user