@antelopejs/dms 0.17.0 → 0.18.1

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 (71) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +7 -11
  3. package/bin/control/backend-records.test.mjs +276 -0
  4. package/bin/control/backend.mjs +212 -0
  5. package/bin/control/backend.test.mjs +325 -0
  6. package/bin/control/base.mjs +3 -7
  7. package/bin/control/browser-client.mjs +6 -4
  8. package/bin/control/browser.mjs +173 -36
  9. package/bin/control/build-cache.mjs +394 -0
  10. package/bin/control/build-cache.test.mjs +270 -0
  11. package/bin/control/build-inputs.mjs +172 -0
  12. package/bin/control/build-key-refusals.test.mjs +138 -0
  13. package/bin/control/build-key.mjs +479 -0
  14. package/bin/control/build-key.test.mjs +392 -0
  15. package/bin/control/build-layout.test.mjs +314 -0
  16. package/bin/control/commands-stack.mjs +46 -6
  17. package/bin/control/commands-verify.mjs +9 -2
  18. package/bin/control/doctor.mjs +87 -16
  19. package/bin/control/forwarder.mjs +86 -0
  20. package/bin/control/forwarder.test.mjs +141 -0
  21. package/bin/control/frontend-check.mjs +54 -0
  22. package/bin/control/frontend-workspace.mjs +150 -0
  23. package/bin/control/frontend-workspace.test.mjs +133 -0
  24. package/bin/control/helpers/env.mjs +21 -0
  25. package/bin/control/helpers/evidence.mjs +13 -0
  26. package/bin/control/helpers/fake-run.mjs +290 -0
  27. package/bin/control/helpers/key-fixture.mjs +82 -0
  28. package/bin/control/helpers/pids.mjs +27 -0
  29. package/bin/control/helpers/repo.mjs +13 -0
  30. package/bin/control/helpers/tree.mjs +40 -0
  31. package/bin/control/identity.mjs +238 -0
  32. package/bin/control/identity.test.mjs +166 -0
  33. package/bin/control/journey.mjs +64 -16
  34. package/bin/control/journey.test.mjs +60 -2
  35. package/bin/control/namespaces.test.mjs +211 -0
  36. package/bin/control/options.mjs +2 -0
  37. package/bin/control/pid-guard.test.mjs +202 -0
  38. package/bin/control/prepared-workspace.mjs +20 -0
  39. package/bin/control/processes.mjs +122 -33
  40. package/bin/control/processes.test.mjs +255 -0
  41. package/bin/control/renderer.test.mjs +2 -1
  42. package/bin/control/run-copy.mjs +77 -0
  43. package/bin/control/run-state.mjs +142 -16
  44. package/bin/control/stack.mjs +259 -210
  45. package/bin/control/tab.mjs +13 -6
  46. package/bin/control/tab.test.mjs +444 -0
  47. package/bin/control/timing.mjs +244 -0
  48. package/bin/control/timing.test.mjs +197 -0
  49. package/bin/control/verify/decode.mjs +34 -21
  50. package/bin/control/verify/decode.test.mjs +39 -0
  51. package/bin/control/verify/doors.test.mjs +2 -0
  52. package/bin/control/verify/map.mjs +57 -7
  53. package/bin/control/verify/map.test.mjs +264 -0
  54. package/bin/control/verify/skill.mjs +12 -3
  55. package/bin/control/verify/types.mjs +2 -2
  56. package/bin/control/verify/verdict.mjs +37 -7
  57. package/bin/dms-control.mjs +14 -6
  58. package/dist/config/internal/state.d.ts +2 -2
  59. package/dist/config/internal/state.js.map +1 -1
  60. package/dist/utils/sign-in-country.d.ts +0 -1
  61. package/dist/utils/sign-in-country.js +7 -17
  62. package/dist/utils/sign-in-country.js.map +1 -1
  63. package/frontend-vue/layers/dms-layout/app/components/layout/DashboardSearch.vue +24 -1
  64. package/frontend-vue/layers/dms-layout/app/composables/layout/usePageHeaderActions.ts +1 -1
  65. package/frontend-vue/package.json +1 -1
  66. package/frontend-vue/scripts/check-autoimport-boundaries.mjs +19 -3
  67. package/frontend-vue/scripts/test-autoimport-boundaries.mjs +19 -0
  68. package/package.json +5 -5
  69. package/skills/dms-project/SKILL.md +6 -3
  70. package/data/NOTICE.md +0 -12
  71. package/data/dbip-country-lite.mmdb +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,70 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.18.1
4
+
5
+ [compare changes](https://github.com/AntelopeJS/dms/compare/v0.18.0...v0.18.1)
6
+
7
+ ### 🚀 Enhancements
8
+
9
+ - **verify-dms:** Run every feature when a shared file changes ([#783](https://github.com/AntelopeJS/dms/pull/783))
10
+ - **dms-control:** Record per-phase timings of a verify run ([#784](https://github.com/AntelopeJS/dms/pull/784))
11
+
12
+ ### 🔥 Performance
13
+
14
+ - **dms-control:** Stop the previous journey's backend at once ([#785](https://github.com/AntelopeJS/dms/pull/785))
15
+ - **ci:** Scan the playground import fixtures together ([#791](https://github.com/AntelopeJS/dms/pull/791))
16
+ - **dms-control:** Start the next journey's backend while the current one runs ([#788](https://github.com/AntelopeJS/dms/pull/788))
17
+ - **docs:** Capture the documentation screenshots in parallel ([#792](https://github.com/AntelopeJS/dms/pull/792))
18
+ - **dms-control:** Reuse the frontend build of unchanged sources ([#787](https://github.com/AntelopeJS/dms/pull/787))
19
+ - **dms-control:** Take screenshots on checks and failures only ([#786](https://github.com/AntelopeJS/dms/pull/786))
20
+
21
+ ### 🩹 Fixes
22
+
23
+ - **dms-control:** Refuse to signal a pid that is not a whole number above 1 ([#789](https://github.com/AntelopeJS/dms/pull/789))
24
+ - **ci:** Check the scanner exit status per diagnostic kind in the import test ([#793](https://github.com/AntelopeJS/dms/pull/793))
25
+
26
+ ### 📖 Documentation
27
+
28
+ - **dms:** Start the quickstart with the dms-starter template ([#782](https://github.com/AntelopeJS/dms/pull/782))
29
+
30
+ ### ❤️ Contributors
31
+
32
+ - Antony Rizzitelli ([@Upd4ting](http://github.com/Upd4ting))
33
+
34
+ ## v0.18.0
35
+
36
+ [compare changes](https://github.com/AntelopeJS/dms/compare/v0.17.0...v0.18.0)
37
+
38
+ ### 🚀 Enhancements
39
+
40
+ - **dms:** Read the sign-in country without a bundled database ([#776](https://github.com/AntelopeJS/dms/pull/776))
41
+
42
+ ### 🩹 Fixes
43
+
44
+ - **dms-layout:** Re-export usePageHeaderActions by relative path so unimport scans it ([#777](https://github.com/AntelopeJS/dms/pull/777))
45
+
46
+ ### 📖 Documentation
47
+
48
+ - **dms:** Explain what the AntelopeJS agent plugin unlocks, External database included ([#773](https://github.com/AntelopeJS/dms/pull/773))
49
+ - **dms:** Mark the ResourceForm mode and the source tables in the docs examples ([#780](https://github.com/AntelopeJS/dms/pull/780))
50
+
51
+ ### 📦 Build
52
+
53
+ - **deps:** Bump @antelopejs packages to the 2026-11-06 releases ([#781](https://github.com/AntelopeJS/dms/pull/781))
54
+
55
+ ### 🏡 Chore
56
+
57
+ - **dms:** Commit the module locks the test runs record ([#775](https://github.com/AntelopeJS/dms/pull/775))
58
+ - **ci:** Remove the weekly mutation caller ([#778](https://github.com/AntelopeJS/dms/pull/778))
59
+
60
+ ### 🤖 CI
61
+
62
+ - Call ci-node.yml@v1 ([#779](https://github.com/AntelopeJS/dms/pull/779))
63
+
64
+ ### ❤️ Contributors
65
+
66
+ - Antony Rizzitelli ([@Upd4ting](http://github.com/Upd4ting))
67
+
3
68
  ## v0.17.0
4
69
 
5
70
  [compare changes](https://github.com/AntelopeJS/dms/compare/v0.16.2...v0.17.0)
package/README.md CHANGED
@@ -46,8 +46,8 @@ The DMS also needs an API module, a module implementing the database interface,
46
46
  Create a project from the `template-dms-demo` template, which loads the DMS, its companion modules and Helio, a demo back office for a solar installer. It needs the Node.js and pnpm releases the template pins, and a MongoDB on `localhost:27017`.
47
47
 
48
48
  ```bash
49
- npx @antelopejs/core project init my-app --template dms-demo
50
- cd my-app
49
+ npx @antelopejs/core project init dms-demo --template dms-demo
50
+ cd dms-demo
51
51
  pnpm dev # backend on http://localhost:5010
52
52
  ```
53
53
 
@@ -57,7 +57,7 @@ When the backend answers, start the dashboard in a second terminal, from the sam
57
57
  pnpm frontend:dev # dashboard on http://localhost:3001
58
58
  ```
59
59
 
60
- Open the address that the backend logs after `No owner exists yet`, and create the first administrator. The [Quickstart](https://dms.antelopejs.com/docs/getting-started/quickstart) walks through each step. A page is a class whose static fields are blocks:
60
+ Open the address that the backend logs after `No owner exists yet`, and create the first administrator. The [Tutorial](https://dms.antelopejs.com/docs/getting-started/tutorial) builds on this project. To start your own project instead, see [Start your project](https://dms.antelopejs.com/docs/getting-started/quickstart). A page is a class whose static fields are blocks:
61
61
 
62
62
  ```ts
63
63
  import { PageController, RegisterPage, pagesCategory } from "@antelopejs/interface-dms/page";
@@ -79,15 +79,15 @@ export class SalesPage extends PageController("sales", {
79
79
 
80
80
  | Package | Supported | Tested with |
81
81
  | ------------------------------------------- | ------------------ | ----------- |
82
- | `@antelopejs/core` | `>=1.20.0 <2` | `1.20.0` |
82
+ | `@antelopejs/core` | `>=1.21.0 <2` | `1.21.0` |
83
83
  | `@antelopejs/interface-api` | `>=0.2.0 <1.0.0` | `0.2.0` |
84
84
  | `@antelopejs/interface-api-util` | `>=0.3.0 <1.0.0` | `0.3.0` |
85
85
  | `@antelopejs/interface-core` | `>=0.4.0 <1.0.0` | `0.4.0` |
86
86
  | `@antelopejs/interface-data-api` | `>=0.6.0 <1.0.0` | `0.6.0` |
87
- | `@antelopejs/interface-database` | `>=0.3.0 <1.0.0` | `0.3.0` |
88
- | `@antelopejs/interface-database-decorators` | `>=0.2.0 <1.0.0` | `0.2.0` |
87
+ | `@antelopejs/interface-database` | `>=0.3.0 <1.0.0` | `0.3.1` |
88
+ | `@antelopejs/interface-database-decorators` | `>=0.2.0 <1.0.0` | `0.2.1` |
89
89
  | `@antelopejs/interface-dms` | `>=0.12.0 <0.13.0` | `0.12.0` |
90
- | `@antelopejs/interface-dms-automation` | `>=0.6.0 <1.0.0` | `0.6.0` |
90
+ | `@antelopejs/interface-dms-automation` | `>=0.6.0 <1.0.0` | `0.6.1` |
91
91
  | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` | `0.0.6` |
92
92
  | `@antelopejs/interface-file-storage` | `>=0.1.4 <1.0.0` | `0.1.4` |
93
93
  | `@antelopejs/interface-redis` | `>=0.0.9 <1.0.0` | `0.0.9` |
@@ -114,10 +114,6 @@ The package ships the core Claude Code skills (`dms`, `dms-auth`, `dms-best-prac
114
114
 
115
115
  This package lives in the [`AntelopeJS/dms`](https://github.com/AntelopeJS/dms) pnpm workspace, next to `@antelopejs/interface-dms`. Read [CONTRIBUTING.md](https://github.com/AntelopeJS/dms/blob/main/CONTRIBUTING.md) and the [repository README](https://github.com/AntelopeJS/dms#contributing) for the development commands.
116
116
 
117
- ## Third-party data
118
-
119
- The package ships the DB-IP IP to Country Lite database (`data/`) to tell which country a sign-in came from. It is licensed under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/): IP Geolocation by [DB-IP](https://db-ip.com). `pnpm country-database` downloads the current edition; packing the package for a release runs it.
120
-
121
117
  ## License
122
118
 
123
119
  [Apache-2.0](./LICENSE)
@@ -0,0 +1,276 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { setTimeout as sleep } from "node:timers/promises";
7
+ import { freshDatabase, restartBackend } from "./backend.mjs";
8
+ import { doctor } from "./doctor.mjs";
9
+ import {
10
+ bystander,
11
+ newRun,
12
+ running,
13
+ served,
14
+ startedOn,
15
+ withoutStartTimes,
16
+ } from "./helpers/fake-run.mjs";
17
+ import { canChoosePid, chooseNextPid } from "./helpers/pids.mjs";
18
+ import { isRunning } from "./identity.mjs";
19
+ import { startDetached } from "./processes.mjs";
20
+ import { backendsFolder, recordBackend } from "./run-state.mjs";
21
+ import { down, liveBackends } from "./stack.mjs";
22
+
23
+ const SIX_DAYS_MS = 6 * 24 * 60 * 60 * 1000;
24
+
25
+ /**
26
+ * What the code writes to stderr during the test, kept off the terminal.
27
+ *
28
+ * @param {import("node:test").TestContext} t The test
29
+ * @returns {() => string} The text written so far
30
+ */
31
+ function stderrOf(t) {
32
+ const write = t.mock.method(process.stderr, "write", () => true);
33
+ return () =>
34
+ write.mock.calls.map((call) => String(call.arguments[0])).join("");
35
+ }
36
+
37
+ await test("a process that took the pid of a backend the run recorded is not stopped, even with that backend's database in its environment", async (t) => {
38
+ const state = await newRun(t);
39
+ await freshDatabase(state, "j001");
40
+ const database = `${state.databasePrefix}_j002`;
41
+ const standby = await startedOn(database);
42
+ const record = liveBackends(state).find(
43
+ (backend) => backend.pid === standby.pid,
44
+ );
45
+ assert.ok(record, "the standby is recorded");
46
+ const other = bystander(t, { ...process.env, MONGO_DATABASE: database });
47
+ recordBackend(state.dir, { ...record, pid: other });
48
+ await freshDatabase(state, "r1");
49
+ assert.equal(isRunning(other), true);
50
+ await down(state);
51
+ assert.equal(isRunning(other), true);
52
+ assert.deepEqual(running(), []);
53
+ });
54
+
55
+ await test("a process that took the pid of a process run.json records is not stopped by a restart or by down", async (t) => {
56
+ const state = await newRun(t);
57
+ await freshDatabase(state, "j001");
58
+ const serving = state.processes.find((entry) => entry.name === "backend");
59
+ assert.ok(serving, "run.json records the backend");
60
+ const other = bystander(t, {
61
+ ...process.env,
62
+ MONGO_DATABASE: state.database,
63
+ });
64
+ const reused = { ...serving, pid: other };
65
+ state.processes = state.processes.map((entry) =>
66
+ entry === serving ? reused : entry,
67
+ );
68
+ await restartBackend(state);
69
+ assert.equal(isRunning(other), true);
70
+ assert.equal((await served(state)).database, state.database);
71
+ state.processes = [...state.processes, { ...reused, name: "frontend" }];
72
+ await down(state);
73
+ assert.equal(isRunning(other), true);
74
+ assert.deepEqual(running(), []);
75
+ });
76
+
77
+ await test("a backend record removed while the records are read counts as gone", async (t) => {
78
+ const state = await newRun(t);
79
+ await freshDatabase(state, "j001");
80
+ const serving = await served(state);
81
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
82
+ symlinkSync(
83
+ join(state.dir, "removed.json"),
84
+ join(backendsFolder(state.dir), "4242.json"),
85
+ );
86
+ const stderr = stderrOf(t);
87
+ assert.deepEqual(
88
+ liveBackends(state)
89
+ .map((backend) => backend.pid)
90
+ .toSorted((a, b) => a - b),
91
+ [serving.pid, standby.pid].toSorted((a, b) => a - b),
92
+ );
93
+ assert.equal(stderr(), "");
94
+ });
95
+
96
+ await test("a backend record that holds no record is skipped and named, and the run still moves on and stops", async (t) => {
97
+ const state = await newRun(t);
98
+ await freshDatabase(state, "j001");
99
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
100
+ const file = join(backendsFolder(state.dir), "77777.json");
101
+ writeFileSync(file, '{"name":"backend","pid":77');
102
+ const stderr = stderrOf(t);
103
+ await freshDatabase(state, "j002");
104
+ assert.equal((await served(state)).pid, standby.pid);
105
+ await down(state);
106
+ assert.deepEqual(running(), []);
107
+ assert.ok(stderr().includes(file), stderr());
108
+ });
109
+
110
+ await test("a backend record whose pid is not a process id above 1 is forgotten, and no call to process.kill reaches it", async (t) => {
111
+ const state = await newRun(t);
112
+ await freshDatabase(state, "j001");
113
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
114
+ const record = liveBackends(state).find(
115
+ (backend) => backend.pid === standby.pid,
116
+ );
117
+ assert.ok(record, "the standby is recorded");
118
+ for (const pid of [-1, 0, 1]) {
119
+ recordBackend(state.dir, { ...record, pid, startTime: null });
120
+ }
121
+ const original = process.kill.bind(process);
122
+ /** @type {typeof process.kill} */
123
+ const passOnAbove1 = (pid, signal) =>
124
+ Math.abs(pid) > 1 ? original(pid, signal) : true;
125
+ const kill = t.mock.method(process, "kill", passOnAbove1);
126
+ await down(state);
127
+ const targets = kill.mock.calls.map((call) => Math.abs(call.arguments[0]));
128
+ assert.notDeepEqual(targets, []);
129
+ assert.deepEqual(
130
+ targets.filter((pid) => pid <= 1),
131
+ [],
132
+ );
133
+ assert.deepEqual(running(), []);
134
+ });
135
+
136
+ /**
137
+ * A process the run records as a backend on `database` that never answers.
138
+ * `down` stops it with the run.
139
+ *
140
+ * @param {import("./run-state.mjs").RunState} state The run
141
+ * @param {string} database The database its record names
142
+ * @returns {import("./run-state.mjs").BackendRecord} Its record
143
+ */
144
+ function silentBackend(state, database) {
145
+ const started = startDetached({
146
+ name: `silent${database.slice(state.databasePrefix.length)}`,
147
+ program: process.execPath,
148
+ args: ["-e", "setInterval(() => {}, 1000)"],
149
+ cwd: state.dir,
150
+ env: process.env,
151
+ logs: state.logs,
152
+ });
153
+ const backend = { ...started, name: "backend", port: 1, database };
154
+ recordBackend(state.dir, backend);
155
+ return backend;
156
+ }
157
+
158
+ /**
159
+ * @param {import("./run-state.mjs").RunState} state The run
160
+ * @returns {import("./run-state.mjs").ProcessRecord} The forwarder run.json records
161
+ */
162
+ function forwarderOf(state) {
163
+ const api = state.processes.find((entry) => entry.name === "api");
164
+ assert.ok(api, "run.json records the forwarder");
165
+ return api;
166
+ }
167
+
168
+ await test("a run.json record without a start time, as an earlier dms-control wrote, is stopped by down only while its pid runs a process started when the record says; a version that trusts the pid alone stops a process started days later", async (t) => {
169
+ const state = await newRun(t);
170
+ const later = bystander(t);
171
+ const own = bystander(t);
172
+ const now = new Date();
173
+ /**
174
+ * @param {string} name
175
+ * @param {number} pid
176
+ * @param {Date} at
177
+ */
178
+ const recorded = (name, pid, at) => ({
179
+ name,
180
+ pid,
181
+ command: "a process an earlier dms-control started",
182
+ cwd: state.dir,
183
+ log: join(state.logs, `${name}.log`),
184
+ startedAt: at.toISOString(),
185
+ });
186
+ state.processes = [
187
+ recorded("frontend", later, new Date(now.getTime() - SIX_DAYS_MS)),
188
+ recorded("mail", own, now),
189
+ ];
190
+ await down(state);
191
+ assert.equal(isRunning(later), true);
192
+ assert.equal(isRunning(own), false);
193
+ });
194
+
195
+ await test("a backend record without a start time, as this branch wrote before, is stopped by down; a version that skips such a record leaves the standby running", async (t) => {
196
+ const state = await newRun(t);
197
+ await freshDatabase(state, "j001");
198
+ await startedOn(`${state.databasePrefix}_j002`);
199
+ assert.equal(withoutStartTimes(state), 2);
200
+ assert.equal(liveBackends(state).length, 2);
201
+ await down(state);
202
+ assert.deepEqual(running(), []);
203
+ });
204
+
205
+ await test(
206
+ "a recorded backend that exits while a fresh database waits for the standby, and whose pid another process takes, is not signalled; a version that kills from the list it read before the wait kills that process",
207
+ {
208
+ skip:
209
+ !canChoosePid() &&
210
+ "choosing the next pid needs a PID namespace the test owns",
211
+ },
212
+ async (t) => {
213
+ const state = await newRun(t);
214
+ await freshDatabase(state, "j001");
215
+ const waitedFor = silentBackend(state, `${state.databasePrefix}_j003`);
216
+ const exits = silentBackend(state, `${state.databasePrefix}_j009`);
217
+ const pending = freshDatabase(state, "j003");
218
+ process.kill(exits.pid, "SIGKILL");
219
+ while (existsSync(`/proc/${exits.pid}`)) await sleep(20);
220
+ chooseNextPid(exits.pid);
221
+ const taker = spawn(
222
+ process.execPath,
223
+ ["-e", "setInterval(() => {}, 1000)"],
224
+ { stdio: "ignore" },
225
+ );
226
+ t.after(() => taker.kill());
227
+ assert.equal(taker.pid, exits.pid, "another process took the pid");
228
+ const original = process.kill.bind(process);
229
+ /** @type {typeof process.kill} */
230
+ const sparesTaker = (pid, signal) =>
231
+ Math.abs(pid) === taker.pid && signal !== 0
232
+ ? true
233
+ : original(pid, signal);
234
+ const kill = t.mock.method(process, "kill", sparesTaker);
235
+ process.kill(waitedFor.pid, "SIGKILL");
236
+ await pending;
237
+ assert.deepEqual(
238
+ kill.mock.calls
239
+ .map((call) => call.arguments)
240
+ .filter(([pid, signal]) => Math.abs(pid) === taker.pid && signal !== 0),
241
+ [],
242
+ );
243
+ assert.equal(
244
+ (await served(state)).database,
245
+ `${state.databasePrefix}_j003`,
246
+ );
247
+ },
248
+ );
249
+
250
+ await test("a forwarder that exited, whose pid another process holds, is started again and the API answers; a version that trusts a live pid leaves the API port closed", async (t) => {
251
+ const state = await newRun(t);
252
+ await freshDatabase(state, "j001");
253
+ const api = forwarderOf(state);
254
+ process.kill(api.pid, "SIGKILL");
255
+ while (isRunning(api.pid)) await sleep(20);
256
+ const other = bystander(t);
257
+ state.processes = state.processes.map((entry) =>
258
+ entry === api ? { ...api, pid: other } : entry,
259
+ );
260
+ await freshDatabase(state, "j002");
261
+ assert.equal((await served(state)).database, `${state.databasePrefix}_j002`);
262
+ assert.equal(isRunning(other), true);
263
+ });
264
+
265
+ await test("doctor fails a recorded process whose pid another process holds; a version that checks only that the pid is alive passes it", async (t) => {
266
+ const state = await newRun(t);
267
+ await freshDatabase(state, "j001");
268
+ const api = forwarderOf(state);
269
+ const other = bystander(t);
270
+ state.processes = [...state.processes, { ...api, name: "mail", pid: other }];
271
+ const lines = await doctor(state);
272
+ const okOf = (/** @type {string} */ check) =>
273
+ lines.find((line) => line.check === check)?.ok;
274
+ assert.equal(okOf(`api pid ${api.pid} alive`), true);
275
+ assert.equal(okOf(`mail pid ${other} alive`), false);
276
+ });
@@ -0,0 +1,212 @@
1
+ import { buildChangedSince, missingBuildRoot } from "./build-inputs.mjs";
2
+ import { apiTargetFile, readTarget, writeTarget } from "./forwarder.mjs";
3
+ import { dropDatabase } from "./mongo.mjs";
4
+ import { killRecorded, stopRecorded } from "./processes.mjs";
5
+ import {
6
+ ensureApi,
7
+ launchBackend,
8
+ liveBackends,
9
+ record,
10
+ resolutionFolders,
11
+ startBackend,
12
+ waitForBackend,
13
+ } from "./stack.mjs";
14
+ import { recordTiming, stopwatch, timed } from "./timing.mjs";
15
+
16
+ /** @typedef {import("./run-state.mjs").RunState} RunState */
17
+ /** @typedef {import("./run-state.mjs").BackendRecord} BackendRecord */
18
+
19
+ /**
20
+ * Refuses a run whose backend holds the API port itself: an earlier
21
+ * dms-control started it, with no forwarder to move the API between
22
+ * backends.
23
+ *
24
+ * @param {RunState} state The run
25
+ * @throws When an earlier dms-control started the run
26
+ */
27
+ export function assertForwardedRun(state) {
28
+ if (
29
+ state.processes.some(
30
+ (entry) => entry.name === "backend" && entry.port === state.apiPort,
31
+ )
32
+ ) {
33
+ throw new Error(
34
+ "this run was started by an older dms-control; run `up` again",
35
+ );
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Stops the backend and starts it again on `state.database`, as a deploy or
41
+ * a crash would, from the run's build or another one (`build`, the base
42
+ * version's). The API keeps its port and reaches the new backend once it
43
+ * answers. A backend whose pid now runs another process has exited, and
44
+ * nothing is stopped for it.
45
+ *
46
+ * @param {RunState} state The run
47
+ * @param {{ playground: string, cwd: string }} [build] Another build to start
48
+ * @returns {Promise<void>} Resolves once the backend answers again
49
+ */
50
+ export async function restartBackend(state, build) {
51
+ const backend = state.processes.find((entry) => entry.name === "backend");
52
+ if (backend) {
53
+ await timed(state, "backend-stop", () => stopRecorded([backend]));
54
+ }
55
+ await timed(state, "backend-start", () => startBackend(state, build));
56
+ }
57
+
58
+ /**
59
+ * Drops the databases the run no longer uses: neither the one it serves
60
+ * nor the one `up` started on, which `down` drops.
61
+ *
62
+ * @param {RunState} state
63
+ * @param {string[]} databases
64
+ */
65
+ async function dropUnused(state, databases) {
66
+ for (const database of new Set(databases)) {
67
+ if (database === state.databasePrefix || database === state.database) {
68
+ continue;
69
+ }
70
+ await dropDatabase(state.mongoUrl, database, resolutionFolders(state));
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Kills backends without a grace period, each only while its pid still
76
+ * runs the backend recorded, timed as `backend-stop` when there is one.
77
+ *
78
+ * @param {RunState} state
79
+ * @param {BackendRecord[]} backends
80
+ */
81
+ async function killBackends(state, backends) {
82
+ if (backends.length === 0) return;
83
+ await timed(state, "backend-stop", () => killRecorded(backends));
84
+ }
85
+
86
+ /**
87
+ * Kills backends, then drops their databases.
88
+ *
89
+ * @param {RunState} state
90
+ * @param {BackendRecord[]} backends
91
+ */
92
+ async function retire(state, backends) {
93
+ await killBackends(state, backends);
94
+ await dropUnused(
95
+ state,
96
+ backends.map((backend) => backend.database),
97
+ );
98
+ }
99
+
100
+ /**
101
+ * The suffix after `suffix`: its trailing number plus one, padded alike
102
+ * (`j004` after `j003`), or `null` when it ends in no number.
103
+ *
104
+ * @param {string} suffix A database suffix
105
+ * @returns {string | null} The next one
106
+ */
107
+ function nextSuffix(suffix) {
108
+ const match = /^(.*?)(\d+)$/.exec(suffix);
109
+ if (!match) return null;
110
+ const [, stem, digits] = match;
111
+ return `${stem}${String(Number(digits) + 1).padStart(digits.length, "0")}`;
112
+ }
113
+
114
+ /**
115
+ * Whether a standby can take over `database`: it was started on it, it
116
+ * answers, and nothing of the run's build changed since it started. The
117
+ * wait is timed as `standby-promote`, failed when the standby is not taken.
118
+ *
119
+ * @param {RunState} state
120
+ * @param {BackendRecord} standby
121
+ * @param {string} database
122
+ * @returns {Promise<boolean>}
123
+ */
124
+ async function fits(state, standby, database) {
125
+ if (standby.database !== database) return false;
126
+ const stop = stopwatch();
127
+ const answers = await waitForBackend(standby).then(
128
+ () => true,
129
+ () => false,
130
+ );
131
+ const fit = answers && buildChangedSince(state, standby.startedAt) === null;
132
+ recordTiming(state, "standby-promote", stop(), fit);
133
+ return fit;
134
+ }
135
+
136
+ /**
137
+ * A backend that answers on `database`: the standby when it fits, else one
138
+ * started now. Every other backend the API does not forward to is killed
139
+ * first and its database dropped.
140
+ *
141
+ * @param {RunState} state
142
+ * @param {string} database
143
+ * @returns {Promise<BackendRecord>}
144
+ */
145
+ async function backendOn(state, database) {
146
+ const target = readTarget(apiTargetFile(state.dir));
147
+ const spares = liveBackends(state).filter(
148
+ (backend) => backend.port !== target,
149
+ );
150
+ const standby = spares.find((backend) => backend.database === database);
151
+ if (standby && (await fits(state, standby, database))) {
152
+ await retire(
153
+ state,
154
+ spares.filter((backend) => backend !== standby),
155
+ );
156
+ return standby;
157
+ }
158
+ await retire(state, spares);
159
+ return timed(state, "backend-start", async () => {
160
+ const backend = await launchBackend(state, database);
161
+ await waitForBackend(backend);
162
+ return backend;
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Moves the run onto an empty database of its own, `<prefix>_<suffix>`,
168
+ * served by a backend that has served nothing else: not onboarded, no user,
169
+ * no session, nothing in memory. That backend is the standby the previous
170
+ * call started when it was started on this database, answers, and nothing
171
+ * of the build changed since it started; else one started now. The API
172
+ * points at it before every other backend is killed. Then the standby for
173
+ * the next suffix starts, unless the run was started with `--no-standby`,
174
+ * and the previous journey database is dropped, so a long run does not
175
+ * exhaust mongod's file handles; its evidence stays.
176
+ *
177
+ * @param {RunState} state The run
178
+ * @param {string} suffix What tells the database apart, such as `j003`
179
+ * @returns {Promise<string>} The database now in use
180
+ * @throws When an earlier dms-control started the run, or a folder of the run's build is missing (a build runs), before it starts or stops anything
181
+ */
182
+ export async function freshDatabase(state, suffix) {
183
+ assertForwardedRun(state);
184
+ const missing = missingBuildRoot(state);
185
+ if (missing) {
186
+ throw new Error(
187
+ `${missing} is missing: the build is not done; finish it, then try again`,
188
+ );
189
+ }
190
+ const previous = state.database;
191
+ const database = `${state.databasePrefix}_${suffix}`;
192
+ const backend = await backendOn(state, database);
193
+ await ensureApi(state);
194
+ writeTarget(apiTargetFile(state.dir), backend.port);
195
+ Object.assign(state, { database, tokens: {}, accounts: {} });
196
+ record(state, backend);
197
+ const replaced = liveBackends(state).filter(
198
+ (other) => other.pid !== backend.pid,
199
+ );
200
+ await killBackends(state, replaced);
201
+ const next = state.noStandby ? null : nextSuffix(suffix);
202
+ if (next) {
203
+ await timed(state, "standby-start", () =>
204
+ launchBackend(state, `${state.databasePrefix}_${next}`),
205
+ );
206
+ }
207
+ await dropUnused(state, [
208
+ previous,
209
+ ...replaced.map((other) => other.database),
210
+ ]);
211
+ return database;
212
+ }