sokko-g/scripts/start-cards-e2e-server.mjs
Shinuwa 2831f01195
Some checks failed
Validate and deploy Sokko G / validate (push) Successful in 22m38s
Validate and deploy Sokko G / deploy (push) Failing after 43s
Let the cards E2E server raise the development login limit
Development logins were capped at a hard-coded 10 per minute per address.
The cards E2E suite logs in 21 times, and with the test added in 067a4a8
the expedition test's login became the eleventh within one minute: it got
"Trop de tentatives", never reached the admin guild tab and timed out in
CI. The limit is now the devAuthRateLimit option, still 10 by default, and
the E2E server raises it as it already did for apiRateLimit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:13:17 +01:00

82 lines
5.2 KiB
JavaScript

// Rôle : démarre le build avec une base Sokko TCG temporaire pour les parcours Playwright.
import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const directory = mkdtempSync(join(tmpdir(), "sokkog-cards-e2e-"));
process.env.NODE_ENV = "production";
process.env.PORT = process.env.PORT || "4180";
process.env.CARDS_ENABLED = "true";
process.env.CARDS_DEV_AUTH = "true";
process.env.CARDS_DB_PATH = join(directory, "cards.sqlite");
process.env.CARDS_PUBLIC_ORIGIN = `http://127.0.0.1:${process.env.PORT}`;
process.env.CARDS_PRIVACY_CONTACT = "privacy@example.invalid";
process.env.CARDS_PRIVACY_CONTROLLER = "Exploitant E2E";
// Rend le bouton Discord visible ; les parcours ne le suivent jamais jusqu'à Discord.
process.env.DISCORD_CLIENT_ID = "e2e-client";
process.env.DISCORD_CLIENT_SECRET = "e2e-secret";
// Un second joueur, avec des doublons et une session, pour les parcours d'échange et de don à deux comptes.
const [{ CardsDatabase }, { CardsService }, { loadCardsCatalog }] = await Promise.all([import("../services/cards/database.js"), import("../services/cards/service.js"), import("../services/cards/catalog.js")]);
const seedDatabase = new CardsDatabase(process.env.CARDS_DB_PATH);
const seedService = new CardsService({ database: seedDatabase, catalog: loadCardsCatalog(join(import.meta.dirname, "..", "website", "public", "data", "cards", "catalog.json")) });
const partner = seedService.upsertPlayer({ discordId: "e2e-partner", displayName: "Partenaire E2E" });
for (const editionId of ["aurora-wolf-standard", "aurora-wolf-standard", "aurora-wolf-standard", "aurora-wolf-standard", "starvoid-dragon-standard", "starvoid-dragon-standard", "starvoid-dragon-standard"]) seedService.addCard(partner.id, editionId);
// Toutes les cartes de destination : le parcours des Expéditions tire ses 4 destinations du jour parmi toutes.
for (const card of seedService.catalog.cards.filter((item) => item.kind === "destination")) seedService.addCard(partner.id, seedService.catalog.editions.find((edition) => edition.cardId === card.id).id);
seedDatabase.db.prepare("UPDATE players SET stardust = 500 WHERE id = ?").run(partner.id);
writeFileSync(join(tmpdir(), "sokkog-cards-e2e-partner.json"), JSON.stringify({ token: seedService.createSession(partner.id).token }));
// Chaque joueur a sa propre Carte du jour, jamais exposée par l'API avant la fin de la partie : le parcours la lit en base.
writeFileSync(join(tmpdir(), "sokkog-cards-e2e-db.json"), JSON.stringify({ path: process.env.CARDS_DB_PATH }));
// Une base neuve n'a aucune variation mythique : les parcours de jeu et d'administration en ont besoin.
const insertVariation = seedDatabase.db.prepare("INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', 0, NULL)");
for (const cardId of ["starvoid-dragon", "crimson-moon-kitsune", "milky-way-panda", "constellation-magpie", "solar-dawn-capybara", "aurora-wolf"]) {
for (const finishId of ["spectral-prism-aurora", "spectral-prism-cosmic"]) insertVariation.run(`${cardId}-${finishId}`, cardId, finishId);
}
insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull", "spectral-prism-solar");
// L'administration distingue les variations déjà possédées : ses parcours ne doivent pas dépendre d'un tirage d'un autre test.
seedService.addCard(partner.id, "starvoid-dragon-spectral-prism-aurora");
seedDatabase.close();
// Horloge du serveur décalable par les parcours (retour d'une expédition sans attendre des heures) : le décalage, en millisecondes,
// est lu dans ce fichier, relu au plus toutes les 200 ms. Il repart de zéro à chaque démarrage.
const clockFile = join(tmpdir(), "sokkog-cards-e2e-clock.json");
writeFileSync(clockFile, JSON.stringify({ offsetMs: 0 }));
let clockOffset = 0;
let clockReadAt = 0;
function now() {
const real = Date.now();
if (real - clockReadAt > 200) {
clockReadAt = real;
try {
clockOffset = Number(JSON.parse(readFileSync(clockFile, "utf8")).offsetMs) || 0;
} catch {
clockOffset = 0;
}
}
return real + clockOffset;
}
const { startServer } = await import("../server.mjs");
const draws = [0.999, 0, 0.999, 0.999, 0.999, 0];
let drawIndex = 0;
// Tous les parcours et leurs deux comptes partagent la même adresse IP : les limites par minute, connexion de développement
// comprise, les feraient échouer au hasard.
// Alertes Discord sans bot : chaque message est écrit dans ce fichier, une ligne JSON par alerte.
const alertsFile = join(tmpdir(), "sokkog-cards-e2e-alerts.jsonl");
writeFileSync(alertsFile, "");
const sendAlert = async (discordId, content) => appendFileSync(alertsFile, `${JSON.stringify({ discordId, content })}\n`);
const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, devAuthRateLimit: 100_000, now, sendAlert, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } });
let stopping = false;
function stop() {
if (stopping) return;
stopping = true;
server.close(() => {
rmSync(directory, { recursive: true, force: true });
process.exit(0);
});
}
process.on("SIGTERM", stop);
process.on("SIGINT", stop);