SPB Git

Repository Public MIT

sync.ts 7.0 KB 174 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/sync.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Sync (contract §1.2): the change feed of the object store and the stream that tells a person's devices to pull it.47 *48 *   GET /api/v2/sync/changes?since=<seq>&kinds=a,b&limit=500   envelopes written after `since`, ascending seq49 *   GET /api/v2/sync/stream                                    SSE: hello, change, hint, comment heartbeats50 *51 * The stream carries no content, only pointers ("this object changed", "your generations changed"): a device that52 * hears one pulls `changes` or the matching list. The bus is in-process and per owner (the app runs as one53 * process); a subscriber only ever receives the events of the person it signed in as.54 */55import type { Express, Request, Response } from "express";56import { logger } from "../utils/logger";57import { currentSeq, isKind, listChanges, type Envelope, type Kind } from "./objects";5859export type HintTopic = "sessions" | "generations" | "quant_jobs";6061const HEARTBEAT_MS = 25_000;62/** Open streams per person: three platforms, a few windows each. Beyond that something is leaking connections. */63const MAX_STREAMS_PER_OWNER = 24;6465const subscribers = new Map<string, Set<Response>>();6667function send(res: Response, text: string): void {68  if (res.writableEnded || res.destroyed) return;69  res.write(text);70  (res as Response & { flush?: () => void }).flush?.();71}7273/** Named SSE event; `type` is repeated in the payload for clients that read `data:` lines only. */74const frame = (event: string, payload: Record<string, unknown>) => `event: ${event}\ndata: ${JSON.stringify({ type: event, ...payload })}\n\n`;7576function broadcast(owner: string, text: string): void {77  const set = subscribers.get(owner);78  if (!set) return;79  for (const res of set) {80    try {81      send(res, text);82    } catch {83      /* a broken stream is removed by its own close handler */84    }85  }86}8788/** Called by the object store after a committed write. */89export function publishChange(owner: string, e: Pick<Envelope, "kind" | "id" | "rev" | "seq" | "deleted" | "device">): void {90  broadcast(owner, frame("change", { kind: e.kind, id: e.id, rev: e.rev, seq: e.seq, deleted: e.deleted, device: e.device }));91}9293/** Tells the person's devices that something outside the object store changed (a generation or a quant job started or finished). */94export function publishHint(owner: string, topic: HintTopic, id?: string): void {95  try {96    broadcast(owner, frame("hint", id ? { topic, id } : { topic }));97  } catch (e) {98    logger.warn(`[sync] hint not sent: ${(e as Error).message}`);99  }100}101102/** Open streams (of one person, or of everyone): used by tests and diagnostics. */103export function streamCount(owner?: string): number {104  if (owner) return subscribers.get(owner)?.size ?? 0;105  let n = 0;106  for (const s of subscribers.values()) n += s.size;107  return n;108}109110const ownerId = (req: Request): string => {111  const user = (req as Request & { vqUser?: { id: string } }).vqUser;112  if (!user) throw new Error("Request reached a handler without passing the access gate");113  return user.id;114};115116export function registerSyncRoutes(app: Express): void {117  app.get("/api/v2/sync/changes", (req: Request, res: Response) => {118    const owner = ownerId(req);119    const sinceRaw = String(req.query.since ?? "0");120    if (!/^\d{1,15}$/.test(sinceRaw)) return res.status(400).json({ error: "since must be a change number (0 for everything)" });121    let kinds: Kind[] | null = null;122    if (typeof req.query.kinds === "string" && req.query.kinds.trim() !== "") {123      const asked = req.query.kinds.split(",").map((k) => k.trim()).filter(Boolean);124      const unknown = asked.find((k) => !isKind(k));125      if (unknown) return res.status(400).json({ error: `Unknown kind: ${unknown.slice(0, 40)}` });126      kinds = asked as Kind[];127    }128    const limit = Number.parseInt(String(req.query.limit ?? "500"), 10);129    try {130      res.set("Cache-Control", "private, no-store").json(listChanges(owner, Number(sinceRaw), kinds, Number.isFinite(limit) ? limit : 500));131    } catch (e) {132      logger.error(`[sync] changes: ${(e as Error).message}`);133      res.status(500).json({ error: "Sync error" });134    }135  });136137  app.get("/api/v2/sync/stream", (req: Request, res: Response) => {138    const owner = ownerId(req);139    let set = subscribers.get(owner);140    if (set && set.size >= MAX_STREAMS_PER_OWNER) return res.status(429).json({ error: "Too many open sync streams for this account." });141    let seq: number;142    try {143      seq = currentSeq(owner);144    } catch (e) {145      logger.error(`[sync] stream: ${(e as Error).message}`);146      return res.status(500).json({ error: "Sync error" });147    }148149    res.setHeader("Content-Type", "text/event-stream");150    res.setHeader("Cache-Control", "no-cache, no-transform");151    res.setHeader("Connection", "keep-alive");152    res.setHeader("X-Accel-Buffering", "no");153    res.flushHeaders();154155    if (!set) subscribers.set(owner, (set = new Set()));156    set.add(res);157    // Subscribed before `hello` is written: a change committed in between is delivered, never lost.158    send(res, frame("hello", { seq }));159160    // Comment lines keep proxies from closing a stream that is silent for a long time.161    const beat = setInterval(() => send(res, ": ping\n\n"), HEARTBEAT_MS);162    beat.unref();163    const cleanup = () => {164      clearInterval(beat);165      const mine = subscribers.get(owner);166      if (!mine) return;167      mine.delete(res);168      if (mine.size === 0) subscribers.delete(owner);169    };170    res.on("close", cleanup);171    res.on("error", cleanup);172  });173}174
Files main
Menu

Theme