Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : scripts/simulate.mjs9 * Module : scripts10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *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 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Simule des participants complets par l'API (peuplement de démonstration et test de charge).44// Usage : node scripts/simulate.mjs --base http://localhost:8090 --players 30 --concurrency 10 [--mode official|training] [--think 0]45const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i >= 0 ? process.argv[i + 1] : fallback; };46const base = arg("base", "http://localhost:8090");47const players = Number(arg("players", 20));48const concurrency = Number(arg("concurrency", 10));49const mode = arg("mode", "official");50const think = Number(arg("think", 0));51const prefix = arg("prefix", "Sim");52const size = Number(arg("size", 10));53const FIRST = ["Camille", "Mathis", "Léa", "Olivier", "Jade", "Samuel", "Rosalie", "Antoine", "Florence", "Xavier", "Maude", "Étienne", "Noémie", "Gabriel", "Laurence", "Félix", "Ariane", "Vincent", "Élodie", "Thomas"];54const LAST = ["Tremblay", "Gagnon", "Roy", "Côté", "Bouchard", "Gauthier", "Morin", "Lavoie", "Fortin", "Gagné", "Ouellet", "Pelletier", "Bélanger", "Lévesque", "Bergeron", "Leblanc", "Paquette", "Girard", "Simard", "Boucher"];55const timings = [];56let errors = 0;5758async function call(path, { method = "GET", body, cookie, game } = {}) {59 const t0 = performance.now();60 const res = await fetch(base + path, {61 method,62 headers: { accept: "application/json", "x-requested-with": "gdi", ...(body ? { "content-type": "application/json" } : {}), ...(cookie ? { cookie } : {}), ...(game ? { "x-game": game } : {}) },63 body: body ? JSON.stringify(body) : undefined,64 });65 const ms = performance.now() - t0;66 timings.push({ path: path.replace(/[0-9a-f-]{36}/g, ":id"), ms });67 const json = await res.json().catch(() => ({}));68 if (!res.ok) { errors += 1; throw new Error(`${res.status} ${path} ${JSON.stringify(json).slice(0, 160)}`); }69 return { json, setCookie: res.headers.getSetCookie?.() ?? [] };70}7172async function playOne(n) {73 const home = (await call("/api/v1/home")).json;74 const name = `${FIRST[n % FIRST.length]} ${LAST[(n * 7 + 3) % LAST.length]} ${prefix}${n}`;75 const course = [null, "IMM1003", "IMM1033"][n % 3];76 const skill = 0.25 + 0.7 * ((n * 37) % 100) / 100; // probabilité de « savoir »77 const start = await call("/api/v1/sessions", { method: "POST", body: { displayName: name, course, mode, competitionId: home.featured?.id, size, consent: true } });78 const id = start.json.session.id;79 const cookie = start.setCookie.map((c) => c.split(";")[0]).join("; ");80 // Chaque propriété est ouverte explicitement (le chrono démarre à l'ouverture).81 const open = async () => (await call("/api/v1/game/next", { method: "POST", game: id, cookie, body: {} })).json.question;82 let question = await open();83 while (question) {84 if (think) await new Promise((r) => setTimeout(r, think * (0.5 + Math.random())));85 // Le simulateur ne connaît pas la réponse : il choisit selon un « instinct » bruité autour du prix médian des choix.86 const sorted = [...question.choices].sort((a, b) => a.price - b.price);87 const pick = Math.random() < skill ? sorted[Math.floor(Math.random() * 4)] : question.choices[Math.floor(Math.random() * 4)];88 const res = (await call("/api/v1/game/answer", { method: "POST", game: id, cookie, body: { questionId: question.id, choiceId: pick.id, idempotencyKey: crypto.randomUUID() } })).json;89 question = res.completed ? null : await open();90 }91 return id;92}9394const t0 = performance.now();95let next = 0;96let done = 0;97await Promise.all(Array.from({ length: concurrency }, async () => {98 while (next < players) {99 const n = next++;100 try { await playOne(n); done += 1; } catch (e) { console.error("échec joueur", n, e.message); }101 }102}));103const total = (performance.now() - t0) / 1000;104const pct = (arr, p) => arr.length ? arr.sort((a, b) => a - b)[Math.min(arr.length - 1, Math.floor(arr.length * p))] : 0;105const by = {};106for (const t of timings) (by[t.path] ??= []).push(t.ms);107console.log(JSON.stringify({ players, done, concurrency, mode, seconds: Number(total.toFixed(1)), requests: timings.length, rps: Number((timings.length / total).toFixed(1)), errors,108 latencyMs: Object.fromEntries(Object.entries(by).map(([k, v]) => [k, { n: v.length, p50: Number(pct(v, 0.5).toFixed(1)), p95: Number(pct(v, 0.95).toFixed(1)), p99: Number(pct(v, 0.99).toFixed(1)), max: Number(Math.max(...v).toFixed(1)) }])) }, null, 1));109