diff --git a/public/app.js b/public/app.js index 6ecf5e1..f6df6ad 100644 --- a/public/app.js +++ b/public/app.js @@ -169,7 +169,7 @@ let busy = false; try { const s = await api('/api/system'); - const hot = s.temp !== null && s.temp >= s.thermalMax - 5; + const hot = s.temp !== null && s.temp >= 70; el.innerHTML = `${s.temp !== null ? `${s.temp} °C` : ''} ${claudeQuota(s.claudeRateLimit, s.linkMode)} ${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)} diff --git a/src/config.js b/src/config.js index 3ff2266..931be91 100644 --- a/src/config.js +++ b/src/config.js @@ -38,6 +38,19 @@ function recaptchaConfig() { return { siteKey, secret, minScore }; } +function positive(v, def, name) { + if (v == null || String(v).trim() === '') return def; + const n = Number(v); + if (!Number.isInteger(n) || n < 1 || n > 64) throw new Error(`${name} doit être un entier entre 1 et 64`); + return n; +} +function ratio(v, def, name) { + if (v == null || String(v).trim() === '') return def; + const n = Number(v); + if (!(n > 0.1 && n <= 4)) throw new Error(`${name} doit être un nombre entre 0,1 et 4 (charge divisée par le nombre de cœurs)`); + return n; +} + const flag = (v, def) => (v == null || v === '' ? def : !/^(0|false|off|no|non)$/i.test(String(v).trim())); // Bac à sable des exécutions Claude. En production il est obligatoire : SANDBOX=off n'y est pas pris en compte. @@ -81,7 +94,9 @@ export function loadConfig() { // Mode « abonnement » (jeton claude setup-token) : désactivable globalement cliModeEnabled: flag(env.CLAUDE_CLI_MODE_ENABLED, true), sandbox: sandboxConfig(), - thermalMax: Number(env.THERMAL_MAX || 75), + // Jobs IA simultanés sur le serveur (un seul par utilisateur) et charge (charge/cœurs) au-delà de laquelle les nouveaux jobs attendent + maxAiJobs: positive(env.MAX_AI_JOBS, 4, 'MAX_AI_JOBS'), + loadMax: ratio(env.LOAD_MAX, 0.9, 'LOAD_MAX'), // Derrière Nginx/CloudPanel : lire X-Forwarded-For, mais seulement depuis un proxy de confiance (voir ratelimit.js) trustProxy: parseTrustProxy(env.TRUST_PROXY), }; diff --git a/src/netguard.js b/src/netguard.js new file mode 100644 index 0000000..cf73e93 --- /dev/null +++ b/src/netguard.js @@ -0,0 +1,83 @@ +// Filtrage des hôtes saisis par l'utilisateur (SMTP, IMAP, base du récap, Forgejo) : un compte ne doit pas pouvoir +// sonder le réseau interne du serveur (MySQL local, métadonnées cloud, autres sites CloudPanel). +// +// Principe : on RÉSOUT le nom, on refuse toute adresse privée, puis on SE CONNECTE À L'ADRESSE VÉRIFIÉE (et non au nom). +// La vérification porte donc sur l'IP réellement utilisée : un nom dont la réponse DNS change entre la saisie et la +// connexion (rebinding) est revérifié à chaque nouvelle connexion, et ne peut pas changer entre la vérification et l'usage. +import { isIP } from 'node:net'; +import dns from 'node:dns/promises'; +import { HttpError } from './http.js'; +import { ALLOWED_PORTS } from './limits.js'; +import { blockedReason } from './ip.js'; + +// ---------- Résolution ---------- + +/** Résolveur par défaut : getaddrinfo, toutes les adresses (comme le fera la connexion). */ +export async function defaultResolve(host) { + const out = await dns.lookup(host, { all: true, verbatim: true }); + return out.map((a) => ({ address: a.address, family: a.family })); +} + +const HOST_RE = /^(?=.{1,253}$)[A-Za-z0-9]([A-Za-z0-9_-]{0,62})(\.[A-Za-z0-9_-]{1,63})*\.?$/; + +/** Exception de développement : adresses privées autorisées (ALLOW_PRIVATE_HOSTS), en production pour les administrateurs seulement. */ +export async function privateAllowed(app, userId) { + if (!app.cfg.allowPrivateHosts) return false; + if (!app.cfg.production) return true; + if (userId == null) return false; + return !!(await app.db.prepare('SELECT is_admin FROM users WHERE id = ?').get(Number(userId)))?.is_admin; +} + +export function assertPort(kind, port, { allowPrivate = false } = {}) { + const n = Number(port); + if (!Number.isInteger(n) || n < 1 || n > 65535) throw new HttpError(400, 'Port invalide', { expose: true }); + if (allowPrivate) return n; + const allowed = ALLOWED_PORTS[kind]; + if (!allowed) throw new Error(`Type d'hôte inconnu : ${kind}`); + if (!allowed.includes(n)) throw new HttpError(400, `Port ${n} refusé pour ce service (ports acceptés : ${allowed.join(', ')})`, { expose: true }); + return n; +} + +/** + * Résout `host` et refuse l'hôte si UNE SEULE de ses adresses est privée (un nom qui répond tantôt public, tantôt interne + * ne passe pas). Une IP littérale est contrôlée telle quelle, sans DNS. + * @returns {Promise<{address: string, family: 4|6, servername: string|null}>} adresse à utiliser pour la connexion + */ +export async function resolvePublic(host, { resolve = defaultResolve, allowPrivate = false, lenient = false } = {}) { + const name = String(host ?? '').trim().replace(/^\[|\]$/g, ''); + const literal = isIP(name) ? name : null; + if (!literal && !HOST_RE.test(name)) throw new HttpError(400, `Hôte invalide : « ${String(host).slice(0, 80)} »`, { expose: true }); + let addrs; + if (literal) addrs = [{ address: literal, family: isIP(literal) }]; + else { + try { addrs = await resolve(name); } + catch { + if (lenient) return null; // enregistrement d'un réglage : le nom pourra devenir résolvable plus tard, il sera revérifié à l'usage + throw new HttpError(400, `Hôte introuvable : « ${name.slice(0, 80)} » ne répond pas au DNS`, { expose: true }); + } + } + if (!addrs?.length) { + if (lenient) return null; + throw new HttpError(400, `Hôte introuvable : « ${name.slice(0, 80)} » ne répond pas au DNS`, { expose: true }); + } + if (!allowPrivate) { + for (const a of addrs) { + const why = blockedReason(a.address); + if (why) throw new HttpError(400, `Hôte refusé : « ${name.slice(0, 80)} » pointe vers une adresse interne ou réservée (${why}). Seuls les serveurs publics sont acceptés.`, { expose: true }); + } + } + return { address: addrs[0].address, family: addrs[0].family || isIP(addrs[0].address), servername: literal ? null : name }; +} + +/** + * Contrôle complet d'une cible saisie par l'utilisateur : port de la liste, résolution, adresses publiques. + * `app.resolveHost` permet aux tests d'injecter un résolveur DNS. `lenient` : à l'enregistrement d'un réglage. + * @param {'smtp'|'imap'|'mysql'|'pg'|'git'} kind + * @returns {Promise<{address: string, family: 4|6, servername: string|null, port: number} | null>} null = hôte non résolu (lenient) + */ +export async function guardTarget(app, userId, kind, host, port, { lenient = false } = {}) { + const allowPrivate = await privateAllowed(app, userId); + const checkedPort = assertPort(kind, port, { allowPrivate }); + const r = await resolvePublic(host, { resolve: app.resolveHost || defaultResolve, allowPrivate, lenient }); + return r && { ...r, port: checkedPort }; +} diff --git a/src/routes.js b/src/routes.js index 9bb9307..befee30 100644 --- a/src/routes.js +++ b/src/routes.js @@ -268,7 +268,7 @@ export function registerRoutes(router, app) { runAfter: r.run_after, startedAt: r.started_at, createdAt: r.created_at, })); json(res, { - temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax, + temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null, linkMode: link?.mode ?? null, }); }); diff --git a/src/server.js b/src/server.js index 35da47b..72afc4c 100644 --- a/src/server.js +++ b/src/server.js @@ -112,7 +112,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch let scheduler = null; if (worker) { w = new Worker(db, makeHandlers(app), { - thermalMax: cfg.thermalMax, cliModeEnabled: cfg.cliModeEnabled !== false, + maxJobs: cfg.maxAiJobs ?? 4, loadMax: cfg.loadMax, cliModeEnabled: cfg.cliModeEnabled !== false, onFinish: (job, r) => notifyJob(app, job, r), budget: (userId) => budgetState(db, userId), isAiJob: (type) => AI_JOBS.has(type), @@ -126,9 +126,9 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch title: 'Job IA reporté (quota serré)', level: 'warn', description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`, }), - onThermal: (t, userId) => notify(app, userId, 'thermal', { - title: 'Pause thermique', level: 'warn', - description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`, + onLoad: (ratio, userId) => notify(app, userId, 'load', { + title: 'Serveur très chargé', level: 'warn', + description: `Charge du serveur à ${Math.round(ratio * 100)} % : tes jobs attendent un instant, ils repartent tout seuls.`, }), }); await w.start(); diff --git a/src/services/jobs.js b/src/services/jobs.js index bde4b6c..33ed299 100644 --- a/src/services/jobs.js +++ b/src/services/jobs.js @@ -1,10 +1,11 @@ -// File de jobs en base, UN seul worker : un seul `claude` à la fois. +// File de jobs en base : jobs IA simultanés (plafond global), un seul par utilisateur, tourniquet entre utilisateurs. import { now } from '../db.js'; import { HttpError } from '../http.js'; import { AI_JOBS } from './budget.js'; import { getUser } from '../users.js'; import { aiRefusal, assertCanRunAi } from '../claudelink.js'; -import { waitCool } from './thermal.js'; +import { loadRatio } from './load.js'; +import { LOAD } from '../limits.js'; import { assertRoom, recordUsage, withUserLock, MAIL_JOBS } from './plans.js'; /** @@ -82,13 +83,27 @@ export async function latestJobs(db, projectId) { return out; } +/** + * File de jobs équitable et simultanée. + * - jusqu'à `maxJobs` jobs en parallèle sur le serveur (MAX_AI_JOBS) ; + * - au plus UN job à la fois par utilisateur ; + * - prochain job choisi en tourniquet entre utilisateurs (le moins récemment servi d'abord), donc pas de famine ; + * à l'intérieur d'un utilisateur, l'ordre des jobs (par id) est conservé, y compris pour les jobs programmés la nuit ; + * - réservation atomique : UPDATE conditionnel dont on contrôle le nombre de lignes affectées ; + * - nouveaux jobs en pause quand la charge du serveur (charge/cœurs) dépasse `loadMax` ; les jobs en cours continuent. + * Budget $ et quota du compte Claude restent évalués par utilisateur. + */ export class Worker { constructor(db, handlers, { - thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal, + maxJobs = 4, loadMax = LOAD.defaultMax, load = loadRatio, pollMs = 3000, log = console, clock = now, onFinish, onLoad, budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold, cliModeEnabled = true, } = {}) { this.cliModeEnabled = cliModeEnabled; this.clock = clock; + this.maxJobs = Math.max(1, Math.floor(Number(maxJobs)) || 1); + this.loadMax = loadMax; + this.load = load; + this.loadPaused = false; this.budget = budget; // async (userId) => {blocked, reason} : budget de CET utilisateur this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint this.onBudget = onBudget; // (reason, userId) → une notif quand le blocage commence @@ -98,15 +113,19 @@ export class Worker { this.onQuotaHold = onQuotaHold; // (reason, userId) → une notif quand le report commence this.quotaBlocked = new Set(); this.onFinish = onFinish; // (job, {status, result, error}) → notifications - this.onThermal = onThermal; // (°C, userId) → une fois par pause + this.onLoad = onLoad; // (ratio, userId) → une fois par pause et par utilisateur en attente + this.loadNotified = new Set(); this.db = db; this.handlers = handlers; - this.thermalMax = thermalMax; this.pollMs = pollMs; this.log = log; - this.current = null; - this.currentJob = null; + this.running = new Map(); // id du job → { job, ctrl } + this.busyUsers = new Set(); // utilisateurs ayant un job réservé ou en cours (un seul à la fois chacun) + this.claiming = 0; // réservations en cours (pour ne jamais dépasser maxJobs) + this.served = new Map(); // utilisateur → rang de son dernier service (tourniquet) + this.turn = 0; this.stopped = false; + this.inflight = new Set(); // jobs lancés par la boucle (attendus à l'arrêt) this.pending = new Set(); // callbacks de notification en vol (attendus à l'arrêt) this.loopDone = null; this.wake = null; @@ -118,23 +137,26 @@ export class Worker { this.loopDone = this.loop(); } - /** Arrête la boucle et attend le job en cours ainsi que les notifications en vol. */ + /** Arrête la boucle, interrompt TOUS les jobs en cours et les attend, ainsi que les notifications en vol. */ async stop() { this.stopped = true; - this.current?.abort(); + for (const { ctrl } of this.running.values()) ctrl.abort(); this.wake?.(); await this.loopDone; + while (this.inflight.size) await Promise.allSettled([...this.inflight]); await this.idle(); } - /** Interrompt le job en cours s'il appartient à cet utilisateur (suppression du compte). */ + /** Interrompt les jobs en cours de cet utilisateur (suppression du compte, suspension). */ abortUser(userId) { - if (this.currentJob && Number(this.currentJob.user_id) === Number(userId)) this.current?.abort(); + for (const { job, ctrl } of this.running.values()) if (Number(job.user_id) === Number(userId)) ctrl.abort(); } - /** Interrompt le job en cours s'il est un job IA de cet utilisateur (déliaison de son accès Claude). */ + /** Interrompt le job IA en cours de cet utilisateur (déliaison de son accès Claude). */ abortUserAi(userId) { - if (this.currentJob && Number(this.currentJob.user_id) === Number(userId) && this.isAiJob?.(this.currentJob.type)) this.current?.abort(); + for (const { job, ctrl } of this.running.values()) { + if (Number(job.user_id) === Number(userId) && this.isAiJob?.(job.type)) ctrl.abort(); + } } /** Attend les callbacks (notifications) lancés par emit(). */ @@ -158,73 +180,124 @@ export class Worker { async loop() { while (!this.stopped) { - let ran = false; - try { ran = await this.tick(); } - catch (e) { this.log.error('[worker]', e.message); } // base indisponible : on réessaie au prochain passage - if (!ran && !this.stopped) { + try { + for (;;) { + const job = await this.claim(); + if (!job) break; + this.launch(job); + } + } catch (e) { this.log.error('[worker]', e.message); } // base indisponible : on réessaie au prochain passage + if (!this.stopped) { await new Promise((r) => { this.wake = r; setTimeout(r, this.pollMs).unref(); }); this.wake = null; } } } + launch(job) { + const p = this.runJob(job).catch((e) => this.log.error(`[job ${job.id}]`, e.message)).finally(() => { this.inflight.delete(p); this.wake?.(); }); + this.inflight.add(p); + } + + /** Réserve et exécute un job (jusqu'à sa fin). Renvoie false s'il n'y avait rien à lancer. Utilisé tel quel par les tests. */ async tick() { - const due = await this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued' - AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock()); - if (!due.length) return false; - - // Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file - // (pas perdus), les autres passent devant. Deux garde-fous indépendants, deux périmètres : - // le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents - // (analyse, évolutions) — la prospection et les envois continuent. Chaque utilisateur a les siens. - const budgets = new Map(), quotas = new Map(); - const perUser = async (cache, fn, userId) => { - if (!cache.has(userId)) cache.set(userId, (await fn?.(userId)) || { blocked: false }); - return cache.get(userId); - }; - const hold = async (j, reason) => { - const msg = JSON.stringify({ message: `En attente : ${reason}` }); - if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id); - }; - let job = null; - const waiting = new Map(), quotaWaiting = new Map(); - for (const j of due) { - // Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution - const refusal = await jobRefusal(this.db, j, { cliModeEnabled: this.cliModeEnabled }); - if (refusal) { - await this.db.prepare("UPDATE jobs SET status = 'error', error = ?, finished_at = ? WHERE id = ? AND status = 'queued'").run(refusal, now(), j.id); - continue; - } - const budget = await perUser(budgets, this.budget, j.user_id); - if (budget.blocked && this.isAiJob?.(j.type)) { waiting.set(j.user_id, budget.reason); await hold(j, budget.reason); continue; } - const quota = await perUser(quotas, this.quota, j.user_id); - if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting.set(j.user_id, quota.reason); await hold(j, quota.reason); continue; } - job = j; - break; - } - for (const [userId, reason] of waiting) if (!this.budgetBlocked.has(userId)) this.emit('onBudget', reason, userId); - this.budgetBlocked = new Set(waiting.keys()); - for (const [userId, reason] of quotaWaiting) if (!this.quotaBlocked.has(userId)) this.emit('onQuotaHold', reason, userId); - this.quotaBlocked = new Set(quotaWaiting.keys()); + const job = await this.claim(); if (!job) return false; - const handler = this.handlers[job.type]; - if (!handler) { - await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id); - return true; - } + await this.runJob(job); + return true; + } - let warned = false; - await waitCool(this.thermalMax, { - onWait: async (t) => { - await setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` }); - if (!warned) { warned = true; this.emit('onThermal', t, job.user_id); } - }, - }); + /** + * Choisit le prochain job et le réserve atomiquement. Renvoie le job réservé (déjà « running » en base), ou null. + * Sûr si appelé en parallèle : un utilisateur n'a jamais deux jobs, le nombre total reste borné. + */ + async claim() { + if (this.stopped || this.running.size + this.claiming >= this.maxJobs) return null; + this.claiming++; + try { + const due = await this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued' + AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock()); + if (!due.length) return null; - await this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id); + // Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file (pas perdus), les autres + // passent devant. Le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents. + const hold = async (j, reason) => { + const msg = JSON.stringify({ message: `En attente : ${reason}` }); + if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id); + }; + const byUser = new Map(); + for (const j of due) { + if (!byUser.has(j.user_id)) byUser.set(j.user_id, []); + byUser.get(j.user_id).push(j); + } + const candidates = []; // un seul candidat par utilisateur : son premier job exécutable + for (const [userId, jobs] of byUser) { + if (this.busyUsers.has(Number(userId))) continue; // déjà un job en cours : les suivants attendent + let budgetReason = null, quotaReason = null, cand = null; + for (const j of jobs) { + // Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution + const refusal = await jobRefusal(this.db, j, { cliModeEnabled: this.cliModeEnabled }); + if (refusal) { + await this.db.prepare("UPDATE jobs SET status = 'error', error = ?, finished_at = ? WHERE id = ? AND status = 'queued'").run(refusal, now(), j.id); + continue; + } + const b = (await this.budget?.(j.user_id)) || { blocked: false }; + if (b.blocked && this.isAiJob?.(j.type)) { budgetReason = b.reason; await hold(j, b.reason); continue; } + const q = (await this.quota?.(j.user_id)) || { blocked: false }; + if (q.blocked && this.isQuotaSensitive?.(j.type)) { quotaReason = q.reason; await hold(j, q.reason); continue; } + cand = j; + break; + } + if (budgetReason && !this.budgetBlocked.has(userId)) this.emit('onBudget', budgetReason, userId); + if (budgetReason) this.budgetBlocked.add(userId); else this.budgetBlocked.delete(userId); + if (quotaReason && !this.quotaBlocked.has(userId)) this.emit('onQuotaHold', quotaReason, userId); + if (quotaReason) this.quotaBlocked.add(userId); else this.quotaBlocked.delete(userId); + if (cand) candidates.push(cand); + } + if (!candidates.length) return null; + + // Charge du serveur : pause des NOUVEAUX jobs (hystérésis pour éviter le yo-yo) + const ratio = await this.load(); + const limit = this.loadPaused ? this.loadMax - LOAD.resumeGap : this.loadMax; + if (ratio >= limit) { + this.loadPaused = true; + for (const j of candidates) { + await hold(j, `charge du serveur élevée (${Math.round(ratio * 100)} %)`); + if (!this.loadNotified.has(j.user_id)) { this.loadNotified.add(j.user_id); this.emit('onLoad', ratio, j.user_id); } + } + return null; + } + this.loadPaused = false; + this.loadNotified.clear(); + + // Tourniquet : le moins récemment servi d'abord (jamais servi = en tête), puis l'ordre des jobs + candidates.sort((a, b) => (this.served.get(a.user_id) ?? -1) - (this.served.get(b.user_id) ?? -1) || a.id - b.id); + for (const job of candidates) { + if (this.busyUsers.has(Number(job.user_id))) continue; // pris entre-temps par un claim concurrent + if (!(await this.reserve(job))) continue; + // Aucun await entre la réservation en base et ces lignes : l'état en mémoire suit toujours la base + this.busyUsers.add(Number(job.user_id)); + this.served.set(job.user_id, ++this.turn); + return job; + } + return null; + } finally { this.claiming--; } + } + + /** + * Passage atomique queued → running. Réussit seulement si le job est encore en file ET si son utilisateur n'a aucun + * autre job en cours (la sous-requête passe par une table dérivée : MySQL interdit de lire la table qu'on met à jour). + */ + async reserve(job) { + const r = await this.db.prepare(`UPDATE jobs SET status = 'running', started_at = ? WHERE id = ? AND status = 'queued' + AND (SELECT COUNT(*) FROM (SELECT id FROM jobs WHERE user_id = ? AND status = 'running' LIMIT 1) busy) = 0`) + .run(now(), job.id, job.user_id); + return r.changes === 1; + } + + async runJob(job) { const ctrl = new AbortController(); - this.current = ctrl; - this.currentJob = job; + this.running.set(job.id, { job, ctrl }); const ctx = { job, params: JSON.parse(job.params_json || '{}'), @@ -237,27 +310,32 @@ export class Worker { const watch = setInterval(() => { this.isCancelled(job.id).then((c) => { if (c) ctrl.abort(); }, () => {}); }, 2000); - try { - const result = await handler(ctx); - if (!(await this.isCancelled(job.id))) { - await this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") - .run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); - this.emit('onFinish', job, { status: 'done', result }); + const handler = this.handlers[job.type]; + if (!handler) { + await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id); + return; } - } catch (e) { - this.log.error(`[job ${job.id} ${job.type}]`, e.message); - if (!(await this.isCancelled(job.id))) { - await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") - .run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); - this.emit('onFinish', job, { status: 'error', error: e.message }); + try { + const result = await handler(ctx); + if (!(await this.isCancelled(job.id))) { + await this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") + .run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); + this.emit('onFinish', job, { status: 'done', result }); + } + } catch (e) { + this.log.error(`[job ${job.id} ${job.type}]`, e.message); + if (!(await this.isCancelled(job.id))) { + await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") + .run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); + this.emit('onFinish', job, { status: 'error', error: e.message }); + } } } finally { clearInterval(watch); - this.current = null; - this.currentJob = null; + this.running.delete(job.id); + this.busyUsers.delete(Number(job.user_id)); } - return true; } } diff --git a/src/services/load.js b/src/services/load.js new file mode 100644 index 0000000..9c86e97 --- /dev/null +++ b/src/services/load.js @@ -0,0 +1,8 @@ +// Charge du serveur : rapport entre la charge moyenne (1 min) et le nombre de cœurs. Remplace la pause thermique du Raspberry. +import os from 'node:os'; + +/** 0 = machine au repos, 1 = tous les cœurs occupés. Toujours 0 sous Windows (loadavg y vaut 0). */ +export function loadRatio() { + const cores = Math.max(1, os.availableParallelism?.() ?? os.cpus().length); + return os.loadavg()[0] / cores; +} diff --git a/src/services/notify.js b/src/services/notify.js index 7b71486..71aa1ab 100644 --- a/src/services/notify.js +++ b/src/services/notify.js @@ -11,7 +11,7 @@ export const EVENTS = { job_error: 'Job en erreur', reply: 'Réponse d\'un prospect', followup: 'Relances envoyées', - thermal: 'Pause thermique du Pi', + load: 'Serveur très chargé : tes jobs attendent', budget: 'Budget IA atteint', quota: 'Quota Claude proche de la limite, ou job reporté', weekly: 'Rapport hebdo', @@ -21,7 +21,7 @@ const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c } const ICONS = { ok: '✅', info: '🔷', warn: '⚠️', error: '⛔' }; const FOOTERS = { job_done: 'Job terminé', job_error: 'Job en échec', reply: 'Réponse prospect', followup: 'Relances', - thermal: 'Température', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test', + load: 'Charge serveur', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test', }; /** Barre de progression en caractères (Discord n'affiche pas d'images inline dans un embed sans hébergement). */ @@ -36,7 +36,8 @@ export async function notifyConfig(app, userId) { try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'discord_webhook_enc')); } catch { url = null; } const raw = await getSetting(app.db, userId, 'discord_events'); - const events = raw ? JSON.parse(raw) : Object.keys(EVENTS); + // « thermal » (ancienne pause du Raspberry) est devenu « load » + const events = raw ? JSON.parse(raw).map((e) => (e === 'thermal' ? 'load' : e)) : Object.keys(EVENTS); return { url, events }; } diff --git a/src/services/thermal.js b/src/services/thermal.js index bdf6c1b..fe2263f 100644 --- a/src/services/thermal.js +++ b/src/services/thermal.js @@ -1,18 +1,7 @@ import { readFileSync } from 'node:fs'; -// Température CPU en °C (null hors Raspberry / Linux sans capteur) +// Température CPU en °C (null hors Raspberry / Linux sans capteur) : simple information pour les admins export function cpuTemp(path = '/sys/class/thermal/thermal_zone0/temp') { try { return Math.round(Number(readFileSync(path, 'utf8')) / 100) / 10; } catch { return null; } } - -// Attend que le CPU repasse sous le seuil (hystérésis de 5 °C pour éviter le yo-yo) -export async function waitCool(max, { read = cpuTemp, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onWait } = {}) { - let t = read(); - if (t === null || t < max) return; - while (t !== null && t >= max - 5) { - await onWait?.(t); - await sleep(30_000); - t = read(); - } -} diff --git a/test/budget.test.js b/test/budget.test.js index 8b22616..3a0c143 100644 --- a/test/budget.test.js +++ b/test/budget.test.js @@ -51,7 +51,7 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u const alerts = []; const h = (name) => async () => { ran.push(name); }; const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, { - thermalMax: 999, log: { error() {} }, + log: { error() {} }, budget: (u) => budgetState(s.db, u), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r), }); await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' }); @@ -105,7 +105,7 @@ test('quota serré : analyse/évolution attendent, la prospection et l\'envoi co const alerts = []; const h = (name) => async () => { ran.push(name); }; const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, { - thermalMax: 999, log: { error() {} }, + log: { error() {} }, quota: (u) => quotaState(s.db, u), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r), }); await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' }); diff --git a/test/claude-link.test.js b/test/claude-link.test.js index 2597531..e4bd08d 100644 --- a/test/claude-link.test.js +++ b/test/claude-link.test.js @@ -283,7 +283,7 @@ test('garde « compte relié » à chaque couche : route, enqueue, worker, wrapp // worker : un job IA déjà en base d'un compte non relié ne s'exécute pas const ran = []; - const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, async () => { ran.push(t); return {}; }])), { thermalMax: 999, log: { error() {} } }); + const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, async () => { ran.push(t); return {}; }])), { log: { error() {} } }); for (const type of [...AI_JOBS, 'send']) await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, ?, 'queued', ?)").run(bare.id, pBare, type, now()); while (await w.tick()) { /* vide la file */ } assert.deepEqual(ran, ['send']); @@ -391,12 +391,12 @@ test('délier un job IA en cours : il est interrompu', async () => { await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run(); // jobs des tests précédents const w = new Worker(s.db, { analyze: (ctx) => new Promise((resolve) => { ctx.signal.addEventListener('abort', () => { aborted = true; resolve({}); }); }), - }, { thermalMax: 999, log: { error() {} }, isAiJob: (t) => AI_JOBS.has(t) }); + }, { log: { error() {} }, isAiJob: (t) => AI_JOBS.has(t) }); s.app.worker = w; try { await enqueue(s.db, { userId: u.id, projectId: p, type: 'analyze' }); const tick = w.tick(); - for (let i = 0; i < 50 && !w.currentJob; i++) await new Promise((r) => setTimeout(r, 20)); + for (let i = 0; i < 50 && !w.running.size; i++) await new Promise((r) => setTimeout(r, 20)); assert.equal((await u.post('/link/unlink', {})).status, 200); await tick; assert.equal(aborted, true); @@ -437,7 +437,7 @@ test('serveur complet (worker démarré par createApp) : job d\'un compte relié const jl = (await enqueue(full.db, { userId: linked.id, projectId: pl, type: 'template' })).id; const jb = Number((await full.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(bare.id, pb, now())).lastInsertRowid); const status = async (id) => full.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(id); - for (let i = 0; i < 100 && ((await status(jl)).status === 'queued' || (await status(jb)).status === 'queued'); i++) await new Promise((r) => setTimeout(r, 100)); + for (let i = 0; i < 100 && (['queued', 'running'].includes((await status(jl)).status) || ['queued', 'running'].includes((await status(jb)).status)); i++) await new Promise((r) => setTimeout(r, 100)); assert.equal((await status(jl)).status, 'done', (await status(jl)).error); assert.deepEqual({ ...(await status(jb)) }, { status: 'error', error: LINK_REQUIRED_MESSAGE }); assert.equal((await full.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pb)).n, 0); diff --git a/test/claude-run.test.js b/test/claude-run.test.js index 8104ad6..f6eb0b6 100644 --- a/test/claude-run.test.js +++ b/test/claude-run.test.js @@ -49,7 +49,7 @@ test('un utilisateur ne lance jamais un job avec le secret d\'un autre (secret r const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) }); const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) }); const pa = await project(a), pb = await project(b); - const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } }); + const w = new Worker(s.db, makeHandlers(s.app), { log: { error() {} } }); await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' }); await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' }); while (await w.tick()) { /* vide la file */ } @@ -69,7 +69,7 @@ test('id de projet ou de job manipulé : le job d\'A ne touche jamais au projet } // Même chose via la file : un job inséré à la main avec le projet de B échoue sans exécution await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(a.id, pb, now()); - const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } }); + const w = new Worker(s.db, makeHandlers(s.app), { log: { error() {} } }); while (await w.tick()) { /* vide la file */ } const row = await s.db.prepare("SELECT status, error FROM jobs WHERE user_id = ? AND project_id = ?").get(a.id, pb); assert.equal(row.status, 'error'); @@ -141,7 +141,7 @@ test('le secret n\'apparaît ni dans les erreurs du CLI, ni dans le job en erreu assert.match(err.message, /\*\*\*/); assert.ok(!err.message.includes(KEY_A)); const p = await project(a); - const w = new Worker(s.db, { template: async () => { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } }, { thermalMax: 999, log: { error() {} } }); + const w = new Worker(s.db, { template: async () => { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } }, { log: { error() {} } }); await enqueue(s.db, { userId: a.id, projectId: p, type: 'template' }); while (await w.tick()) { /* vide la file */ } const row = await s.db.prepare('SELECT status, error FROM jobs WHERE project_id = ?').get(p); @@ -312,7 +312,7 @@ test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît ja const b = await s.newUser({ admin: false, link: tokenLink(TOK_B) }); // 33 % const pa = await project(a), pb = await project(b); const w = new Worker(s.db, makeHandlers(s.app), { - thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), budget: (uid) => budgetState(s.db, uid), + log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), budget: (uid) => budgetState(s.db, uid), }); await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' }); await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' }); @@ -328,7 +328,7 @@ test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît ja await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run(); const done = []; const w2 = new Worker(s.db, { analyze: async (ctx) => { done.push(ctx.job.user_id); return {}; } }, { - thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), + log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), }); await enqueue(s.db, { userId: a.id, projectId: pa, type: 'analyze' }); await enqueue(s.db, { userId: b.id, projectId: pb, type: 'analyze' }); diff --git a/test/fixtures/fake-claude.js b/test/fixtures/fake-claude.js index 2f44223..cfebe38 100755 --- a/test/fixtures/fake-claude.js +++ b/test/fixtures/fake-claude.js @@ -3,6 +3,11 @@ const prompt = process.argv[process.argv.indexOf('-p') + 1] || ''; const out = (o) => process.stdout.write(JSON.stringify(o) + '\n'); out({ type: 'system', subtype: 'init', args: process.argv.slice(2) }); +// Concurrence : FAKE_LOG = fichier où noter début et fin (clé de l'utilisateur), FAKE_DELAY_MS = durée simulée du travail +const who = (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || '').slice(-4); +const trace = async (what) => { if (process.env.FAKE_LOG) (await import('node:fs')).appendFileSync(process.env.FAKE_LOG, what + ' ' + who + ' ' + Date.now() + String.fromCharCode(10)); }; +await trace('start'); +if (process.env.FAKE_DELAY_MS) await new Promise((r) => setTimeout(r, Number(process.env.FAKE_DELAY_MS))); if (prompt.includes('CRASH')) process.exit(3); // Le secret de l'utilisateur fuit dans stderr : l'application ne doit jamais le répercuter if (prompt.includes('LEAK')) { process.stderr.write('echec avec ' + (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || '') + ' fin'); process.exit(3); } @@ -29,4 +34,5 @@ out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWin five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? ((process.env.CLAUDE_CODE_OAUTH_TOKEN || '').includes('HOT') ? 0.9 : 0.33)), resetsAt: 1_700_000_000 }, seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 }, } } }); +await trace('end'); out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } }); diff --git a/test/followup.test.js b/test/followup.test.js index 61d1eb2..b5fa833 100644 --- a/test/followup.test.js +++ b/test/followup.test.js @@ -64,7 +64,7 @@ async function setup() { .run(id, pid, email, t, `Une idée pour ${email}`, ``); return pid; }; - const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } }); + const worker = new Worker(db, makeHandlers(app), { log: { error() {} } }); const scheduler = new Scheduler(app, { log: { error() {} } }); return { tmp, db, app, id, userId, add, inboxOk, worker, scheduler, sentMails }; } diff --git a/test/handlers.test.js b/test/handlers.test.js index 73e58ac..6f5a084 100644 --- a/test/handlers.test.js +++ b/test/handlers.test.js @@ -42,7 +42,7 @@ async function setup() { await setSetting(db, userId, 'send_delay_min', '0'); await setSetting(db, userId, 'send_delay_max', '0'); const id = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: `file://${src}` }); - const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } }); + const worker = new Worker(db, makeHandlers(app), { log: { error: (...a) => console.error(...a) } }); return { tmp, db, app, id, userId, worker, sentMails }; } diff --git a/test/helpers/server.js b/test/helpers/server.js index 2c93152..7eaf2e9 100644 --- a/test/helpers/server.js +++ b/test/helpers/server.js @@ -22,7 +22,7 @@ export async function startApp({ cfg = {}, worker = false, rateLimit = false, cr const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-')); const config = { appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [], - secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, cliModeEnabled: true, + secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', cliModeEnabled: true, sandbox: { enabled: false, production: false, roBinds: [], serverHome: tmp }, ...cfg, }; const limiter = rateLimit ? new RateLimiter(rateLimit === true ? {} : rateLimit) : unlimited(); diff --git a/test/http.test.js b/test/http.test.js index 3104c8a..eea6088 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -17,7 +17,7 @@ before(async () => { tmp = mkdtempSync(join(tmpdir(), 'aitools-http-')); const cfg = { appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'], - secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, sandbox: { enabled: false, production: false }, + secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', sandbox: { enabled: false, production: false }, }; app = await createApp(cfg, { db: await testDb(), worker: false }); await new Promise((r) => app.server.listen(0, '127.0.0.1', r)); diff --git a/test/night.test.js b/test/night.test.js index 3fc642c..1b4a5a6 100644 --- a/test/night.test.js +++ b/test/night.test.js @@ -31,7 +31,7 @@ test('le worker ne démarre pas un job programmé avant son heure', async () => let clock = now(); const ran = []; const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } }, - { thermalMax: 999, log: { error() {} }, clock: () => clock }); + { log: { error() {} }, clock: () => clock }); const u = await addUser(db); await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now()); await enqueue(db, { userId: u, projectId: 1, type: 'prospect', runAfter: clock + 3600 }); diff --git a/test/notify.test.js b/test/notify.test.js index d3e95b2..1b778a0 100644 --- a/test/notify.test.js +++ b/test/notify.test.js @@ -82,7 +82,7 @@ test('le worker notifie en fin de job, et un callback qui plante ne le bloque pa const s = await setup(); const seen = []; const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, { - thermalMax: 999, log: { error() {} }, + log: { error() {} }, onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); }, }); await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'prospect' }); diff --git a/test/queue.test.js b/test/queue.test.js new file mode 100644 index 0000000..644189f --- /dev/null +++ b/test/queue.test.js @@ -0,0 +1,249 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { now } from '../src/db.js'; +import { encrypt } from '../src/crypto.js'; +import { testDb } from './helpers/db.js'; +import { addUser } from './helpers/users.js'; +import { startApp } from './helpers/server.js'; +import { makeClaudeBin } from './helpers/claude-bin.js'; +import { Worker, enqueue } from '../src/services/jobs.js'; +import { makeHandlers } from '../src/handlers.js'; +import { loadConfig } from '../src/config.js'; + +// File de jobs équitable et simultanée : plafond global, un job à la fois par utilisateur, tourniquet, +// réservation atomique, pause de charge, arrêt propre. Les jobs « prospect » et « evolution » des tests sont de simples +// fonctions instrumentées ; le dernier test lance le vrai circuit avec le CLI simulé. + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const log = { error() {} }; + +async function world(n = 3) { + const db = await testDb(); + const users = []; + for (let i = 0; i < n; i++) { + const id = await addUser(db); + const p = Number((await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', ?, ?)").run(id, `https://git.test/${id}.git`, now())).lastInsertRowid); + users.push({ id, p }); + } + return { db, users }; +} +const q = (db, u, type) => enqueue(db, { userId: u.id, projectId: u.p, type }).then((r) => r.id); +async function until(fn, ms = 5000) { + const t0 = Date.now(); + while (!(await fn())) { if (Date.now() - t0 > ms) throw new Error('délai dépassé'); await sleep(10); } +} + +test('plafond global : jamais plus de maxJobs en parallèle, jamais deux jobs du même utilisateur', async () => { + const { db, users } = await world(3); + let cur = 0, max = 0; + const perUser = new Map(); let perUserMax = 0; + const starts = []; + const handler = async (ctx) => { + cur++; max = Math.max(max, cur); + const n = (perUser.get(ctx.job.user_id) || 0) + 1; perUser.set(ctx.job.user_id, n); perUserMax = Math.max(perUserMax, n); + starts.push(ctx.job.user_id); + await sleep(40); + cur--; perUser.set(ctx.job.user_id, n - 1); + return {}; + }; + for (const u of users) { await q(db, u, 'prospect'); await q(db, u, 'evolution'); } + const w = new Worker(db, { prospect: handler, evolution: handler }, { maxJobs: 2, pollMs: 10, log }); + await w.start(); + await until(async () => (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0); + await w.stop(); + assert.equal(max, 2, 'deux jobs en parallèle, pas plus'); + assert.equal(perUserMax, 1, 'jamais deux jobs du même utilisateur en même temps'); + assert.equal(starts.length, 6); + // Tourniquet : le 3e utilisateur démarre avant que le 1er ne reçoive son 2e job + const [a, b, c] = users.map((u) => u.id); + assert.deepEqual(starts.slice(0, 3), [a, b, c]); + assert.deepEqual(starts.slice(3), [a, b, c]); +}); + +test('un seul utilisateur avec beaucoup de jobs ne prend qu\'un emplacement, les autres passent', async () => { + const { db, users } = await world(2); + const order = []; + const w = new Worker(db, { + prospect: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; }, + evolution: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; }, + template: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; }, + }, { maxJobs: 4, pollMs: 10, log }); + const [a, b] = users; + await q(db, a, 'prospect'); await q(db, a, 'evolution'); await q(db, a, 'template'); + await q(db, b, 'prospect'); + await w.start(); + await until(async () => (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0); + await w.stop(); + assert.equal(order[0], `${a.id}:prospect`); + assert.equal(order[1], `${b.id}:prospect`, 'B part tout de suite, malgré la file de A et 4 emplacements libres'); + assert.deepEqual(order.filter((x) => x.startsWith(`${a.id}:`)), [`${a.id}:prospect`, `${a.id}:evolution`, `${a.id}:template`], 'ordre propre à l\'utilisateur conservé'); +}); + +test('réservation atomique : deux workers sur la même base, un job n\'est réservé qu\'une fois', async () => { + const { db, users } = await world(1); + const [u] = users; + const id = await q(db, u, 'prospect'); + const w1 = new Worker(db, {}, { log }), w2 = new Worker(db, {}, { log }); + const [j1, j2] = await Promise.all([w1.claim(), w2.claim()]); + assert.equal([j1, j2].filter(Boolean).length, 1, 'un seul worker obtient le job'); + assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(id)).status, 'running'); + // Le second job du même utilisateur ne peut pas être réservé tant que le premier tourne (garde en base, pas seulement en mémoire) + const id2 = await q(db, u, 'evolution'); + const intruder = (await db.prepare('SELECT * FROM jobs WHERE id = ?').get(id2)); + assert.equal(await new Worker(db, {}, { log }).reserve(intruder), false); + assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(id2)).status, 'queued'); + // Et un job déjà réservé ne l'est pas deux fois + assert.equal(await new Worker(db, {}, { log }).reserve({ id, user_id: 999 }), false); +}); + +test('claim() appelé en rafale : le plafond et l\'unicité par utilisateur tiennent', async () => { + const { db, users } = await world(5); + for (const u of users) { await q(db, u, 'prospect'); await q(db, u, 'evolution'); } + const w = new Worker(db, {}, { maxJobs: 3, log }); + const got = (await Promise.all(Array.from({ length: 12 }, () => w.claim()))).filter(Boolean); + assert.equal(got.length, 3); + assert.equal(new Set(got.map((j) => j.user_id)).size, 3, 'trois utilisateurs différents'); + assert.equal((await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'running'").get()).n, 3); +}); + +test('jobs programmés : ni avant l\'heure, ni dans le désordre ; l\'ordre par id est conservé après', async () => { + const { db, users } = await world(2); + const [a, b] = users; + let clock = 1000; + const night = 5000; + const ids = {}; + ids.a = (await enqueue(db, { userId: a.id, projectId: a.p, type: 'prospect', runAfter: night })).id; + ids.b = (await enqueue(db, { userId: b.id, projectId: b.p, type: 'prospect', runAfter: night })).id; + ids.a2 = (await enqueue(db, { userId: a.id, projectId: a.p, type: 'evolution' })).id; + const w = new Worker(db, {}, { maxJobs: 4, clock: () => clock, log }); + const first = await w.claim(); + assert.equal(first.id, ids.a2, 'seul le job sans heure est dû'); + assert.equal(await w.claim(), null, 'le job de nuit d\'A attend, et A est déjà occupé'); + clock = night; + const second = await w.claim(); + assert.equal(second.id, ids.b, 'B (jamais servi) avant A'); + await db.prepare("UPDATE jobs SET status = 'done' WHERE id = ?").run(ids.a2); + w.busyUsers.delete(a.id); + assert.equal((await w.claim()).id, ids.a); +}); + +test('pause de charge : les nouveaux jobs attendent (message clair), reprise avec hystérésis, jobs en cours épargnés', async () => { + const { db, users } = await world(2); + const [a, b] = users; + let ratio = 0.95; + const notified = []; + const w = new Worker(db, {}, { maxJobs: 4, loadMax: 0.9, load: () => ratio, log, onLoad: (r, uid) => notified.push(uid) }); + const ja = await q(db, a, 'prospect'); + assert.equal(await w.claim(), null); + const prog = JSON.parse((await db.prepare('SELECT progress_json FROM jobs WHERE id = ?').get(ja)).progress_json); + assert.match(prog.message, /charge du serveur élevée \(95 %\)/); + assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(ja)).status, 'queued'); + await w.claim(); await w.idle(); + assert.deepEqual(notified, [a.id], 'une seule notification par pause'); + ratio = 0.85; // sous 0,9 mais pas sous 0,8 : on reste en pause + assert.equal(await w.claim(), null); + ratio = 0.79; + assert.equal((await w.claim()).id, ja); + // Charge de nouveau élevée : le job de B attend, celui de A (en cours) n'est pas touché + ratio = 0.99; + await q(db, b, 'prospect'); + assert.equal(await w.claim(), null); + assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(ja)).status, 'running'); +}); + +test('arrêt propre : tous les jobs en cours sont interrompus ET attendus', async () => { + const { db, users } = await world(3); + let started = 0; + const finished = []; + const handler = (ctx) => new Promise((_, reject) => { + started++; + ctx.signal.addEventListener('abort', () => setTimeout(() => { finished.push(ctx.job.id); reject(new Error('Annulé')); }, 30), { once: true }); + }); + for (const u of users) await q(db, u, 'prospect'); + const w = new Worker(db, { prospect: handler }, { maxJobs: 3, pollMs: 10, log }); + await w.start(); + await until(() => started === 3); + await w.stop(); + assert.equal(finished.length, 3, 'les trois jobs ont fini avant le retour de stop()'); + assert.equal(w.running.size, 0); + assert.equal(w.busyUsers.size, 0); + assert.equal((await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'error'").get()).n, 3); + assert.equal(await w.claim(), null, 'plus rien ne démarre après l\'arrêt'); +}); + +test('suppression d\'un compte et déliaison n\'interrompent que les jobs de ce compte', async () => { + const { db, users } = await world(2); + const aborted = []; + const handler = (ctx) => new Promise((resolve) => { + ctx.signal.addEventListener('abort', () => { aborted.push(ctx.job.user_id); resolve({}); }, { once: true }); + setTimeout(resolve, 300); + }); + for (const u of users) await q(db, u, 'prospect'); + const w = new Worker(db, { prospect: handler }, { maxJobs: 2, pollMs: 10, log, isAiJob: () => true }); + await w.start(); + await until(() => w.running.size === 2); + w.abortUser(users[0].id); + w.abortUserAi(users[1].id); + await until(() => aborted.length === 2); + assert.deepEqual(aborted.sort(), users.map((u) => u.id).sort()); + await w.stop(); +}); + +test('configuration : MAX_AI_JOBS (4 par défaut) et LOAD_MAX validés', () => { + const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' }; + const keep = { ...process.env }; + const withEnv = (extra, fn) => { + delete process.env.MAX_AI_JOBS; delete process.env.LOAD_MAX; + Object.assign(process.env, base, extra); + try { return fn(); } finally { + for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; + Object.assign(process.env, keep); + } + }; + assert.equal(withEnv({}, () => loadConfig().maxAiJobs), 4); + assert.equal(withEnv({}, () => loadConfig().loadMax), 0.9); + assert.equal(withEnv({ MAX_AI_JOBS: '2', LOAD_MAX: '1.2' }, () => loadConfig().maxAiJobs), 2); + assert.throws(() => withEnv({ MAX_AI_JOBS: '0' }, loadConfig), /MAX_AI_JOBS/); + assert.throws(() => withEnv({ MAX_AI_JOBS: 'beaucoup' }, loadConfig), /MAX_AI_JOBS/); + assert.throws(() => withEnv({ LOAD_MAX: '0' }, loadConfig), /LOAD_MAX/); +}); + +test('avec le CLI simulé : deux utilisateurs tournent en parallèle, jamais deux processus pour le même utilisateur', async () => { + const tmp = mkdtempSync(join(tmpdir(), 'aitools-q-')); + const trace = join(tmp, 'trace.log'); + const s = await startApp({ cfg: { claudeBin: makeClaudeBin(tmp, { env: { FAKE_LOG: trace.split('\\').join('/'), FAKE_DELAY_MS: '350' } }) } }); + try { + const key = (c) => `sk-ant-api03-${'x'.repeat(30)}${c.repeat(4)}`; + const mk = async (c) => { + const u = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true, last4: c, secret_enc: encrypt(s.app.cfg.secretKey, key(c)) } }); + const p = Number((await s.db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at) VALUES(?, ?, ?, ?, ?, 1, ?)') + .run(u.id, 'P', `https://git.test/${c}.git`, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid); + return { ...u, p }; + }; + const [A, B, C] = [await mk('A'), await mk('B'), await mk('C')]; + for (const u of [A, B, C]) { await enqueue(s.db, { userId: u.id, projectId: u.p, type: 'template' }); await enqueue(s.db, { userId: u.id, projectId: u.p, type: 'followup_template' }); } + mkdirSync(join(tmp, 'x'), { recursive: true }); + const w = new Worker(s.db, makeHandlers(s.app), { maxJobs: 2, pollMs: 20, log }); + await w.start(); + await until(async () => (await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0, 20000); + await w.stop(); + const bad = await s.db.prepare("SELECT error FROM jobs WHERE status = 'error'").all(); assert.deepEqual(bad, []); + assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'done'").get()).n, 6); + + const events = readFileSync(trace, 'utf8').trim().split('\n').map((l) => { const [what, who, t] = l.split(' '); return { what, who, t: Number(t) }; }).sort((x, y) => x.t - y.t); + let open = 0, maxOpen = 0; const live = new Set(); let sameUser = false; + for (const e of events) { + if (e.what === 'start') { if (live.has(e.who)) sameUser = true; live.add(e.who); open++; maxOpen = Math.max(maxOpen, open); } + else { live.delete(e.who); open--; } + } + assert.equal(maxOpen, 2, 'deux processus simultanés (maxJobs = 2), pas trois'); + assert.equal(sameUser, false, 'jamais deux processus du même utilisateur'); + assert.equal(events.filter((e) => e.what === 'start').length, 6); + // Équité : C (jamais servi au 3e tour) démarre avant le 2e job de A + const starts = events.filter((e) => e.what === 'start').map((e) => e.who[0]); + assert.ok(starts.indexOf('C') < starts.lastIndexOf('A'), `ordre des départs : ${starts.join('')}`); + } finally { await s.close(); rmSync(tmp, { recursive: true, force: true }); } +}); diff --git a/test/services.test.js b/test/services.test.js index cda43a4..2ef6c3d 100644 --- a/test/services.test.js +++ b/test/services.test.js @@ -2,7 +2,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { resolve } from 'node:path'; import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js'; -import { waitCool } from '../src/services/thermal.js'; import { now } from '../src/db.js'; import { testDb } from './helpers/db.js'; import { addUser } from './helpers/users.js'; @@ -49,14 +48,6 @@ test('extractJson gère texte, fences et accolades dans les chaînes', () => { assert.throws(() => extractJson('rien'), /Aucun JSON/); }); -test('waitCool attend la redescente avec hystérésis', async () => { - const temps = [80, 78, 72, 69]; - let waits = 0; - await waitCool(75, { read: () => temps.shift(), sleep: async () => {}, onWait: () => waits++ }); - assert.equal(waits, 3); - await waitCool(75, { read: () => null }); -}); - test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => { const db = await testDb(); const u = await addUser(db); @@ -67,7 +58,7 @@ test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; }, boom: async () => { throw new Error('raté'); }, }; - const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } }); + const w = new Worker(db, handlers, { log: { error() {} } }); assert.equal(await w.tick(), true); await enqueue(db, { userId: u, projectId: 1, type: 'boom' }); await w.tick(); diff --git a/test/worker.test.js b/test/worker.test.js index 0f95e72..6b12860 100644 --- a/test/worker.test.js +++ b/test/worker.test.js @@ -22,12 +22,12 @@ test('start puis stop : la boucle s\'arrête, le job en cours est annulé et att started(); ctx.signal.addEventListener('abort', () => reject(new Error('Annulé')), { once: true }); }), - }, { thermalMax: 999, pollMs: 10, log: { error() {} } }); + }, { pollMs: 10, log: { error() {} } }); await enqueue(db, { userId: db.userId, projectId: 1, type: 'prospect' }); await w.start(); await running; await w.stop(); - assert.equal(w.current, null); + assert.equal(w.running.size, 0); const job = (await latestJobs(db, 1)).prospect; assert.equal(job.status, 'error'); assert.match(job.error, /Annulé/); @@ -38,7 +38,7 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ const seen = []; const errors = []; const w = new Worker(db, { prospect: async () => ({ ok: true }), evolution: async () => { throw new Error('boum'); } }, { - thermalMax: 999, pollMs: 10, log: { error: (...a) => errors.push(a.join(' ')) }, + pollMs: 10, log: { error: (...a) => errors.push(a.join(' ')) }, onFinish: async (job, r) => { await new Promise((res) => setTimeout(res, 30)); seen.push(`${job.type}:${r.status}`); @@ -57,7 +57,7 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ test('un job "running" laissé par un crash est marqué en erreur au démarrage', async () => { const db = await setup(); await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, 1, 'analyze', 'running', ?)").run(db.userId, now()); - const w = new Worker(db, {}, { thermalMax: 999, pollMs: 10, log: { error() {} } }); + const w = new Worker(db, {}, { pollMs: 10, log: { error() {} } }); await w.start(); await w.stop(); const job = (await latestJobs(db, 1)).analyze;