SPB Git

Repository Public

jobs.ts 24.5 KB 291 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : services/control-api/src/core/jobs.ts9 * Module           : core10 * 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 { createHash } from 'node:crypto';43import { canTransitionJob, type JobMode, type JobState } from '@mls/contracts';44import { checkFrequency, effectiveJobMode } from '@mls/policy-engine';45import type { Tx } from '../db.ts';46import { audit, type Actor } from '../audit.ts';47import { bad, conflict, forbidden, notFound } from './errors.ts';48import { activePolicy, emergencyState } from './policy.ts';49import { acquireLease, dropLease, lockSession, transition } from './sessions.ts';5051const SYSTEM: Actor = { kind: 'system', id: 'scheduler' };52export const MAX_PREPARE_ATTEMPTS = 3;53export const idempotencyKey = (pageId: string, hash: string, slot: Date) => createHash('sha256').update(`${pageId}|${hash}|${Math.floor(slot.getTime() / 60000)}`).digest('hex');5455export async function setJobState(tx: Tx, job: any, to: JobState, reason: string, actor: Actor, correlationId?: string, extra = '') {56  if (!canTransitionJob(job.state, to)) throw conflict('invalid_job_transition', `Transition ${job.state} → ${to} interdite`);57  await tx.query(`UPDATE publication_jobs SET state=$2, state_reason=$3, updated_at=now()${extra} WHERE id=$1`, [job.id, to, reason]);58  await audit(tx, { correlationId, actor, action: 'job.transition', targetKind: 'job', targetId: job.id, brandId: job.brand_id, result: 'ok', detail: { from: job.state, to, reason } });59  job.state = to; job.state_reason = reason;60}61/** A job is bound to the exact approved hash, page and slot. The idempotency key makes a duplicate request a no-op. */62export async function createJob(tx: Tx, input: { contentId: string; scheduledAt: string; mode: JobMode }, actor: Actor, correlationId?: string) {63  const item = (await tx.query('SELECT c.*, b.frequency, b.timezone FROM content_items c JOIN brands b ON b.id=c.brand_id WHERE c.id=$1 FOR UPDATE OF c', [input.contentId])).rows[0];64  if (!item) throw notFound('contenu');65  if (item.state !== 'APPROVED') throw conflict('not_approved', 'Le contenu doit être approuvé.');66  const v = (await tx.query('SELECT * FROM content_versions WHERE id=$1', [item.current_version_id])).rows[0];67  const ap = (await tx.query("SELECT * FROM approvals WHERE content_id=$1 AND version_id=$2 AND content_hash=$3 AND page_id=$4 AND decision='approve' AND invalidated_at IS NULL ORDER BY created_at DESC LIMIT 1", [item.id, v.id, v.content_hash, item.page_id])).rows[0];68  if (!ap) throw conflict('no_valid_approval', 'Aucune approbation valide pour cette version et cette page.');69  const page = (await tx.query('SELECT * FROM pages WHERE id=$1', [item.page_id])).rows[0];70  if (page.status !== 'confirmed') throw conflict('page_not_confirmed', "La page n'est pas confirmée.");71  const slot = new Date(input.scheduledAt);72  if (slot.getTime() < Date.now() - 5 * 60_000) throw bad('slot_in_past', 'Le créneau est passé.');73  const key = idempotencyKey(page.id, v.content_hash, slot);74  const dup = (await tx.query('SELECT * FROM publication_jobs WHERE idempotency_key=$1', [key])).rows[0];75  if (dup) return { job: dup, duplicate: true };76  const policy = await activePolicy(tx);77  const eff = effectiveJobMode(policy, page.composer_url ?? page.url, input.mode);78  if (!eff.mode) throw forbidden('platform_forbidden', `Plateforme hors politique : ${eff.basis}`);79  await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`slot:${page.id}`]); // serialise slot checks per page80  const others = (await tx.query("SELECT scheduled_at FROM publication_jobs WHERE page_id=$1 AND state NOT IN ('CANCELLED','FAILED')", [page.id])).rows.map((r) => new Date(r.scheduled_at));81  const fq = checkFrequency(policy, item.frequency, slot, others, item.timezone);82  if (!fq.allow) throw conflict('frequency_limit', `Limite de fréquence : ${fq.reason}`);83  const job = (await tx.query(`INSERT INTO publication_jobs(brand_id, content_id, version_id, content_hash, page_id, approval_id, scheduled_at, mode, idempotency_key, next_run_at, created_by)84    VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$7,$10) RETURNING *`, [item.brand_id, item.id, v.id, v.content_hash, page.id, ap.id, slot.toISOString(), eff.mode, key, actor.kind === 'user' ? actor.id : null])).rows[0];85  await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.created', $1)", [JSON.stringify({ jobId: job.id, brandId: job.brand_id, scheduledAt: job.scheduled_at })]);86  await audit(tx, { correlationId, actor, action: 'job.create', targetKind: 'job', targetId: job.id, brandId: job.brand_id, result: 'ok', detail: { hash: v.content_hash, pageId: page.id, scheduledAt: slot.toISOString(), requestedMode: input.mode, mode: eff.mode, policyLevel: eff.level } });87  return { job, duplicate: false, clamped: eff.mode !== input.mode ? { requested: input.mode, granted: eff.mode, basis: eff.basis } : null };88}89/** Everything that must still hold right before anything touches the platform. Returns a refusal reason or null. */90export async function preflight(tx: Tx, job: any): Promise<string | null> {91  if ((await emergencyState(tx)).emergency_stop) return 'emergency_stop';92  const ap = (await tx.query('SELECT * FROM approvals WHERE id=$1', [job.approval_id])).rows[0];93  if (!ap || ap.invalidated_at || ap.decision !== 'approve') return 'approval_invalidated';94  const item = (await tx.query('SELECT * FROM content_items WHERE id=$1', [job.content_id])).rows[0];95  const v = (await tx.query('SELECT * FROM content_versions WHERE id=$1', [item.current_version_id])).rows[0];96  if (item.state !== 'APPROVED' || v.id !== job.version_id || v.content_hash !== job.content_hash || ap.content_hash !== job.content_hash) return 'content_changed_after_approval';97  if (item.page_id !== job.page_id || ap.page_id !== job.page_id) return 'page_changed_after_approval';98  const page = (await tx.query('SELECT * FROM pages WHERE id=$1', [job.page_id])).rows[0];99  if (page.status !== 'confirmed') return 'page_not_confirmed';100  const eff = effectiveJobMode(await activePolicy(tx), page.composer_url ?? page.url, job.mode);101  if (eff.mode !== job.mode) return 'policy_no_longer_allows_mode';102  return null;103}104export async function cancelJob(tx: Tx, id: string, actor: Actor, correlationId?: string) {105  const job = (await tx.query('SELECT * FROM publication_jobs WHERE id=$1 FOR UPDATE', [id])).rows[0];106  if (!job) throw notFound('tâche');107  const submitting = (await tx.query("SELECT 1 FROM job_attempts WHERE job_id=$1 AND phase IN ('submitting','submitted')", [id])).rowCount;108  if (['SUBMITTED', 'VERIFIED', 'UNKNOWN_OUTCOME'].includes(job.state) || submitting) {109    // Nothing here can take a publication down. Record the request and say so.110    await tx.query('UPDATE publication_jobs SET cancel_requested_at=now(), cancelled_after_submission=true WHERE id=$1', [id]);111    await audit(tx, { correlationId, actor, action: 'job.cancel', targetKind: 'job', targetId: id, brandId: job.brand_id, result: 'refused', detail: { state: job.state, note: 'après soumission : aucun retrait garanti' } });112    return { cancelled: false, afterSubmission: true, state: job.state as JobState };113  }114  if (job.state === 'CANCELLED' || job.state === 'FAILED') return { cancelled: job.state === 'CANCELLED', afterSubmission: false, state: job.state as JobState };115  await setJobState(tx, job, 'CANCELLED', 'annulée avant soumission', actor, correlationId, ', cancel_requested_at=now(), locked_by=NULL, locked_until=NULL');116  return { cancelled: true, afterSubmission: false, state: 'CANCELLED' as JobState };117}118119/* ───────────── Worker side ───────────── */120export type Task = { kind: 'prepare' | 'submit' | 'verify'; job: any; sessionId: string; fencingToken: number };121/** Hands a worker at most one task. All checks happen here, in one transaction, with SKIP LOCKED so two workers never get the same job. */122export async function claimTask(tx: Tx, workerId: string, leaseTtl = 60): Promise<Task | null> {123  if ((await emergencyState(tx)).emergency_stop) return null;124  const actor: Actor = { kind: 'worker', id: workerId };125  const sessions = (await tx.query(`SELECT s.id, s.scope_page_ids FROM navigator_sessions s JOIN navigator_profiles p ON p.id=s.profile_id WHERE p.worker_id=$1 AND s.state='READY' AND s.confirmed_at IS NOT NULL AND s.wanted='running'`, [workerId])).rows;126  for (const s of sessions) {127    if (!s.scope_page_ids.length) continue;128    const job = (await tx.query(`SELECT j.* FROM publication_jobs j WHERE j.page_id = ANY($1::uuid[]) AND j.mode <> 'manual_assisted' AND (129        (j.state='QUEUED' AND j.next_run_at <= now())130        OR (j.state='AWAITING_CONFIRMATION' AND j.mode='auto_submit' AND j.submit_confirmed_at IS NOT NULL AND NOT EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=j.id AND a.phase IN ('submitting','submitted')))131        OR (j.state='SUBMITTED' AND NOT EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=j.id AND a.phase='verify')))132      AND (j.locked_until IS NULL OR j.locked_until < now()) ORDER BY j.next_run_at LIMIT 1 FOR UPDATE OF j SKIP LOCKED`, [s.scope_page_ids])).rows[0];133    if (!job) continue;134    const kind: Task['kind'] = job.state === 'QUEUED' ? 'prepare' : job.state === 'SUBMITTED' ? 'verify' : 'submit';135    if (kind !== 'verify') { // verification is read-only and must run even if the approval was later invalidated136      const why = await preflight(tx, job);137      if (why) { await setJobState(tx, job, 'FAILED', `contrôle préalable : ${why}`, SYSTEM); continue; }138    }139    const sess = await lockSession(tx, s.id);140    if (sess.state !== 'READY') continue;141    let lease;142    try { lease = await acquireLease(tx, sess, { kind: 'agent', id: `job:${job.id}` }, leaseTtl); } catch { continue; } // a human holds it143    await transition(tx, sess, 'BUSY', `tâche ${kind}`, actor);144    const n = ((await tx.query('SELECT coalesce(max(n),0) AS n FROM job_attempts WHERE job_id=$1', [job.id])).rows[0].n as number) + 1;145    if (kind === 'prepare') {146      await setJobState(tx, job, 'PREPARING', 'préparation du compositeur', actor, undefined, `, prepare_attempts=prepare_attempts+1, locked_by='${workerId}', locked_until=now()+interval '5 minutes', fencing_token=${lease.fencing_token}`);147      await tx.query("INSERT INTO job_attempts(job_id, n, phase, worker_id) VALUES ($1,$2,'prepare',$3)", [job.id, n, workerId]);148    } else {149      await tx.query("UPDATE publication_jobs SET locked_by=$2, locked_until=now()+interval '5 minutes', fencing_token=$3 WHERE id=$1", [job.id, workerId, lease.fencing_token]);150      if (kind === 'verify') await tx.query("INSERT INTO job_attempts(job_id, n, phase, worker_id) VALUES ($1,$2,'verify',$3)", [job.id, n, workerId]);151    }152    return { kind, job, sessionId: s.id, fencingToken: lease.fencing_token };153  }154  return null;155}156export type Report = { event: 'prepared' | 'prepare_failed' | 'submitting' | 'submitted' | 'submit_failed_before_click' | 'verified' | 'not_found' | 'aborted'; fencingToken: number; steps?: unknown[]; error?: string; externalUrl?: string | null; evidence?: { label: string; ref: string; sha256: string }[] };157/** Worker progress. A report carrying a stale fencing token is rejected: that worker lost the lease and must not be believed. */158export async function reportTask(tx: Tx, workerId: string, jobId: string, r: Report) {159  const job = (await tx.query('SELECT * FROM publication_jobs WHERE id=$1 FOR UPDATE', [jobId])).rows[0];160  if (!job) throw notFound('tâche');161  const actor: Actor = { kind: 'worker', id: workerId };162  if (job.locked_by !== workerId || job.fencing_token !== r.fencingToken) {163    await audit(tx, { actor, action: 'job.report', targetKind: 'job', targetId: jobId, brandId: job.brand_id, result: 'refused', detail: { event: r.event, reason: 'stale_fencing_token' } });164    throw conflict('stale_fencing_token', 'Bail perdu : rapport refusé.');165  }166  const sid = (await tx.query("SELECT session_id FROM worker_leases WHERE fencing_token=$1", [r.fencingToken])).rows[0]?.session_id as string | undefined;167  const steps = JSON.stringify(r.steps ?? []);168  const endAttempt = (phase: string, outcome: string) => tx.query('UPDATE job_attempts SET ended_at=now(), outcome=$3, error=$4, steps=$5 WHERE job_id=$1 AND phase=$2 AND ended_at IS NULL', [jobId, phase, outcome, r.error ?? null, steps]);169  const free = async (to: 'READY' | null = 'READY') => {170    await tx.query('UPDATE publication_jobs SET locked_by=NULL, locked_until=NULL, fencing_token=NULL WHERE id=$1', [jobId]);171    if (!sid) return;172    await dropLease(tx, sid, r.fencingToken);173    const s = await lockSession(tx, sid);174    if (to && s.state === 'BUSY') await transition(tx, s, to, 'tâche terminée', actor);175  };176  for (const e of r.evidence ?? []) await tx.query("INSERT INTO publication_receipts(job_id, kind, evidence_ref, evidence_sha256, label) VALUES ($1,'evidence',$2,$3,$4)", [jobId, e.ref, e.sha256, e.label]);177  switch (r.event) {178    case 'prepared':179      await endAttempt('prepare', 'prepared');180      await setJobState(tx, job, 'AWAITING_CONFIRMATION', 'compositeur prêt, confirmation humaine requise', actor);181      await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.awaiting_confirmation', $1)", [JSON.stringify({ jobId })]);182      await free(); break;183    case 'prepare_failed': case 'aborted': {184      if (job.state !== 'PREPARING') { await free(); break; } // an abort during submit/verify is handled by the sweeper, never by a retry185      await endAttempt('prepare', r.event);186      // Preparation has no external effect: bounded exponential retry, then dead letter.187      if (job.prepare_attempts >= MAX_PREPARE_ATTEMPTS) { await setJobState(tx, job, 'FAILED', `préparation échouée après ${job.prepare_attempts} essais : ${r.error ?? ''}`.slice(0, 300), actor, undefined, ', dead_letter=true'); await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.dead_letter', $1)", [JSON.stringify({ jobId })]); }188      else await setJobState(tx, job, 'QUEUED', `nouvel essai de préparation (${r.error ?? r.event})`.slice(0, 300), actor, undefined, `, next_run_at=now()+make_interval(secs=>${30 * 2 ** job.prepare_attempts})`);189      await free(); break;190    }191    case 'submitting': { // durable marker written BEFORE the click192      const n = ((await tx.query('SELECT coalesce(max(n),0) AS n FROM job_attempts WHERE job_id=$1', [jobId])).rows[0].n as number) + 1;193      await tx.query("INSERT INTO job_attempts(job_id, n, phase, worker_id) VALUES ($1,$2,'submitting',$3)", [jobId, n, workerId]);194      await audit(tx, { actor, action: 'job.submitting', targetKind: 'job', targetId: jobId, brandId: job.brand_id, result: 'ok' }); break;195    }196    case 'submit_failed_before_click': // the control was not there: nothing was clicked, the human decides what next197      await tx.query('UPDATE publication_jobs SET submit_confirmed_at=NULL, submit_confirmed_by=NULL, state_reason=$2 WHERE id=$1', [jobId, `soumission non tentée : ${r.error ?? ''}`.slice(0, 300)]);198      await free(); break;199    case 'submitted':200      await endAttempt('submitting', 'clicked');201      await setJobState(tx, job, 'SUBMITTED', 'soumission effectuée, vérification à faire', actor);202      await free(); break;203    case 'verified':204      await endAttempt('verify', 'verified');205      await tx.query("INSERT INTO publication_receipts(job_id, kind, external_url, label) VALUES ($1,'observed',$2,'résultat visible vérifié')", [jobId, r.externalUrl ?? null]);206      await setJobState(tx, job, 'VERIFIED', 'publication visible vérifiée', actor);207      await free(); break;208    case 'not_found':209      await endAttempt('verify', 'not_found');210      await setJobState(tx, job, 'UNKNOWN_OUTCOME', 'résultat introuvable après soumission : réconciliation manuelle', actor);211      await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.unknown_outcome', $1)", [JSON.stringify({ jobId })]);212      await free(); break;213  }214  return { state: job.state as JobState };215}216/** Human step on an AWAITING_CONFIRMATION job. */217export async function confirmJob(tx: Tx, id: string, action: 'authorize_submit' | 'human_published', externalUrl: string | null, user: Actor, correlationId?: string) {218  const job = (await tx.query('SELECT * FROM publication_jobs WHERE id=$1 FOR UPDATE', [id])).rows[0];219  if (!job) throw notFound('tâche');220  if (job.state !== 'AWAITING_CONFIRMATION') throw conflict('not_awaiting', 'La tâche n’attend pas de confirmation.');221  if (action === 'authorize_submit') {222    if (job.mode !== 'auto_submit') throw forbidden('mode_forbids_submit', 'La politique n’autorise pas la soumission automatique pour cette plateforme.');223    const why = await preflight(tx, job);224    if (why) throw conflict('preflight_failed', why);225    await tx.query('UPDATE publication_jobs SET submit_confirmed_by=$2, submit_confirmed_at=now() WHERE id=$1', [id, user.id]);226    await audit(tx, { correlationId, actor: user, action: 'job.authorize_submit', targetKind: 'job', targetId: id, brandId: job.brand_id, result: 'ok', detail: { hash: job.content_hash } });227    return { state: job.state };228  }229  const n = ((await tx.query('SELECT coalesce(max(n),0) AS n FROM job_attempts WHERE job_id=$1', [id])).rows[0].n as number) + 1;230  await tx.query("INSERT INTO job_attempts(job_id, n, phase, ended_at, outcome) VALUES ($1,$2,'manual',now(),'human_published')", [id, n]);231  await setJobState(tx, job, 'SUBMITTED', 'publiée manuellement par un administrateur', user, correlationId, `, submit_confirmed_by='${user.id}', submit_confirmed_at=now()`);232  if (job.mode === 'manual_assisted') { // no automated read of the platform is allowed: the receipt is a human attestation, labelled as such233    await tx.query("INSERT INTO publication_receipts(job_id, kind, external_url, label, attested_by) VALUES ($1,'human_attested',$2,'attestation de l’administrateur',$3)", [id, externalUrl, user.id]);234    await setJobState(tx, job, 'VERIFIED', 'attestée par un administrateur (non vérifiée par la machine)', user, correlationId);235  }236  return { state: job.state };237}238/** Manual reconciliation of an ambiguous result. The system never republishes on its own. */239export async function reconcileJob(tx: Tx, id: string, input: { outcome: 'published' | 'not_published'; externalUrl: string | null; note: string }, user: Actor, correlationId?: string) {240  const job = (await tx.query('SELECT * FROM publication_jobs WHERE id=$1 FOR UPDATE', [id])).rows[0];241  if (!job) throw notFound('tâche');242  if (job.state !== 'UNKNOWN_OUTCOME') throw conflict('not_unknown', 'Seul un résultat inconnu se réconcilie.');243  if (input.outcome === 'published') {244    await tx.query("INSERT INTO publication_receipts(job_id, kind, external_url, label, attested_by) VALUES ($1,'human_attested',$2,$3,$4)", [id, input.externalUrl, `réconciliation : ${input.note}`.slice(0, 300), user.id]);245    await setJobState(tx, job, 'VERIFIED', 'réconciliée : publiée (attestation humaine)', user, correlationId);246  } else await setJobState(tx, job, 'FAILED', `réconciliée : non publiée. ${input.note}`.slice(0, 300), user, correlationId);247  return { state: job.state };248}249250/* ───────────── Scheduler sweeps ───────────── */251export async function sweep(tx: Tx): Promise<Record<string, number>> {252  const out = { manual_due: 0, requeued: 0, dead: 0, unknown: 0, leases: 0, workers_offline: 0 };253  const stop = (await emergencyState(tx)).emergency_stop;254  // 1. Manual-assisted jobs reaching their slot wait for a human; nothing is automated.255  if (!stop) for (const job of (await tx.query("SELECT * FROM publication_jobs WHERE state='QUEUED' AND mode='manual_assisted' AND next_run_at <= now() FOR UPDATE SKIP LOCKED")).rows) {256    const why = await preflight(tx, job);257    if (why) { await setJobState(tx, job, 'FAILED', `contrôle préalable : ${why}`, SYSTEM); continue; }258    await setJobState(tx, job, 'AWAITING_CONFIRMATION', 'créneau atteint : publication manuelle assistée', SYSTEM);259    await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.awaiting_confirmation', $1)", [JSON.stringify({ jobId: job.id })]);260    out.manual_due++;261  }262  // 2. A submission marker older than 2 minutes without a "submitted" report: the click may or may not have happened.263  for (const job of (await tx.query(`SELECT j.* FROM publication_jobs j WHERE j.state='AWAITING_CONFIRMATION' AND EXISTS (SELECT 1 FROM job_attempts a WHERE a.job_id=j.id AND a.phase='submitting' AND a.ended_at IS NULL AND a.started_at < now()-interval '2 minutes') FOR UPDATE OF j SKIP LOCKED`)).rows) {264    await tx.query("UPDATE job_attempts SET ended_at=now(), outcome='lost' WHERE job_id=$1 AND phase='submitting' AND ended_at IS NULL", [job.id]);265    await setJobState(tx, job, 'UNKNOWN_OUTCOME', 'interruption pendant la soumission : résultat inconnu, aucune republication', SYSTEM, undefined, ', locked_by=NULL, locked_until=NULL, fencing_token=NULL');266    await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.unknown_outcome', $1)", [JSON.stringify({ jobId: job.id })]);267    out.unknown++;268  }269  // 3. SUBMITTED but never verified within 15 minutes.270  for (const job of (await tx.query("SELECT * FROM publication_jobs WHERE state='SUBMITTED' AND updated_at < now()-interval '15 minutes' FOR UPDATE SKIP LOCKED")).rows) {271    await setJobState(tx, job, 'UNKNOWN_OUTCOME', 'vérification impossible dans le délai : réconciliation manuelle', SYSTEM, undefined, ', locked_by=NULL, locked_until=NULL, fencing_token=NULL');272    await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.unknown_outcome', $1)", [JSON.stringify({ jobId: job.id })]);273    out.unknown++;274  }275  // 4. Preparation whose worker went silent: no external effect happened, bounded retry.276  for (const job of (await tx.query("SELECT * FROM publication_jobs WHERE state='PREPARING' AND locked_until < now() FOR UPDATE SKIP LOCKED")).rows) {277    await tx.query("UPDATE job_attempts SET ended_at=now(), outcome='lost' WHERE job_id=$1 AND phase='prepare' AND ended_at IS NULL", [job.id]);278    if (job.prepare_attempts >= MAX_PREPARE_ATTEMPTS) { await setJobState(tx, job, 'FAILED', 'préparation perdue trop de fois', SYSTEM, undefined, ', dead_letter=true, locked_by=NULL, locked_until=NULL, fencing_token=NULL'); await tx.query("INSERT INTO outbox_events(topic, payload) VALUES ('job.dead_letter', $1)", [JSON.stringify({ jobId: job.id })]); out.dead++; }279    else { await setJobState(tx, job, 'QUEUED', 'worker silencieux pendant la préparation : nouvel essai', SYSTEM, undefined, `, locked_by=NULL, locked_until=NULL, fencing_token=NULL, next_run_at=now()+make_interval(secs=>${30 * 2 ** job.prepare_attempts})`); out.requeued++; }280  }281  // 5. Expired leases: an agent that stopped heart-beating frees the session; a human who left returns it to rest.282  for (const l of (await tx.query('DELETE FROM worker_leases WHERE expires_at < now() RETURNING session_id, holder_kind')).rows) {283    const s = await lockSession(tx, l.session_id);284    if (s.state === 'BUSY' || s.state === 'MANUAL_CONTROL') await transition(tx, s, s.confirmed_at ? 'READY' : 'LOGIN_REQUIRED', 'bail expiré', SYSTEM);285    out.leases++;286  }287  // 6. Workers without heartbeat.288  out.workers_offline = (await tx.query("UPDATE workers SET status='offline' WHERE status='online' AND last_heartbeat_at < now()-interval '45 seconds'")).rowCount ?? 0;289  return out;290}291
Files main
Menu

Theme