SPB Git

Repository Public

harness.ts 7.9 KB 90 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : tests/e2e/harness.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { createServer } from 'node:net';43import { existsSync } from 'node:fs';44import { join } from 'node:path';45import WebSocket from 'ws';46import { makeEnv, type Env, type TestUser } from '../helpers.ts';47import { startFixtureSite, type FixtureSite } from '../../services/fixture-site/src/site.ts';48import { startGateway } from '../../services/navigator-gateway/src/gateway.ts';49import { SECURITY_HEADERS } from '../../services/control-api/src/app.ts';50import { NavigatorWorker } from '../../workers/navigator-worker/src/worker.ts';51import { startScheduler } from '../../services/scheduler/src/scheduler.ts';5253export const freePort = () => new Promise<number>((res) => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = (s.address() as any).port; s.close(() => res(p)); }); });54export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));55export async function until<T>(fn: () => Promise<T | false | null | undefined> | T | false | null | undefined, what: string, timeoutMs = 20000, every = 100): Promise<T> {56  const t0 = Date.now(); let last: unknown; for (;;) { try { const v = await fn(); if (v) return v as T; } catch (e) { last = e; } if (Date.now() - t0 > timeoutMs) throw new Error(`attente expirée : ${what}${last ? ` (${String((last as Error).message)})` : ''}`); await sleep(every); }57}58export type Stack = { env: Env; site: FixtureSite; gw: Awaited<ReturnType<typeof startGateway>>; ctlUrl: string; navOrigin: string; gwInternal: number; owner: TestUser; logs: object[]; profilesDir: string;59  startWorker: (name: string) => Promise<{ id: string; token: string; worker: NavigatorWorker }>; close: () => Promise<void>; nav: (u: TestUser, method: string, path: string, body?: unknown) => Promise<{ status: number; json: any }>; viewer: (u: TestUser | null, sessionId: string, opts?: { origin?: string | null; cookie?: string | null }) => Promise<Viewer> };60export type Viewer = { ws: WebSocket; msgs: any[]; frames: { n: number; w: number; h: number; bytes: number; at: number }[]; send: (m: object) => void; wait: (pred: (m: any) => boolean, what: string, ms?: number) => Promise<any>; close: () => void; last: (t: string) => any };6162export async function makeStack(): Promise<Stack> {63  const site = await startFixtureSite(0); const ctlPort = await freePort(); const gwPort = await freePort(); const gwInternal = await freePort();64  const ctlUrl = `http://127.0.0.1:${ctlPort}`; const navOrigin = `http://127.0.0.1:${gwPort}`;65  const env = await makeEnv({ MLS_FIXTURE_ORIGIN: site.url, MLS_SOCIAL_ORIGIN: ctlUrl, MLS_NAVIGATOR_ORIGIN: navOrigin, MLS_GATEWAY_INTERNAL_URL: `http://127.0.0.1:${gwInternal}`, MLS_CONTROL_INTERNAL_URL: ctlUrl, PORT: String(ctlPort) });66  // real notifications to the real gateway (makeEnv captured them in an array; re-point the context)67  env.ctx.notifyGateway = (event) => { env.notified.push(event); fetch(`http://127.0.0.1:${gwInternal}/internal/notify`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${env.ctx.serviceToken}` }, body: JSON.stringify(event) }).catch(() => {}); };68  await env.app.listen({ host: '127.0.0.1', port: ctlPort });69  const gw = await startGateway({ host: '127.0.0.1', port: gwPort, internalPort: gwInternal, origin: navOrigin, controlUrl: ctlUrl, serviceToken: env.ctx.serviceToken, webDir: '', cookieName: 'mls', trustProxy: [], securityHeaders: SECURITY_HEADERS });70  const stopScheduler = startScheduler(env.db, env.cfg); const owner = await env.user('owner'); const workers: NavigatorWorker[] = []; const logs: object[] = []; const profilesDir = join(env.dir, 'profiles');71  const navHost = new URL(navOrigin).host;72  return { env, site, gw, ctlUrl, navOrigin, gwInternal, owner, logs, profilesDir,73    async startWorker(name) { const w = await env.call(owner, 'POST', '/v1/workers', { name }); if (w.status !== 200) throw new Error(JSON.stringify(w.json));74      const worker = new NavigatorWorker({ controlUrl: ctlUrl, gatewayWsUrl: `ws://127.0.0.1:${gwInternal}/worker`, token: w.json.token, profilesDir, headed: process.env.MLS_E2E_HEADED === '1', version: 'e2e', heartbeatMs: 250, claimMs: 250, log: (o) => logs.push(o) });75      await worker.start(); workers.push(worker); return { id: w.json.id, token: w.json.token, worker }; },76    /** Calls go through the navigator gateway's HTTP proxy, like a real browser on navigator.spboucher.ai. */77    async nav(u, method, path, body) { const r = await fetch(`${navOrigin}${path}`, { method, headers: { cookie: `mls=${u.cookie}${navHost}`, 'x-csrf': u.csrf, origin: navOrigin, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: r.status, json: await r.json().catch(() => null) }; },78    viewer(u, sessionId, opts = {}) { return new Promise<Viewer>((resolve, reject) => {79      const headers: Record<string, string> = {}; const origin = opts.origin === undefined ? navOrigin : opts.origin; if (origin) headers.origin = origin;80      const cookie = opts.cookie === undefined ? (u ? `mls=${u.cookie}${navHost}` : null) : opts.cookie; if (cookie) headers.cookie = cookie;81      const ws = new WebSocket(`ws://127.0.0.1:${gwPort}/nav/ws?session=${sessionId}`, { headers });82      const v: Viewer = { ws, msgs: [], frames: [], send: (m) => ws.send(JSON.stringify(m)), close: () => ws.close(), last: (t) => v.msgs.filter((m) => m.t === t).at(-1),83        wait: (pred, what, ms = 15000) => until(() => v.msgs.find(pred), what, ms, 40) };84      ws.on('message', (raw: Buffer, isBinary) => { if (isBinary) { const n = raw.readUInt32BE(0); v.frames.push({ n, w: raw.readUInt16BE(4), h: raw.readUInt16BE(6), bytes: raw.length - 8, at: Date.now() }); if (raw[8] !== 0xff || raw[9] !== 0xd8) throw new Error('trame non JPEG'); ws.send(JSON.stringify({ t: 'ack', frame: n })); } else v.msgs.push(JSON.parse(raw.toString())); });85      ws.on('open', () => resolve(v)); ws.on('unexpected-response', (_req, res) => reject(new Error(`HTTP ${res.statusCode}`))); ws.on('error', (e) => reject(e));86    }); },87    async close() { stopScheduler(); for (const w of workers) await w.stop(); await gw.close(); await site.close(); await env.close(); } };88}89export const profileDirs = (s: Stack) => (existsSync(s.profilesDir) ? require('node:fs').readdirSync(s.profilesDir).filter((f: string) => !f.endsWith('.lock')) : []);90
Files main
Menu

Theme