@roomi-fields/grillhouse 0.52.0 → 0.54.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 (155) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +96 -0
  3. package/agents/direct.md +1 -1
  4. package/cadre/templates/projet/docs/agents/issue-tracker.md +2 -2
  5. package/cadre/templates/projet/vitest.config.cjs +45 -0
  6. package/charte/superviseur.md +36 -37
  7. package/charte.md +13 -1
  8. package/dist/temporal/circuit/appel.d.ts +2 -0
  9. package/dist/temporal/circuit/appel.js +24 -2
  10. package/dist/temporal/circuit/appel.js.map +1 -1
  11. package/dist/temporal/circuit/client.d.ts +14 -5
  12. package/dist/temporal/circuit/client.js +41 -9
  13. package/dist/temporal/circuit/client.js.map +1 -1
  14. package/dist/temporal/circuit/commande.js +17 -6
  15. package/dist/temporal/circuit/commande.js.map +1 -1
  16. package/dist/temporal/circuit/contrat.d.ts +9 -0
  17. package/dist/temporal/circuit/contrat.js +6 -0
  18. package/dist/temporal/circuit/contrat.js.map +1 -1
  19. package/dist/temporal/circuit/deroule.js +29 -12
  20. package/dist/temporal/circuit/deroule.js.map +1 -1
  21. package/dist/temporal/client.d.ts +35 -1
  22. package/dist/temporal/client.js +144 -1
  23. package/dist/temporal/client.js.map +1 -1
  24. package/dist/temporal/commande.js +31 -13
  25. package/dist/temporal/commande.js.map +1 -1
  26. package/dist/temporal/etat.d.ts +3 -1
  27. package/dist/temporal/etat.js +31 -17
  28. package/dist/temporal/etat.js.map +1 -1
  29. package/dist/temporal/file/activites.js +1 -1
  30. package/dist/temporal/file/activites.js.map +1 -1
  31. package/dist/temporal/file/contrat.d.ts +4 -5
  32. package/dist/temporal/file/contrat.js +2 -2
  33. package/dist/temporal/file/contrat.js.map +1 -1
  34. package/dist/temporal/file/deroule.js +7 -5
  35. package/dist/temporal/file/deroule.js.map +1 -1
  36. package/dist/temporal/installation.d.ts +116 -53
  37. package/dist/temporal/installation.js +898 -241
  38. package/dist/temporal/installation.js.map +1 -1
  39. package/dist/temporal/nuits/deroule.js +3 -1
  40. package/dist/temporal/nuits/deroule.js.map +1 -1
  41. package/dist/temporal/places/deroule.js +2 -1
  42. package/dist/temporal/places/deroule.js.map +1 -1
  43. package/dist/temporal/sonde/deroule.js +2 -1
  44. package/dist/temporal/sonde/deroule.js.map +1 -1
  45. package/dist/temporal/tickets/deroule.js +4 -3
  46. package/dist/temporal/tickets/deroule.js.map +1 -1
  47. package/dist/temporal/travailleur.d.ts +7 -1
  48. package/dist/temporal/travailleur.js +49 -25
  49. package/dist/temporal/travailleur.js.map +1 -1
  50. package/docs/INTERFACE.md +37 -12
  51. package/docs/architecture/circuit.md +21 -18
  52. package/docs/architecture/entree.md +10 -11
  53. package/docs/architecture/greffon.md +45 -27
  54. package/docs/architecture/installation.md +92 -59
  55. package/docs/architecture/machine.md +2 -2
  56. package/docs/architecture/tests.md +15 -6
  57. package/docs/lexique.md +2 -2
  58. package/hooks/hooks.json +10 -0
  59. package/hooks/register.tsx +59 -39
  60. package/package.json +3 -2
  61. package/scripts/activites.mjs +5 -4
  62. package/scripts/aiguillage.mjs +5 -2
  63. package/scripts/bd-garde.mjs +69 -0
  64. package/scripts/ci-de-main.mjs +259 -56
  65. package/scripts/circuit.mjs +274 -47
  66. package/scripts/circuits-du-serveur.mjs +3 -2
  67. package/scripts/circuits-tenus.d.mts +7 -0
  68. package/scripts/circuits-tenus.mjs +17 -0
  69. package/scripts/commandes-composees.mjs +1 -1
  70. package/scripts/copie-de-montee.mjs +354 -0
  71. package/scripts/copies-du-depot.d.mts +13 -0
  72. package/scripts/copies-du-depot.mjs +66 -0
  73. package/scripts/copies-finies.mjs +6 -40
  74. package/scripts/crochets.mjs +16 -2
  75. package/scripts/direct.mjs +2 -2
  76. package/scripts/droits.mjs +13 -6
  77. package/scripts/engendres.mjs +5 -3
  78. package/scripts/enveloppe/travail-de-la-copie.mjs +77 -0
  79. package/scripts/etapes.mjs +11 -3
  80. package/scripts/faits-du-circuit.mjs +12 -5
  81. package/scripts/file-des-tickets.d.mts +13 -2
  82. package/scripts/file-des-tickets.mjs +71 -21
  83. package/scripts/greffons.mjs +42 -27
  84. package/scripts/grillhouse-maj.mjs +105 -85
  85. package/scripts/init.mjs +1 -1
  86. package/scripts/integration/file.mjs +5 -2
  87. package/scripts/integration/integrer.mjs +14 -4
  88. package/scripts/jointure.d.ts +16 -0
  89. package/scripts/langages/c/commandes.mjs +18 -8
  90. package/scripts/langages/cargo/commandes.mjs +88 -35
  91. package/scripts/langages/cargo/index.mjs +6 -3
  92. package/scripts/langages/cargo/sccache.mjs +15 -12
  93. package/scripts/langages/cargo/tailles-des-tests.mjs +115 -6
  94. package/scripts/langages/python/commandes.mjs +19 -9
  95. package/scripts/langages/python/squelette.mjs +2 -2
  96. package/scripts/langages/typescript/code-mort.mjs +36 -3
  97. package/scripts/langages/typescript/configurations-de-vitest.mjs +118 -0
  98. package/scripts/langages/typescript/index.mjs +2 -0
  99. package/scripts/langages/typescript/migrations/configurations-en-commonjs.mjs +370 -0
  100. package/scripts/langages/typescript/mise-a-jour.mjs +49 -12
  101. package/scripts/langages/typescript/parcours.mjs +5 -1
  102. package/scripts/langages/typescript/squelette.mjs +20 -17
  103. package/scripts/langages/typescript/tests-de-nuit.mjs +3 -3
  104. package/scripts/langages/typescript/turbo-des-paquets.mjs +24 -37
  105. package/scripts/langages/typescript/vitest-config/base.mjs +1 -1
  106. package/scripts/langages/typescript/vitest-config/bornes.mjs +1 -1
  107. package/scripts/langages/typescript/vitest-config/cibles.mjs +2 -2
  108. package/scripts/langages/typescript/{vitest.nuit.config.mjs → vitest.nuit.config.cjs} +61 -50
  109. package/scripts/langages.d.mts +6 -0
  110. package/scripts/langages.mjs +6 -0
  111. package/scripts/lire.mjs +236 -0
  112. package/scripts/mesure/pression.mjs +5 -3
  113. package/scripts/migrations/cout-des-jetons-au-registre.mjs +136 -0
  114. package/scripts/migrations/lire-un-ticket.mjs +46 -0
  115. package/scripts/migrations.mjs +4 -0
  116. package/scripts/montee.mjs +588 -0
  117. package/scripts/nuit.sh +21 -12
  118. package/scripts/outil.mjs +5 -3
  119. package/scripts/paquet-npm.mjs +22 -0
  120. package/scripts/paquet.mjs +5 -5
  121. package/scripts/pre-compact.mjs +25 -0
  122. package/scripts/registre.d.mts +7 -1
  123. package/scripts/registre.mjs +114 -102
  124. package/scripts/reponses-du-circuit.d.mts +17 -2
  125. package/scripts/reponses-du-circuit.mjs +78 -20
  126. package/scripts/resultats.mjs +55 -17
  127. package/scripts/retirer-les-copies-finies.mjs +4 -7
  128. package/scripts/seances.mjs +28 -3
  129. package/scripts/services-du-noyau.mjs +7 -2
  130. package/scripts/session-start.sh +18 -11
  131. package/scripts/sortie.mjs +4 -7
  132. package/scripts/sous-commandes.mjs +2 -0
  133. package/scripts/suiveur.mjs +12 -4
  134. package/scripts/superviseur.mjs +135 -84
  135. package/scripts/tableau.mjs +651 -224
  136. package/scripts/tarifs.mjs +67 -0
  137. package/scripts/ticket-du-circuit.mjs +25 -4
  138. package/scripts/transitions.d.mts +6 -14
  139. package/scripts/transitions.mjs +126 -49
  140. package/scripts/verdict-de-la-nuit.mjs +2 -2
  141. package/scripts/verrou-de-fichier.d.mts +11 -0
  142. package/skills/direct/SKILL.md +21 -11
  143. package/skills/explorateur/SKILL.md +16 -6
  144. package/skills/grill/SKILL.md +9 -7
  145. package/skills/grill/references/paquets.md +4 -4
  146. package/skills/mesure/SKILL.md +4 -3
  147. package/skills/pitmaster/SKILL.md +56 -35
  148. package/skills/pitmaster/references/consigne-agent.md +1 -1
  149. package/skills/pitmaster/references/erreurs.md +4 -2
  150. package/skills/pitmaster/references/tour.md +11 -4
  151. package/skills/relecteur/SKILL.md +8 -1
  152. package/skills/testwriter/SKILL.md +1 -1
  153. package/types/index.d.ts +3 -1
  154. package/cadre/templates/projet/vitest.config.ts +0 -44
  155. package/scripts/base-des-workflows.mjs +0 -58
@@ -1,10 +1,12 @@
1
1
  // The installation of the account's Temporal (`grillhouse temporal installer`): the program
2
2
  // `temporal` at its pinned version, its archive checked against its pinned sum, laid down under
3
- // ~/.cache/grillhouse/temporal/<version>/temporal; the units of the account's systemd (the server,
4
- // the worker of the project, the worker of the machine), each started again by systemd; the
5
- // worker's unit gets `Environment=TEMPORAL=<the program laid down>`, the package.json untouched.
6
- // The mechanism is installation.md §5.3 (step 4, the program and the units), §3.1, in
7
- // packages/grillhouse/docs/architecture/.
3
+ // ~/.cache/grillhouse/temporal/<version>/temporal; the units of the account's systemd: the server,
4
+ // and one template of unit per task queue (the worker of the project, the worker of the machine),
5
+ // whose instance names the version of the frame it runs, each started again by systemd; the
6
+ // templates get `Environment=TEMPORAL=<the program laid down>`, the package.json untouched. The
7
+ // mechanism is installation.md §5.3 (step 4, the program and the units), §3.1, in
8
+ // packages/grillhouse/docs/architecture/: Temporal's Worker Deployments, one living worker per
9
+ // version.
8
10
  //
9
11
  // - The pin (EPINGLE) is the version of the program and the SHA-256 of the archive of each
10
12
  // platform, as its release publishes them (checksums.txt); an archive whose sum differs is
@@ -20,59 +22,104 @@
20
22
  // - Applying the server's unit (its text changed, or the program newly laid down) asks the server
21
23
  // for the circuits in flight before any writing; when there is one (`circuitsEnVol`; a server
22
24
  // that does not answer has none), the server's unit alone is deferred to a later run, the
23
- // circuits named in the report (`serveurDiffere`), the program laid down and the workers' units
24
- // applied all the same; otherwise it stops the server, compacts
25
- // its database (`compacterLaBase`, `VACUUM` by the runtime's `node:sqlite`) and starts it again,
26
- // and the report says the sizes before and after. A failed compaction starts the server again and
25
+ // circuits named in the report (`serveurDiffere`), the program laid down and the workers'
26
+ // templates applied all the same; otherwise it stops the server, compacts its database
27
+ // (`compacterLaBase`, `VACUUM` by the runtime's `node:sqlite`) and starts it again, and the
28
+ // report says the sizes before and after. A failed compaction starts the server again and
27
29
  // refuses the installation by its name, the unit not recorded as applied.
30
+ // - The server's unit carries the version of the frame that wrote it (`X-Grillhouse-Version`, that
31
+ // the project installs). A pass that installs an earlier version neither writes nor applies it,
32
+ // and says so (`serveurPlusNeuf`); a unit without a version is replaced. A unit that changes by
33
+ // that line alone is written and systemd told of it, the server neither stopped nor restarted.
28
34
  // - `purger` deletes by query the workflows closed for longer than the retention, never a running
29
35
  // one (the server keeps the deletion timer a workflow got when it closed, under the retention of
30
36
  // then), waits until the server counts none left, then stops the server, removes the history trees
31
37
  // no execution references (`retirerLesOrphelins`, in SQL: a gap to the reference), compacts the
32
38
  // database as above and starts the server again. A circuit in flight refuses it by its tickets,
33
39
  // before the deletion and again before the stop.
34
- // - Each worker runs the frame's worker (dist/temporal/travailleur.js) on its task queue:
35
- // `grillhouse-projet-<projet>` for the project's, `grillhouse-machine` for the machine's. A
36
- // project that names its version of the frame (`grillhouse.outil`, scripts/aiguillage.mjs) runs
37
- // the worker of that published version, installed under the cache of the home
38
- // (~/.cache/grillhouse/outil/<version>/) when absent, as the circuit's command does; another, its
39
- // own version (its node_modules/@roomi-fields/grillhouse), else this package.
40
+ // - The version a project installs is its key `grillhouse.outil` (scripts/aiguillage.mjs), else
41
+ // that of the package it installed. It is laid down under the cache of the home
42
+ // (~/.cache/grillhouse/outil/<version>/) before any unit is written, and refused, named, when it
43
+ // does not install, carries no worker or, without the key, when the integrity the project's lock
44
+ // file gives the installed package differs from the cache's, or is missing on either side.
45
+ // - Each template runs dist/temporal/travailleur.js of the version its instance names (`%i`), from
46
+ // that cache, on its task queue: `grillhouse-projet-<projet>` for the project's,
47
+ // `grillhouse-machine` for the machine's. Its text is the same from a version to the next; an
48
+ // instance that starts again reads it as it is then.
40
49
  // - Every refusal comes before any writing (the archive, an account's tool, a fault of
41
- // `grillhouse.outils`, a published version without a worker), but the published version
42
- // itself: it is laid down in its cache before its refusal, which reads it there.
43
- // - A unit of systemd starts with a bare PATH: each worker's unit names the PATH of the account's
44
- // tools a circuit runs (node, npm, claude, bd, gh), found in the installer's PATH, and the tools
45
- // of the project (`grillhouse.outils`), each its variable; a tool of the account not found is
46
- // refused by its name before anything is written.
50
+ // `grillhouse.outils`), but the published version itself: it is laid down in its cache before
51
+ // its refusal, which reads it there.
52
+ // - A unit of systemd starts with a bare PATH: each template names the PATH of the account's tools
53
+ // a circuit runs (node, npm, claude, bd, gh), found in the installer's PATH, and the tools of the
54
+ // project (`grillhouse.outils`), each its variable.
55
+ // - No running instance is ever restarted: the pass writes the templates, has systemd read them,
56
+ // starts the instance of the version it installs (`enable --now`), and names the running
57
+ // instances started under a former text. The server's unit alone is restarted.
58
+ // - Once its instance started, the version becomes the current one of the Worker Deployment of the
59
+ // task queue (`rendreCourante`, ./client.ts), which waits for the server within a bounded delay;
60
+ // past it, the installation fails, naming the version and the queue, no instance stopped.
61
+ // - Each pass retires (stops, disables, forgets) the instance whose version is not current, is not
62
+ // the one it installs, is drained or was never current (on the machine's queue, never current and
63
+ // lower than the current one), and whose process holds no started activity of a running workflow;
64
+ // a server that does not answer keeps every instance. The unit of before the template
65
+ // (`grillhouse-travailleur-<…>.service`) leaves, file and sum, at the first pass that finds its
66
+ // queue current on the version installed and its process holding no activity.
67
+ // - The drop-ins of a unit of before the template (`<unit>.d/*.conf`, systemd.unit(5)) follow it to
68
+ // the folder of its template: each pass that finds the unit copies them there before any instance
69
+ // starts, content unchanged, and the pass that retires the unit removes the former ones, before
70
+ // the file of the unit, then their folder once empty. A name the folder of the template holds with
71
+ // another content is neither overwritten nor removed. The output names each copy, each move and
72
+ // each such pair of paths; a pass that changes nothing speaks of none.
73
+ // - A single pass of installation plays on the account, from the laying down of the project's
74
+ // version to the end of the purge: a lock under the home (cheminsDe, `verrou`), which a second
75
+ // pass waits for, and which the lock of a dead process does not hold.
76
+ // - The last gesture of a pass that succeeds is the purge of the versions of the tool nothing names
77
+ // (`purgerLesVersions`): a version `x.y.z` of ~/.cache/grillhouse/outil/, with its failure mark
78
+ // `<version>.echec` (or the mark alone), leaves unless one of these names it: a project of the
79
+ // machine (the pass's own, and those the WorkingDirectory of a worker unit names, while their
80
+ // folder stands) by the version of its main tree (its key, else the package it installed); a unit
81
+ // of the account (an applied instance, or a unit file whose text plays that version of the
82
+ // cache); a copy of a circuit not finished (listed by `git worktree list`, its circuit held by
83
+ // the server, or its `.travail` there and its ticket not closed); a living process whose command
84
+ // line names a path of it; a Worker Deployment of a project of the machine, or of the machine,
85
+ // where it is current, draining or of an unknown drainage. When the server, the processes, the
86
+ // copies or a key that counts do not read, no version leaves; tickets that do not read only keep
87
+ // every copy beside its `.travail`. A version leaves by a rename first
88
+ // (`<version>.retrait-<id>`), so that a removal interrupted or failed is never taken for a
89
+ // version installed; the next purge removes what is left. It calls no systemctl.
47
90
  // - Played again on an installation up to date, it changes nothing: the program of the pinned
48
- // version is not downloaded again, a unit and the package.json are written only when they
49
- // differ, and systemd is told only of what it has not applied yet (daemon-reload, enable,
50
- // restart of those units). What systemd applied is kept apart from what is written: the sum of
51
- // each unit's text once systemctl succeeded (~/.local/state/grillhouse/temporal/
52
- // unites-appliquees.json), so that a systemctl that failed is played again at the next run.
53
- // - An account holds several projects: the server and the worker of the machine are the account's,
54
- // a project's worker is the project's. An installation keeps the sums applied for the units of
55
- // the other projects. The unit of the machine belongs to the project that wrote it, which
56
- // answers for its whole text; another project takes it only to raise it to a later version of
57
- // the frame (`textesDuProjet`).
91
+ // version is not downloaded again, a unit is written only when it differs, and systemd is told
92
+ // only of what it has not applied yet. What systemd applied is kept apart from what is written:
93
+ // the sum of each unit's text once systemctl succeeded
94
+ // (~/.local/state/grillhouse/temporal/unites-appliquees.json), an instance under the sum of the
95
+ // template it started under, so that a systemctl that failed is played again at the next run.
96
+ // - An account holds several projects: the server and the template of the machine are the
97
+ // account's, a project's template is the project's. An installation keeps the sums applied for
98
+ // the units of the other projects. The worker of the machine plays the highest version a project
99
+ // of the account installed on it: the highest its applied instances name, and the one of the unit
100
+ // of before the template while it stands. A project below it starts no instance of the machine.
101
+ // The template of the machine belongs to the project that wrote it, which answers for its whole
102
+ // text; another project takes it only to raise the version (`textesDuProjet`), or once that
103
+ // project is gone.
58
104
  // - `poserLeProgramme` lays down the program alone, no unit, no package.json, no systemd: the mode
59
105
  // `--programme-seul` of the command, by which the night gets the pinned program as a user does.
60
106
  // - The home, the directory of the units and the project are parameters (`lieuxDe`), as systemctl,
61
- // the download, the published version and the account's tools are: a test installs under a
62
- // trial home, never in the account's systemd.
107
+ // the download, the published version, the server and the account's tools are: a test installs
108
+ // under a trial home, never in the account's systemd.
63
109
  import { spawnSync } from 'node:child_process';
64
- import { createHash } from 'node:crypto';
65
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
110
+ import { createHash, randomUUID } from 'node:crypto';
111
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync, lstatSync, readdirSync, realpathSync, } from 'node:fs';
66
112
  import { createRequire } from 'node:module';
67
113
  import os from 'node:os';
68
114
  import path from 'node:path';
69
- import { fileURLToPath } from 'node:url';
70
- import { cacheDesOutils, installer as installerLOutil, versionDeLOutil, } from '../../scripts/aiguillage.mjs';
115
+ import { cacheDesOutils, installer as installerLOutil, versionDeLOutil, X_Y_Z, } from '../../scripts/aiguillage.mjs';
116
+ import { ticketsTenus } from '../../scripts/circuits-tenus.mjs';
71
117
  import { trouverDansLePath } from '../../scripts/commandes-du-path.mjs';
118
+ import { copiesListees, ticketsDuStatut } from '../../scripts/copies-du-depot.mjs';
72
119
  import { langagesDe } from '../../scripts/langages.mjs';
73
120
  import { lireOutils } from '../../scripts/outils-cles.mjs';
121
+ import { lacherVerrou, prendreVerrou } from '../../scripts/verrou-de-fichier.mjs';
74
122
  import { ATTRIBUTS_DE_RECHERCHE } from './attributs.js';
75
- import { idDeLaFile, L_ETAT_DE_LA_FILE, RELANCER } from './file/contrat.js';
76
123
  /** The pin: temporal 1.9.1 (Server 1.32.0), its sums from the release's checksums.txt. */
77
124
  export const EPINGLE = {
78
125
  version: '1.9.1',
@@ -102,10 +149,14 @@ const OUTILS_DU_COMPTE = ['node', 'npm', 'claude', 'bd', 'gh'];
102
149
  const PATH_DU_SYSTEME = ['/usr/local/bin', '/usr/bin', '/bin'];
103
150
  /** The unit of the server. */
104
151
  export const UNITE_DU_SERVEUR = 'grillhouse-temporal.service';
105
- /** The unit of the worker of the machine. */
106
- export const UNITE_DE_LA_MACHINE = 'grillhouse-travailleur-machine.service';
152
+ /** The template of the units of the worker of the machine. */
153
+ const GABARIT_DE_LA_MACHINE = 'grillhouse-travailleur-machine@.service';
107
154
  /** The task queue of the worker of the machine. */
108
155
  export const FILE_DE_LA_MACHINE = 'grillhouse-machine';
156
+ // The instance of the template <gabarit> for the version <version>.
157
+ const instanceDe = (gabarit, version) => gabarit.replace('@.service', () => `@${version}.service`);
158
+ // The unit of before the template <gabarit>, which no instance marks.
159
+ const uniteDAvant = (gabarit) => gabarit.replace('@.service', '.service');
109
160
  /** The platform of Node's <platform> and <arch>; refused by its name when the pin has none. */
110
161
  export function plateformeDe(platform = process.platform, arch = process.arch) {
111
162
  const os = { linux: 'linux', darwin: 'darwin' }[platform];
@@ -126,12 +177,16 @@ export function lieuxDe({ maison, unites, racine } = {}, env = process.env) {
126
177
  racine: path.resolve(racine ?? process.cwd()),
127
178
  };
128
179
  }
129
- /** The program of <version> and the server's database file, under the home of <lieux>. */
180
+ /**
181
+ * The program of <version>, the server's database file, the units applied and the lock of the
182
+ * installation, under the home of <lieux>.
183
+ */
130
184
  export function cheminsDe(lieux, version) {
131
185
  return {
132
186
  programme: path.join(lieux.maison, '.cache/grillhouse/temporal', version, 'temporal'),
133
187
  donnees: path.join(lieux.maison, '.local/share/grillhouse/temporal/temporal.db'),
134
188
  appliquees: path.join(lieux.maison, '.local/state/grillhouse/temporal/unites-appliquees.json'),
189
+ verrou: path.join(lieux.maison, '.local/state/grillhouse/temporal/installation.verrou'),
135
190
  };
136
191
  }
137
192
  // The name of the project at <racine>, for a unit and a task queue: its package's name, else its
@@ -152,20 +207,39 @@ function nomDuProjet(racine) {
152
207
  .replace(/[^a-z0-9]+/g, '-')
153
208
  .replace(/^-+|-+$/g, '');
154
209
  }
155
- /** The unit of the worker of the project at <racine>. */
156
- export const uniteDuProjet = (racine) => `grillhouse-travailleur-${nomDuProjet(racine)}.service`;
210
+ // The template of the units of the worker of the project at <racine>.
211
+ const gabaritDuProjet = (racine) => `grillhouse-travailleur-${nomDuProjet(racine)}@.service`;
157
212
  /** The task queue of the worker of the project at <racine>. */
158
213
  export const fileDuProjet = (racine) => `grillhouse-projet-${nomDuProjet(racine)}`;
159
- /** The three units, in their order: the server, the worker of the project, the machine's. */
214
+ /** The two templates of the workers, each with its task queue: the project's, the machine's. */
215
+ export const gabaritsDe = (racine) => [
216
+ { gabarit: gabaritDuProjet(racine), file: fileDuProjet(racine) },
217
+ { gabarit: GABARIT_DE_LA_MACHINE, file: FILE_DE_LA_MACHINE },
218
+ ];
219
+ /** The three unit files, in their order: the server, the templates of the project and the machine. */
160
220
  export const unitesDe = (racine) => [
161
221
  UNITE_DU_SERVEUR,
162
- uniteDuProjet(racine),
163
- UNITE_DE_LA_MACHINE,
222
+ ...gabaritsDe(racine).map(g => g.gabarit),
164
223
  ];
224
+ /**
225
+ * The instances of the template <gabarit> among the units applied at the places <lieux>, each with
226
+ * the version it names.
227
+ */
228
+ export function instancesAppliquees(lieux, gabarit, epingle = EPINGLE) {
229
+ return instancesDe(lireLesAppliquees(cheminsDe(lieux, epingle.version).appliquees), gabarit);
230
+ }
231
+ // The instances of <gabarit> among the units of <appliquees>.
232
+ function instancesDe(appliquees, gabarit) {
233
+ const prefixe = gabarit.slice(0, -'.service'.length);
234
+ return Object.keys(appliquees)
235
+ .filter(u => u.startsWith(prefixe) && u.endsWith('.service'))
236
+ .map(unite => ({ unite, version: unite.slice(prefixe.length, -'.service'.length) }))
237
+ .filter(i => i.version !== '');
238
+ }
165
239
  // An argument of ExecStart, quoted as systemd reads it when it holds a space or a quote.
166
240
  const arg = (s) => (/[\s"\\]/.test(s) ? `"${s.replace(/["\\]/g, c => `\\${c}`)}"` : s);
167
241
  /** The text of each unit of the account, by its file's name. */
168
- export function textesDesUnites(lieux, { version, node, travailleur, chemin, outils }) {
242
+ export function textesDesUnites(lieux, { version, node, chemin, outils }) {
169
243
  const { programme, donnees } = cheminsDe(lieux, version);
170
244
  const serveur = [
171
245
  programme,
@@ -207,6 +281,8 @@ export function textesDesUnites(lieux, { version, node, travailleur, chemin, out
207
281
  '',
208
282
  ].join('\n');
209
283
  const apres = [`After=${UNITE_DU_SERVEUR}`, `Wants=${UNITE_DU_SERVEUR}`];
284
+ // The worker of the version the instance names (%i), from the cache of the home.
285
+ const travailleur = path.join(cacheDesOutils(lieux.maison), '%i', 'node_modules/@roomi-fields/grillhouse', TRAVAILLEUR);
210
286
  const travailleurSur = (file) => [
211
287
  `WorkingDirectory=${arg(lieux.racine)}`,
212
288
  `Environment=TEMPORAL_ADDRESS=127.0.0.1:${PORT_DU_SERVEUR}`,
@@ -220,29 +296,74 @@ export function textesDesUnites(lieux, { version, node, travailleur, chemin, out
220
296
  `ExecStart=${serveur.map(arg).join(' ')}`,
221
297
  `ExecStartPost=/bin/sh -c ${arg(retenir)}`,
222
298
  ]),
223
- [uniteDuProjet(lieux.racine)]: service(`Grillhouse : le travailleur du projet ${nomDuProjet(lieux.racine)}`, travailleurSur(fileDuProjet(lieux.racine)), apres),
224
- [UNITE_DE_LA_MACHINE]: service('Grillhouse : le travailleur de la machine', travailleurSur(FILE_DE_LA_MACHINE), apres),
299
+ [gabaritDuProjet(lieux.racine)]: service(`Grillhouse : le travailleur du projet ${nomDuProjet(lieux.racine)}, version %i`, travailleurSur(fileDuProjet(lieux.racine)), apres),
300
+ [GABARIT_DE_LA_MACHINE]: service('Grillhouse : le travailleur de la machine, version %i', travailleurSur(FILE_DE_LA_MACHINE), apres),
225
301
  };
226
302
  }
227
- /** The package that runs: two levels above this module, in src/ as in dist/. */
228
- const PAQUET = fileURLToPath(new URL('../..', import.meta.url));
229
303
  const TRAVAILLEUR = 'dist/temporal/travailleur.js';
230
- /**
231
- * The frame's worker of the project at <racine>: that of the published version it names, laid down
232
- * by <outil> (its folder), refused when that version carries none; else its own version of the
233
- * frame, else this one.
234
- */
235
- export function travailleurDe(racine, outil, exiger = true) {
236
- const version = versionDeLOutil(racine);
237
- if (version !== null) {
238
- const f = path.join(outil(version), 'node_modules/@roomi-fields/grillhouse', TRAVAILLEUR);
239
- if (exiger && !existsSync(f)) {
240
- throw new Error(`temporal : @roomi-fields/grillhouse@${version}, la version que nomme grillhouse.outil, ne porte pas de travailleur (${TRAVAILLEUR}).`);
304
+ const PAQUET_INSTALLE = 'node_modules/@roomi-fields/grillhouse';
305
+ // The `version` of the package.json of the folder <paquet>, or null when none reads.
306
+ function versionDuPaquet(paquet) {
307
+ try {
308
+ const v = JSON.parse(readFileSync(path.join(paquet, 'package.json'), 'utf8')).version;
309
+ return typeof v === 'string' && v ? v : null;
310
+ }
311
+ catch {
312
+ return null;
313
+ }
314
+ }
315
+ // The version of the frame the project at <racine> installs: its key `grillhouse.outil`, else that
316
+ // of the package it installed; refused without either.
317
+ function versionDuProjet(racine) {
318
+ const cle = versionDeLOutil(racine);
319
+ if (cle !== null) {
320
+ return { version: cle, nommee: true };
321
+ }
322
+ const version = versionDuPaquet(path.join(racine, PAQUET_INSTALLE));
323
+ if (version === null) {
324
+ throw new Error(`temporal : le projet ne nomme aucune version (grillhouse.outil) et ${PAQUET_INSTALLE} n'en déclare aucune ; aucune unité n'est écrite.`);
325
+ }
326
+ return { version, nommee: false };
327
+ }
328
+ // The integrity the first of the lock files <verrous> that gives one gives the frame's package.
329
+ function empreinte(...verrous) {
330
+ for (const f of verrous) {
331
+ try {
332
+ const i = JSON.parse(readFileSync(f, 'utf8')).packages?.[PAQUET_INSTALLE]?.integrity;
333
+ if (typeof i === 'string' && i) {
334
+ return i;
335
+ }
336
+ }
337
+ catch {
338
+ // absent or unreadable: the next one
339
+ }
340
+ }
341
+ return null;
342
+ }
343
+ // Lays down by <outil> the version the project at <racine> installs, and refuses it, by its name,
344
+ // when it carries no worker or, for a project without the key, when its integrity in the cache is
345
+ // not that of the installed package.
346
+ function poserLaVersionDuProjet(racine, outil) {
347
+ const { version, nommee } = versionDuProjet(racine);
348
+ const nom = `@roomi-fields/grillhouse@${version}`;
349
+ const refuser = (raison) => {
350
+ throw new Error(`temporal : ${nom}, la version que le projet installe, ${raison}.`);
351
+ };
352
+ const installee = nommee ? null : empreinte(path.join(racine, 'package-lock.json'));
353
+ if (!nommee && installee === null) {
354
+ refuser('n’a aucune empreinte (integrity) au fichier de verrou du projet : un paquet lié, une archive locale ou une version non publiée n’installe aucune unité');
355
+ }
356
+ const dossier = outil(version);
357
+ if (!existsSync(path.join(dossier, PAQUET_INSTALLE, TRAVAILLEUR))) {
358
+ refuser(`ne porte pas de travailleur (${TRAVAILLEUR})`);
359
+ }
360
+ if (!nommee) {
361
+ const posee = empreinte(path.join(dossier, 'package-lock.json'), path.join(dossier, 'node_modules/.package-lock.json'));
362
+ if (posee !== installee) {
363
+ refuser(`a au cache (${dossier}) une empreinte (integrity) ${posee === null ? 'absente' : 'différente'} de celle du paquet installé`);
241
364
  }
242
- return f;
243
365
  }
244
- const local = path.join(racine, 'node_modules/@roomi-fields/grillhouse');
245
- return path.join(existsSync(local) ? realpathSync(local) : PAQUET, TRAVAILLEUR);
366
+ return version;
246
367
  }
247
368
  /**
248
369
  * The PATH of each worker's unit: the folder of Node <node>, then those of the account's tools
@@ -286,87 +407,55 @@ async function telecharger(url) {
286
407
  }
287
408
  return Buffer.from(await r.arrayBuffer());
288
409
  }
289
- /**
290
- * The client of the account's server (its address and namespace from Temporal's variables). A
291
- * queue that is not there, or a server that does not answer within 5 s, is a failure, which the
292
- * installation takes for no queue.
293
- */
294
- function laFileDuServeur() {
410
+ // The Worker Deployments of the account's server (`deploiementsDuServeur`, ./client.ts).
411
+ function deploiementsDuCompte() {
295
412
  const avec = async (f) => {
296
- const { ouvrirLeClient } = await import('./client.js');
297
- const ouvert = ouvrirLeClient();
298
- let minuteur;
299
- try {
300
- return await Promise.race([
301
- f(ouvert.client),
302
- new Promise((_, rejet) => {
303
- minuteur = setTimeout(() => rejet(new Error('le serveur ne répond pas')), 5000);
304
- }),
305
- ]);
306
- }
307
- finally {
308
- clearTimeout(minuteur);
309
- await ouvert.fermer().catch(() => undefined);
310
- }
413
+ const { adresseDuServeur, deploiementsDuServeur } = await import('./client.js');
414
+ return f(deploiementsDuServeur(adresseDuServeur()));
311
415
  };
312
416
  return {
313
- vue: id => avec(c => c.workflow.getHandle(id).query(L_ETAT_DE_LA_FILE)),
314
- relancer: id => avec(c => c.workflow.getHandle(id).signal(RELANCER)),
417
+ lire: file => avec(s => s.lire(file)),
418
+ rendreCourante: (file, version) => avec(s => s.rendreCourante(file, version)),
419
+ activitesTenues: () => avec(s => s.activitesTenues()),
315
420
  };
316
421
  }
317
- const AUCUNE_FILE = 'aucune';
318
- const VERSION_INCONNUE = 'inconnue';
319
- /**
320
- * The version of the tool of the package the worker <travailleur> belongs to: the `version` of its
321
- * package.json, two levels above the worker's path, the file the queue's activity reads; null when
322
- * it does not read.
323
- */
324
- function versionInstallee(travailleur) {
325
- try {
326
- const v = JSON.parse(readFileSync(path.join(path.resolve(travailleur, '../../..'), 'package.json'), 'utf8')).version;
327
- return typeof v === 'string' && v ? v : null;
328
- }
329
- catch {
330
- return null;
331
- }
422
+ /** What the command writes of a report: its line, then those of the purge of the versions. */
423
+ export function texteDeLInstallation(r) {
424
+ return `${ligneDeLInstallation(r)}${lignesDeLaPurgeDesVersions(r.versions)}`;
332
425
  }
333
426
  /**
334
- * The queue of the project <racine> restarted when the version it started under differs from the
335
- * installed one <installee> (« inconnue » for a view that carries none, which differs): signalled
336
- * once, after <avantLeSignal> restarted the worker's unit when this pass did not. No queue, a
337
- * queue of the installed version, a version that does not read, a server that does not answer or a
338
- * signal lost leave « aucune »; the next pass makes up a signal lost.
427
+ * The exit code of an installation: 1 when a source that blocks every removal does not read, or a
428
+ * removal fails. The tickets of a project that do not read are said in the report, without it.
339
429
  */
340
- async function relancerLaFile(file, racine, installee, avantLeSignal) {
341
- const id = idDeLaFile(racine);
342
- try {
343
- const vue = await file.vue(id);
344
- if (vue === null || installee === null) {
345
- return { file: AUCUNE_FILE };
346
- }
347
- const ancienne = vue.version ?? VERSION_INCONNUE;
348
- const versions = { versionDeLaFile: ancienne, versionInstallee: installee };
349
- if (ancienne === installee) {
350
- return { file: AUCUNE_FILE, ...versions };
351
- }
352
- avantLeSignal();
353
- await file.relancer(id);
354
- const deVersion = `(${ancienne} → ${installee})`;
355
- return {
356
- file: vue.enCours === null
357
- ? `repartie ${deVersion}`
358
- : `repart après l'entrée de ${vue.enCours} ${deVersion}`,
359
- ...versions,
360
- };
361
- }
362
- catch {
363
- return { file: AUCUNE_FILE };
364
- }
430
+ export const codeDeLInstallation = (r) => r.versions.illisibles.length || r.versions.echecs.length ? 1 : 0;
431
+ const REJOUER = 'à rejouer : npx grillhouse temporal installer';
432
+ // The lines of the purge of the versions: each version removed with the place it gave back, each
433
+ // version kept with what names it, each source unread and each removal failed.
434
+ function lignesDeLaPurgeDesVersions(p) {
435
+ const mo = (octets) => `${(octets / 1024 / 1024).toFixed(1).replace('.', ',')} Mo`;
436
+ return [
437
+ ...p.retirees.map(v => {
438
+ const quoi = v.reste ? 'restes d’un retrait de la version' : 'version';
439
+ return `purge : ${quoi} ${v.version} ${v.reste ? 'retirés' : 'retirée'}, ${mo(v.octets)} rendus`;
440
+ }),
441
+ ...p.gardees.map(v => `purge : version ${v.version} gardée : ${v.raisons.join(' ; ')}`),
442
+ ...[...p.illisibles, ...p.ticketsIllisibles].map(l => `purge : ${l} ; ${REJOUER}`),
443
+ ...p.echecs.map(e => `purge : le retrait de la version ${e.version} échoue (${enUneLigne(e.raison)}) ; ${REJOUER}`),
444
+ ]
445
+ .map(l => `${l}\n`)
446
+ .join('');
365
447
  }
366
- /** The line the command writes of a report. */
367
- export function texteDeLInstallation(r) {
448
+ // The line of the installation itself.
449
+ function ligneDeLInstallation(r) {
450
+ const liste = (titre, unites) => unites.length ? ` ; ${titre} : ${unites.join(', ')}` : '';
451
+ const retenues = liste('retenues par une activité en cours', r.retenues);
452
+ const { copies, deplaces, conflits } = r.complements;
453
+ const chemins = (titre, c, entre = ' → ') => liste(titre, c.map(({ depart, arrivee }) => `${depart}${entre}${arrivee}`));
454
+ const plusNeuf = r.serveurPlusNeuf
455
+ ? ` ; l'unité du serveur, écrite par la ${r.serveurPlusNeuf.ecrite}, n'est pas réécrite par la ${r.serveurPlusNeuf.installee}, antérieure`
456
+ : '';
368
457
  if (!r.change) {
369
- return 'temporal : l’installation est à jour, rien ne change.\n';
458
+ return `temporal : l’installation est à jour, rien ne change${retenues}${plusNeuf}.\n`;
370
459
  }
371
460
  return (`temporal : ${r.pose ? 'programme posé' : 'programme à jour'} (${r.programme}) ; ` +
372
461
  `unités écrites : ${r.unites.join(', ') || 'aucune'} ; ` +
@@ -377,7 +466,15 @@ export function texteDeLInstallation(r) {
377
466
  (r.serveurDiffere
378
467
  ? ` ; l'unité du serveur attend, le serveur n'étant ni arrêté ni compacté : circuits en vol (${r.serveurDiffere.join(', ')}), à rejouer quand ils sont arrêtés`
379
468
  : '') +
380
- ` ; file : ${r.file}` +
469
+ plusNeuf +
470
+ liste('instances démarrées', r.demarrees) +
471
+ liste('rendues courantes', r.courantes) +
472
+ liste('retirées', r.retirees) +
473
+ retenues +
474
+ chemins('compléments copiés', copies.filter(c => !deplaces.some(d => d.depart === c.depart))) +
475
+ chemins('compléments déplacés', deplaces) +
476
+ chemins('compléments en conflit, laissés chacun à sa place', conflits, ' et ') +
477
+ liste('en marche sous l’ancien texte de leur gabarit', r.sousLAncienTexte) +
381
478
  '.\n');
382
479
  }
383
480
  // Opens the database file <base> of the server by the runtime's `node:sqlite`, no tool of the PATH.
@@ -463,12 +560,13 @@ function retirerLesOrphelins(base) {
463
560
  * <programme>, the workflows `circuitDuTicket` Running (their id `circuit:<racine>:<ticket>`). A
464
561
  * server that does not answer, or an answer that does not read, is no circuit in flight.
465
562
  */
466
- function circuitsEnVolDuServeur(programme) {
563
+ async function circuitsEnVolDuServeur(programme) {
564
+ const { adresseDuServeur } = await import('./client.js');
467
565
  const r = spawnSync(programme, [
468
566
  'workflow',
469
567
  'list',
470
568
  '--address',
471
- `127.0.0.1:${PORT_DU_SERVEUR}`,
569
+ adresseDuServeur(),
472
570
  '--query',
473
571
  "WorkflowType='circuitDuTicket' AND ExecutionStatus='Running'",
474
572
  '--output',
@@ -565,12 +663,12 @@ function lireLesAppliquees(f) {
565
663
  * `installer` and by the detection of a stale worker. Every refusal of the tools (an account's
566
664
  * tool not found, a fault of `grillhouse.outils`) is thrown here, before any writing.
567
665
  */
568
- function textesAttendus({ lieux, epingle = EPINGLE, node = process.execPath, trouver = nom => trouverDansLePath(nom), travailleur, }) {
666
+ function textesAttendus({ lieux, declarations = lieux.racine, epingle = EPINGLE, node = process.execPath, trouver = nom => trouverDansLePath(nom), }) {
569
667
  const { programme } = cheminsDe(lieux, epingle.version);
570
- const executables = langagesDe(lieux.racine).flatMap(m => m.executables);
668
+ const executables = langagesDe(declarations).flatMap(m => m.executables);
571
669
  const chemin = cheminDesUnites(node, trouver, executables);
572
670
  const pkg = JSON.parse(readFileSync(path.join(lieux.racine, 'package.json'), 'utf8'));
573
- // The tools as written, without a TEMPORAL key left in the package.json: the worker's unit takes
671
+ // The tools as written, without a TEMPORAL key left in the package.json: the workers' templates take
574
672
  // the program laid down. A faulty value is refused as it is written.
575
673
  const brut = pkg.grillhouse?.outils;
576
674
  const { outils: lus, fautes } = lireOutils({
@@ -589,7 +687,6 @@ function textesAttendus({ lieux, epingle = EPINGLE, node = process.execPath, tro
589
687
  const textes = textesDesUnites(lieux, {
590
688
  version: epingle.version,
591
689
  node,
592
- travailleur: travailleur(),
593
690
  chemin,
594
691
  outils,
595
692
  });
@@ -612,19 +709,14 @@ function travailleurDeLUnite(texte) {
612
709
  // (`…/<version>/node_modules/@roomi-fields/grillhouse/…`); null when neither reads.
613
710
  function versionDuTravailleur(travailleur) {
614
711
  const paquet = path.resolve(travailleur, '../../..');
615
- const cache = `${path.sep}node_modules${path.sep}@roomi-fields${path.sep}grillhouse`;
616
- try {
617
- const v = JSON.parse(readFileSync(path.join(paquet, 'package.json'), 'utf8')).version;
618
- if (typeof v === 'string' && v) {
619
- return v;
620
- }
621
- }
622
- catch {
623
- // no package.json: the folder of the published version
712
+ const v = versionDuPaquet(paquet);
713
+ if (v !== null) {
714
+ return v;
624
715
  }
716
+ const cache = `${path.sep}node_modules${path.sep}@roomi-fields${path.sep}grillhouse`;
625
717
  if (paquet.endsWith(cache)) {
626
- const v = path.basename(paquet.slice(0, -cache.length));
627
- return /^\d+\.\d+\.\d+/.test(v) ? v : null;
718
+ const d = path.basename(paquet.slice(0, -cache.length));
719
+ return /^\d+\.\d+\.\d+/.test(d) ? d : null;
628
720
  }
629
721
  return null;
630
722
  }
@@ -653,43 +745,80 @@ function racineDeLUnite(texte) {
653
745
  const v = ligne.slice('WorkingDirectory='.length);
654
746
  return /^".*"$/.test(v) ? v.slice(1, -1).replace(/\\(.)/g, '$1') : v;
655
747
  }
748
+ // The highest version the account installed on the machine, read without the server: of the
749
+ // versions the applied instances of the machine name and, while it stands, of the worker of the unit
750
+ // of before the template; null without any.
751
+ function plusHauteDeLaMachine(lieux, appliquees) {
752
+ const versions = instancesDe(appliquees, GABARIT_DE_LA_MACHINE).map(i => i.version);
753
+ const f = path.join(lieux.unites, uniteDAvant(GABARIT_DE_LA_MACHINE));
754
+ if (existsSync(f)) {
755
+ const t = travailleurDeLUnite(readFileSync(f, 'utf8'));
756
+ const v = t === null ? null : versionDuTravailleur(t);
757
+ if (v !== null) {
758
+ versions.push(v);
759
+ }
760
+ }
761
+ return versions.reduce((h, v) => (h === null || auMoins(v, h) ? v : h), null);
762
+ }
763
+ // The line of the server's unit that carries the version of the frame that wrote it; systemd ignores
764
+ // a key prefixed by `X-` (systemd.unit(5)).
765
+ const CLE_DE_LA_VERSION = 'X-Grillhouse-Version=';
766
+ const LIGNE_DE_LA_VERSION = new RegExp(`^${CLE_DE_LA_VERSION}(.*)\n`, 'm');
767
+ // The server's unit <texte> written by the version <version>, in its [Unit] section.
768
+ const marquer = (texte, version) => texte.replace('[Unit]\n', () => `[Unit]\n${CLE_DE_LA_VERSION}${version}\n`);
769
+ const sansVersion = (texte) => texte.replace(LIGNE_DE_LA_VERSION, '');
770
+ // The version that wrote the server's unit standing at the places <lieux>, when it is later than
771
+ // <version>; null without a unit, without a version in it, or when <version> is at least it.
772
+ function serveurPlusNeuf(lieux, version) {
773
+ const f = path.join(lieux.unites, UNITE_DU_SERVEUR);
774
+ const ecrite = existsSync(f) ? LIGNE_DE_LA_VERSION.exec(readFileSync(f, 'utf8'))?.[1] : undefined;
775
+ return ecrite !== undefined && !auMoins(version, ecrite) ? ecrite : null;
776
+ }
777
+ // Whether the server's unit <texte> differs from the applied one by its version alone: the unit
778
+ // standing is the one systemd applied (<somme>), the same but for that line.
779
+ function seuleLaVersion(lieux, texte, somme) {
780
+ const f = path.join(lieux.unites, UNITE_DU_SERVEUR);
781
+ if (!existsSync(f)) {
782
+ return false;
783
+ }
784
+ const pose = readFileSync(f, 'utf8');
785
+ return somme === sommeDe(pose) && sansVersion(pose) === sansVersion(texte);
786
+ }
656
787
  /**
657
- * The texts of <textes> the project at <lieux> answers for: its own units, and the unit of the
658
- * machine while that unit is its own. The worker of the machine is the account's, one for every
659
- * project, as one agent of a cluster serves every job; its unit belongs to the project that wrote
660
- * it (its WorkingDirectory), which answers for its whole text (Node, PATH, tools) and for what
661
- * systemd applied of it. Another project takes it only to raise it: when it plays an earlier
662
- * version of the frame than that project's, when its version does not read, or when the project
663
- * it belongs to is gone. So the worker of the machine plays the highest version a project of the
664
- * account installed, whatever the order of the installations.
788
+ * The texts of <textes> the project at <lieux>, which installs <version>, answers for: the server,
789
+ * marked with that version, unless a later version wrote the one standing; its own template; and
790
+ * the template of the machine while it is its own. The server is the account's, replaced only by a
791
+ * version at least as late as the one that wrote it. The template of the machine
792
+ * is the account's, one for every project, as one agent of a cluster serves every job; it belongs
793
+ * to the project that wrote it (its WorkingDirectory), which answers for its whole text (Node,
794
+ * PATH, tools). Another project takes it only to raise the version the machine plays (<plusHaute>),
795
+ * or once the project it belongs to is gone.
665
796
  */
666
- function textesDuProjet(lieux, textes) {
667
- const f = path.join(lieux.unites, UNITE_DE_LA_MACHINE);
797
+ function textesDuProjet(lieux, textes, version, plusHaute) {
798
+ const { [UNITE_DU_SERVEUR]: serveur, ...gabarits } = textes;
799
+ const duProjet = serveurPlusNeuf(lieux, version) === null
800
+ ? { [UNITE_DU_SERVEUR]: marquer(serveur, version), ...gabarits }
801
+ : gabarits;
802
+ const f = path.join(lieux.unites, GABARIT_DE_LA_MACHINE);
668
803
  if (!existsSync(f)) {
669
- return textes;
804
+ return duProjet;
670
805
  }
671
- const posee = readFileSync(f, 'utf8');
672
- const racine = racineDeLUnite(posee);
806
+ const racine = racineDeLUnite(readFileSync(f, 'utf8'));
673
807
  if (racine === null || path.resolve(racine) === lieux.racine || !existsSync(racine)) {
674
- return textes;
808
+ return duProjet;
675
809
  }
676
- const version = (texte) => {
677
- const t = travailleurDeLUnite(texte);
678
- return t === null ? null : versionDuTravailleur(t);
679
- };
680
- const [tenue, voulue] = [version(posee), version(textes[UNITE_DE_LA_MACHINE] ?? '')];
681
- if (tenue === null || voulue === null || !auMoins(tenue, voulue)) {
682
- return textes;
810
+ if (plusHaute === null || !auMoins(plusHaute, version)) {
811
+ return duProjet;
683
812
  }
684
- return Object.fromEntries(Object.entries(textes).filter(([n]) => n !== UNITE_DE_LA_MACHINE));
813
+ return Object.fromEntries(Object.entries(duProjet).filter(([n]) => n !== GABARIT_DE_LA_MACHINE));
685
814
  }
686
815
  /**
687
- * Whether the worker the account runs is stale: the units applied by `installer` (the sums of
688
- * unites-appliquees.json) differ from the texts `installer` would write now, for the version
689
- * `grillhouse.outil` names (its worker deduced from its folder in the cache of the home, nothing
690
- * laid down) or, without the key, for the repository's. Without an applied state, false: the
691
- * initial deployment is not a rise. Any error of the computation (a tool not found) is stale, as
692
- * `installer` refuses it by its name. It plays nothing and writes nothing.
816
+ * Whether the worker the account runs is stale: a unit applied by `installer` (the sums of
817
+ * unites-appliquees.json) differs from the text `installer` would write now, or the instance of the
818
+ * version the project installs (`grillhouse.outil`, else its installed package) is not among them;
819
+ * nothing laid down. Without an applied state, false: the initial deployment is not a rise. Any
820
+ * error of the computation (a tool not found) is stale, as `installer` refuses it by its name. It
821
+ * plays nothing and writes nothing.
693
822
  */
694
823
  export function travailleurPerime({ lieux, epingle = EPINGLE, node, trouver, }) {
695
824
  const deja = lireLesAppliquees(cheminsDe(lieux, epingle.version).appliquees);
@@ -697,14 +826,11 @@ export function travailleurPerime({ lieux, epingle = EPINGLE, node, trouver, })
697
826
  return false;
698
827
  }
699
828
  try {
700
- const { textes } = textesAttendus({
701
- lieux,
702
- epingle,
703
- node,
704
- trouver,
705
- travailleur: () => travailleurDe(lieux.racine, v => path.join(cacheDesOutils(lieux.maison), v), false),
706
- });
707
- return Object.entries(textesDuProjet(lieux, textes)).some(([n, t]) => deja[n] !== sommeDe(t));
829
+ const { textes } = textesAttendus({ lieux, epingle, node, trouver });
830
+ const { version } = versionDuProjet(lieux.racine);
831
+ const duProjet = textesDuProjet(lieux, textes, version, plusHauteDeLaMachine(lieux, deja));
832
+ return (!(instanceDe(gabaritDuProjet(lieux.racine), version) in deja) ||
833
+ Object.entries(duProjet).some(([n, t]) => deja[n] !== sommeDe(t)));
708
834
  }
709
835
  catch {
710
836
  return true;
@@ -728,8 +854,8 @@ function serveurArrete(systemctl, jouer, geste, suite) {
728
854
  * not answer within 30 s is a failure.
729
855
  */
730
856
  async function compterSurLeServeur(requete) {
731
- const { ouvrirLeClient } = await import('./client.js');
732
- const ouvert = ouvrirLeClient({ adresse: `127.0.0.1:${PORT_DU_SERVEUR}`, espace: 'default' });
857
+ const { adresseDuServeur, ouvrirLeClient } = await import('./client.js');
858
+ const ouvert = ouvrirLeClient({ adresse: adresseDuServeur(), espace: 'default' });
733
859
  try {
734
860
  const { client } = ouvert;
735
861
  return await client.connection.withDeadline(Date.now() + 30_000, async () => {
@@ -764,23 +890,24 @@ export function texteDeLaPurge(r) {
764
890
  */
765
891
  export async function purger({ lieux, systemctl, epingle = EPINGLE, circuitsEnVol = () => circuitsEnVolDuServeur(cheminsDe(lieux, epingle.version).programme), compter = compterSurLeServeur, temporal = jouerTemporal, retirer = retirerLesOrphelins, compacter = compacterLaBase, maintenant = Date.now, attendre = ms => new Promise(fin => setTimeout(fin, ms)), }) {
766
892
  const { programme, donnees } = cheminsDe(lieux, epingle.version);
767
- const refuserSousUnVol = (suite) => {
768
- const vols = circuitsEnVol();
893
+ const refuserSousUnVol = async (suite) => {
894
+ const vols = await circuitsEnVol();
769
895
  if (vols.length) {
770
896
  throw new Error(`temporal : circuits en vol (${vols.join(', ')}) ; ${suite}, à rejouer quand ils sont arrêtés.`);
771
897
  }
772
898
  };
773
- refuserSousUnVol('rien n’est purgé');
899
+ await refuserSousUnVol('rien n’est purgé');
774
900
  // One cutoff for the whole purge: what closes meanwhile stays within the retention.
775
901
  const limite = new Date(maintenant() - RETENTION_EN_HEURES * 3_600_000).toISOString();
776
902
  const requete = `ExecutionStatus != 'Running' AND CloseTime < '${limite}'`;
777
903
  const supprimes = await compter(requete);
778
904
  if (supprimes > 0) {
905
+ const { adresseDuServeur } = await import('./client.js');
779
906
  const r = temporal(programme, [
780
907
  'workflow',
781
908
  'delete',
782
909
  '--address',
783
- `127.0.0.1:${PORT_DU_SERVEUR}`,
910
+ adresseDuServeur(),
784
911
  '--namespace',
785
912
  'default',
786
913
  '--query',
@@ -809,7 +936,7 @@ export async function purger({ lieux, systemctl, epingle = EPINGLE, circuitsEnVo
809
936
  if (!existsSync(donnees)) {
810
937
  return { supprimes };
811
938
  }
812
- refuserSousUnVol('la suppression est faite, ni les orphelins retirés ni la base compactée');
939
+ await refuserSousUnVol('la suppression est faite, ni les orphelins retirés ni la base compactée');
813
940
  let geste = `le retrait des historiques orphelins de la base ${donnees}`;
814
941
  const retrait = serveurArrete(systemctl, () => {
815
942
  const { orphelins, avant } = retirer(donnees);
@@ -819,34 +946,521 @@ export async function purger({ lieux, systemctl, epingle = EPINGLE, circuitsEnVo
819
946
  systemd(systemctl, ['start', UNITE_DU_SERVEUR]);
820
947
  return { supprimes, ...retrait };
821
948
  }
822
- /** Installs the account's Temporal at the places <lieux> (see the header). */
823
- export async function installer({ lieux, systemctl, epingle = EPINGLE, plateforme = plateformeDe(), obtenir = telecharger, node = process.execPath, outil = v => installerLOutil(v, { cache: cacheDesOutils(lieux.maison) }).dossier, travailleur, trouver = nom => trouverDansLePath(nom), circuitsEnVol = () => circuitsEnVolDuServeur(cheminsDe(lieux, epingle.version).programme), compacter = compacterLaBase, file = laFileDuServeur(), }) {
949
+ // Whether the unit <unite> runs.
950
+ const tourne = (systemctl, unite) => systemctl(['is-active', unite]).stdout.trim() === 'active';
951
+ // A reading of the server, or null when it does not answer.
952
+ const lu = (lecture) => lecture.catch(() => null);
953
+ // Whether the process of the unit <unite> holds one of the activities <tenues>, by the identity a
954
+ // worker takes from the SDK (`<pid>@<host>`).
955
+ function tientUneActivite(systemctl, unite, tenues) {
956
+ const pid = Number(systemctl(['show', '--property=MainPID', '--value', unite]).stdout.trim());
957
+ return pid > 0 && tenues.includes(`${pid}@${os.hostname()}`);
958
+ }
959
+ // The drop-ins of the unit of before the template <gabarit>, each with its path in the folder of
960
+ // that unit (`depart`) and in the folder of the template (`arrivee`).
961
+ function complementsDe(lieux, gabarit) {
962
+ const depart = path.join(lieux.unites, `${uniteDAvant(gabarit)}.d`);
963
+ const arrivee = path.join(lieux.unites, `${gabarit}.d`);
964
+ if (!existsSync(depart)) {
965
+ return [];
966
+ }
967
+ return readdirSync(depart, { withFileTypes: true })
968
+ .filter(f => f.name.endsWith('.conf') && !f.isDirectory())
969
+ .map(f => ({ depart: path.join(depart, f.name), arrivee: path.join(arrivee, f.name) }))
970
+ .sort((a, b) => a.depart.localeCompare(b.depart));
971
+ }
972
+ const memeContenu = ({ depart, arrivee }) => readFileSync(depart).equals(readFileSync(arrivee));
973
+ // Copies to the folder of the template the drop-ins of each unit of before the template that stands,
974
+ // among the templates this pass plays. A file is laid down whole, by a rename: a copy cut short is
975
+ // never taken for another drop-in of the same name. A name already there is never overwritten.
976
+ function copierLesComplements(lieux, joueLaMachine) {
977
+ const copies = [];
978
+ const conflits = [];
979
+ for (const { gabarit, file } of gabaritsDe(lieux.racine)) {
980
+ if ((file === FILE_DE_LA_MACHINE && !joueLaMachine) ||
981
+ !existsSync(path.join(lieux.unites, uniteDAvant(gabarit)))) {
982
+ continue;
983
+ }
984
+ for (const c of complementsDe(lieux, gabarit)) {
985
+ if (existsSync(c.arrivee)) {
986
+ if (!memeContenu(c)) {
987
+ conflits.push(c);
988
+ }
989
+ continue;
990
+ }
991
+ mkdirSync(path.dirname(c.arrivee), { recursive: true });
992
+ const partiel = `${c.arrivee}.partiel`;
993
+ writeFileSync(partiel, readFileSync(c.depart));
994
+ renameSync(partiel, c.arrivee);
995
+ copies.push(c);
996
+ }
997
+ }
998
+ return { copies, conflits };
999
+ }
1000
+ // Removes the former drop-ins of the unit of before the template <gabarit> whose copy the folder of
1001
+ // the template holds, then their folder once empty; those it removed.
1002
+ function retirerLesComplements(lieux, gabarit) {
1003
+ const deplaces = complementsDe(lieux, gabarit).filter(c => existsSync(c.arrivee) && memeContenu(c));
1004
+ for (const { depart } of deplaces) {
1005
+ rmSync(depart);
1006
+ }
1007
+ const dossier = path.join(lieux.unites, `${uniteDAvant(gabarit)}.d`);
1008
+ if (existsSync(dossier) && readdirSync(dossier).length === 0) {
1009
+ rmdirSync(dossier);
1010
+ }
1011
+ return deplaces;
1012
+ }
1013
+ /**
1014
+ * Stops, disables and removes from the units applied each instance that may leave, then the units of
1015
+ * before the template with their drop-ins (see the header); the units retired, those a started
1016
+ * activity retains, and the drop-ins moved.
1017
+ */
1018
+ async function retirerLesInstances({ lieux, systemctl, serveur, version, joueLaMachine, appliquees, enregistrer, }) {
1019
+ const retirees = [];
1020
+ const retenues = [];
1021
+ const deplaces = [];
1022
+ let tenues;
1023
+ // Retires <unite> unless its process holds an activity; kept when the server does not say them.
1024
+ // A unit of before the template names its template and its file.
1025
+ const retirer = async (unite, davant) => {
1026
+ const activites = await (tenues ??= lu(serveur.activitesTenues()));
1027
+ if (activites === null) {
1028
+ return;
1029
+ }
1030
+ if (tientUneActivite(systemctl, unite, activites)) {
1031
+ retenues.push(unite);
1032
+ return;
1033
+ }
1034
+ systemd(systemctl, ['disable', '--now', unite]);
1035
+ if (davant) {
1036
+ // The drop-ins first: a failure leaves the file, which the next pass retires.
1037
+ deplaces.push(...retirerLesComplements(lieux, davant.gabarit));
1038
+ rmSync(davant.fichier, { force: true });
1039
+ }
1040
+ delete appliquees[unite];
1041
+ enregistrer();
1042
+ retirees.push(unite);
1043
+ };
1044
+ for (const { gabarit, file } of gabaritsDe(lieux.racine)) {
1045
+ const autres = instancesDe(appliquees, gabarit).filter(i => i.version !== version);
1046
+ const deploiement = autres.length ? await lu(serveur.lire(file)) : null;
1047
+ if (deploiement === null) {
1048
+ continue;
1049
+ }
1050
+ const { courante, versions } = deploiement;
1051
+ for (const i of autres) {
1052
+ const etat = versions[i.version];
1053
+ // On the queue of the machine, a version never current leaves only when it is lower than the
1054
+ // current one: a higher one is a rise another project still has to make current.
1055
+ const jamais = etat === 'jamais-courante' &&
1056
+ (file !== FILE_DE_LA_MACHINE || (courante !== null && !auMoins(i.version, courante)));
1057
+ if (i.version !== courante && (etat === 'drainee' || jamais)) {
1058
+ await retirer(i.unite);
1059
+ }
1060
+ }
1061
+ }
1062
+ let fichierRetire = false;
1063
+ for (const { gabarit, file } of gabaritsDe(lieux.racine)) {
1064
+ const unite = uniteDAvant(gabarit);
1065
+ const fichier = path.join(lieux.unites, unite);
1066
+ if ((file === FILE_DE_LA_MACHINE && !joueLaMachine) ||
1067
+ !existsSync(fichier) ||
1068
+ (await lu(serveur.lire(file)))?.courante !== version) {
1069
+ continue;
1070
+ }
1071
+ await retirer(unite, { gabarit, fichier });
1072
+ fichierRetire ||= !existsSync(fichier);
1073
+ }
1074
+ if (fichierRetire) {
1075
+ systemd(systemctl, ['daemon-reload']);
1076
+ }
1077
+ return { retirees, retenues, deplaces };
1078
+ }
1079
+ // The command line of each living process of the machine, from /proc; a process that ends during
1080
+ // the reading has none.
1081
+ function processusDeLaMachine() {
1082
+ return readdirSync('/proc')
1083
+ .filter(n => /^\d+$/.test(n))
1084
+ .flatMap(n => {
1085
+ try {
1086
+ return [readFileSync(`/proc/${n}/cmdline`, 'utf8').split('\0').filter(Boolean)];
1087
+ }
1088
+ catch (e) {
1089
+ if (['ENOENT', 'ESRCH'].includes(e.code ?? '')) {
1090
+ return [];
1091
+ }
1092
+ throw e;
1093
+ }
1094
+ });
1095
+ }
1096
+ // The tickets of the project at <racine> whose circuit the account's server holds.
1097
+ const circuitsTenusDuCompte = async (racine) => {
1098
+ const { adresseDuServeur } = await import('./client.js');
1099
+ return ticketsTenus(racine, { adresse: adresseDuServeur(), espace: 'default' });
1100
+ };
1101
+ // The closed tickets of the project at <racine>, by bd.
1102
+ function ticketsFermesDuProjet(racine) {
1103
+ const fermes = ticketsDuStatut(racine, 'closed');
1104
+ if (fermes === null) {
1105
+ throw new Error('bd list ne répond pas');
1106
+ }
1107
+ return [...fermes];
1108
+ }
1109
+ // A message as one line of the report.
1110
+ const enUneLigne = (e) => (e instanceof Error ? e.message : String(e)).replace(/\s+/g, ' ').trim();
1111
+ // What <lecture> gives, or null when the file or folder is not there; any other fault is thrown.
1112
+ function siLa(lecture) {
1113
+ try {
1114
+ return lecture();
1115
+ }
1116
+ catch (e) {
1117
+ if (['ENOENT', 'ENOTDIR'].includes(e.code ?? '')) {
1118
+ return null;
1119
+ }
1120
+ throw e;
1121
+ }
1122
+ }
1123
+ // The version of the frame the tree at <racine> names: its key, else the package it installed;
1124
+ // null without either; a faulty key is thrown.
1125
+ const versionNommee = (racine) => versionDeLOutil(racine) ?? versionDuPaquet(path.join(racine, PAQUET_INSTALLE));
1126
+ // Whether the folder <dossier> stands in a git repository.
1127
+ function sousGit(dossier) {
1128
+ return (existsSync(path.join(dossier, '.git')) ||
1129
+ (path.dirname(dossier) !== dossier && sousGit(path.dirname(dossier))));
1130
+ }
1131
+ // The units of the account: the versions they name, and the projects of the machine, the pass's
1132
+ // own and those the worker units lead to, while their folder stands.
1133
+ function lireLesUnites(lieux, appliquees, versionsDans, { nommer, bloquer }) {
1134
+ const racines = new Set([lieux.racine]);
1135
+ try {
1136
+ const texte = siLa(() => readFileSync(appliquees, 'utf8'));
1137
+ for (const unite of Object.keys(JSON.parse(texte ?? '{}'))) {
1138
+ const v = /@(.+)\.service$/.exec(unite)?.[1];
1139
+ if (v) {
1140
+ nommer(v, `unité appliquée ${unite}`);
1141
+ }
1142
+ }
1143
+ }
1144
+ catch (e) {
1145
+ bloquer(`les unités appliquées (${appliquees}) ne se lisent pas (${enUneLigne(e)})`);
1146
+ }
1147
+ try {
1148
+ for (const f of siLa(() => readdirSync(lieux.unites, { withFileTypes: true })) ?? []) {
1149
+ if (f.isDirectory() || !f.name.endsWith('.service')) {
1150
+ continue;
1151
+ }
1152
+ const texte = siLa(() => readFileSync(path.join(lieux.unites, f.name), 'utf8'));
1153
+ if (texte === null) {
1154
+ continue;
1155
+ }
1156
+ for (const v of versionsDans(texte.replace(/\\(.)/g, '$1'))) {
1157
+ nommer(v, `fichier d'unité ${f.name}`);
1158
+ }
1159
+ const racine = f.name.startsWith('grillhouse-travailleur-') ? racineDeLUnite(texte) : null;
1160
+ if (racine !== null) {
1161
+ racines.add(racine);
1162
+ }
1163
+ }
1164
+ }
1165
+ catch (e) {
1166
+ bloquer(`les unités du compte (${lieux.unites}) ne se lisent pas (${enUneLigne(e)})`);
1167
+ }
1168
+ return [...racines].filter(racine => {
1169
+ try {
1170
+ return siLa(() => statSync(racine)) !== null;
1171
+ }
1172
+ catch (e) {
1173
+ bloquer(`le projet ${racine} ne se lit pas (${enUneLigne(e)})`);
1174
+ return false;
1175
+ }
1176
+ });
1177
+ }
1178
+ // The versions the copies of a circuit not finished name, among the copies of the project at
1179
+ // <racine>.
1180
+ async function lireLesCopies(racine, { circuitsTenus, ticketsFermes }, { nommer, bloquer, signaler }) {
1181
+ let copies;
1182
+ try {
1183
+ copies = sousGit(racine)
1184
+ ? copiesListees(racine)
1185
+ .slice(1)
1186
+ .map(c => c.chemin)
1187
+ : [];
1188
+ }
1189
+ catch (e) {
1190
+ bloquer(`les copies du projet ${racine} ne se listent pas (${enUneLigne(e)})`);
1191
+ return;
1192
+ }
1193
+ if (!copies.length) {
1194
+ return;
1195
+ }
1196
+ let tenus;
1197
+ try {
1198
+ tenus = await circuitsTenus(racine);
1199
+ }
1200
+ catch (e) {
1201
+ bloquer(`le serveur Temporal ne dit pas les circuits qu'il tient du projet ${racine} (${enUneLigne(e)})`);
1202
+ return;
1203
+ }
1204
+ let fermes;
1205
+ const estFerme = (ticket) => {
1206
+ if (!fermes) {
1207
+ try {
1208
+ fermes = new Set(ticketsFermes(racine));
1209
+ }
1210
+ catch (e) {
1211
+ fermes = new Set();
1212
+ signaler(`les tickets du projet ${racine} ne se lisent pas (${enUneLigne(e)}), ses copies au dossier .travail gardent leurs versions`);
1213
+ }
1214
+ }
1215
+ return fermes.has(ticket);
1216
+ };
1217
+ for (const copie of copies) {
1218
+ const ticket = path.basename(copie);
1219
+ if (!tenus.includes(ticket) && !(existsSync(`${copie}.travail`) && !estFerme(ticket))) {
1220
+ continue;
1221
+ }
1222
+ try {
1223
+ const v = versionNommee(copie);
1224
+ if (v !== null) {
1225
+ nommer(v, `copie ${copie} (ticket ${ticket})`);
1226
+ }
1227
+ }
1228
+ catch (e) {
1229
+ bloquer(`la copie ${copie} du ticket ${ticket} ne dit pas sa version : ${enUneLigne(e)}`);
1230
+ }
1231
+ }
1232
+ }
1233
+ // The size of the files under <chemin>, in bytes; what does not read counts for nothing.
1234
+ function tailleDe(chemin) {
1235
+ try {
1236
+ const s = lstatSync(chemin);
1237
+ return s.isDirectory()
1238
+ ? readdirSync(chemin).reduce((t, n) => t + tailleDe(path.join(chemin, n)), 0)
1239
+ : s.size;
1240
+ }
1241
+ catch {
1242
+ return 0;
1243
+ }
1244
+ }
1245
+ /** The folder a version leaves under, and the folder of a removal that did not end. */
1246
+ const EN_RETRAIT = /^(\d+\.\d+\.\d+)\.retrait-/;
1247
+ // Removes from the cache <cache> the version <version> (its folder, renamed first, what an
1248
+ // earlier removal left of it, and its failure mark), or, with <restesSeuls>, what an earlier
1249
+ // removal left of a version something names; the size given back.
1250
+ function retirerLaVersion(cache, version, entrees, restesSeuls) {
1251
+ const dossier = path.join(cache, version);
1252
+ const restes = entrees
1253
+ .map(e => e.name)
1254
+ .filter(n => EN_RETRAIT.exec(n)?.[1] === version)
1255
+ .map(n => path.join(cache, n));
1256
+ if (!restesSeuls) {
1257
+ if (existsSync(dossier)) {
1258
+ const ecarte = `${dossier}.retrait-${randomUUID()}`;
1259
+ renameSync(dossier, ecarte);
1260
+ restes.push(ecarte);
1261
+ }
1262
+ rmSync(`${dossier}.echec`, { force: true });
1263
+ }
1264
+ let octets = 0;
1265
+ for (const reste of restes) {
1266
+ const taille = tailleDe(reste);
1267
+ rmSync(reste, { recursive: true, force: true });
1268
+ octets += taille;
1269
+ }
1270
+ return octets;
1271
+ }
1272
+ /**
1273
+ * Removes from the cache of the home each version of the tool nothing names (see the header), as
1274
+ * `brew cleanup` removes the old versions of the installed formulae; its report.
1275
+ */
1276
+ async function purgerLesVersions({ lieux, appliquees, serveur, processus, circuitsTenus, ticketsFermes, }) {
1277
+ const r = {
1278
+ retirees: [],
1279
+ gardees: [],
1280
+ illisibles: [],
1281
+ ticketsIllisibles: [],
1282
+ echecs: [],
1283
+ };
1284
+ const cache = cacheDesOutils(lieux.maison);
1285
+ const entrees = siLa(() => readdirSync(cache, { withFileTypes: true })) ?? [];
1286
+ // The versions installed or marked, and those an earlier removal left a folder of.
1287
+ const presentes = new Set();
1288
+ const aFinir = new Set();
1289
+ for (const e of entrees) {
1290
+ const v = e.isDirectory() ? e.name : /^(.*)\.echec$/.exec(e.name)?.[1];
1291
+ if (v !== undefined && X_Y_Z.test(v)) {
1292
+ presentes.add(v);
1293
+ }
1294
+ const reste = e.isDirectory() ? EN_RETRAIT.exec(e.name)?.[1] : undefined;
1295
+ if (reste !== undefined) {
1296
+ aFinir.add(reste);
1297
+ }
1298
+ }
1299
+ const raisons = new Map();
1300
+ let bloquee = false;
1301
+ const noms = {
1302
+ nommer: (v, raison) => raisons.set(v, (raisons.get(v) ?? new Set()).add(raison)),
1303
+ bloquer: ligne => {
1304
+ bloquee = true;
1305
+ r.illisibles.push(`${ligne} : aucune version retirée`);
1306
+ },
1307
+ };
1308
+ // The versions of the cache a text names by a path under it, the home as written or resolved.
1309
+ const caches = [...new Set([cache, siLa(() => realpathSync(cache)) ?? cache])];
1310
+ const sousLeCache = new RegExp(`(?:${caches.map(c => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})/(\\d+\\.\\d+\\.\\d+)/`, 'g');
1311
+ const versionsDans = (texte) => [...texte.matchAll(sousLeCache)].map(m => m[1]);
1312
+ const racines = lireLesUnites(lieux, appliquees, versionsDans, noms);
1313
+ const files = new Set([FILE_DE_LA_MACHINE]);
1314
+ for (const racine of racines) {
1315
+ files.add(fileDuProjet(racine));
1316
+ try {
1317
+ const v = versionNommee(racine);
1318
+ if (v !== null) {
1319
+ noms.nommer(v, `projet ${racine}`);
1320
+ }
1321
+ }
1322
+ catch (e) {
1323
+ noms.bloquer(`le projet ${racine} ne dit pas sa version : ${enUneLigne(e)}`);
1324
+ }
1325
+ await lireLesCopies(racine, { circuitsTenus, ticketsFermes }, { ...noms, signaler: ligne => r.ticketsIllisibles.push(ligne) });
1326
+ }
1327
+ try {
1328
+ for (const argv of processus()) {
1329
+ for (const v of argv.flatMap(versionsDans)) {
1330
+ noms.nommer(v, 'processus vivant');
1331
+ }
1332
+ }
1333
+ }
1334
+ catch (e) {
1335
+ noms.bloquer(`la liste des processus ne se lit pas (${enUneLigne(e)})`);
1336
+ }
1337
+ for (const file of files) {
1338
+ try {
1339
+ const { courante, versions } = await serveur.lire(file);
1340
+ for (const [v, etat] of Object.entries(versions)) {
1341
+ if (etat !== 'drainee' && etat !== 'jamais-courante') {
1342
+ noms.nommer(v, `déploiement ${file} (${etat})`);
1343
+ }
1344
+ }
1345
+ if (courante !== null) {
1346
+ noms.nommer(courante, `déploiement ${file} (courante)`);
1347
+ }
1348
+ }
1349
+ catch (e) {
1350
+ noms.bloquer(`le serveur Temporal ne dit pas le déploiement ${file} (${enUneLigne(e)})`);
1351
+ }
1352
+ }
1353
+ for (const version of [...new Set([...presentes, ...aFinir])].sort()) {
1354
+ const nommee = raisons.get(version);
1355
+ if (presentes.has(version) && (nommee || bloquee)) {
1356
+ r.gardees.push({
1357
+ version,
1358
+ raisons: nommee ? [...nommee] : ['une source ne se lit pas'],
1359
+ });
1360
+ }
1361
+ // What names a version keeps its folder and its mark; what a removal left of it goes.
1362
+ if (bloquee || (nommee && !aFinir.has(version))) {
1363
+ continue;
1364
+ }
1365
+ try {
1366
+ const reste = nommee !== undefined;
1367
+ r.retirees.push({ version, reste, octets: retirerLaVersion(cache, version, entrees, reste) });
1368
+ }
1369
+ catch (e) {
1370
+ r.echecs.push({ version, raison: enUneLigne(e) });
1371
+ }
1372
+ }
1373
+ return r;
1374
+ }
1375
+ // How long a pass waits between two tries of the lock another pass holds.
1376
+ const ENTRE_DEUX_PRISES_MS = 200;
1377
+ /** Installs the account's Temporal at the places <lieux>, one pass at a time (see the header). */
1378
+ export async function installer(options) {
1379
+ const { verrou } = cheminsDe(options.lieux, (options.epingle ?? EPINGLE).version);
1380
+ const dossier = path.dirname(verrou);
1381
+ // The first folder the lock had to create, which a pass that writes nothing else takes back.
1382
+ let cree;
1383
+ for (;;) {
1384
+ cree = mkdirSync(dossier, { recursive: true }) ?? cree;
1385
+ try {
1386
+ if (prendreVerrou(verrou, { attendre: false })) {
1387
+ break;
1388
+ }
1389
+ }
1390
+ catch (e) {
1391
+ // Another pass took back the folder between the two gestures.
1392
+ if (e.code !== 'ENOENT') {
1393
+ throw e;
1394
+ }
1395
+ }
1396
+ await new Promise(fin => setTimeout(fin, ENTRE_DEUX_PRISES_MS));
1397
+ }
1398
+ try {
1399
+ return await jouerLInstallation(options);
1400
+ }
1401
+ finally {
1402
+ lacherVerrou(verrou);
1403
+ if (cree !== undefined) {
1404
+ retirerLesDossiersVides(dossier, cree);
1405
+ }
1406
+ }
1407
+ }
1408
+ // Removes <dossier> and its parents up to <premier>, each while it is empty.
1409
+ function retirerLesDossiersVides(dossier, premier) {
1410
+ try {
1411
+ rmdirSync(dossier);
1412
+ }
1413
+ catch {
1414
+ return;
1415
+ }
1416
+ if (dossier !== premier) {
1417
+ retirerLesDossiersVides(path.dirname(dossier), premier);
1418
+ }
1419
+ }
1420
+ // The gestures of one pass of installation, under its lock.
1421
+ async function jouerLInstallation({ lieux, systemctl, epingle = EPINGLE, plateforme = plateformeDe(), obtenir = telecharger, node = process.execPath, outil = v => installerLOutil(v, { cache: cacheDesOutils(lieux.maison) }).dossier, trouver = nom => trouverDansLePath(nom), declarations = lieux.racine, circuitsEnVol = () => circuitsEnVolDuServeur(cheminsDe(lieux, epingle.version).programme), compacter = compacterLaBase, serveur = deploiementsDuCompte(), processus = processusDeLaMachine, circuitsTenus = circuitsTenusDuCompte, ticketsFermes = ticketsFermesDuProjet, }) {
824
1422
  const { donnees, appliquees: fichierDesAppliquees } = cheminsDe(lieux, epingle.version);
825
- // Every refusal before any writing: the archive, the account's tools, the project's tools , then the worker of the published version, which lays that
826
- // version down in its cache first.
1423
+ // Every refusal before any writing: the archive, the account's tools, the project's tools, then
1424
+ // the version the project installs, laid down in its cache first.
827
1425
  const { programme, contenu } = await obtenirLeProgramme({ lieux, epingle, plateforme, obtenir });
828
- const { textes: tous } = textesAttendus({
829
- lieux,
830
- epingle,
831
- node,
832
- trouver,
833
- travailleur: () => travailleur ?? travailleurDe(lieux.racine, outil),
834
- });
835
- const duProjet = textesDuProjet(lieux, tous);
1426
+ const { textes: tous } = textesAttendus({ lieux, declarations, epingle, node, trouver });
1427
+ const version = poserLaVersionDuProjet(declarations, outil);
836
1428
  const deja = lireLesAppliquees(fichierDesAppliquees);
1429
+ const plusHaute = plusHauteDeLaMachine(lieux, deja);
1430
+ const joueLaMachine = plusHaute === null || auMoins(version, plusHaute);
1431
+ const duProjet = textesDuProjet(lieux, tous, version, plusHaute);
837
1432
  const enAttenteDe = (t) => Object.keys(t).filter(n => deja[n] !== sommeDe(t[n]));
838
- // The server's unit is applied when a program is laid down, or when it is still to apply.
1433
+ const ecrite = serveurPlusNeuf(lieux, version);
1434
+ // The server's unit is applied when a program is laid down, or when it is still to apply; a later
1435
+ // version alone is told to systemd, which neither stops nor restarts the server for it.
1436
+ const versionSeule = duProjet[UNITE_DU_SERVEUR] !== undefined &&
1437
+ seuleLaVersion(lieux, duProjet[UNITE_DU_SERVEUR], deja[UNITE_DU_SERVEUR]);
1438
+ const aRedemarrer = (t) => UNITE_DU_SERVEUR in t &&
1439
+ (contenu !== null || (!versionSeule && enAttenteDe(t).includes(UNITE_DU_SERVEUR)));
839
1440
  // Before any writing: a circuit in flight defers the server's unit alone (its stop, its
840
1441
  // compaction), which a later run applies; the program is laid down all the same, in a directory
841
- // of its own version, and the workers' units, which name it, are applied, since neither stops
842
- // the server.
843
- const differe = contenu !== null || enAttenteDe(duProjet).includes(UNITE_DU_SERVEUR) ? circuitsEnVol() : [];
1442
+ // of its own version, and the templates, which name it, are applied, since neither stops the
1443
+ // server.
1444
+ const differe = aRedemarrer(duProjet) ? await circuitsEnVol() : [];
844
1445
  const textes = differe.length
845
1446
  ? Object.fromEntries(Object.entries(duProjet).filter(([n]) => n !== UNITE_DU_SERVEUR))
846
1447
  : duProjet;
847
1448
  const pose = contenu !== null;
848
1449
  const enAttente = enAttenteDe(textes);
849
- const serveurApplique = (pose && differe.length === 0) || enAttente.includes(UNITE_DU_SERVEUR);
1450
+ const redemarre = aRedemarrer(textes);
1451
+ const appliquees = redemarre ? [...new Set([UNITE_DU_SERVEUR, ...enAttente])] : enAttente;
1452
+ // The instances this pass installs, those still to start or to record, and the running ones a
1453
+ // changed template leaves under its former text; read before any gesture.
1454
+ const visees = gabaritsDe(lieux.racine)
1455
+ .filter(g => g.file !== FILE_DE_LA_MACHINE || joueLaMachine)
1456
+ .map(g => ({ ...g, unite: instanceDe(g.gabarit, version) }));
1457
+ const aDemarrer = visees
1458
+ .map(v => ({ ...v, marche: tourne(systemctl, v.unite) }))
1459
+ .filter(v => !v.marche || !(v.unite in deja));
1460
+ const sousLAncienTexte = gabaritsDe(lieux.racine)
1461
+ .filter(g => enAttente.includes(g.gabarit) && g.gabarit in deja)
1462
+ .flatMap(g => instancesDe(deja, g.gabarit).map(i => i.unite))
1463
+ .filter(u => tourne(systemctl, u));
850
1464
  if (contenu) {
851
1465
  poser(contenu, programme);
852
1466
  }
@@ -861,51 +1475,94 @@ export async function installer({ lieux, systemctl, epingle = EPINGLE, plateform
861
1475
  writeFileSync(f, texte);
862
1476
  unites.push(nom);
863
1477
  }
864
- // A program newly laid down starts again the units of this project, the machine's when it is
865
- // its own.
866
- const appliquees = pose ? Object.keys(textes) : enAttente;
1478
+ // The sums of this project's units, beside those of the other projects of the account.
1479
+ const sommes = { ...deja };
1480
+ const enregistrer = () => {
1481
+ mkdirSync(path.dirname(fichierDesAppliquees), { recursive: true });
1482
+ writeFileSync(fichierDesAppliquees, `${JSON.stringify(sommes, null, 2)}\n`);
1483
+ };
1484
+ // Before any instance starts, and before systemd reads the units again.
1485
+ const { copies, conflits } = copierLesComplements(lieux, joueLaMachine);
1486
+ if (appliquees.length || copies.length) {
1487
+ systemd(systemctl, ['daemon-reload']);
1488
+ }
867
1489
  let compactage;
868
1490
  if (appliquees.length) {
869
- systemd(systemctl, ['daemon-reload']);
870
- systemd(systemctl, ['enable', ...unitesDe(lieux.racine).filter(n => appliquees.includes(n))]);
871
- if (serveurApplique) {
872
- // The server stopped, its database compacted, then every unit applied started again; without
873
- // a database file there is nothing to compact, and the server is not stopped.
1491
+ if (redemarre) {
1492
+ systemd(systemctl, ['enable', UNITE_DU_SERVEUR]);
1493
+ // The server stopped, its database compacted, then started again; without a database file
1494
+ // there is nothing to compact, and the server is not stopped.
874
1495
  if (existsSync(donnees)) {
875
1496
  compactage = serveurArrete(systemctl, () => compacter(donnees), () => `le compactage de la base ${donnees}`, "l'unité sera appliquée au prochain passage");
876
1497
  }
1498
+ systemd(systemctl, ['restart', UNITE_DU_SERVEUR]);
877
1499
  }
878
- systemd(systemctl, ['restart', ...appliquees]);
879
- mkdirSync(path.dirname(fichierDesAppliquees), { recursive: true });
880
- // The sums of this project's units, beside those of the other projects of the account.
881
- const sommes = {
882
- ...deja,
883
- ...Object.fromEntries(Object.entries(textes).map(([n, t]) => [n, sommeDe(t)])),
884
- };
885
- writeFileSync(fichierDesAppliquees, `${JSON.stringify(sommes, null, 2)}\n`);
1500
+ for (const n of appliquees) {
1501
+ sommes[n] = sommeDe(textes[n]);
1502
+ }
1503
+ enregistrer();
1504
+ }
1505
+ for (const { gabarit, unite } of aDemarrer) {
1506
+ systemd(systemctl, ['enable', '--now', unite]);
1507
+ // An instance is recorded under the template it started under.
1508
+ sommes[unite] = sommeDe(readFileSync(path.join(lieux.unites, gabarit), 'utf8'));
1509
+ enregistrer();
886
1510
  }
887
- // The queue restarts under the installed code: the worker's unit restarts first when this pass
888
- // did not.
889
- const unite = uniteDuProjet(lieux.racine);
890
- const { file: etatDeLaFile, ...versions } = await relancerLaFile(file, lieux.racine, versionInstallee(travailleur ?? travailleurDe(lieux.racine, outil)), () => {
891
- if (!appliquees.includes(unite)) {
892
- systemd(systemctl, ['restart', unite]);
1511
+ const demarrees = aDemarrer.filter(v => !v.marche).map(v => v.unite);
1512
+ // Current only once its instance started.
1513
+ const courantes = [];
1514
+ for (const { file, unite } of visees) {
1515
+ if ((await lu(serveur.lire(file)))?.courante === version) {
1516
+ continue;
893
1517
  }
1518
+ await serveur.rendreCourante(file, version);
1519
+ courantes.push(unite);
1520
+ }
1521
+ const { retirees, retenues, deplaces } = await retirerLesInstances({
1522
+ lieux,
1523
+ systemctl,
1524
+ serveur,
1525
+ version,
1526
+ joueLaMachine,
1527
+ appliquees: sommes,
1528
+ enregistrer,
1529
+ });
1530
+ // The last gesture: the version installed is current and the instances are retired.
1531
+ const versions = await purgerLesVersions({
1532
+ lieux,
1533
+ appliquees: fichierDesAppliquees,
1534
+ serveur,
1535
+ processus,
1536
+ circuitsTenus,
1537
+ ticketsFermes,
894
1538
  });
895
1539
  return {
896
1540
  programme,
897
1541
  pose,
898
1542
  unites,
899
1543
  appliquees,
1544
+ demarrees,
1545
+ courantes,
1546
+ retirees,
1547
+ retenues,
1548
+ sousLAncienTexte,
1549
+ complements: { copies, deplaces, conflits },
900
1550
  change: pose ||
901
- unites.length > 0 ||
902
- appliquees.length > 0 ||
903
1551
  differe.length > 0 ||
904
- etatDeLaFile !== AUCUNE_FILE,
905
- file: etatDeLaFile,
906
- ...versions,
1552
+ [
1553
+ unites,
1554
+ appliquees,
1555
+ copies,
1556
+ demarrees,
1557
+ courantes,
1558
+ retirees,
1559
+ versions.retirees,
1560
+ versions.echecs,
1561
+ ].some(l => l.length > 0),
1562
+ versions,
907
1563
  ...(compactage ? { compactage } : {}),
908
1564
  ...(differe.length ? { serveurDiffere: differe } : {}),
1565
+ ...(ecrite === null ? {} : { serveurPlusNeuf: { ecrite, installee: version } }),
909
1566
  };
910
1567
  }
911
1568
  //# sourceMappingURL=installation.js.map