SPB Git

Repository Public MIT

testkit.ts 9.4 KB 227 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/testkit.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 * Test harness of the platform module (used by server/next/*.test.ts only; nothing in the app imports it).47 *48 * Boots an Express app in-process on an ephemeral port, on a temporary SQLite database, with a fake gate that49 * signs a request in as the person named by the `x-test-user` header (and, optionally, as the native device named50 * by `x-test-device`). Everything behind the gate is the real code.51 */52import type { Express, NextFunction, Request, Response } from "express";53import type Database from "better-sqlite3";54import { randomBytes } from "node:crypto";55import fs from "node:fs";56import http from "node:http";57import type { AddressInfo } from "node:net";58import os from "node:os";59import path from "node:path";6061export interface TestApp {62  app: Express;63  base: string;64  port: number;65  db: Database.Database;66  /** JSON request as a person (null: not signed in). */67  api(user: string | null, method: string, url: string, body?: unknown, headers?: Record<string, string>): Promise<{ status: number; body: any; headers: Headers }>;68  close(): Promise<void>;69}7071export const USERS: Record<string, string> = { alice: "Alice", bob: "Bob", carol: "Carol", dave: "Dave", erin: "Erin", frank: "Frank" };7273/** Tables the app's own bootstrap creates elsewhere (drizzle migrations, routes/quant.ts): the columns the platform module reads. */74const LEGACY_SCHEMA = `75  CREATE TABLE IF NOT EXISTS conversation_sessions (76    id TEXT PRIMARY KEY, session_id TEXT NOT NULL UNIQUE, user_id TEXT, title TEXT NOT NULL, messages TEXT NOT NULL,77    input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0, total_cost REAL DEFAULT 0, pinned INTEGER DEFAULT 0,78    owner TEXT NOT NULL DEFAULT 'simon', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL79  );80  CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, sources TEXT, created_at INTEGER NOT NULL);81  CREATE TABLE IF NOT EXISTS shared_reports (82    id TEXT PRIMARY KEY, share_id TEXT NOT NULL UNIQUE, question TEXT NOT NULL, answer TEXT NOT NULL,83    tool_results TEXT, sources TEXT, custom_python_figures TEXT, created_at INTEGER NOT NULL84  );85  CREATE TABLE IF NOT EXISTS vq_quant_jobs (86    id TEXT PRIMARY KEY, owner TEXT NOT NULL, tool TEXT NOT NULL, params TEXT NOT NULL, status TEXT NOT NULL,87    started_at INTEGER NOT NULL, finished_at INTEGER, result TEXT, code TEXT, error TEXT,88    progress REAL, engine_version TEXT, project_id TEXT, session_id TEXT89  );90`;9192export async function bootTestApp(configure?: (app: Express) => void | Promise<void>): Promise<TestApp> {93  const file = path.join(os.tmpdir(), `vq-next-test-${process.pid}-${randomBytes(6).toString("hex")}.db`);94  // Before the first import of server/db: that module opens the database when it is loaded.95  process.env.DATABASE_URL = `sqlite://${file}`;96  process.env.ACCESS_KEY = "test-access-key-".repeat(4);97  process.env.VQ_SKIP_MIGRATION_BACKUP = "1";9899  const { pool } = await import("../db");100  const db = pool as Database.Database;101  db.exec(LEGACY_SCHEMA);102  const { runMigrations } = await import("./migrations");103  runMigrations();104105  const express = (await import("express")).default;106  const app = express();107  app.use(express.json({ limit: "10mb" }));108109  // The fake gate. The cookie form is what the server's own loopback calls send (internalAccessCookie).110  app.use((req: Request, res: Response, next: NextFunction) => {111    const cookieUser = /(?:^|;\s*)vq_access=([a-z]+)\./.exec(decodeURIComponent(String(req.headers.cookie ?? "")))?.[1];112    const id = String(req.headers["x-test-user"] ?? cookieUser ?? "");113    if (!USERS[id]) return res.status(401).json({ error: "Accès verrouillé" });114    (req as Request & { vqUser?: { id: string; name: string } }).vqUser = { id, name: USERS[id] };115    const device = req.headers["x-test-device"];116    if (typeof device === "string" && device) (req as Request & { vqDeviceId?: string }).vqDeviceId = device;117    next();118  });119120  const { registerWorkspaceRoutes } = await import("../routes/workspace");121  const { registerObjectRoutes } = await import("./objects");122  const { registerSyncRoutes } = await import("./sync");123  const { registerProjectRoutes } = await import("./projects");124  const { registerSearchRoutes } = await import("./search");125  const { registerAuditRoutes } = await import("./audit");126  const { registerMemoryRoutes } = await import("./memory");127  registerWorkspaceRoutes(app);128  registerObjectRoutes(app);129  registerSyncRoutes(app);130  registerProjectRoutes(app);131  registerSearchRoutes(app);132  registerAuditRoutes(app);133  registerMemoryRoutes(app);134  await configure?.(app);135136  const server = http.createServer(app);137  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));138  const port = (server.address() as AddressInfo).port;139  // The project "run" wrapper calls the app's own chat endpoint on this port.140  process.env.PORT = String(port);141  const base = `http://127.0.0.1:${port}`;142143  return {144    app,145    base,146    port,147    db,148    async api(user, method, url, body, headers = {}) {149      const res = await fetch(base + url, {150        method,151        headers: { ...(user ? { "x-test-user": user } : {}), ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...headers },152        body: body !== undefined ? JSON.stringify(body) : undefined,153      });154      const text = await res.text();155      let parsed: unknown = text;156      try {157        parsed = JSON.parse(text);158      } catch {159        /* not JSON: the raw text is returned */160      }161      return { status: res.status, body: parsed, headers: res.headers };162    },163    async close() {164      server.closeAllConnections();165      await new Promise<void>((resolve) => server.close(() => resolve()));166      db.close();167      for (const suffix of ["", "-wal", "-shm"]) fs.rmSync(file + suffix, { force: true });168    },169  };170}171172export interface SseEvent {173  event: string;174  data: any;175}176177/** An open SSE connection: collects named events and comments; `waitFor` resolves when one matches. */178export function openStream(base: string, user: string, url = "/api/v2/sync/stream") {179  const events: SseEvent[] = [];180  const comments: string[] = [];181  let status = 0;182  let headers: http.IncomingHttpHeaders = {};183  let buffer = "";184  const waiters: Array<() => void> = [];185  const req = http.get(base + url, { headers: { "x-test-user": user, Accept: "text/event-stream" } }, (res) => {186    status = res.statusCode ?? 0;187    headers = res.headers;188    res.setEncoding("utf8");189    res.on("data", (chunk: string) => {190      buffer += chunk;191      let cut: number;192      while ((cut = buffer.indexOf("\n\n")) >= 0) {193        const block = buffer.slice(0, cut);194        buffer = buffer.slice(cut + 2);195        if (block.startsWith(":")) comments.push(block);196        else {197          const event = /^event: (.+)$/m.exec(block)?.[1] ?? "message";198          const data = /^data: (.+)$/m.exec(block)?.[1];199          events.push({ event, data: data ? JSON.parse(data) : null });200        }201      }202      for (const w of waiters.splice(0)) w();203    });204    for (const w of waiters.splice(0)) w();205  });206  req.on("error", () => undefined);207  const waitFor = async (pred: (e: SseEvent) => boolean, ms = 3000): Promise<SseEvent> => {208    const until = Date.now() + ms;209    for (;;) {210      const hit = events.find(pred);211      if (hit) return hit;212      const left = until - Date.now();213      if (left <= 0) throw new Error(`no matching SSE event within ${ms} ms (got ${JSON.stringify(events)})`);214      await new Promise<void>((resolve) => {215        const t = setTimeout(resolve, Math.min(left, 100));216        waiters.push(() => {217          clearTimeout(t);218          resolve();219        });220      });221    }222  };223  return { events, comments, waitFor, close: () => req.destroy(), status: () => status, headers: () => headers };224}225226export const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));227
Files main
Menu

Theme