@mostajs/delegation 0.0.0-stage → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +224 -0
- package/LICENSE +15 -0
- package/README.md +226 -2
- package/bin/delegation-agent.mjs +98 -0
- package/bin/delegation-cle.mjs +44 -0
- package/bin/delegation-lancer.mjs +17 -0
- package/bin/delegation-service.mjs +38 -0
- package/bin/delegation-train.mjs +16 -0
- package/bin/delegation-veilleur.mjs +24 -0
- package/bin/installer-machine-macos.sh +270 -0
- package/bin/installer-machine.ps1 +330 -0
- package/bin/installer-machine.sh +266 -0
- package/llms.txt +68 -0
- package/package.json +51 -4
- package/src/agent.js +334 -0
- package/src/api.js +368 -0
- package/src/bornes.js +72 -0
- package/src/file.js +175 -0
- package/src/index.js +17 -0
- package/src/lanceur.js +164 -0
- package/src/parc.js +282 -0
- package/src/plateforme.js +134 -0
- package/src/services.js +154 -0
- package/src/signature.js +116 -0
- package/src/stockage.js +30 -0
- package/src/train.js +370 -0
- package/src/types.js +98 -0
- package/src/veilleur.js +80 -0
package/src/api.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
// @mostajs/delegation — l'API des agents, côté console ou CENTRALE (lots L2, C1).
|
|
2
|
+
//
|
|
3
|
+
// C'est l'AGENT qui tire : la centrale ne pousse rien et n'a aucun accès ssh aux machines (§4 du plan 01). Chaque machine
|
|
4
|
+
// s'authentifie par SON jeton ; la centrale n'en garde que l'empreinte SHA-256. Une machine n'agit que sur ses tâches.
|
|
5
|
+
// Depuis 0.3.0 (plan 02, §8.2-1), la centrale n'envoie JAMAIS d'étapes ni de commandes : `{ id, type, titre, entrees }`,
|
|
6
|
+
// que l'agent revalide avec son propre registre avant de fabriquer lui-même ses étapes.
|
|
7
|
+
// POST /api/agent/annonce { capacites, roles, types, telemetrie } → { machine }
|
|
8
|
+
// POST /api/agent/tirer → { tache } | 204
|
|
9
|
+
// POST /api/agent/miennes → { taches: [{ tache }] } (reprise)
|
|
10
|
+
// POST /api/agent/taches/<id>/demarrer
|
|
11
|
+
// POST /api/agent/taches/<id>/progression { progression } (N1 : 403 autre machine, 409 non démarrée)
|
|
12
|
+
// POST /api/agent/taches/<id>/rendre { ok, resultat } (N3 : resultat.finJournal ≤ 8 Ko)
|
|
13
|
+
// POST /api/agent/taches/<id>/interrompue { motif } (0.6.0 : au retour d'un redémarrage → { decision })
|
|
14
|
+
// POST /api/agent/taches/<id>/battement (0.6.0 : le bail ; 403 reprise ailleurs, 409 plus en cours)
|
|
15
|
+
// POST /api/agent/enroler { jeton | code, nom?, roles?, detecte } (annonce du fondateur, ou inscription depuis le PC)
|
|
16
|
+
// 0.6.0 (décision du fondateur, 20/11/2026) :
|
|
17
|
+
// - la CENTRALE est le maestro : son propre agent (`centrale: { jeton: <empreinte> }`, id « centrale ») ne tire que si
|
|
18
|
+
// le réglage du parc l'autorise, seulement les types permis, dans la limite de concurrence ; jamais le train ;
|
|
19
|
+
// - le CANAL direct (`canal: true`, @mostajs/canal-network sous /canal) : `distribuer(tache)` réveille les machines
|
|
20
|
+
// ACCEPTÉES qui savent faire ; `demander(id, evenement)` les interroge ; l'agent se réannonce à chaque reconnexion ;
|
|
21
|
+
// - la MARCHE : hors ligne après `battementsManques` battements de `battementS` sans signe de vie (HTTP ou canal),
|
|
22
|
+
// en ligne au retour ; une tâche d'une machine hors ligne depuis `repriseApresS` est interrompue (politique du type).
|
|
23
|
+
// 0.7.0 (durcissement, 21/11/2026) :
|
|
24
|
+
// - R1 : la tâche part avec son ORDRE signé (`tache.ordre`), que l'agent vérifie avec ses clés publiques ;
|
|
25
|
+
// - R2 : l'annonce d'une machine du parc ne vaut que pour ses capacités et rôles ACCEPTÉS ; la réponse dit `refusees` ;
|
|
26
|
+
// - R4 : délais par type (`demarrageMaxS`, `dureeMaxMin`, `silenceMaxS`), battements par tâche ; machines muettes
|
|
27
|
+
// depuis `muetteJours` mises en sommeil ;
|
|
28
|
+
// - R6 : `exigerHttps` : seulement en HTTPS, ou derrière un mandataire LOCAL qui l'atteste (X-Forwarded-Proto) ; 426.
|
|
29
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
30
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
31
|
+
import { creerCentrale as creerCentraleCanal } from '@mostajs/canal-network';
|
|
32
|
+
import { CAPACITE_CONDUCTEUR } from './types.js';
|
|
33
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
34
|
+
import { bornerJson, bornerTelemetrie, finDeJournal } from './bornes.js';
|
|
35
|
+
|
|
36
|
+
const LIMITE = 256 * 1024;
|
|
37
|
+
const STATUTS = { E_INCONNUE: 404, E_TRANSITION: 409, E_FEU_VERT: 409, E_CAPACITE: 409, E_COMMENCEE: 409, E_ENTREES: 400, E_INTERDIT: 403, E_SIGNATURE: 403 };
|
|
38
|
+
const LOCALE = /^(127\.|::1$|::ffff:127\.)/;
|
|
39
|
+
/** L'identifiant de l'agent de la centrale (maestro) ; aucune machine du parc ne peut le prendre. */
|
|
40
|
+
export const CENTRALE_ID = 'centrale';
|
|
41
|
+
const CAPACITE = /^[A-Za-z0-9@._-]{1,40}$/;
|
|
42
|
+
const PROGRESSION_MAX = 32 * 1024;
|
|
43
|
+
|
|
44
|
+
/** L'empreinte d'un jeton : c'est elle, et elle seule, que la configuration de la console garde. */
|
|
45
|
+
export const empreinteJeton = (jeton) => createHash('sha256').update(String(jeton)).digest('hex');
|
|
46
|
+
|
|
47
|
+
const repondre = (res, statut, corps) => {
|
|
48
|
+
if (corps === undefined) { res.writeHead(statut); return res.end(); }
|
|
49
|
+
const b = JSON.stringify(corps);
|
|
50
|
+
res.writeHead(statut, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
51
|
+
res.end(b);
|
|
52
|
+
};
|
|
53
|
+
const lireJson = (req) => new Promise((ok, ko) => {
|
|
54
|
+
let n = 0; const morceaux = [];
|
|
55
|
+
// Au-delà de la limite, on cesse de garder mais on laisse finir l'envoi : la réponse 413 arrive alors au client.
|
|
56
|
+
req.on('data', (b) => { n += b.length; if (n <= LIMITE) morceaux.push(b); });
|
|
57
|
+
req.on('end', () => {
|
|
58
|
+
if (n > LIMITE) return ko(Object.assign(new Error('corps trop grand'), { statut: 413 }));
|
|
59
|
+
const t = Buffer.concat(morceaux).toString('utf8');
|
|
60
|
+
if (!t) return ok({});
|
|
61
|
+
try { const v = JSON.parse(t); ok(v && typeof v === 'object' && !Array.isArray(v) ? v : {}); } catch { ko(Object.assign(new Error('JSON illisible'), { statut: 400 })); }
|
|
62
|
+
});
|
|
63
|
+
req.on('error', ko);
|
|
64
|
+
});
|
|
65
|
+
const liste = (v) => (Array.isArray(v) ? [...new Set(v.filter((x) => typeof x === 'string' && CAPACITE.test(x)))].slice(0, 64) : []);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {{ file: ReturnType<import('./file.js').creerFile>, machines?: { id: string, jeton: string }[], machinesFichier?: string,
|
|
69
|
+
* maintenant?: () => Date, absenceMs?: number }} o
|
|
70
|
+
* `jeton` est l'EMPREINTE (empreinteJeton) ; `absenceMs` : sans annonce depuis ce délai, la machine est « absente ».
|
|
71
|
+
* `machinesFichier` (N4) : un JSON [{ id, jeton: <empreinte> }] relu dès qu'il change, sans redémarrer la centrale ;
|
|
72
|
+
* `declarer(liste)` fait de même à la main.
|
|
73
|
+
*/
|
|
74
|
+
export function creerApiAgents({ file, machines = [], machinesFichier = null, parc = null, maintenant = () => new Date(), absenceMs = null,
|
|
75
|
+
battementS = 30, battementsManques = 3, repriseApresS = 900, centrale = null, canal = false,
|
|
76
|
+
demarrageMaxS = 900, silenceMaxS = 600, muetteJours = 30, exigerHttps = false, mandataireDeConfiance = (adresse) => LOCALE.test(String(adresse || '')) }) {
|
|
77
|
+
const vie = new Map(); // tâche → dernier signe de vie de son exécution (démarrage, progression, battement)
|
|
78
|
+
const absence = absenceMs ?? battementS * battementsManques * 1000;
|
|
79
|
+
const demarrage = maintenant().getTime();
|
|
80
|
+
// Les machines du PARC (0.5.0) : annoncées depuis la centrale, enrôlées, acceptées. Leur état de marche est tenu ici.
|
|
81
|
+
const dyn = new Map();
|
|
82
|
+
const etat = new Map();
|
|
83
|
+
/** Remplace la liste des machines admises ; celles qui restent gardent leur état, les autres sont oubliées (401). */
|
|
84
|
+
const declarer = (liste) => {
|
|
85
|
+
const garder = new Set();
|
|
86
|
+
for (const m of Array.isArray(liste) ? liste : []) {
|
|
87
|
+
if (!m || typeof m.id !== 'string' || m.id === CENTRALE_ID || !/^[0-9a-f]{64}$/.test(String(m.jeton))) continue;
|
|
88
|
+
garder.add(m.id);
|
|
89
|
+
const x = etat.get(m.id);
|
|
90
|
+
const empreinte = Buffer.from(String(m.jeton), 'hex');
|
|
91
|
+
if (x) x.empreinte = empreinte;
|
|
92
|
+
else etat.set(m.id, { id: m.id, empreinte, roles: [], capacites: [], types: null, telemetrie: null, vu: null, tache: null });
|
|
93
|
+
}
|
|
94
|
+
for (const id of [...etat.keys()]) if (!garder.has(id) && !etat.get(id).estCentrale) etat.delete(id);
|
|
95
|
+
};
|
|
96
|
+
declarer(machines);
|
|
97
|
+
// L'agent de la centrale : un jeton né en mémoire au démarrage de la centrale (empreinte seule ici).
|
|
98
|
+
if (centrale?.jeton && /^[0-9a-f]{64}$/.test(String(centrale.jeton))) {
|
|
99
|
+
etat.set(CENTRALE_ID, { id: CENTRALE_ID, empreinte: Buffer.from(String(centrale.jeton), 'hex'), roles: ['centrale'], capacites: [], types: null, telemetrie: null, vu: null, tache: null, estCentrale: true });
|
|
100
|
+
}
|
|
101
|
+
const reglage = async () => (centrale?.reglage ? centrale.reglage() : parc ? parc.reglageCentrale() : { executer: false, types: [], concurrence: 1 });
|
|
102
|
+
let signature = null;
|
|
103
|
+
const relire = () => {
|
|
104
|
+
if (!machinesFichier) return;
|
|
105
|
+
let s;
|
|
106
|
+
try { const st = statSync(machinesFichier); s = `${st.mtimeMs}:${st.size}`; } catch { s = 'absent'; }
|
|
107
|
+
if (s === signature) return;
|
|
108
|
+
if (s === 'absent') { signature = s; return declarer([]); }
|
|
109
|
+
try { declarer(JSON.parse(readFileSync(machinesFichier, 'utf8'))); signature = s; } catch { /* en cours d'écriture : on garde la liste */ }
|
|
110
|
+
};
|
|
111
|
+
relire();
|
|
112
|
+
|
|
113
|
+
const quiEst = async (req) => {
|
|
114
|
+
const m = /^Bearer\s+(\S{16,512})$/.exec(req.headers.authorization || '');
|
|
115
|
+
if (!m) return null;
|
|
116
|
+
const e = Buffer.from(empreinteJeton(m[1]), 'hex');
|
|
117
|
+
for (const x of etat.values()) if (x.empreinte.length === e.length && timingSafeEqual(x.empreinte, e)) return x;
|
|
118
|
+
if (!parc) return null;
|
|
119
|
+
const p = await parc.identifier(m[1]);
|
|
120
|
+
if (!p) return null;
|
|
121
|
+
const x = dyn.get(p.id) || { id: p.id, roles: [], capacites: [], types: null, telemetrie: null, vu: null, tache: null };
|
|
122
|
+
x.etatParc = p.etat; x.nom = p.nom; dyn.set(p.id, x);
|
|
123
|
+
return x;
|
|
124
|
+
};
|
|
125
|
+
const presenceCanal = () => (canalC ? new Map(canalC.presence().map((p) => [p.id, p])) : new Map());
|
|
126
|
+
/** Présente : un signe de vie (HTTP) depuis moins de N battements, ou un canal ouvert. */
|
|
127
|
+
const presente = (x, pc = presenceCanal()) => {
|
|
128
|
+
const vu = x.vu ? new Date(x.vu).getTime() : null;
|
|
129
|
+
return (vu != null && maintenant().getTime() - vu <= absence) || pc.get(x.id)?.etat === 'connectee';
|
|
130
|
+
};
|
|
131
|
+
const vue = (x, pc = presenceCanal()) => {
|
|
132
|
+
const p = presente(x, pc); const c = pc.get(x.id);
|
|
133
|
+
return { id: x.id, roles: [...x.roles], capacites: [...x.capacites], types: x.types ? [...x.types] : null, telemetrie: x.telemetrie ? structuredClone(x.telemetrie) : null,
|
|
134
|
+
vu: x.vu, tache: x.tache, etat: !p ? 'absente' : x.tache ? 'occupee' : 'libre', ...(x.horsLigneDepuis ? { horsLigneDepuis: x.horsLigneDepuis } : {}),
|
|
135
|
+
...(x.estCentrale ? { centrale: true } : {}), ...(c ? { canal: { etat: c.etat, mode: c.mode } } : {}), ...(x.etatParc ? { etatParc: x.etatParc, nom: x.nom } : {}) };
|
|
136
|
+
};
|
|
137
|
+
// ── Le canal direct (0.6.0) : admis = machines du parc en attente, acceptées, suspendues + celles de la configuration ──
|
|
138
|
+
const canalC = canal ? creerCentraleCanal({ machines: [], prefixe: '/canal', ...(typeof canal === 'object' ? canal : {}) }) : null;
|
|
139
|
+
// Les admis au canal sont relus à chaque requête du canal ET chaque seconde : une machine retirée ou révoquée voit son
|
|
140
|
+
// flux fermé (401) sans attendre qu'elle se reconnecte.
|
|
141
|
+
const rafraichir = canalC ? setInterval(() => { admisCanal().then((l) => canalC.declarer(l)).catch(() => {}); }, 1000) : null;
|
|
142
|
+
rafraichir?.unref?.();
|
|
143
|
+
const dejaInvitees = new Set(); // une invitation à se réannoncer par machine et par vie de la centrale
|
|
144
|
+
const admisCanal = async () => [
|
|
145
|
+
...[...etat.values()].filter((x) => !x.estCentrale).map((x) => ({ id: x.id, jeton: x.empreinte.toString('hex') })),
|
|
146
|
+
...(parc ? await parc.empreintes() : []),
|
|
147
|
+
];
|
|
148
|
+
const gererCanal = async (req, res) => {
|
|
149
|
+
relire();
|
|
150
|
+
const admis = await admisCanal();
|
|
151
|
+
canalC.declarer(admis);
|
|
152
|
+
// Une machine qui revient (centrale redémarrée, coupure) est invitée à se réannoncer, une fois, sans attendre son tour.
|
|
153
|
+
const b = /^Bearer\s+(\S{16,512})$/.exec(req.headers.authorization || '');
|
|
154
|
+
if (b) {
|
|
155
|
+
const e = empreinteJeton(b[1]); const qui = admis.find((x) => x.jeton === e);
|
|
156
|
+
if (qui && !dejaInvitees.has(qui.id) && !(dyn.get(qui.id) || etat.get(qui.id))?.capacites?.length) { dejaInvitees.add(qui.id); canalC.pousser(qui.id, 'annoncer', {}); }
|
|
157
|
+
}
|
|
158
|
+
if (!canalC.gerer(req, res)) repondre(res, 404, { erreur: 'route inconnue' });
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// Ce qui part vers la machine : le type et les entrées, jamais d'étapes ni de commandes (§8.2-1).
|
|
162
|
+
const pourAgent = (t) => ({ tache: { id: t.id, type: t.type, titre: t.titre, entrees: structuredClone(t.entrees), etat: t.etat, ...(t.ordre ? { ordre: { ...t.ordre } } : {}) } });
|
|
163
|
+
/** R6 : la requête est-elle venue en HTTPS (directement, ou par un mandataire local qui l'atteste) ? */
|
|
164
|
+
const enHttps = (req) => req.socket?.encrypted === true
|
|
165
|
+
|| (mandataireDeConfiance(req.socket?.remoteAddress) && /^https$/i.test(String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim()));
|
|
166
|
+
|
|
167
|
+
const traiter = async (req, res) => {
|
|
168
|
+
const u = new URL(req.url, 'http://x');
|
|
169
|
+
if (exigerHttps && !enHttps(req)) return repondre(res, 426, { erreur: 'HTTPS requis' });
|
|
170
|
+
if (canalC && (u.pathname === '/canal' || u.pathname.startsWith('/canal/'))) return gererCanal(req, res);
|
|
171
|
+
if (req.method !== 'POST' || !u.pathname.startsWith('/api/agent/')) return repondre(res, 404, { erreur: 'route inconnue' });
|
|
172
|
+
relire();
|
|
173
|
+
const chemin = u.pathname.slice('/api/agent/'.length);
|
|
174
|
+
// L'enrôlement : le jeton d'enrôlement (usage unique, durée courte) vient dans le corps ; il rend le jeton durable.
|
|
175
|
+
if (chemin === 'enroler') {
|
|
176
|
+
if (!parc) return repondre(res, 404, { erreur: 'route inconnue' });
|
|
177
|
+
const b = await lireJson(req);
|
|
178
|
+
try {
|
|
179
|
+
const r = await parc.enroler(String(b.jeton || b.code || ''), { detecte: b.detecte, nom: typeof b.nom === 'string' ? b.nom : undefined, roles: b.roles });
|
|
180
|
+
return repondre(res, 200, { machine: r.id, jeton: r.jeton });
|
|
181
|
+
} catch (e) {
|
|
182
|
+
if (e.code === 'E_ENROLEMENT') return repondre(res, 401, { erreur: e.message });
|
|
183
|
+
throw e;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const m = await quiEst(req);
|
|
187
|
+
if (!m) return repondre(res, 401, { erreur: 'jeton de machine absent ou inconnu' });
|
|
188
|
+
const corps = await lireJson(req);
|
|
189
|
+
m.vu = maintenant().toISOString();
|
|
190
|
+
if (parc && m.etatParc) parc.noterVu(m.id, m.vu).catch(() => {});
|
|
191
|
+
if (m.horsLigneDepuis) { m.horsLigneDepuis = null; if (parc && m.etatParc) await parc.noterMarche(m.id, 'en-ligne'); m.annonceEnLigne = true; }
|
|
192
|
+
// Rien n'est exécuté sur une machine non acceptée : en attente, elle ne peut que s'annoncer ; suspendue, elle ne tire
|
|
193
|
+
// plus rien de nouveau (elle peut finir et rendre ce qu'elle avait).
|
|
194
|
+
if (m.etatParc === 'en_attente' && chemin !== 'annonce') return repondre(res, 403, { erreur: 'machine en attente d’acceptation' });
|
|
195
|
+
if (m.etatParc === 'suspendue' && chemin === 'tirer') return repondre(res, 403, { erreur: 'machine suspendue' });
|
|
196
|
+
|
|
197
|
+
if (chemin === 'annonce') {
|
|
198
|
+
m.capacites = liste(corps.capacites); m.roles = liste(corps.roles);
|
|
199
|
+
// La centrale n'est jamais conducteur de train (décision du 20/11/2026), quoi que dise son agent.
|
|
200
|
+
if (m.estCentrale) { m.capacites = m.capacites.filter((c) => c !== CAPACITE_CONDUCTEUR); m.roles = ['centrale']; }
|
|
201
|
+
m.types = Array.isArray(corps.types) ? liste(corps.types) : null; // null : agent d'avant 0.3.0, sans liste de types
|
|
202
|
+
m.telemetrie = bornerTelemetrie(corps.telemetrie);
|
|
203
|
+
let refusees = { capacites: [], roles: [] };
|
|
204
|
+
if (parc && m.etatParc && !m.estCentrale) { // R2 : seules les capacités et rôles acceptés valent
|
|
205
|
+
const r = await parc.noterAnnonce(m.id, { capacites: m.capacites, roles: m.roles });
|
|
206
|
+
m.capacites = r.capacites; m.roles = r.roles; refusees = r.refusees;
|
|
207
|
+
}
|
|
208
|
+
return repondre(res, 200, { machine: m.id, refusees });
|
|
209
|
+
}
|
|
210
|
+
if (chemin === 'tirer') {
|
|
211
|
+
if (!m.capacites.length) return repondre(res, 409, { erreur: 'annoncez d’abord vos capacités' });
|
|
212
|
+
let types = m.types;
|
|
213
|
+
if (m.estCentrale) {
|
|
214
|
+
// Le maestro n'exécute rien par défaut ; seulement les types permis, dans la limite de concurrence.
|
|
215
|
+
const r = await reglage();
|
|
216
|
+
if (!r.executer) return repondre(res, 403, { erreur: 'la centrale n’exécute aucune tâche (réglage désactivé)' });
|
|
217
|
+
const enCours = (await file.taches()).filter((x) => x.machine === CENTRALE_ID && ['affectee', 'en_cours'].includes(x.etat)).length;
|
|
218
|
+
if (enCours >= r.concurrence) return repondre(res, 204);
|
|
219
|
+
types = (m.types || r.types).filter((x) => r.types.includes(x) && x !== 'train');
|
|
220
|
+
}
|
|
221
|
+
const t = await file.tirer({ id: m.id, capacites: m.capacites, ...(types ? { types } : {}), ...(m.estCentrale ? { centrale: true } : {}) });
|
|
222
|
+
if (!t) return repondre(res, 204);
|
|
223
|
+
m.tache = t.id;
|
|
224
|
+
return repondre(res, 200, pourAgent(t));
|
|
225
|
+
}
|
|
226
|
+
if (chemin === 'miennes') {
|
|
227
|
+
const t = (await file.taches()).filter((x) => x.machine === m.id && ['affectee', 'en_cours'].includes(x.etat));
|
|
228
|
+
return repondre(res, 200, { taches: t.map(pourAgent) });
|
|
229
|
+
}
|
|
230
|
+
const a = /^taches\/([A-Za-z0-9-]{1,80})\/(demarrer|progression|rendre|interrompue|battement)$/.exec(chemin);
|
|
231
|
+
if (!a) return repondre(res, 404, { erreur: 'route inconnue' });
|
|
232
|
+
const t = await file.tache(a[1]);
|
|
233
|
+
if (!t) return repondre(res, 404, { erreur: 'tâche inconnue' });
|
|
234
|
+
if (t.machine !== m.id) return repondre(res, 403, { erreur: 'cette tâche est affectée à une autre machine' });
|
|
235
|
+
if (a[2] === 'demarrer') { m.tache = t.id; const x = await file.demarrer(t.id, { par: m.id }); vie.set(t.id, maintenant().getTime()); return repondre(res, 200, { tache: x }); }
|
|
236
|
+
// Au retour d'un redémarrage (ou d'un bail dépassé) : la machine déclare sa tâche interrompue ; Delegate décide.
|
|
237
|
+
const interrompre = async (motif) => {
|
|
238
|
+
const r = await file.interrompre(t.id, { par: m.id, motif: String(motif || 'interrompue').slice(0, 200) });
|
|
239
|
+
if (r.decision !== 'reprendre' && m.tache === t.id) m.tache = null;
|
|
240
|
+
return r;
|
|
241
|
+
};
|
|
242
|
+
if (a[2] === 'interrompue' || (a[2] === 'rendre' && corps.interrompue === true)) {
|
|
243
|
+
const r = await interrompre(corps.motif || corps.resultat?.motif);
|
|
244
|
+
return repondre(res, 200, { decision: r.decision, tache: r.tache });
|
|
245
|
+
}
|
|
246
|
+
if (a[2] === 'battement') {
|
|
247
|
+
if (t.etat !== 'en_cours') return repondre(res, 409, { erreur: `la tâche ${t.id} est « ${t.etat} »` });
|
|
248
|
+
vie.set(t.id, maintenant().getTime());
|
|
249
|
+
return repondre(res, 200, { ok: true });
|
|
250
|
+
}
|
|
251
|
+
if (a[2] === 'progression') {
|
|
252
|
+
const p = bornerJson(corps.progression ?? null);
|
|
253
|
+
if (JSON.stringify(p).length > PROGRESSION_MAX) return repondre(res, 413, { erreur: 'progression trop grande' });
|
|
254
|
+
await file.progression(t.id, { progression: p });
|
|
255
|
+
vie.set(t.id, maintenant().getTime());
|
|
256
|
+
return repondre(res, 200, { ok: true });
|
|
257
|
+
}
|
|
258
|
+
let resultat = null;
|
|
259
|
+
if (corps.resultat && typeof corps.resultat === 'object' && !Array.isArray(corps.resultat)) {
|
|
260
|
+
const { finJournal, ...reste } = corps.resultat;
|
|
261
|
+
resultat = bornerJson(reste);
|
|
262
|
+
if (typeof finJournal === 'string' && finJournal) resultat.finJournal = finDeJournal(finJournal);
|
|
263
|
+
}
|
|
264
|
+
const fin = await file.terminer(t.id, { par: m.id, ok: corps.ok === true, resultat });
|
|
265
|
+
if (m.tache === t.id) m.tache = null;
|
|
266
|
+
return repondre(res, 200, { tache: fin });
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
const api = (req, res) => traiter(req, res).catch((e) => {
|
|
270
|
+
if (res.headersSent) return res.end();
|
|
271
|
+
repondre(res, e.statut || STATUTS[e.code] || 500, { erreur: e.statut || STATUTS[e.code] ? e.message : 'erreur interne' });
|
|
272
|
+
});
|
|
273
|
+
api.machines = () => { relire(); const pc = presenceCanal(); return [...etat.values(), ...dyn.values()].map((x) => vue(x, pc)); };
|
|
274
|
+
api.declarer = (liste) => { declarer(liste); };
|
|
275
|
+
|
|
276
|
+
/** Le maestro distribue : réveille par le canal les machines ACCEPTÉES qui savent faire la tâche. Rend leurs ids. */
|
|
277
|
+
api.distribuer = async (tacheOuId) => {
|
|
278
|
+
if (!canalC) return [];
|
|
279
|
+
const t = typeof tacheOuId === 'string' ? await file.tache(tacheOuId) : tacheOuId;
|
|
280
|
+
if (!t || t.etat !== 'proposee' || !t.feuVert) return [];
|
|
281
|
+
const pc = presenceCanal(); const ids = [];
|
|
282
|
+
for (const x of [...etat.values(), ...dyn.values()]) {
|
|
283
|
+
if (parc && dyn.has(x.id)) { const p = await parc.machine(x.id); x.etatParc = p?.etat; }
|
|
284
|
+
if (x.estCentrale || (x.etatParc && x.etatParc !== 'acceptee')) continue;
|
|
285
|
+
if (parc && !x.etatParc && dyn.has(x.id)) continue;
|
|
286
|
+
if (Array.isArray(x.types) && !x.types.includes(t.type)) continue;
|
|
287
|
+
if (!pc.has(x.id)) continue;
|
|
288
|
+
canalC.pousser(x.id, 'tache', { id: t.id, type: t.type }); ids.push(x.id);
|
|
289
|
+
}
|
|
290
|
+
return ids;
|
|
291
|
+
};
|
|
292
|
+
/** Interroge une machine présente sur le canal (E_ABSENTE, E_DELAI). */
|
|
293
|
+
api.demander = (id, evenement, donnees = {}, o = {}) => {
|
|
294
|
+
if (!canalC) return Promise.reject(Object.assign(new Error('canal non ouvert'), { code: 'E_CANAL' }));
|
|
295
|
+
return canalC.demander(id, evenement, donnees, o);
|
|
296
|
+
};
|
|
297
|
+
/**
|
|
298
|
+
* La marche : hors ligne / en ligne (journal du parc), et la reprise des tâches des machines hors ligne depuis
|
|
299
|
+
* `repriseApresS`. Rend { horsLigne, enLigne, reprises: [{ tache, machine, decision }] }.
|
|
300
|
+
*/
|
|
301
|
+
api.verifier = async () => {
|
|
302
|
+
relire();
|
|
303
|
+
if (canalC) canalC.declarer(await admisCanal());
|
|
304
|
+
const pc = presenceCanal(); const t0 = maintenant().getTime();
|
|
305
|
+
const r = { horsLigne: [], enLigne: [], reprises: [], enSommeil: [] };
|
|
306
|
+
const tous = new Map([...etat.values(), ...dyn.values()].map((x) => [x.id, x]));
|
|
307
|
+
for (const x of tous.values()) {
|
|
308
|
+
const p = presente(x, pc);
|
|
309
|
+
if (!p && !x.horsLigneDepuis && x.vu) {
|
|
310
|
+
x.horsLigneDepuis = new Date(new Date(x.vu).getTime() + absence).toISOString(); r.horsLigne.push(x.id);
|
|
311
|
+
if (parc && x.etatParc) await parc.noterMarche(x.id, 'hors-ligne', `${battementsManques} battements manqués`);
|
|
312
|
+
} else if (p && (x.horsLigneDepuis || x.annonceEnLigne)) {
|
|
313
|
+
if (x.horsLigneDepuis && parc && x.etatParc) await parc.noterMarche(x.id, 'en-ligne');
|
|
314
|
+
x.horsLigneDepuis = null; x.annonceEnLigne = false; r.enLigne.push(x.id);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const reprendre = async (t, x, motif, politique) => {
|
|
318
|
+
const d = await file.interrompre(t.id, { par: 'centrale', motif, ...(politique ? { politique } : {}) });
|
|
319
|
+
if (x && x.tache === t.id) x.tache = null;
|
|
320
|
+
vie.delete(t.id);
|
|
321
|
+
r.reprises.push({ tache: t.id, machine: t.machine, decision: d.decision });
|
|
322
|
+
};
|
|
323
|
+
for (const t of await file.taches()) {
|
|
324
|
+
if (!['affectee', 'en_cours'].includes(t.etat) || !t.machine) continue;
|
|
325
|
+
const x = tous.get(t.machine);
|
|
326
|
+
if (x && presente(x, pc)) {
|
|
327
|
+
// R4 : la machine est là, mais la tâche ne vit pas comme elle devrait.
|
|
328
|
+
const def = file.type ? file.type(t.type) : null;
|
|
329
|
+
const depuis = Math.max(Date.parse(t.maj) || 0, demarrage);
|
|
330
|
+
if (t.etat === 'affectee') {
|
|
331
|
+
const lim = def?.demarrageMaxS ?? demarrageMaxS;
|
|
332
|
+
if (lim && t0 - depuis > lim * 1000) await reprendre(t, x, `non démarrée en ${lim} s`, 'remettre');
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const duree = def?.dureeMaxMin;
|
|
336
|
+
if (duree && t0 - (Date.parse(t.maj) || demarrage) > duree * 60_000) { await reprendre(t, x, `durée dépassée (plus de ${duree} min)`); continue; }
|
|
337
|
+
const lim = def?.silenceMaxS ?? silenceMaxS;
|
|
338
|
+
const dernier = Math.max(vie.get(t.id) || 0, depuis, Date.parse(t.progressionMaj || '') || 0);
|
|
339
|
+
if (lim && t0 - dernier > lim * 1000) await reprendre(t, x, `silence depuis plus de ${lim} s`);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
// Inconnue depuis le démarrage de la centrale : hors ligne depuis ce démarrage.
|
|
343
|
+
const depuis = x?.horsLigneDepuis ? Date.parse(x.horsLigneDepuis) : x?.vu ? new Date(x.vu).getTime() + absence : demarrage;
|
|
344
|
+
if (t0 - depuis < repriseApresS * 1000) continue;
|
|
345
|
+
await reprendre(t, x, `machine ${t.machine} hors ligne depuis plus de ${repriseApresS} s`);
|
|
346
|
+
}
|
|
347
|
+
// R4 : les machines acceptées muettes depuis `muetteJours` sont mises en sommeil (suspendues), jamais effacées.
|
|
348
|
+
if (parc && muetteJours) {
|
|
349
|
+
for (const p of await parc.machines()) {
|
|
350
|
+
if (p.etat !== 'acceptee') continue;
|
|
351
|
+
const x = tous.get(p.id);
|
|
352
|
+
const vu = Math.max(x?.vu ? Date.parse(x.vu) : 0, p.vu ? Date.parse(p.vu) : 0, Date.parse(p.maj) || 0);
|
|
353
|
+
if (t0 - vu > muetteJours * 86400_000 && await parc.mettreEnSommeil(p.id, `muette depuis plus de ${muetteJours} jours`)) {
|
|
354
|
+
r.enSommeil.push(p.id); if (x) x.etatParc = 'suspendue';
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return r;
|
|
359
|
+
};
|
|
360
|
+
/** La surveillance périodique de la marche ; rend la fonction d'arrêt. */
|
|
361
|
+
api.surveiller = ({ periodeS = battementS } = {}) => {
|
|
362
|
+
const h = setInterval(() => { api.verifier().catch(() => {}); }, Math.max(1, periodeS) * 1000); h.unref?.();
|
|
363
|
+
return () => clearInterval(h);
|
|
364
|
+
};
|
|
365
|
+
api.presence = () => (canalC ? canalC.presence() : []);
|
|
366
|
+
api.fermer = () => { if (rafraichir) clearInterval(rafraichir); canalC?.fermer(); };
|
|
367
|
+
return api;
|
|
368
|
+
}
|
package/src/bornes.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// @mostajs/delegation — ce que la centrale accepte d'une machine est BORNÉ : profondeur, longueur des chaînes et des
|
|
2
|
+
// listes, nombres finis ; la télémétrie n'a que des clés connues ; la fin d'un journal tient en 8 Ko, sans codes couleur
|
|
3
|
+
// ni jeton lisible. Une machine (ou un jeton volé) ne peut ni gonfler la file ni y glisser n'importe quoi.
|
|
4
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
5
|
+
|
|
6
|
+
export const FIN_JOURNAL_OCTETS = 8192;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Copie bornée d'une valeur JSON : chaînes ≤ `chaine`, listes ≤ `liste`, objets ≤ `cles` clés, profondeur ≤ `profondeur`
|
|
10
|
+
* (au-delà : null), nombres non finis → null, fonctions et autres → ignorés.
|
|
11
|
+
*/
|
|
12
|
+
export function bornerJson(v, { chaine = 300, liste = 50, cles = 40, profondeur = 6 } = {}, n = 0) {
|
|
13
|
+
if (v == null || typeof v === 'boolean') return v ?? null;
|
|
14
|
+
if (typeof v === 'number') return Number.isFinite(v) ? v : null;
|
|
15
|
+
if (typeof v === 'string') return v.length > chaine ? v.slice(0, chaine) : v;
|
|
16
|
+
if (n >= profondeur) return null;
|
|
17
|
+
const o = { chaine, liste, cles, profondeur };
|
|
18
|
+
if (Array.isArray(v)) return v.slice(0, liste).map((x) => bornerJson(x, o, n + 1));
|
|
19
|
+
if (typeof v === 'object') {
|
|
20
|
+
const r = {};
|
|
21
|
+
for (const [k, x] of Object.entries(v).slice(0, cles)) {
|
|
22
|
+
if (typeof x === 'function' || typeof x === 'symbol' || typeof x === 'bigint') continue;
|
|
23
|
+
r[k.slice(0, 60)] = bornerJson(x, o, n + 1);
|
|
24
|
+
}
|
|
25
|
+
return r;
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const nombre = (v, min, max) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : null);
|
|
31
|
+
const mot = (v, motif, long) => (typeof v === 'string' && v ? (motif.test(v.slice(0, long)) ? v.slice(0, long) : null) : null);
|
|
32
|
+
const HOTE = /^[A-Za-z0-9._-]+$/;
|
|
33
|
+
const VERSION = /^\d+\.\d+\.\d+[A-Za-z0-9.+-]*$/;
|
|
34
|
+
const SIMPLE = /^[A-Za-z0-9._@+-]+$/;
|
|
35
|
+
|
|
36
|
+
/** La télémétrie d'une annonce, réduite aux clés connues et bornée (plan 02, N2). */
|
|
37
|
+
export function bornerTelemetrie(t) {
|
|
38
|
+
if (!t || typeof t !== 'object' || Array.isArray(t)) return null;
|
|
39
|
+
const mo = (x) => (x && typeof x === 'object' ? x : {});
|
|
40
|
+
return {
|
|
41
|
+
hote: mot(t.hote, HOTE, 64),
|
|
42
|
+
charge: nombre(t.charge, 0, 1000),
|
|
43
|
+
cpus: nombre(t.cpus, 0, 4096),
|
|
44
|
+
memoire: { totaleMo: nombre(mo(t.memoire).totaleMo, 0, 1e9), libreMo: nombre(mo(t.memoire).libreMo, 0, 1e9) },
|
|
45
|
+
disque: { totalMo: nombre(mo(t.disque).totalMo, 0, 1e12), libreMo: nombre(mo(t.disque).libreMo, 0, 1e12) },
|
|
46
|
+
version: mot(t.version, VERSION, 32),
|
|
47
|
+
node: mot(t.node, VERSION, 32),
|
|
48
|
+
plateforme: mot(t.plateforme, SIMPLE, 32),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
53
|
+
const SECRETS = [
|
|
54
|
+
/(Bearer\s+)[^\s"']+/gi,
|
|
55
|
+
/((?:token|jeton|password|passwd|mot[-_ ]?de[-_ ]?passe|secret|api[-_]?key|cle|clé)["']?\s*[=:]\s*["']?)[^\s"',;]+/gi,
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* La fin d'un texte de journal, ≤ `octets` (UTF-8), nettoyée des codes couleur, les jetons et mots de passe masqués
|
|
60
|
+
* (plan 02, N3). Jamais le journal entier.
|
|
61
|
+
*/
|
|
62
|
+
export function finDeJournal(texte, octets = FIN_JOURNAL_OCTETS) {
|
|
63
|
+
let t = String(texte ?? '').replace(ANSI, '');
|
|
64
|
+
for (const s of SECRETS) t = t.replace(s, '$1***');
|
|
65
|
+
let b = Buffer.from(t, 'utf8');
|
|
66
|
+
if (b.length <= octets) return t;
|
|
67
|
+
const marque = '…\n';
|
|
68
|
+
b = b.subarray(b.length - (octets - Buffer.byteLength(marque)));
|
|
69
|
+
let r = b.toString('utf8').replace(/^�+/, '');
|
|
70
|
+
while (Buffer.byteLength(marque + r) > octets) r = r.slice(1);
|
|
71
|
+
return marque + r;
|
|
72
|
+
}
|
package/src/file.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// @mostajs/delegation — la file des tâches : états portés par @mostajs/statemachine, feu vert, journal (qui, quand).
|
|
2
|
+
//
|
|
3
|
+
// Une tâche naît « proposée », feu vert OFF (décision D-4) : rien ne part sans l'accord du Maître d'ouvrage.
|
|
4
|
+
// ON la rend affectable ; OFF sur une tâche affectée mais non commencée la RETIRE (retour à « proposée »).
|
|
5
|
+
// Une tâche ne porte jamais de commande : un type et des entrées validées. Les étapes viennent du type (§4 du plan).
|
|
6
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
8
|
+
import { defineMachine } from '@mostajs/statemachine';
|
|
9
|
+
import { manquesPour, exigeConducteur, SI_INTERROMPUE } from './types.js';
|
|
10
|
+
import { verifierOrdre, nouvelOrdre } from './signature.js';
|
|
11
|
+
|
|
12
|
+
export const ETATS = Object.freeze(['proposee', 'affectee', 'en_cours', 'faite', 'echec', 'annulee']);
|
|
13
|
+
const erreur = (code, message) => Object.assign(new Error(message), { code });
|
|
14
|
+
|
|
15
|
+
const CYCLE = {
|
|
16
|
+
states: [
|
|
17
|
+
{ id: 'proposee', initial: true }, { id: 'affectee' }, { id: 'en_cours' },
|
|
18
|
+
{ id: 'faite', terminal: true }, { id: 'echec', terminal: true }, { id: 'annulee', terminal: true },
|
|
19
|
+
],
|
|
20
|
+
transitions: [
|
|
21
|
+
{ id: 'affecter', from: ['proposee'], to: 'affectee', guard: (c) => c.data?.feuVert === true },
|
|
22
|
+
{ id: 'retirer', from: ['affectee', 'en_cours'], to: 'proposee' },
|
|
23
|
+
{ id: 'demarrer', from: ['affectee'], to: 'en_cours' },
|
|
24
|
+
{ id: 'reussir', from: ['en_cours'], to: 'faite' },
|
|
25
|
+
{ id: 'echouer', from: ['affectee', 'en_cours'], to: 'echec' },
|
|
26
|
+
{ id: 'annuler', from: ['proposee', 'affectee', 'en_cours'], to: 'annulee' },
|
|
27
|
+
],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {{ registre: ReturnType<import('./types.js').creerRegistre>, stockage: { lire: () => Promise<object>, ecrire: (d: object) => Promise<void> }, maintenant?: () => Date }} o
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* siInterrompue : la politique par défaut d'une tâche interrompue (le type peut déclarer la sienne) ;
|
|
35
|
+
* interruptionsMax : au-delà, la tâche est arrêtée (elle ne tourne pas en rond).
|
|
36
|
+
* clesPubliques (0.7.0, R1) : avec elles, le feu vert ON exige un ordre signé valide (E_SIGNATURE) ; l'ordre est gardé
|
|
37
|
+
* sur la tâche et part avec elle vers l'agent, qui le vérifie avec SES clés. La file ne voit jamais de clé privée.
|
|
38
|
+
*/
|
|
39
|
+
export function creerFile({ registre, stockage, maintenant = () => new Date(), siInterrompue = 'remettre', interruptionsMax = 3, clesPubliques = null }) {
|
|
40
|
+
if (!SI_INTERROMPUE.includes(siInterrompue)) throw erreur('E_OPTION', `siInterrompue : ${SI_INTERROMPUE.join(' | ')}`);
|
|
41
|
+
if (!registre || !stockage) throw erreur('E_OPTION', 'creerFile : registre et stockage requis');
|
|
42
|
+
let d = null; // l'état chargé, relu une fois puis tenu en mémoire et réécrit à chaque changement
|
|
43
|
+
let suite = Promise.resolve(); // une opération à la fois : la file ne se dispute pas avec elle-même
|
|
44
|
+
|
|
45
|
+
// Le journal de la machine à états EST celui de la file : une transition s'y inscrit telle qu'elle s'est faite.
|
|
46
|
+
const audit = {
|
|
47
|
+
async record(t) { d.journal.push({ tache: t.entityId, quoi: t.toState, de: t.fromState, par: t.actorId ?? null, quand: t.timestamp, ...(t.comment ? { motif: t.comment } : {}) }); },
|
|
48
|
+
async list(ref) { return d.journal.filter((l) => l.tache === ref.entityId && ETATS.includes(l.quoi)); },
|
|
49
|
+
};
|
|
50
|
+
const cycle = defineMachine(CYCLE, { audit, now: maintenant });
|
|
51
|
+
|
|
52
|
+
const enSerie = (fn) => { const p = suite.then(async () => { if (!d) d = await stockage.lire(); return fn(); }); suite = p.catch(() => {}); return p; };
|
|
53
|
+
const sauver = () => stockage.ecrire(d);
|
|
54
|
+
const trouver = (id) => { const t = d.taches.find((x) => x.id === id); if (!t) throw erreur('E_INCONNUE', `tâche inconnue « ${id} »`); return t; };
|
|
55
|
+
const noter = (t, quoi, par, motif) => d.journal.push({ tache: t.id, quoi, par: par ?? null, quand: maintenant().toISOString(), ...(motif ? { motif } : {}) });
|
|
56
|
+
const passer = async (t, vers, { par, motif, feuVert } = {}) => {
|
|
57
|
+
try {
|
|
58
|
+
await cycle.transition({ entityType: 'tache', entityId: t.id }, t.etat, vers, { actorId: par, comment: motif, data: { feuVert: feuVert ?? t.feuVert } });
|
|
59
|
+
} catch (e) {
|
|
60
|
+
throw erreur('E_TRANSITION', `« ${t.etat} » → « ${vers} » refusé pour la tâche ${t.id}${e?.message ? ` (${e.message})` : ''}`);
|
|
61
|
+
}
|
|
62
|
+
t.etat = vers; t.maj = maintenant().toISOString();
|
|
63
|
+
};
|
|
64
|
+
const copie = (t) => (t ? structuredClone(t) : null);
|
|
65
|
+
|
|
66
|
+
const affecterA = async (t, machine, par) => {
|
|
67
|
+
if (!t.feuVert) throw erreur('E_FEU_VERT', `la tâche ${t.id} n'a pas le feu vert`);
|
|
68
|
+
// La centrale (Delegate) n'est jamais conducteur de train, même si elle a le droit d'exécuter (décision du 20/11/2026).
|
|
69
|
+
if (machine.centrale && exigeConducteur(registre.type(t.type))) throw erreur('E_INTERDIT', `« ${t.type} » ne va jamais à la centrale`);
|
|
70
|
+
const manque = manquesPour(machine, registre.type(t.type));
|
|
71
|
+
if (manque.length) throw erreur('E_CAPACITE', `la machine ${machine.id} ne sait pas faire « ${t.type} » : il lui manque ${manque.join(', ')}`);
|
|
72
|
+
await passer(t, 'affectee', { par });
|
|
73
|
+
t.machine = machine.id;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
/** Propose une tâche : type connu, entrées validées ; feu vert OFF. */
|
|
78
|
+
proposer: ({ type, entrees = {}, par, titre = null }) => enSerie(async () => {
|
|
79
|
+
const f = registre.valider(type, entrees);
|
|
80
|
+
if (f.length) throw erreur('E_ENTREES', `tâche refusée : ${f.join(' ; ')}`);
|
|
81
|
+
const quand = maintenant().toISOString();
|
|
82
|
+
const t = { id: `${quand.slice(0, 10).replace(/-/g, '')}-${randomBytes(4).toString('hex')}`, type, titre: titre || type,
|
|
83
|
+
entrees: { ...entrees }, etat: 'proposee', feuVert: false, machine: null, cree: quand, maj: quand, par: par ?? null, resultat: null };
|
|
84
|
+
d.taches.push(t); noter(t, 'proposee', par); await sauver();
|
|
85
|
+
return copie(t);
|
|
86
|
+
}),
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Bascule le feu vert. OFF sur une tâche affectée non commencée la retire ; OFF refusé une fois commencée.
|
|
90
|
+
* `ordre` (R1) : { echeance, nonce, cle, signature } signé sur le poste ; exigé si la file a des clés publiques.
|
|
91
|
+
*/
|
|
92
|
+
feuVert: (id, on, { par, ordre = null } = {}) => enSerie(async () => {
|
|
93
|
+
const t = trouver(id);
|
|
94
|
+
if (!on && !['proposee', 'affectee'].includes(t.etat)) throw erreur('E_COMMENCEE', `la tâche ${id} est « ${t.etat} » : le feu vert ne se retire plus`);
|
|
95
|
+
if (on && t.etat !== 'proposee') throw erreur('E_TRANSITION', `la tâche ${id} est « ${t.etat} »`);
|
|
96
|
+
if (on && Array.isArray(clesPubliques) && clesPubliques.length) {
|
|
97
|
+
const v = verifierOrdre(t, ordre, clesPubliques, { maintenant });
|
|
98
|
+
if (!v.ok) throw erreur('E_SIGNATURE', `feu vert refusé pour ${id} : ${v.motif}`);
|
|
99
|
+
}
|
|
100
|
+
const o = on && ordre && typeof ordre === 'object'
|
|
101
|
+
? { echeance: String(ordre.echeance), nonce: String(ordre.nonce), cle: String(ordre.cle), signature: String(ordre.signature) } : null;
|
|
102
|
+
t.feuVert = Boolean(on);
|
|
103
|
+
if (o) t.ordre = o; else delete t.ordre;
|
|
104
|
+
noter(t, on ? 'feu-vert:on' : 'feu-vert:off', par, o ? `signé ${o.cle}` : undefined);
|
|
105
|
+
if (!on && t.etat === 'affectee') { await passer(t, 'proposee', { par, motif: 'feu vert retiré' }); t.machine = null; }
|
|
106
|
+
await sauver(); return copie(t);
|
|
107
|
+
}),
|
|
108
|
+
|
|
109
|
+
/** L'ordre à faire signer sur le poste pour le feu vert de cette tâche (R1) : { id, type, entrees, echeance, nonce }. */
|
|
110
|
+
ordreASigner: (id, { dureeH = 24 } = {}) => enSerie(async () => { const t = trouver(id); return nouvelOrdre(t, { dureeH, maintenant }); }),
|
|
111
|
+
|
|
112
|
+
/** Affecte une tâche à une machine (confirmation humaine d'une proposition, ou affectation directe). */
|
|
113
|
+
affecter: (id, machine, { par } = {}) => enSerie(async () => { const t = trouver(id); await affecterA(t, machine, par); await sauver(); return copie(t); }),
|
|
114
|
+
|
|
115
|
+
/** Une machine TIRE la plus ancienne tâche au feu vert qu'elle sait faire ; null s'il n'y en a pas. */
|
|
116
|
+
tirer: (machine) => enSerie(async () => {
|
|
117
|
+
// Une machine qui annonce ses types (0.3.0) ne reçoit que ceux-là : elle seule sait les exécuter (§8.2-1).
|
|
118
|
+
const sait = (x) => !Array.isArray(machine.types) || machine.types.includes(x.type);
|
|
119
|
+
const permis = (x) => !(machine.centrale && exigeConducteur(registre.type(x.type)));
|
|
120
|
+
const t = d.taches.find((x) => x.etat === 'proposee' && x.feuVert && sait(x) && permis(x) && registre.type(x.type) && !manquesPour(machine, registre.type(x.type)).length);
|
|
121
|
+
if (!t) return null;
|
|
122
|
+
await affecterA(t, machine, machine.id); await sauver(); return copie(t);
|
|
123
|
+
}),
|
|
124
|
+
|
|
125
|
+
demarrer: (id, { par } = {}) => enSerie(async () => { const t = trouver(id); await passer(t, 'en_cours', { par }); await sauver(); return copie(t); }),
|
|
126
|
+
terminer: (id, { par, ok, resultat = null } = {}) => enSerie(async () => {
|
|
127
|
+
const t = trouver(id); await passer(t, ok ? 'faite' : 'echec', { par, motif: ok ? undefined : resultat?.motif }); t.resultat = resultat; await sauver(); return copie(t);
|
|
128
|
+
}),
|
|
129
|
+
/** La dernière progression d'une tâche en cours (plan 02, N1) ; elle remplace la précédente, sans journal. */
|
|
130
|
+
progression: (id, { progression } = {}) => enSerie(async () => {
|
|
131
|
+
const t = trouver(id);
|
|
132
|
+
if (t.etat !== 'en_cours') throw erreur('E_TRANSITION', `la tâche ${id} est « ${t.etat} » : pas de progression`);
|
|
133
|
+
t.progression = progression ?? null; t.progressionMaj = maintenant().toISOString(); await sauver(); return copie(t);
|
|
134
|
+
}),
|
|
135
|
+
/**
|
|
136
|
+
* Une tâche INTERROMPUE (machine redémarrée, hors ligne trop longtemps, bail dépassé) : jamais perdue en silence.
|
|
137
|
+
* Politique : `politique` donnée, sinon celle du type, sinon celle de la file. Rend { decision, tache }.
|
|
138
|
+
* remettre → « proposée », feu vert gardé, plus de machine (l'ancienne ne peut plus ni progresser ni rendre) ;
|
|
139
|
+
* arreter → « échec », motif « interrompue : … » ;
|
|
140
|
+
* reprendre → reste à sa machine, qui la reprend sans rejouer les étapes faites.
|
|
141
|
+
* Au-delà de `interruptionsMax`, toujours arrêtée.
|
|
142
|
+
*/
|
|
143
|
+
interrompre: (id, { par, motif = 'interrompue', politique } = {}) => enSerie(async () => {
|
|
144
|
+
const t = trouver(id);
|
|
145
|
+
if (!['affectee', 'en_cours'].includes(t.etat)) throw erreur('E_TRANSITION', `la tâche ${id} est « ${t.etat} » : rien à interrompre`);
|
|
146
|
+
t.interruptions = (t.interruptions || 0) + 1;
|
|
147
|
+
let decision = politique || registre.type(t.type)?.siInterrompue || siInterrompue;
|
|
148
|
+
if (!SI_INTERROMPUE.includes(decision)) decision = siInterrompue;
|
|
149
|
+
if (t.interruptions > interruptionsMax) decision = 'arreter';
|
|
150
|
+
noter(t, 'interrompue', par, `${motif} → ${decision}`);
|
|
151
|
+
if (decision === 'remettre') { await passer(t, 'proposee', { par, motif: 'remise en file' }); t.machine = null; t.progression = null; }
|
|
152
|
+
if (decision === 'arreter') {
|
|
153
|
+
await passer(t, 'echec', { par, motif: `interrompue : ${motif}` });
|
|
154
|
+
t.resultat = { etat: 'echec', motif: `interrompue : ${motif}${t.interruptions > interruptionsMax ? ` (plus de ${interruptionsMax} interruptions)` : ''}`, etapes: [] };
|
|
155
|
+
}
|
|
156
|
+
await sauver(); return { decision, tache: copie(t) };
|
|
157
|
+
}),
|
|
158
|
+
annuler: (id, { par, motif } = {}) => enSerie(async () => { const t = trouver(id); await passer(t, 'annulee', { par, motif }); await sauver(); return copie(t); }),
|
|
159
|
+
|
|
160
|
+
tache: (id) => enSerie(async () => copie(d.taches.find((x) => x.id === id) || null)),
|
|
161
|
+
/** La définition d'un type (délais, politique) telle que la file la connaît ; null si inconnu. */
|
|
162
|
+
type: (nom) => registre.type(nom),
|
|
163
|
+
taches: (filtre = {}) => enSerie(async () => d.taches.filter((t) => !filtre.etat || t.etat === filtre.etat).map(copie)),
|
|
164
|
+
/** Les tâches qu'une machine avait commencées : elle les retrouve en revenant (reprise). */
|
|
165
|
+
enCoursDe: (machineId) => enSerie(async () => d.taches.filter((t) => t.machine === machineId && t.etat === 'en_cours').map(copie)),
|
|
166
|
+
journal: (id) => enSerie(async () => d.journal.filter((l) => l.tache === id).map((l) => ({ ...l }))),
|
|
167
|
+
|
|
168
|
+
/** L'exécution d'une tâche, au format du lanceur : les étapes viennent du TYPE, à partir des entrées validées. */
|
|
169
|
+
execution: (id) => enSerie(async () => {
|
|
170
|
+
const t = trouver(id); const def = registre.type(t.type);
|
|
171
|
+
if (typeof def?.etapes !== 'function') throw erreur('E_ETAPES', `le type « ${t.type} » n'a pas d'étapes ici (registre de centrale : les étapes vivent chez l'agent)`);
|
|
172
|
+
return { id: t.id, titre: t.titre, etapes: def.etapes(structuredClone(t.entrees)) };
|
|
173
|
+
}),
|
|
174
|
+
};
|
|
175
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// @mostajs/delegation — déléguer des tâches typées à des machines, sous feu vert (plan 01 lots L1-L2, plan 02 lot C1).
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
3
|
+
export { creerRegistre, manquesPour, SI_INTERROMPUE, CAPACITE_CONDUCTEUR, exigeConducteur, DELAIS } from './types.js';
|
|
4
|
+
export { creerFile, ETATS } from './file.js';
|
|
5
|
+
export { creerStockageMemoire, creerStockageFichier, FORMAT_FILE } from './stockage.js';
|
|
6
|
+
export { lancerExecution, analyseur } from './lanceur.js';
|
|
7
|
+
export { creerApiAgents, empreinteJeton, CENTRALE_ID } from './api.js';
|
|
8
|
+
export { creerAgent, releverTelemetrie, VERSION_AGENT, detecterCapacites, enrolerMachine, creerAgentCentrale } from './agent.js';
|
|
9
|
+
export { creerParc, ETATS_MACHINE, FORMAT_PARC, REGLAGE_CENTRALE, empreinteMachine } from './parc.js';
|
|
10
|
+
export { creerCleSignature, empreinteCle, nouvelOrdre, signerOrdre, verifierOrdre, lireClePrivee, canonique, TOLERANCE_HORLOGE_MS,
|
|
11
|
+
signerAttestation, verifierAttestation, FORMAT_ATTESTATION } from './signature.js';
|
|
12
|
+
export { bornerJson, bornerTelemetrie, finDeJournal, FIN_JOURNAL_OCTETS } from './bornes.js';
|
|
13
|
+
export { creerTypeTrain, phaseTrain, validerConfigTrain, lireConfigTrain, phasesDe, PHASES_VERIFICATION, PHASES_INTEGRATION } from './train.js';
|
|
14
|
+
export { cheminsAgent, etendreTilde, signauxArret, estAdministrateur, commandeArretArbre, trouverProgramme, trouverBash, trouverChrome,
|
|
15
|
+
droitsTropOuverts, restreindreAcces } from './plateforme.js';
|
|
16
|
+
export { plistLaunchd, cheminPlist, tacheWindows, ecrireConfigurationAgent, LABEL_LAUNCHD, TACHE_WINDOWS } from './services.js';
|
|
17
|
+
export { veiller, tournerJournal } from './veilleur.js';
|