@roomi-fields/grillhouse 0.43.2 → 0.45.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.
Files changed (72) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/cadre/templates/projet/.claude/settings.json +5 -0
  4. package/cadre/templates/projet/.github/workflows/ci.yml +11 -17
  5. package/cadre/templates/projet/.github/workflows/nuit.yml +3 -3
  6. package/cadre/templates/projet/CLAUDE.md +15 -2
  7. package/cadre/templates/projet/docs/agents/issue-tracker.md +1 -1
  8. package/cadre/templates/projet/package.json +1 -1
  9. package/charte.md +3 -2
  10. package/dist/temporal/circuit/client.d.ts +7 -0
  11. package/dist/temporal/circuit/client.js +12 -2
  12. package/dist/temporal/circuit/client.js.map +1 -1
  13. package/dist/temporal/commande.js +5 -1
  14. package/dist/temporal/commande.js.map +1 -1
  15. package/dist/temporal/installation.d.ts +21 -1
  16. package/dist/temporal/installation.js +207 -16
  17. package/dist/temporal/installation.js.map +1 -1
  18. package/dist/temporal/tickets/activites.js +3 -1
  19. package/dist/temporal/tickets/activites.js.map +1 -1
  20. package/docs/ARCHITECTURE.md +238 -77
  21. package/docs/INTERFACE.md +30 -15
  22. package/package.json +2 -2
  23. package/scripts/activites.mjs +59 -43
  24. package/scripts/aiguillage.mjs +1 -0
  25. package/scripts/attente-de-la-machine.mjs +312 -0
  26. package/scripts/avancement.mjs +38 -31
  27. package/scripts/bilan.mjs +30 -5
  28. package/scripts/circuit.mjs +10 -7
  29. package/scripts/codes-de-sortie.mjs +1 -1
  30. package/scripts/coeurs-dedies.mjs +427 -0
  31. package/scripts/composants-affectes.mjs +3 -1
  32. package/scripts/consommation-des-passes.mjs +382 -0
  33. package/scripts/consommation.mjs +45 -0
  34. package/scripts/copies-finies.mjs +2 -2
  35. package/scripts/depart-du-ticket.mjs +7 -5
  36. package/scripts/disque-des-copies.mjs +1 -1
  37. package/scripts/echantillonneur-de-la-passe.mjs +103 -0
  38. package/scripts/enveloppe/enveloppe.mjs +3 -13
  39. package/scripts/enveloppe/lancer.sh +1 -1
  40. package/scripts/enveloppe/travail-de-la-copie.mjs +3 -2
  41. package/scripts/grillhouse-maj.mjs +8 -4
  42. package/scripts/integration/file.mjs +10 -4
  43. package/scripts/jointure.d.ts +20 -9
  44. package/scripts/langages/cargo/commandes.mjs +8 -8
  45. package/scripts/langages/python/commandes.mjs +7 -6
  46. package/scripts/langages/typescript/tests-de-nuit.mjs +17 -4
  47. package/scripts/langages/typescript/tests.mjs +15 -6
  48. package/scripts/langages/typescript/verifier.mjs +23 -17
  49. package/scripts/langages/typescript/vitest-config/base.mjs +3 -3
  50. package/scripts/langages/typescript/vitest-config/machine.setup.mjs +7 -7
  51. package/scripts/langages.d.mts +2 -0
  52. package/scripts/langages.mjs +79 -0
  53. package/scripts/mesure/base-de-passe.mjs +1 -1
  54. package/scripts/migrations/0.44.0-node-26-seul.mjs +47 -0
  55. package/scripts/migrations/0.44.0-seuil-des-codes-de-tickets.mjs +47 -0
  56. package/scripts/migrations.mjs +4 -0
  57. package/scripts/passe-de-la-machine.mjs +456 -31
  58. package/scripts/places-de-la-machine.mjs +508 -61
  59. package/scripts/plafond-de-la-machine.d.mts +47 -2
  60. package/scripts/plafond-de-la-machine.mjs +197 -5
  61. package/scripts/preparation.mjs +1 -0
  62. package/scripts/regles-des-places.d.mts +40 -0
  63. package/scripts/regles-des-places.mjs +91 -0
  64. package/scripts/retirer-les-copies-finies.mjs +1 -1
  65. package/scripts/seances.mjs +4 -3
  66. package/scripts/services-du-noyau.mjs +3 -3
  67. package/scripts/sortie.mjs +3 -2
  68. package/scripts/sous-commandes.mjs +6 -7
  69. package/scripts/tableau.mjs +121 -112
  70. package/scripts/ticket-du-circuit.mjs +5 -1
  71. package/scripts/verrous/verrou.mjs +3 -3
  72. package/scripts/verrou-de-machine.mjs +0 -829
@@ -1,829 +0,0 @@
1
- // The lock of the machine for the heavy measure: one heavy measure at a time on the machine,
2
- // whatever repository it plays in, as GNU make's job server shares its slots between every make of
3
- // one build, and as Bazel holds a test that declares it wants the whole machine. Taken by every
4
- // `npm run verifier` (scripts/langages/typescript/verifier.mjs: the night's, a supervisor's) and by the heavy passes of the circuit of a ticket (scripts/circuit.mjs: the proof
5
- // of the red and the checks), so that a measure gives the result of the code, not that of another
6
- // measure beside it.
7
- //
8
- // - The lock is one file of the user's cache, shared by every repository of the machine:
9
- // `${XDG_CACHE_HOME:-~/.cache}/grillhouse/mesure-lourde.lock`; GRILLHOUSE_VERROU_MACHINE names
10
- // another file (the base configuration of the tests gives each test file its own,
11
- // scripts/langages/typescript/vitest-config/machine.setup.mjs). It is taken through scripts/verrou-de-fichier.mjs,
12
- // judged by its owner's process: a lock whose process is gone is taken over.
13
- // - A second measure waits for the end of the first, then plays once it holds the lock. It says
14
- // that it waits and whom for (the process that holds the lock, its working directory, its
15
- // command, since when) when it begins, then every 30 s, so that a log shows a pass is not
16
- // frozen.
17
- // - The wait is bounded, as `flock -w` and a database's lock timeout: ATTENTE_MACHINE_MS, 60 min,
18
- // longer than the longest full pass measured (the frame's, 21 min; a final pass of BPScript
19
- // 320.3, 35.5 min, a wait for rest of the CPU included); GRILLHOUSE_ATTENTE_MACHINE_MS names
20
- // another bound, in ms. The bound reached, the measure stops at « à repasser » (75): another
21
- // measure holds the machine, which is neither green nor red, and whoever launched the measure
22
- // presents it again later. The stop throws an AttenteDeLaMachine, which names the holder.
23
- // - A lock held by an ancestor of the waiting process (its parent, its parent's parent…, or the
24
- // process itself) is a deadlock: the ancestor waits for its descendant, which waits for the
25
- // lock. The wait says so at once and stops, red (1): the descendant lost the mark of the taking
26
- // (an environment rebuilt, a test's), a defect to correct and not a load to wait out. It does
27
- // not play under the ancestor's lock: make plays such a child at `-j1` because it cannot tell,
28
- // but here the lost mark is the defect, and playing would hide it.
29
- // - Who holds the lock passes it to its children, as make passes its job server in MAKEFLAGS: the
30
- // variable GRILLHOUSE_MESURE_TENUE carries the mark of the taking, and a process whose variable
31
- // names the mark the lock holds plays under it without taking it again (the final pass of the
32
- // circuit, `npm run verifier`, under the circuit's lock).
33
- // - In the envelope of an agent (GRILLHOUSE_ENVELOPPE set, scripts/enveloppe/paquets-du-plan.mjs)
34
- // no lock is taken: the envelope has its own process space, where an owner's number means nothing
35
- // outside, and its home shows no cache.
36
- // - A measure has a rank, as the job server of GNU make serves its own build first and Bazel's
37
- // `--experimental_local_test_priority` orders the tests that wait for the machine. A measure
38
- // played in the frame's own repository (one whose workspaces hold the package
39
- // @roomi-fields/grillhouse in development, its agent copies included: `rangDeLaMesure`) is of
40
- // the first rank, « mesure du cadre »; a project's (a circuit, a `npm run verifier`) is of the
41
- // second, « mesure d'un projet ». A measure that waits for the lock names its rank among the
42
- // waits (`<lock>.attentes/`, below); a measure of the second rank does not take the lock, even
43
- // free, while a live measure of the first waits for it, so a check of the frame, whose next
44
- // version every project waits for, never waits behind the projects' measures (the verification
45
- // of 0.26.0 waited 61 min behind five measures of two projects). Between measures of one rank,
46
- // the first to find the lock free takes it. The bound of the wait is the same for both ranks,
47
- // and the wait says its rank.
48
- // - The lock names its holder and its waits, as lslocks names who holds a lock and cargo's
49
- // « Blocking waiting for file lock » says what a wait waits for. Whoever takes it, a pass out of
50
- // a ticket or the circuit of a ticket, of any project of the machine, names itself beside it in
51
- // `<lock>.detenteur.json`: its mark, its process, its project, its copy, its ticket or null, its kind
52
- // (`sorte`: « Vérification » by default, or GRILLHOUSE_VERIFICATION_SORTE and
53
- // GRILLHOUSE_VERIFICATION_TICKET from the caller, a step's title for a circuit), since when, and its progress
54
- // directory once it names it (`nommerLAvancement`); the name goes with the lock. Each measure
55
- // that waits, for the lock or for room in the temporary directory, names itself in the
56
- // directory `<lock>.attentes/`, one file per waiting process (its process, its rank, its
57
- // project, copy, ticket and kind, what it waits for `quoi`, since when), removed once it stops
58
- // waiting. The project is named by the root of the main tree of the repository the measure
59
- // plays in, its copies included (`depot`, `racineDuDepot`); the board gives it the name it
60
- // gives that project, its folder's for a project out of the board (scripts/tableau.mjs). The copy
61
- // is the root of the working tree the measure plays in (`copie`, `racineDeLaCopie`): the main tree
62
- // or a copy under .claude/worktrees/, which names a measure without a ticket.
63
- // `lireLeVerrou` reads them for the board (through `lireLaMesure` of scripts/avancement.mjs): a
64
- // holder or a wait whose process is gone names no one, and the wait's file goes; a lock a live
65
- // process holds without naming itself (a frame older than this naming) shows as the repository
66
- // of its process's directory, of the kind « Verrou ».
67
- // - The lock is let go at the end of the measure, whether it succeeds or throws.
68
- // - A measure first wants room in the temporary directory (`os.tmpdir()` under its environment),
69
- // a disk in memory that the sessions of the machine share: under LIBRE_MIN, 4 GB free
70
- // (GRILLHOUSE_TEMPORAIRE_LIBRE names another floor, in bytes; the base configuration of the
71
- // tests sets 0, scripts/langages/typescript/vitest-config/machine.setup.mjs), it waits for room
72
- // instead of failing for lack of it (ENOSPC: 25 reds of the night of 2026-11-01, the
73
- // scratchpads holding 8 GB of 16), as Kubernetes schedules no new pod on a node under
74
- // DiskPressure. It says so, with what holds the directory (its largest
75
- // entries, by the blocks their files hold, the temporary directory of a ticket naming its
76
- // ticket), when it begins and every 30 s, under the same bound as the
77
- // lock's, then « à repasser » (75).
78
- // - It then wants room on the disk of the copy it plays in (its root, `racine`), where cargo
79
- // writes its target directories: under LIBRE_MIN as well (GRILLHOUSE_COPIE_LIBRE names another
80
- // floor, in bytes; the base configuration of the tests sets 0), it waits the same way, under
81
- // the same bound counted from the start of the wait, and says what holds that disk: the copies
82
- // of its repository, the largest first, each with its ticket and its tools' outputs
83
- // (`occupantsDesCopies` of scripts/copies-finies.mjs: « .claude/worktrees/SH-ae6.2.7 (le
84
- // ticket SH-ae6.2.7, 5,0 Go, dont target 4,8 Go) »), as Bazel and Buildkite refuse to start a
85
- // build under a floor of free room rather than fail in its middle (the main disk full on
86
- // 2026-11-01, three circuits killed without a word, grillhouse-k5y).
87
- import { spawnSync } from 'node:child_process';
88
- import { randomUUID } from 'node:crypto';
89
- import {
90
- lstatSync,
91
- mkdirSync,
92
- readdirSync,
93
- readFileSync,
94
- readlinkSync,
95
- rmSync,
96
- statfsSync,
97
- statSync,
98
- } from 'node:fs';
99
- import { homedir, tmpdir } from 'node:os';
100
- import path from 'node:path';
101
- import { occupantsDesCopies } from './copies-finies.mjs';
102
- import { paquetsDeLEnveloppe } from './enveloppe/paquets-du-plan.mjs';
103
- import { paquets } from './paquets.mjs';
104
- import { attendreUnPeu, lacherVerrou, prendreVerrou } from './verrou-de-fichier.mjs';
105
- import { ecrireAtomique } from './mesure/avancement.mjs';
106
- import { ticketDeLaBase, vivant } from './mesure/base-de-passe.mjs';
107
- import { A_REPASSER } from './codes-de-sortie.mjs';
108
-
109
- const VARIABLE_VERROU = 'GRILLHOUSE_VERROU_MACHINE';
110
- const VARIABLE_TENUE = 'GRILLHOUSE_MESURE_TENUE';
111
- const VARIABLE_VERIFICATION_SORTE = 'GRILLHOUSE_VERIFICATION_SORTE';
112
- const VARIABLE_VERIFICATION_TICKET = 'GRILLHOUSE_VERIFICATION_TICKET';
113
- const VARIABLE_ATTENTE = 'GRILLHOUSE_ATTENTE_MACHINE_MS';
114
- const VARIABLE_LIBRE = 'GRILLHOUSE_TEMPORAIRE_LIBRE';
115
- const VARIABLE_COPIE = 'GRILLHOUSE_COPIE_LIBRE';
116
-
117
- /** The room a heavy measure wants free in the temporary directory, and on the disk of its copy,
118
- * in bytes: 4 GB. */
119
- export const LIBRE_MIN = 4 * 1024 ** 3;
120
-
121
- // The name of the frame's package, which a repository of the first rank develops.
122
- const CADRE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).name;
123
-
124
- /**
125
- * The rank of a measure played at <racine>: 1 in the frame's own repository (its workspaces hold
126
- * the package @roomi-fields/grillhouse in development), 2 elsewhere.
127
- * @param {string} racine the root of the repository the measure plays in
128
- * @returns {1 | 2}
129
- */
130
- export function rangDeLaMesure(racine) {
131
- return paquets(racine).some(p => p.pkg.name === CADRE) ? 1 : 2;
132
- }
133
-
134
- const RANGS = { 1: 'mesure du cadre', 2: "mesure d'un projet" };
135
-
136
- /** The longest wait for the lock of the machine, in ms, unless GRILLHOUSE_ATTENTE_MACHINE_MS names another. */
137
- export const ATTENTE_MACHINE_MS = 60 * 60_000;
138
- // The gap between two lines that say the wait goes on.
139
- const RAPPEL_MS = 30_000;
140
-
141
- /** The stop of a wait for the lock of the machine: `code` is 75 at the bound, 1 for a deadlock. */
142
- export class AttenteDeLaMachine extends Error {
143
- /**
144
- * @param {string} message what stops the wait, the holder named
145
- * @param {number} code the exit code the measure ends on
146
- */
147
- constructor(message, code) {
148
- super(message);
149
- this.name = 'AttenteDeLaMachine';
150
- this.code = code;
151
- }
152
- }
153
-
154
- // The lock file of the machine under <env>, beside which its holder and its waits name
155
- // themselves.
156
- export function verrouDeMachine(env = process.env) {
157
- if (env[VARIABLE_VERROU]) {
158
- return env[VARIABLE_VERROU];
159
- }
160
- const cache = env.XDG_CACHE_HOME || path.join(env.HOME || homedir(), '.cache');
161
- return path.join(cache, 'grillhouse', 'mesure-lourde.lock');
162
- }
163
-
164
- const lire = f => {
165
- try {
166
- return readFileSync(f, 'utf8').trim();
167
- } catch {
168
- return null;
169
- }
170
- };
171
-
172
- // The process number in the lock <verrou>, or null.
173
- function detenteur(verrou) {
174
- const pid = /^(\d+)/.exec(lire(verrou) ?? '')?.[1];
175
- return pid ? Number(pid) : null;
176
- }
177
-
178
- const heure = ms => new Date(ms).toTimeString().slice(0, 8);
179
- const duree = ms =>
180
- ms < 120_000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60_000)} min`;
181
-
182
- // The process <pid>, its working directory and command when they read (on one line, cut at 200
183
- // characters): « le processus 12 (dans /d) : node x ».
184
- function processus(pid) {
185
- let ou = '';
186
- try {
187
- ou = ` (dans ${readlinkSync(`/proc/${pid}/cwd`)})`;
188
- } catch {
189
- // its directory does not read: the process alone is named
190
- }
191
- const commande = (lire(`/proc/${pid}/cmdline`) ?? '')
192
- .split('\0')
193
- .filter(Boolean)
194
- .join(' ')
195
- .replace(/\s+/g, ' ');
196
- const quoi = commande
197
- ? ` : ${commande.length > 200 ? `${commande.slice(0, 200)}…` : commande}`
198
- : '';
199
- return `le processus ${pid}${ou}${quoi}`;
200
- }
201
-
202
- // Who holds the lock <verrou>: its process (`processus`) and since when the lock stands
203
- // (« le processus 12 (dans /d) : node x, depuis 10:04:31 (3 min) »).
204
- function qui(verrou) {
205
- const pid = detenteur(verrou);
206
- if (pid === null) {
207
- return 'une autre mesure';
208
- }
209
- let depuis = '';
210
- try {
211
- const t = statSync(verrou).mtimeMs;
212
- depuis = `, depuis ${heure(t)} (${duree(Date.now() - t)})`;
213
- } catch {
214
- // the lock is gone meanwhile
215
- }
216
- return `${processus(pid)}${depuis}`;
217
- }
218
-
219
- /**
220
- * The root of the working tree at <racine>, the main tree or a copy (git's top level); <racine>
221
- * itself out of git.
222
- * @param {string} racine
223
- * @returns {string}
224
- */
225
- export function racineDeLaCopie(racine) {
226
- const r = spawnSync('git', ['-C', racine, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
227
- return r.status === 0 ? r.stdout.trim() : path.resolve(racine);
228
- }
229
-
230
- /**
231
- * The root of the repository at <racine>: its main tree, its copies included (the parent of its
232
- * common directory of git); <racine> itself out of git.
233
- * @param {string} racine
234
- * @returns {string}
235
- */
236
- export function racineDuDepot(racine) {
237
- const r = spawnSync(
238
- 'git',
239
- ['-C', racine, 'rev-parse', '--path-format=absolute', '--git-common-dir'],
240
- { encoding: 'utf8' }
241
- );
242
- return r.status === 0 ? path.dirname(r.stdout.trim()) : path.resolve(racine);
243
- }
244
-
245
- const lireJson = f => {
246
- try {
247
- return JSON.parse(readFileSync(f, 'utf8'));
248
- } catch {
249
- return null;
250
- }
251
- };
252
-
253
- // The file where the holder of <verrou> names itself, and the directory of its waits.
254
- const fichierDuDetenteur = verrou => `${verrou}.detenteur.json`;
255
- const dossierDesAttentes = verrou => `${verrou}.attentes`;
256
-
257
- // Who a measure is, from its options: `{ depot, copie, ticket, sorte }`, the root of its
258
- // repository and of its working tree read when first asked.
259
- // The kind and the ticket come from the option of the caller (the circuit) when it gives one,
260
- // else from the caller's environment (GRILLHOUSE_VERIFICATION_SORTE, GRILLHOUSE_VERIFICATION_TICKET,
261
- // empty as absent), else « Vérification » and null.
262
- function identite({ racine, env = {}, ticket, sorte }) {
263
- ticket = ticket ?? (env[VARIABLE_VERIFICATION_TICKET] || null);
264
- sorte = sorte ?? (env[VARIABLE_VERIFICATION_SORTE] || 'Vérification');
265
- let depot = null;
266
- let copie = null;
267
- return {
268
- get depot() {
269
- depot ??= racineDuDepot(racine);
270
- return depot;
271
- },
272
- get copie() {
273
- copie ??= racineDeLaCopie(racine);
274
- return copie;
275
- },
276
- ticket,
277
- sorte,
278
- };
279
- }
280
-
281
- // Names this process, <id>, among the waits of <verrou>, waiting for <quoi> (« verrou »,
282
- // « place ») at the rank <rang> (null for room); a function that removes its name.
283
- function inscrireLAttente(verrou, id, quoi, rang = null) {
284
- const f = path.join(dossierDesAttentes(verrou), `${process.pid}-${randomUUID()}.json`);
285
- try {
286
- ecrireAtomique(f, {
287
- pid: process.pid,
288
- rang,
289
- depot: id.depot,
290
- copie: id.copie,
291
- ticket: id.ticket,
292
- sorte: id.sorte,
293
- quoi,
294
- depuis: Date.now(),
295
- });
296
- } catch {
297
- return () => {};
298
- }
299
- return () => rmSync(f, { force: true });
300
- }
301
-
302
- // The waits of <verrou> whose process lives, the oldest first; the file of a process that is gone
303
- // is removed.
304
- function attentesDe(verrou) {
305
- const dossier = dossierDesAttentes(verrou);
306
- let noms;
307
- try {
308
- noms = readdirSync(dossier);
309
- } catch {
310
- return [];
311
- }
312
- const out = [];
313
- for (const nom of noms) {
314
- const pid = Number(/^(\d+)-/.exec(nom)?.[1]);
315
- if (!pid || !vivant(pid)) {
316
- rmSync(path.join(dossier, nom), { force: true });
317
- continue;
318
- }
319
- const a = nom.endsWith('.json') ? lireJson(path.join(dossier, nom)) : null;
320
- if (a?.pid === pid) {
321
- out.push(a);
322
- }
323
- }
324
- return out.sort((a, b) => (a.depuis ?? 0) - (b.depuis ?? 0));
325
- }
326
-
327
- // The live processes of the measures of the first rank that wait for <verrou>.
328
- const premiersQuiAttendent = verrou =>
329
- attentesDe(verrou)
330
- .filter(a => a.quoi === 'verrou' && a.rang === 1)
331
- .map(a => a.pid);
332
-
333
- // Names this process, <id>, holder of <verrou> under the mark it holds; a function that removes
334
- // the name while it is still this taking's.
335
- function nommerLeDetenteur(verrou, id) {
336
- const f = fichierDuDetenteur(verrou);
337
- const marque = lire(verrou);
338
- try {
339
- ecrireAtomique(f, {
340
- marque,
341
- pid: process.pid,
342
- depot: id.depot,
343
- copie: id.copie,
344
- ticket: id.ticket,
345
- sorte: id.sorte,
346
- depuis: Date.now(),
347
- dossier: null,
348
- });
349
- } catch {
350
- return () => {};
351
- }
352
- return () => {
353
- if (lireJson(f)?.marque === marque) {
354
- rmSync(f, { force: true });
355
- }
356
- };
357
- }
358
-
359
- /**
360
- * Names the progress directory <dossier> of the measure that holds the lock of the machine under
361
- * <env> (its mark in GRILLHOUSE_MESURE_TENUE), beside the lock, where the board reads it; a
362
- * function that takes it out. Nothing without a lock this environment holds (in the envelope of
363
- * an agent).
364
- * @param {{ env?: Record<string, string | undefined>, dossier: string }} o
365
- * @returns {() => void}
366
- */
367
- export function nommerLAvancement({ env = process.env, dossier }) {
368
- const f = fichierDuDetenteur(verrouDeMachine(env));
369
- const marque = env[VARIABLE_TENUE];
370
- const ecrire = d => {
371
- const n = lireJson(f);
372
- if (!marque || n?.marque !== marque) {
373
- return false;
374
- }
375
- try {
376
- ecrireAtomique(f, { ...n, dossier: d });
377
- return true;
378
- } catch {
379
- return false;
380
- }
381
- };
382
- return ecrire(dossier) ? () => void ecrire(null) : () => {};
383
- }
384
-
385
- /**
386
- * Who holds the lock of the machine under <env> and who waits for it. `detenteur`: its process,
387
- * repository (`depot`, the root of its main tree, and `projet`, its folder), ticket, kind, since
388
- * when (ms) and progress directory; null when the lock is free or its process gone; a live process
389
- * that names nothing beside the lock shows as the repository of its directory, of the kind
390
- * « Verrou ». `attentes`: each live wait, the oldest first, its process, rank, repository,
391
- * ticket, kind, what it waits for (`quoi`: « verrou » or « place ») and since when.
392
- * @param {Record<string, string | undefined>} [env]
393
- */
394
- export function lireLeVerrou(env = process.env) {
395
- const verrou = verrouDeMachine(env);
396
- const attentes = attentesDe(verrou).map(
397
- ({ pid, rang, depot, copie, ticket, sorte, quoi, depuis }) => ({
398
- pid,
399
- rang,
400
- depot,
401
- copie: copie ?? null,
402
- projet: path.basename(String(depot)),
403
- ticket,
404
- sorte,
405
- quoi,
406
- depuis,
407
- })
408
- );
409
- const marque = lire(verrou);
410
- const pid = detenteur(verrou);
411
- if (marque === null || pid === null || !vivant(pid)) {
412
- return { detenteur: null, attentes };
413
- }
414
- const n = lireJson(fichierDuDetenteur(verrou));
415
- if (n?.marque === marque) {
416
- const { depot, copie = null, ticket, sorte, depuis, dossier } = n;
417
- const projet = path.basename(String(depot));
418
- return { detenteur: { pid, depot, copie, projet, ticket, sorte, depuis, dossier }, attentes };
419
- }
420
- let depuis = null;
421
- let ou = null;
422
- try {
423
- depuis = statSync(verrou).mtimeMs;
424
- ou = readlinkSync(`/proc/${pid}/cwd`);
425
- } catch {
426
- // the lock gone meanwhile, or the directory of its process unreadable: its number names it
427
- }
428
- const depot = ou ? racineDuDepot(ou) : null;
429
- return {
430
- detenteur: {
431
- pid,
432
- depot,
433
- copie: ou ? racineDeLaCopie(ou) : null,
434
- projet: depot ? path.basename(depot) : `processus ${pid}`,
435
- ticket: null,
436
- sorte: 'Verrou',
437
- depuis,
438
- dossier: null,
439
- },
440
- attentes,
441
- };
442
- }
443
-
444
- // Whom a measure of the rank <rang> waits for at <verrou>: the holder of the lock, and for the
445
- // second rank the measures of the first that wait too, which pass first.
446
- function attendus(verrou, rang) {
447
- const tenu = detenteur(verrou) === null ? 'libre' : `tenu par ${qui(verrou)}`;
448
- const premiers = rang === 2 ? premiersQuiAttendent(verrou) : [];
449
- const avant = !premiers.length
450
- ? ''
451
- : premiers.length === 1
452
- ? ` ; une mesure du cadre attend aussi et passe d'abord : ${processus(premiers[0])}`
453
- : ` ; ${premiers.length} mesures du cadre attendent aussi et passent d'abord : ${premiers.map(processus).join(' ; ')}`;
454
- return `le verrou de la mesure lourde (${verrou}) est ${tenu}${avant}`;
455
- }
456
-
457
- // Whether a measure of the rank <rang> may take the lock <verrou>: the second rank only while no
458
- // measure of the first waits.
459
- const peutPrendre = (verrou, rang) => rang === 1 || premiersQuiAttendent(verrou).length === 0;
460
-
461
- // The parent of the process <pid>, read in /proc (the field after the state, which follows the
462
- // command, itself free to hold spaces and parentheses), or null.
463
- function parent(pid) {
464
- const stat = lire(`/proc/${pid}/stat`);
465
- const ppid = stat ? Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]) : NaN;
466
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
467
- }
468
-
469
- // Whether <pid> is this process or one of its ancestors.
470
- function ancetre(pid) {
471
- for (let p = process.pid; p !== null; p = parent(p)) {
472
- if (p === pid) {
473
- return true;
474
- }
475
- }
476
- return false;
477
- }
478
-
479
- // The floor of room the variable <variable> names under <env>, in bytes, LIBRE_MIN by default.
480
- function plancherDe(env, variable) {
481
- const n = Number(env[variable]);
482
- return env[variable] && Number.isFinite(n) && n >= 0 ? n : LIBRE_MIN;
483
- }
484
-
485
- // The room free in <dossier>, in bytes; Infinity when it does not read.
486
- function libreDans(dossier) {
487
- try {
488
- const s = statfsSync(dossier);
489
- return s.bavail * s.bsize;
490
- } catch {
491
- return Infinity;
492
- }
493
- }
494
-
495
- const go = octets => `${(octets / 1024 ** 3).toFixed(1).replace('.', ',')} Go`;
496
-
497
- // The entries a count of what holds the temporary directory reads at most, so that it stays
498
- // short on a directory of millions of files: past it, a size is a floor.
499
- const ENTREES_LUES = 500_000;
500
-
501
- // The largest entries of <dossier>, the five first, each by the blocks its files hold, as `du`
502
- // counts them: « claude-1000 (8,0 Go), grillhouse-vitest-x (1,2 Go) ».
503
- function occupants(dossier) {
504
- let noms;
505
- try {
506
- noms = readdirSync(dossier);
507
- } catch {
508
- return 'illisible';
509
- }
510
- if (noms.length === 0) {
511
- return 'rien';
512
- }
513
- let budget = ENTREES_LUES;
514
- const taille = racine => {
515
- let octets = 0;
516
- const pile = [racine];
517
- while (pile.length > 0 && budget-- > 0) {
518
- const p = pile.pop();
519
- let e;
520
- try {
521
- e = lstatSync(p);
522
- } catch {
523
- continue;
524
- }
525
- octets += e.blocks * 512;
526
- if (e.isDirectory()) {
527
- try {
528
- for (const n of readdirSync(p)) {
529
- pile.push(path.join(p, n));
530
- }
531
- } catch {
532
- // an unreadable directory counts for itself alone
533
- }
534
- }
535
- }
536
- return octets;
537
- };
538
- return noms
539
- .map(nom => ({ nom, octets: taille(path.join(dossier, nom)) }))
540
- .sort((a, b) => b.octets - a.octets)
541
- .slice(0, 5)
542
- .map(o => {
543
- const ticket = ticketDeLaBase(o.nom);
544
- return `${o.nom} (${ticket ? `le ticket ${ticket}, ` : ''}${go(o.octets)})`;
545
- })
546
- .join(', ');
547
- }
548
-
549
- // The disks a heavy pass waits for room on, in order: `{ nom, ou, variable }`, the words of its
550
- // lines (« le dossier temporaire », « dans le dossier temporaire »), and the variable of its floor.
551
- const DISQUES = {
552
- temporaire: {
553
- nom: 'le dossier temporaire',
554
- ou: 'dans le dossier temporaire',
555
- variable: VARIABLE_LIBRE,
556
- },
557
- copie: {
558
- nom: 'le disque de la copie',
559
- ou: 'sur le disque de la copie',
560
- variable: VARIABLE_COPIE,
561
- },
562
- };
563
-
564
- // Waits until <dossier> holds <plancher> bytes free (`libre`, a statfs at each turn), saying so
565
- // (`dire`) in the words of <disque> (DISQUES) with what holds it (`occupe`, counted only when a
566
- // line is written) when it begins and every <rappelMs>, and naming itself among the waits once it
567
- // waits (`inscrire`, a function that returns the removal of its name). Throws an
568
- // AttenteDeLaMachine (75) at <borneMs> from <debut> (now by default), the start of the whole wait.
569
- function attendreLaPlace(dossier, { inscrire, ...o }) {
570
- let retirer = null;
571
- try {
572
- return attendreLaPlaceEnNommant(dossier, {
573
- ...o,
574
- nommer: () => {
575
- retirer ??= inscrire();
576
- },
577
- });
578
- } finally {
579
- retirer?.();
580
- }
581
- }
582
-
583
- function attendreLaPlaceEnNommant(
584
- dossier,
585
- {
586
- disque,
587
- plancher,
588
- libre,
589
- occupe,
590
- dire,
591
- borneMs,
592
- rappelMs,
593
- nommer,
594
- maintenant = Date.now,
595
- dormir = attendreUnPeu,
596
- debut = maintenant(),
597
- }
598
- ) {
599
- let dit = null;
600
- for (;;) {
601
- const l = libre(dossier);
602
- if (l >= plancher) {
603
- if (dit !== null) {
604
- dire(`✓ place ${disque.ou} après ${duree(maintenant() - debut)}.`);
605
- }
606
- return;
607
- }
608
- nommer();
609
- const t = maintenant();
610
- const etat = () =>
611
- `${disque.nom} (${dossier}) n'a que ${go(l)} libres, moins des ${go(plancher)} qu'une passe lourde demande (${disque.variable}) ; l'occupent : ${occupe(dossier)}`;
612
- if (t - debut >= borneMs) {
613
- throw new AttenteDeLaMachine(
614
- `⏱ attente de place bornée à ${duree(borneMs)} (${VARIABLE_ATTENTE}) : ${etat()} ; à repasser (code ${A_REPASSER}).`,
615
- A_REPASSER
616
- );
617
- }
618
- if (dit === null) {
619
- dire(`⏳ ${etat()} ; attente de place, ${duree(borneMs)} au plus.`);
620
- } else if (t - dit >= rappelMs) {
621
- dire(`⏳ attente de place depuis ${duree(t - debut)} : ${etat()}.`);
622
- }
623
- if (dit === null || t - dit >= rappelMs) {
624
- dit = t;
625
- }
626
- dormir(Math.max(1, Math.min(200, borneMs - (maintenant() - debut))));
627
- }
628
- }
629
-
630
- /**
631
- * Waits for room in the temporary directory under <env> (`os.tmpdir()` as it reads it), then on
632
- * the disk of the copy at <racine>, where the pass writes its target directories: what a heavy
633
- * pass does before it plays (see the header).
634
- * @param {{ env?: Record<string, string | undefined>, dire?: (l: string) => void, borneMs?: number,
635
- * rappelMs?: number, libre?: (dossier: string) => number, occupe?: (dossier: string) => string,
636
- * occupeLaCopie?: (racine: string) => string, racine?: string, ticket?: string | null,
637
- * sorte?: string, maintenant?: () => number, dormir?: (ms: number) => void }} [o]
638
- * `maintenant` and `dormir` are the clock (Date.now) and the sleep of the wait, the real ones
639
- * when left out; `libre` reads the room of each disk, `occupe` what holds the temporary
640
- * directory, `occupeLaCopie` the copies that hold the disk of the copy; the wait names its
641
- * project <racine>, its ticket and its kind among the waits of the lock of the machine under
642
- * <env> while it waits
643
- * @throws {AttenteDeLaMachine} at the bound of the wait (code 75)
644
- */
645
- export function attendreDeLaPlace({
646
- env = process.env,
647
- dire = l => process.stdout.write(`${l}\n`),
648
- borneMs = borneDe(env),
649
- rappelMs = RAPPEL_MS,
650
- libre = libreDans,
651
- occupe = occupants,
652
- occupeLaCopie = occupantsDesCopies,
653
- racine = process.cwd(),
654
- ticket,
655
- sorte,
656
- maintenant = Date.now,
657
- dormir = attendreUnPeu,
658
- } = {}) {
659
- const temporaire = env.TMPDIR || env.TMP || env.TEMP || tmpdir();
660
- const id = identite({ racine, env, ticket, sorte });
661
- const inscrire = () => inscrireLAttente(verrouDeMachine(env), id, 'place');
662
- const debut = maintenant();
663
- const commun = { libre, dire, borneMs, rappelMs, inscrire, debut, maintenant, dormir };
664
- attendreLaPlace(temporaire, {
665
- ...commun,
666
- disque: DISQUES.temporaire,
667
- plancher: plancherDe(env, VARIABLE_LIBRE),
668
- occupe,
669
- });
670
- attendreLaPlace(racine, {
671
- ...commun,
672
- disque: DISQUES.copie,
673
- plancher: plancherDe(env, VARIABLE_COPIE),
674
- occupe: occupeLaCopie,
675
- });
676
- }
677
-
678
- /**
679
- * The bound of the wait under <env>, in ms (GRILLHOUSE_ATTENTE_MACHINE_MS, else ATTENTE_MACHINE_MS);
680
- * the wait for a place of the machine (scripts/places-de-la-machine.mjs) has the same.
681
- * @param {Record<string, string | undefined>} env
682
- * @returns {number}
683
- */
684
- export function borneDe(env) {
685
- const n = Number(env[VARIABLE_ATTENTE]);
686
- return env[VARIABLE_ATTENTE] && Number.isFinite(n) && n >= 0 ? n : ATTENTE_MACHINE_MS;
687
- }
688
-
689
- // Waits for the lock <verrou> at the rank <rang>, saying so (`dire`) when it begins and every
690
- // <rappelMs>; returns the time waited, in ms. Throws an AttenteDeLaMachine at once when an ancestor
691
- // holds the lock, and at the bound <borneMs>. The measure, <id>, names itself among the waits,
692
- // with its rank, while it waits.
693
- function attendreLaMachine(verrou, { id, rang, dire, borneMs, rappelMs, maintenant, dormir }) {
694
- const retirer = inscrireLAttente(verrou, id, 'verrou', rang);
695
- try {
696
- return attendreAuRang(verrou, { rang, dire, borneMs, rappelMs, maintenant, dormir });
697
- } finally {
698
- retirer();
699
- }
700
- }
701
-
702
- function attendreAuRang(
703
- verrou,
704
- { rang, dire, borneMs, rappelMs, maintenant = Date.now, dormir = attendreUnPeu }
705
- ) {
706
- const debut = maintenant();
707
- let dit = null;
708
- for (;;) {
709
- const pid = detenteur(verrou);
710
- if (pid !== null && ancetre(pid)) {
711
- throw new AttenteDeLaMachine(
712
- `✗ blocage : le verrou de la mesure lourde (${verrou}) est tenu par un ancêtre de ce processus (${process.pid}), ${qui(verrou)} ; il attend la fin de ce processus, qui attendrait la sienne. L'environnement a perdu la marque de la prise (${VARIABLE_TENUE}) ; un essai nomme son propre verrou (${VARIABLE_VERROU}).`,
713
- 1
714
- );
715
- }
716
- const t = maintenant();
717
- if (t - debut >= borneMs) {
718
- throw new AttenteDeLaMachine(
719
- `⏱ attente du verrou de la machine bornée à ${duree(borneMs)} (${VARIABLE_ATTENTE}), ${RANGS[rang]} : ${attendus(verrou, rang)} ; à repasser (code ${A_REPASSER}).`,
720
- A_REPASSER
721
- );
722
- }
723
- if (dit === null) {
724
- dire(
725
- `⏳ ${RANGS[rang]}, la machine mesure déjà : ${attendus(verrou, rang)} ; attente de son tour, ${duree(borneMs)} au plus.`
726
- );
727
- } else if (t - dit >= rappelMs) {
728
- dire(
729
- `⏳ ${RANGS[rang]}, attente du verrou de la machine depuis ${duree(t - debut)} : ${attendus(verrou, rang)}.`
730
- );
731
- }
732
- if (dit === null || t - dit >= rappelMs) {
733
- dit = t;
734
- }
735
- if (peutPrendre(verrou, rang) && prendreVerrou(verrou, { attendre: false })) {
736
- return maintenant() - debut;
737
- }
738
- dormir(Math.max(1, Math.min(200, borneMs - (maintenant() - debut))));
739
- }
740
- }
741
-
742
- /**
743
- * Runs <mesure> under the lock of the machine and returns what it returns. <mesure> receives the
744
- * environment of its children, which carries the lock to them.
745
- * @param {(envEnfant: Record<string, string | undefined>) => T} mesure a synchronous measure
746
- * @param {{ env?: Record<string, string | undefined>, racine?: string,
747
- * dire?: (ligne: string) => void, borneMs?: number, rappelMs?: number,
748
- * libre?: (dossier: string) => number, occupe?: (dossier: string) => string,
749
- * ticket?: string | null, sorte?: string, maintenant?: () => number,
750
- * dormir?: (ms: number) => void }} options `maintenant` and `dormir`, the clock and the sleep of
751
- * the wait (Date.now and the real sleep when left out); `racine`, the
752
- * root of the repository the measure plays in, which gives its rank (`rangDeLaMesure`; the
753
- * working directory by default); `borneMs`, the bound of the wait
754
- * (GRILLHOUSE_ATTENTE_MACHINE_MS, else ATTENTE_MACHINE_MS); `rappelMs`, the gap between two
755
- * lines that say the wait goes on (30 s); `libre`, the room free in a directory, in bytes
756
- * (`statfs`, at each turn); `occupe`, what holds it, counted when a line of the wait is written;
757
- * `ticket` (null out of a ticket) and `sorte` (« Vérification » by default), who the measure is;
758
- * an option left out is read from GRILLHOUSE_VERIFICATION_TICKET and GRILLHOUSE_VERIFICATION_SORTE,
759
- * named beside the lock while it waits and while it holds it, with its project
760
- * @returns {T}
761
- * @throws {AttenteDeLaMachine} at the bound of the wait (code 75), or at once when an ancestor
762
- * holds the lock (code 1)
763
- * @template T
764
- */
765
- export function avecLaMachine(
766
- mesure,
767
- {
768
- env = process.env,
769
- racine = process.cwd(),
770
- dire = l => process.stdout.write(`${l}\n`),
771
- borneMs = borneDe(env),
772
- rappelMs = RAPPEL_MS,
773
- libre = libreDans,
774
- occupe = occupants,
775
- ticket,
776
- sorte,
777
- maintenant = Date.now,
778
- dormir = attendreUnPeu,
779
- } = {}
780
- ) {
781
- if (paquetsDeLEnveloppe(env)) {
782
- return mesure(env);
783
- }
784
- const verrou = verrouDeMachine(env);
785
- if (env[VARIABLE_TENUE] && lire(verrou) === env[VARIABLE_TENUE]) {
786
- return mesure(env);
787
- }
788
- attendreDeLaPlace({
789
- env,
790
- libre,
791
- occupe,
792
- dire,
793
- borneMs,
794
- rappelMs,
795
- racine,
796
- ticket,
797
- sorte,
798
- maintenant,
799
- dormir,
800
- });
801
- const id = identite({ racine, env, ticket, sorte });
802
- mkdirSync(path.dirname(verrou), { recursive: true });
803
- const rang = rangDeLaMesure(racine);
804
- if (!(peutPrendre(verrou, rang) && prendreVerrou(verrou, { attendre: false }))) {
805
- const attendu = attendreLaMachine(verrou, {
806
- id,
807
- rang,
808
- dire,
809
- borneMs,
810
- rappelMs,
811
- maintenant,
812
- dormir,
813
- });
814
- dire(`✓ verrou de la machine pris après ${Math.round(attendu / 1000)} s.`);
815
- }
816
- let oublier = () => {};
817
- try {
818
- oublier = nommerLeDetenteur(verrou, id);
819
- const {
820
- [VARIABLE_VERIFICATION_SORTE]: _s,
821
- [VARIABLE_VERIFICATION_TICKET]: _t,
822
- ...enfant
823
- } = env;
824
- return mesure({ ...enfant, [VARIABLE_TENUE]: lire(verrou) ?? '' });
825
- } finally {
826
- oublier();
827
- lacherVerrou(verrou);
828
- }
829
- }