@antelopejs/dms 0.20.0 → 0.20.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 (144) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +19 -12
  3. package/bin/control/backend-mode.test.mjs +41 -1
  4. package/bin/control/backend-records.test.mjs +154 -100
  5. package/bin/control/backend.mjs +1 -1
  6. package/bin/control/backend.test.mjs +4 -1
  7. package/bin/control/base.mjs +6 -1
  8. package/bin/control/build-key-refusals.test.mjs +8 -8
  9. package/bin/control/build-key.mjs +8 -6
  10. package/bin/control/build-key.test.mjs +3 -2
  11. package/bin/control/build-layout.test.mjs +5 -4
  12. package/bin/control/forwarder.test.mjs +19 -11
  13. package/bin/control/helpers/fake-run.mjs +59 -60
  14. package/bin/control/helpers/key-fixture.mjs +1 -1
  15. package/bin/control/helpers/pids.mjs +10 -0
  16. package/bin/control/helpers/tree.mjs +4 -4
  17. package/bin/control/journey.test.mjs +32 -32
  18. package/bin/control/mongo-server.test.mjs +64 -19
  19. package/bin/control/mongo.mjs +12 -3
  20. package/bin/control/namespaces.test.mjs +50 -31
  21. package/bin/control/processes.mjs +13 -1
  22. package/bin/control/processes.test.mjs +98 -64
  23. package/bin/control/renderer.test.mjs +2 -2
  24. package/bin/control/run-ports.test.mjs +24 -9
  25. package/bin/control/stack.mjs +16 -3
  26. package/bin/control/tab.test.mjs +1 -1
  27. package/bin/control/verify/formal.test.mjs +2 -2
  28. package/checks/dms-components.d.mts +38 -0
  29. package/data/mockup-spec.schema.json +4 -2
  30. package/data/module-store/catalog.json +1 -7
  31. package/dist/builder.js +2 -1
  32. package/dist/builder.js.map +1 -1
  33. package/dist/crons/cleanup-user-invites.js +7 -1
  34. package/dist/crons/cleanup-user-invites.js.map +1 -1
  35. package/dist/dev/module-update-notifications.js +2 -4
  36. package/dist/dev/module-update-notifications.js.map +1 -1
  37. package/dist/implementations/dms/dev-handshake.js +2 -5
  38. package/dist/implementations/dms/dev-handshake.js.map +1 -1
  39. package/dist/implementations/dms-auth/index.d.ts +3 -4
  40. package/dist/implementations/dms-auth/index.js +20 -4
  41. package/dist/implementations/dms-auth/index.js.map +1 -1
  42. package/dist/implementations/dms-auth/token-session.d.ts +2 -2
  43. package/dist/implementations/dms-auth/token-session.js +1 -4
  44. package/dist/implementations/dms-auth/token-session.js.map +1 -1
  45. package/dist/implementations/dms-builder/engine/connection-access-config.js +2 -7
  46. package/dist/implementations/dms-builder/engine/connection-access-config.js.map +1 -1
  47. package/dist/implementations/dms-builder/engine/driver-packages.js +4 -1
  48. package/dist/implementations/dms-builder/engine/driver-packages.js.map +1 -1
  49. package/dist/implementations/dms-builder/engine/file-paths.d.ts +3 -0
  50. package/dist/implementations/dms-builder/engine/file-paths.js +18 -0
  51. package/dist/implementations/dms-builder/engine/file-paths.js.map +1 -0
  52. package/dist/implementations/dms-builder/engine/index.d.ts +2 -0
  53. package/dist/implementations/dms-builder/engine/index.js +2 -0
  54. package/dist/implementations/dms-builder/engine/index.js.map +1 -1
  55. package/dist/implementations/dms-builder/engine/inherited-variables.d.ts +2 -0
  56. package/dist/implementations/dms-builder/engine/inherited-variables.js +19 -0
  57. package/dist/implementations/dms-builder/engine/inherited-variables.js.map +1 -0
  58. package/dist/implementations/dms-builder/engine/map-resources.js +1 -1
  59. package/dist/implementations/dms-builder/engine/map-resources.js.map +1 -1
  60. package/dist/implementations/dms-builder/engine/modules.js +3 -5
  61. package/dist/implementations/dms-builder/engine/modules.js.map +1 -1
  62. package/dist/implementations/dms-builder/engine/placement.js +2 -1
  63. package/dist/implementations/dms-builder/engine/placement.js.map +1 -1
  64. package/dist/implementations/dms-builder/engine/project-config-ops.js +2 -1
  65. package/dist/implementations/dms-builder/engine/project-config-ops.js.map +1 -1
  66. package/dist/implementations/dms-builder/engine/project-env.js +5 -0
  67. package/dist/implementations/dms-builder/engine/project-env.js.map +1 -1
  68. package/dist/implementations/dms-builder/engine/project-scaffold.js +18 -8
  69. package/dist/implementations/dms-builder/engine/project-scaffold.js.map +1 -1
  70. package/dist/implementations/dms-builder/engine/theme-app-config.d.ts +1 -1
  71. package/dist/implementations/dms-builder/engine/theme-app-config.js +96 -22
  72. package/dist/implementations/dms-builder/engine/theme-app-config.js.map +1 -1
  73. package/dist/mcp/project-files.js +2 -8
  74. package/dist/mcp/project-files.js.map +1 -1
  75. package/dist/mcp/tools/preview-blocks.js +8 -24
  76. package/dist/mcp/tools/preview-blocks.js.map +1 -1
  77. package/dist/mcp/tools/typecheck.js +2 -5
  78. package/dist/mcp/tools/typecheck.js.map +1 -1
  79. package/dist/mockup/json-schema.js +2 -2
  80. package/dist/mockup/json-schema.js.map +1 -1
  81. package/dist/mockup/sketch-allowlist.d.ts +11 -0
  82. package/dist/mockup/sketch-allowlist.js +368 -0
  83. package/dist/mockup/sketch-allowlist.js.map +1 -0
  84. package/dist/mockup/sketch-css.d.ts +3 -0
  85. package/dist/mockup/sketch-css.js +306 -0
  86. package/dist/mockup/sketch-css.js.map +1 -0
  87. package/dist/mockup/sketch-html.d.ts +7 -0
  88. package/dist/mockup/sketch-html.js +243 -0
  89. package/dist/mockup/sketch-html.js.map +1 -0
  90. package/dist/mockup/sketch-limits.d.ts +1 -0
  91. package/dist/mockup/sketch-limits.js +5 -0
  92. package/dist/mockup/sketch-limits.js.map +1 -0
  93. package/dist/mockup/sketch-scan.d.ts +1 -0
  94. package/dist/mockup/sketch-scan.js +136 -0
  95. package/dist/mockup/sketch-scan.js.map +1 -0
  96. package/dist/mockup/sketch-tokens.d.ts +22 -0
  97. package/dist/mockup/sketch-tokens.js +42 -0
  98. package/dist/mockup/sketch-tokens.js.map +1 -0
  99. package/dist/mockup/sketch.d.ts +19 -1
  100. package/dist/mockup/sketch.js +78 -94
  101. package/dist/mockup/sketch.js.map +1 -1
  102. package/dist/routes/auth/logout.d.ts +2 -2
  103. package/dist/routes/auth/logout.js +3 -9
  104. package/dist/routes/auth/logout.js.map +1 -1
  105. package/dist/routes/auth/refresh.js +6 -8
  106. package/dist/routes/auth/refresh.js.map +1 -1
  107. package/dist/routes/auth/switch-tenant.js +8 -11
  108. package/dist/routes/auth/switch-tenant.js.map +1 -1
  109. package/dist/routes/auth.js +1 -1
  110. package/dist/routes/auth.js.map +1 -1
  111. package/dist/store/registry.js +2 -4
  112. package/dist/store/registry.js.map +1 -1
  113. package/dist/store/tarball.js +12 -6
  114. package/dist/store/tarball.js.map +1 -1
  115. package/dist/utils/index.d.ts +1 -0
  116. package/dist/utils/index.js +1 -0
  117. package/dist/utils/index.js.map +1 -1
  118. package/dist/utils/owner-only-file.d.ts +1 -0
  119. package/dist/utils/owner-only-file.js +60 -0
  120. package/dist/utils/owner-only-file.js.map +1 -0
  121. package/dist/utils/package-manager/index.d.ts +1 -0
  122. package/dist/utils/package-manager/index.js +18 -0
  123. package/dist/utils/package-manager/index.js.map +1 -0
  124. package/dist/utils/package-manager.d.ts +12 -0
  125. package/dist/utils/package-manager.js +28 -0
  126. package/dist/utils/package-manager.js.map +1 -0
  127. package/frontend-vue/layers/dms-auth/app/middleware/auth.ts +11 -7
  128. package/frontend-vue/layers/dms-layout/app/composables/useHeaderActions.ts +4 -4
  129. package/frontend-vue/layers/dms-layout/i18n/locales/layout-en-GB.json +0 -4
  130. package/frontend-vue/layers/dms-layout/i18n/locales/layout-fr-FR.json +0 -4
  131. package/frontend-vue/layers/dms-ui/app/build/utils/sketch.ts +9 -0
  132. package/frontend-vue/package.json +1 -1
  133. package/frontend-vue/scripts/check-autoimport-boundaries.mjs +12 -7
  134. package/frontend-vue/scripts/check-dms-components.mjs +519 -0
  135. package/frontend-vue/scripts/check-invariants.mjs +7 -1
  136. package/frontend-vue/scripts/dms-components-dependencies.mjs +89 -0
  137. package/frontend-vue/scripts/test-dms-components.mjs +255 -0
  138. package/package.json +29 -16
  139. package/skills/dms/REFERENCE.md +1 -1
  140. package/skills/dms/SKILL.md +1 -1
  141. package/skills/dms-module/SKILL.md +1 -1
  142. package/skills/dms-module/cases.json +3 -3
  143. package/skills/dms-project/SKILL.md +1 -1
  144. package/skills/dms-project/scripts/dms-dev.sh +1 -1
@@ -19,7 +19,7 @@ import { namesIn, treeOf } from "./helpers/tree.mjs";
19
19
  import { ExitError } from "./processes.mjs";
20
20
 
21
21
  const PAGE = join("frontend-vue", "page.vue");
22
- const SOURCE = join("frontend-modules", "page");
22
+ const SOURCE = "frontend-modules/page";
23
23
  const REGISTRY = "generated-frontend-modules.json";
24
24
 
25
25
  /**
@@ -92,7 +92,7 @@ function fixture(t) {
92
92
  log("frontend-build");
93
93
  if (!prepared) setUp(workspace, copySources);
94
94
  options.build?.(workspace, prepared);
95
- const page = treeOf(workspace)?.[join(SOURCE, "page.vue")] ?? "";
95
+ const page = treeOf(workspace)?.[`${SOURCE}/page.vue`] ?? "";
96
96
  write(join(workspace, "dist", "index.html"), page);
97
97
  return Promise.resolve();
98
98
  },
@@ -106,7 +106,7 @@ function fixture(t) {
106
106
  workspace,
107
107
  builds,
108
108
  frontendBuild: state.frontendBuild,
109
- served: laidOut[join("dist", "index.html")],
109
+ served: laidOut["dist/index.html"],
110
110
  registry: laidOut[REGISTRY],
111
111
  };
112
112
  };
@@ -339,7 +339,8 @@ await test("an install record above TMPDIR that the key cannot read leaves the r
339
339
  write(record, '{"layoutVersion":5}\n');
340
340
  write(join(outer, "tmp", ".keep"), "");
341
341
  symlinkSync(join(outer, "tmp"), join(outer, "linked-tmp"));
342
- setEnv(t, { TMPDIR: join(outer, "linked-tmp") });
342
+ const linked = join(outer, "linked-tmp");
343
+ setEnv(t, { TMPDIR: linked, TEMP: linked, TMP: linked });
343
344
  const { dir, up } = fixture(t);
344
345
  write(join(dir, "node_modules", ".modules.yaml"), "layoutVersion: 5\n");
345
346
  assert.match(
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawnSync } from "node:child_process";
3
- import { mkdtempSync, rmSync } from "node:fs";
3
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
4
4
  import { createConnection, createServer } from "node:net";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
@@ -247,13 +247,21 @@ await test(
247
247
  },
248
248
  );
249
249
 
250
- await test("a restartable port lies outside the kernel's ephemeral range and is free to listen on", async () => {
251
- const { low, high } = ephemeralRange();
252
- const port = await restartablePort();
253
- assert.ok(
254
- port < low || port > high,
255
- `${port} lies in the ephemeral range ${low}-${high}`,
256
- );
257
- const server = await serveForwarder(port, join(tmpdir(), "unused-target"));
258
- server.close();
259
- });
250
+ await test(
251
+ "a restartable port lies outside the kernel's ephemeral range and is free to listen on",
252
+ {
253
+ skip:
254
+ !existsSync(EPHEMERAL_RANGE_FILE) &&
255
+ "the kernel's ephemeral range is read from /proc",
256
+ },
257
+ async () => {
258
+ const { low, high } = ephemeralRange();
259
+ const port = await restartablePort();
260
+ assert.ok(
261
+ port < low || port > high,
262
+ `${port} lies in the ephemeral range ${low}-${high}`,
263
+ );
264
+ const server = await serveForwarder(port, join(tmpdir(), "unused-target"));
265
+ server.close();
266
+ },
267
+ );
@@ -13,19 +13,29 @@ import { createServer, get } from "node:http";
13
13
  import { tmpdir } from "node:os";
14
14
  import { dirname, join } from "node:path";
15
15
  import { setTimeout as sleep } from "node:timers/promises";
16
- import { arrayOf, decode, isNumber, isString, objectOf } from "../json.mjs";
16
+ import {
17
+ arrayOf,
18
+ decode,
19
+ isNumber,
20
+ isString,
21
+ nullable,
22
+ objectOf,
23
+ } from "../json.mjs";
17
24
  import { isSameProcess, startTimeOf } from "../identity.mjs";
18
- import { freePort } from "../processes.mjs";
19
- import { backendsFolder, createRunFolders, saveRun } from "../run-state.mjs";
25
+ import { freePort, restartablePort, stopRecorded } from "../processes.mjs";
26
+ import {
27
+ backendsFolder,
28
+ createRunFolders,
29
+ readRun,
30
+ saveRun,
31
+ } from "../run-state.mjs";
20
32
  import { down } from "../stack.mjs";
21
33
 
22
34
  /** How many runs the tests made, which tells their databases apart */
23
35
  let runs = 0;
24
36
  const REGISTRY_WAIT_MS = 10_000;
25
- const FIRST_UNPRIVILEGED_PORT = 1024;
26
- const LAST_PORT = 65_535;
27
37
 
28
- /** A backend that answers every request with its pid and the database it was started on, and reports both to the test's registry once it listens, with the \`ajs project\` command that started it. */
38
+ /** A backend that answers every request with its pid and the database it was started on, and reports both to the test's registry once it listens, with the \`ajs project\` command that started it and the module folder its configuration loads the module from (\`DMS_MODULE_ROOT\`, else none). The report stays open while the backend runs, so its end tells the registry the backend is gone. */
29
39
  const FAKE_BACKEND = `
30
40
  const http = require("node:http");
31
41
  const self = JSON.stringify({ pid: process.pid, database: process.env.MONGO_DATABASE });
@@ -36,7 +46,7 @@ const server = http.createServer((request, response) => {
36
46
  server.listen(Number(process.env.PORT), "127.0.0.1", () => {
37
47
  const report = http.request(process.env.FAKE_REGISTRY, { method: "POST" });
38
48
  report.on("error", () => undefined);
39
- report.end(JSON.stringify({ pid: process.pid, database: process.env.MONGO_DATABASE, command: process.argv.slice(3, process.argv.indexOf("-e")).join(" ") }));
49
+ report.write(JSON.stringify({ pid: process.pid, database: process.env.MONGO_DATABASE, command: process.argv.slice(3, process.argv.indexOf("-e")).join(" "), moduleRoot: process.env.DMS_MODULE_ROOT ?? null }) + "\\n");
40
50
  });
41
51
  `;
42
52
 
@@ -72,18 +82,19 @@ const isReported = objectOf({
72
82
  pid: isNumber,
73
83
  database: isString,
74
84
  command: isString,
85
+ moduleRoot: nullable(isString),
75
86
  });
76
87
  const isDropped = arrayOf(isString);
77
88
 
78
- /** @type {{ pid: number, database: string, command: string, startTime: number | null }[]} Every fake backend the tests started, in the order they listened, with the `ajs project` command that started it and the start time that tells it from a later process given its pid */
89
+ /** @type {{ pid: number, database: string, command: string, startTime: number | null, reporting: boolean }[]} Every fake backend the tests started, in the order they listened, with the `ajs project` command that started it, the start time that tells it from a later process given its pid, and whether its report is still open, which tells it from a later process given its pid where there is no start time */
79
90
  const started = [];
80
91
 
81
- const registry = createServer((request, response) => {
92
+ const registry = createServer((request) => {
93
+ request.socket.unref();
82
94
  let body = "";
83
95
  request.on("data", (chunk) => {
84
96
  body += String(chunk);
85
- });
86
- request.on("end", () => {
97
+ if (!body.endsWith("\n")) return;
87
98
  /** @type {unknown} */
88
99
  const parsed = JSON.parse(body);
89
100
  const backend = decode(
@@ -92,57 +103,24 @@ const registry = createServer((request, response) => {
92
103
  "a report",
93
104
  "a pid, database and command",
94
105
  );
95
- started.push({ ...backend, startTime: startTimeOf(backend.pid) });
96
- response.end();
106
+ const entry = {
107
+ ...backend,
108
+ startTime: startTimeOf(backend.pid),
109
+ reporting: true,
110
+ };
111
+ started.push(entry);
112
+ request.socket.once("close", () => {
113
+ entry.reporting = false;
114
+ });
97
115
  });
98
116
  });
117
+ registry.requestTimeout = 0;
99
118
  const registryPort = await freePort();
100
119
  await new Promise((resolve) =>
101
120
  registry.listen(registryPort, "127.0.0.1", resolve),
102
121
  );
103
122
  registry.unref();
104
123
 
105
- /**
106
- * @param {number} port A loopback port
107
- * @returns {Promise<boolean>} Whether a server can listen on it now
108
- */
109
- function canListen(port) {
110
- return new Promise((resolve) => {
111
- const probe = createServer();
112
- probe.once("error", () => resolve(false));
113
- probe.listen(port, "127.0.0.1", () => probe.close(() => resolve(true)));
114
- });
115
- }
116
-
117
- /**
118
- * A free loopback port outside the kernel's ephemeral range. No outgoing
119
- * connection takes it as its source port, so a forwarder the test kills can
120
- * listen on it again: a port from `freePort` can be held by another
121
- * connection's TIME_WAIT by then.
122
- *
123
- * @returns {Promise<number>} The port
124
- */
125
- async function portOutsideEphemeralRange() {
126
- const [low, high] = readFileSync(
127
- "/proc/sys/net/ipv4/ip_local_port_range",
128
- "utf8",
129
- )
130
- .trim()
131
- .split(/\s+/)
132
- .map(Number);
133
- const below = Math.max(low - FIRST_UNPRIVILEGED_PORT, 0);
134
- const above = LAST_PORT - high;
135
- assert.ok(below + above > 0, "some port lies outside the ephemeral range");
136
- for (;;) {
137
- const index = Math.floor(Math.random() * (below + above));
138
- const port =
139
- index < below
140
- ? FIRST_UNPRIVILEGED_PORT + index
141
- : high + 1 + index - below;
142
- if (await canListen(port)) return port;
143
- }
144
- }
145
-
146
124
  /**
147
125
  * The backend started on `database`, once it listens. Fails the test when
148
126
  * none does, so no test signals a pid it made up.
@@ -171,10 +149,29 @@ export async function startedOn(database) {
171
149
  * @returns {Promise<string>} Its command
172
150
  */
173
151
  export async function commandOf(pid) {
152
+ return (await reportOf(pid)).command;
153
+ }
154
+
155
+ /**
156
+ * The module folder the backend `pid` was told to load the module from,
157
+ * once it listens, or `null` when it loads it where its configuration says.
158
+ *
159
+ * @param {number} pid The backend
160
+ * @returns {Promise<string | null>} Its `DMS_MODULE_ROOT`
161
+ */
162
+ export async function moduleRootOfBackend(pid) {
163
+ return (await reportOf(pid)).moduleRoot;
164
+ }
165
+
166
+ /**
167
+ * @param {number} pid The backend
168
+ * @returns {Promise<{ command: string, moduleRoot: string | null }>} What it reported once it listened
169
+ */
170
+ async function reportOf(pid) {
174
171
  const deadline = Date.now() + REGISTRY_WAIT_MS;
175
172
  for (;;) {
176
173
  const backend = started.findLast((entry) => entry.pid === pid);
177
- if (backend) return backend.command;
174
+ if (backend) return backend;
178
175
  assert.ok(Date.now() < deadline, `backend ${pid} reports its command`);
179
176
  await sleep(20);
180
177
  }
@@ -197,10 +194,10 @@ export function bystander(t, env = process.env) {
197
194
  return child.pid;
198
195
  }
199
196
 
200
- /** @returns {number[]} The pids of the fake backends that still run, each only while its pid still runs that backend */
197
+ /** @returns {number[]} The pids of the fake backends that still run, each only while its pid still runs that backend and its report is open */
201
198
  export function running() {
202
199
  return started
203
- .filter((backend) => isSameProcess(backend))
200
+ .filter((backend) => backend.reporting && isSameProcess(backend))
204
201
  .map((backend) => backend.pid)
205
202
  .toSorted((a, b) => a - b);
206
203
  }
@@ -209,8 +206,9 @@ export function running() {
209
206
  * A run whose playground starts the fake backend, with no process yet, and
210
207
  * the files a build writes: the module's `dist`, the `dist` of a workspace
211
208
  * package the playground links, the playground's `dist` and its project
212
- * build, which `up` records as the run's build folders. `down` stops what
213
- * the test started.
209
+ * build, which `up` records as the run's build folders. After the test,
210
+ * `down` stops what the test started, and what `run.json` records stops
211
+ * first, for a test that drives a copy of the run loaded from it.
214
212
  *
215
213
  * @param {import("node:test").TestContext} t The test
216
214
  * @returns {Promise<import("../run-state.mjs").RunState>} The run
@@ -228,7 +226,7 @@ export async function newRun(t) {
228
226
  join(playground, "node_modules/@antelopejs/interface-t"),
229
227
  );
230
228
  const paths = createRunFolders(join(parent, "run"));
231
- const apiPort = await portOutsideEphemeralRange();
229
+ const apiPort = await restartablePort();
232
230
  runs += 1;
233
231
  const prefix = `verify_t${runs}`;
234
232
  const state = {
@@ -264,6 +262,7 @@ export async function newRun(t) {
264
262
  };
265
263
  saveRun(state);
266
264
  t.after(async () => {
265
+ await stopRecorded(readRun(state.dir).processes);
267
266
  await down(state);
268
267
  rmSync(parent, { recursive: true, force: true });
269
268
  });
@@ -18,7 +18,7 @@ import { write } from "./repo.mjs";
18
18
  * @param {import("node:test").TestContext} t The test
19
19
  */
20
20
  export function fixture(t) {
21
- const dir = realpathSync(
21
+ const dir = realpathSync.native(
22
22
  mkdtempSync(join(tmpdir(), "dms-control-build-key-test-")),
23
23
  );
24
24
  t.after(() => rmSync(dir, { recursive: true, force: true }));
@@ -17,6 +17,16 @@ export function canChoosePid() {
17
17
  }
18
18
  }
19
19
 
20
+ /**
21
+ * The pid a process wrote to `file`.
22
+ *
23
+ * @param {string} file The file
24
+ * @returns {number} The pid
25
+ */
26
+ export function pidIn(file) {
27
+ return Number(readFileSync(file, "utf8"));
28
+ }
29
+
20
30
  /**
21
31
  * Makes `pid` the next one the kernel gives a new process, once it is free.
22
32
  *
@@ -1,10 +1,10 @@
1
1
  import { existsSync, readdirSync, readFileSync, readlinkSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { join, posix } from "node:path";
3
3
 
4
4
  /**
5
5
  * What a folder holds, for a test to compare: each file's text and each
6
- * symbolic link's target (as `-> target`), by path, or null when the folder
7
- * does not exist.
6
+ * symbolic link's target (as `-> target`), by its path joined with `/` on
7
+ * every system, or null when the folder does not exist.
8
8
  *
9
9
  * @param {string} folder The folder
10
10
  * @returns {Record<string, string> | null} Its content
@@ -18,7 +18,7 @@ export function treeOf(folder) {
18
18
  for (const entry of readdirSync(join(folder, prefix), {
19
19
  withFileTypes: true,
20
20
  })) {
21
- const name = join(prefix, entry.name);
21
+ const name = posix.join(prefix, entry.name);
22
22
  const path = join(folder, name);
23
23
  if (entry.isSymbolicLink()) content[name] = `-> ${readlinkSync(path)}`;
24
24
  else if (entry.isDirectory()) walk(name);
@@ -1,17 +1,11 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn } from "node:child_process";
3
- import {
4
- chmodSync,
5
- mkdirSync,
6
- mkdtempSync,
7
- rmSync,
8
- writeFileSync,
9
- } from "node:fs";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
10
4
  import { createConnection } from "node:net";
11
5
  import { tmpdir } from "node:os";
12
6
  import { join } from "node:path";
13
7
  import test from "node:test";
14
- import { isSameProcess } from "./identity.mjs";
8
+ import { hasProc, isSameProcess } from "./identity.mjs";
15
9
  import { JourneyContext, runJourney, runJourneyFile } from "./journey.mjs";
16
10
  import { loadJourneys } from "./journey-load.mjs";
17
11
  import { apiTargetFile, writeTarget } from "./forwarder.mjs";
@@ -195,7 +189,7 @@ await test("a run whose backend holds the API port itself is refused before its
195
189
  );
196
190
  });
197
191
 
198
- const FAKE_MONGOD = `#!/usr/bin/env node
192
+ const FAKE_MONGOD = `
199
193
  const { existsSync, readFileSync, writeFileSync } = require("node:fs");
200
194
  const option = (name) => process.argv[process.argv.indexOf(name) + 1];
201
195
  const starts = require("node:path").join(option("--dbpath"), "starts");
@@ -252,15 +246,16 @@ function starts(port) {
252
246
 
253
247
  /**
254
248
  * A run that owns a mongod, a fake one that listens on the port it is given.
249
+ * After the test, its processes and recorded backends stop before its folder
250
+ * is removed, which Windows refuses while a process holds a file there.
255
251
  *
256
252
  * @param {import("node:test").TestContext} t The test
257
253
  * @returns {Promise<{ state: { dir: string, logs: string, mongo: string, processes: import("./run-state.mjs").ProcessRecord[], ownsMongo: boolean }, context: JourneyContext, port: number }>} The run, a journey's context and the mongod's port
258
254
  */
259
255
  async function runOwningMongod(t) {
260
256
  const dir = mkdtempSync(join(tmpdir(), "dms-control-journey-mongod-"));
261
- const binary = join(dir, "mongod");
257
+ const binary = join(dir, "mongod.cjs");
262
258
  writeFileSync(binary, FAKE_MONGOD);
263
- chmodSync(binary, 0o755);
264
259
  for (const [name, source] of [
265
260
  ["mongodb", FAKE_DRIVER],
266
261
  ["mongodb-memory-server-core", "module.exports = {};"],
@@ -285,7 +280,7 @@ async function runOwningMongod(t) {
285
280
  processes: [mongod.record],
286
281
  };
287
282
  t.after(async () => {
288
- await stopRecorded(state.processes);
283
+ await stopRecorded([...state.processes, ...liveBackends(state)]);
289
284
  if (previous === undefined) delete process.env.DMS_CONTROL_MONGOD;
290
285
  else process.env.DMS_CONTROL_MONGOD = previous;
291
286
  rmSync(dir, { recursive: true, force: true });
@@ -353,8 +348,7 @@ function recordedBackend(state, port) {
353
348
  await test("stopping the database kills the standby, which would boot without its database and be promoted, and keeps the backend the API forwards to", async (t) => {
354
349
  const { state, context } = await runOwningMongod(t);
355
350
  const serving = recordedBackend(state, 41001);
356
- const standby = recordedBackend(state, 41002);
357
- t.after(() => stopRecorded([serving, standby]));
351
+ recordedBackend(state, 41002);
358
352
  writeTarget(apiTargetFile(state.dir), serving.port);
359
353
  await context.stopDatabase();
360
354
  assert.deepEqual(
@@ -363,21 +357,27 @@ await test("stopping the database kills the standby, which would boot without it
363
357
  );
364
358
  });
365
359
 
366
- await test("a mongod that cannot take its port while another program holds it fails to start, instead of the run trusting that program", async (t) => {
367
- const { state, context, port } = await runOwningMongod(t);
368
- await context.stopDatabase();
369
- const squatter = startDetached({
370
- name: "squatter",
371
- program: process.execPath,
372
- args: [
373
- "-e",
374
- `require("node:net").createServer((s) => s.end()).listen(${port}, "127.0.0.1")`,
375
- ],
376
- cwd: state.dir,
377
- env: process.env,
378
- logs: state.logs,
379
- });
380
- t.after(() => stopRecorded([squatter]));
381
- await waitForPort(port, squatter, 5_000);
382
- await assert.rejects(context.startDatabase(), /does not listen on/);
383
- });
360
+ await test(
361
+ "a mongod that cannot take its port while another program holds it fails to start, instead of the run trusting that program",
362
+ {
363
+ skip: !hasProc() && "the process that listens on a port is read from /proc",
364
+ },
365
+ async (t) => {
366
+ const { state, context, port } = await runOwningMongod(t);
367
+ await context.stopDatabase();
368
+ const squatter = startDetached({
369
+ name: "squatter",
370
+ program: process.execPath,
371
+ args: [
372
+ "-e",
373
+ `require("node:net").createServer((s) => s.end()).listen(${port}, "127.0.0.1")`,
374
+ ],
375
+ cwd: state.dir,
376
+ env: process.env,
377
+ logs: state.logs,
378
+ });
379
+ t.after(() => stopRecorded([squatter]));
380
+ await waitForPort(port, squatter, 5_000);
381
+ await assert.rejects(context.startDatabase(), /does not listen on/);
382
+ },
383
+ );
@@ -1,5 +1,4 @@
1
1
  import assert from "node:assert/strict";
2
- import { spawnSync } from "node:child_process";
3
2
  import {
4
3
  chmodSync,
5
4
  mkdirSync,
@@ -7,36 +6,83 @@ import {
7
6
  rmSync,
8
7
  writeFileSync,
9
8
  } from "node:fs";
10
- import { tmpdir } from "node:os";
9
+ import { platform, tmpdir } from "node:os";
11
10
  import { dirname, join } from "node:path";
12
11
  import test from "node:test";
13
12
  import { fileURLToPath } from "node:url";
14
13
  import { MongoClient } from "mongodb";
14
+ import { pidIn } from "./helpers/pids.mjs";
15
+ import { isAlive } from "./identity.mjs";
15
16
  import { mongodBinary, startMongod } from "./mongo.mjs";
16
17
  import { stopRecorded } from "./processes.mjs";
17
18
 
18
19
  const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
19
20
 
20
21
  /**
22
+ * A run's folders, removed after the test once its `teardown` stopped what
23
+ * the test started there: Windows removes no file a running process holds,
24
+ * and frees those of a killed one a moment after it ends.
25
+ *
21
26
  * @param {import("node:test").TestContext} t
22
- * @returns {{ root: string, mongo: string, logs: string }} A run's folders, removed after the test
27
+ * @returns {{ root: string, mongo: string, logs: string, teardown: () => Promise<void> }} The folders, and what to run before they are removed
23
28
  */
24
29
  function runFolders(t) {
25
30
  const root = mkdtempSync(join(tmpdir(), "dms-control-mongod-test-"));
26
- t.after(() => rmSync(root, { recursive: true, force: true }));
27
- const paths = { root, mongo: join(root, "mongo"), logs: join(root, "logs") };
31
+ const paths = {
32
+ root,
33
+ mongo: join(root, "mongo"),
34
+ logs: join(root, "logs"),
35
+ teardown: () => Promise.resolve(),
36
+ };
37
+ t.after(async () => {
38
+ await paths.teardown();
39
+ rmSync(root, { recursive: true, force: true, maxRetries: 10 });
40
+ });
28
41
  mkdirSync(paths.logs);
29
42
  return paths;
30
43
  }
31
44
 
45
+ /**
46
+ * Writes a mongod command that starts `binary` outside any replica set,
47
+ * whatever it is asked, and records the mongod's pid in `spawned`. Where a
48
+ * shell can `exec`, mongod keeps the pid the run records. Windows has no
49
+ * `exec`, so there the command is a script that starts mongod as its child.
50
+ *
51
+ * @param {string} folder Where to write it
52
+ * @param {string} binary The real mongod
53
+ * @param {string} spawned The file that receives mongod's pid
54
+ * @returns {string} The command, for `DMS_CONTROL_MONGOD`
55
+ */
56
+ function standaloneMongod(folder, binary, spawned) {
57
+ if (platform() === "win32") {
58
+ const script = join(folder, "mongod-standalone.cjs");
59
+ writeFileSync(
60
+ script,
61
+ `const option = (name) => process.argv[process.argv.indexOf(name) + 1];
62
+ const mongod = require("node:child_process").spawn(${JSON.stringify(binary)}, ["--dbpath", option("--dbpath"), "--port", option("--port"), "--bind_ip", "127.0.0.1"], { stdio: "inherit" });
63
+ require("node:fs").writeFileSync(${JSON.stringify(spawned)}, String(mongod.pid));
64
+ mongod.on("exit", (code) => process.exit(code ?? 1));
65
+ `,
66
+ );
67
+ return script;
68
+ }
69
+ const shell = join(folder, "mongod-standalone");
70
+ writeFileSync(
71
+ shell,
72
+ `#!/bin/sh\necho $$ > "${spawned}"\nexec "${binary}" --dbpath "$2" --port "$4" --bind_ip 127.0.0.1\n`,
73
+ );
74
+ chmodSync(shell, 0o755);
75
+ return shell;
76
+ }
77
+
32
78
  await test("the run's mongod serves a change stream", async (t) => {
33
79
  const paths = runFolders(t);
34
80
  const server = await startMongod(paths, [PACKAGE_ROOT]);
35
81
  const client = new MongoClient(server.url);
36
- t.after(async () => {
82
+ paths.teardown = async () => {
37
83
  await client.close();
38
84
  await stopRecorded([server.record]);
39
- });
85
+ };
40
86
  const items = client.db("verify_test").collection("items");
41
87
  const stream = items.watch();
42
88
  assert.equal(await stream.tryNext(), null);
@@ -49,24 +95,23 @@ await test("the run's mongod serves a change stream", async (t) => {
49
95
  });
50
96
 
51
97
  await test("a mongod that cannot join the replica set is stopped", async (t) => {
52
- const paths = runFolders(t);
53
- const binary = await mongodBinary([PACKAGE_ROOT]);
54
- const wrapper = join(paths.root, "mongod-standalone");
55
- writeFileSync(
56
- wrapper,
57
- `#!/bin/sh\nexec "${binary}" --dbpath "$2" --port "$4" --bind_ip 127.0.0.1\n`,
58
- );
59
- chmodSync(wrapper, 0o755);
60
98
  const saved = process.env.DMS_CONTROL_MONGOD;
61
- process.env.DMS_CONTROL_MONGOD = wrapper;
62
99
  t.after(() => {
63
100
  if (saved === undefined) delete process.env.DMS_CONTROL_MONGOD;
64
101
  else process.env.DMS_CONTROL_MONGOD = saved;
65
102
  });
103
+ const paths = runFolders(t);
104
+ const binary = await mongodBinary([PACKAGE_ROOT]);
105
+ const spawned = join(paths.root, "mongod.pid");
106
+ process.env.DMS_CONTROL_MONGOD = standaloneMongod(
107
+ paths.root,
108
+ binary,
109
+ spawned,
110
+ );
66
111
  await assert.rejects(startMongod(paths, [PACKAGE_ROOT]), {
67
112
  message: "This node was not started with replication enabled.",
68
113
  });
69
- assert.equal(spawnSync("pgrep", ["-f", paths.mongo]).status, 1);
114
+ assert.equal(isAlive(pidIn(spawned)), false);
70
115
  });
71
116
 
72
117
  await test("a mongod restarted on its port and data folder serves a change stream again", async (t) => {
@@ -75,10 +120,10 @@ await test("a mongod restarted on its port and data folder serves a change strea
75
120
  await stopRecorded([first.record]);
76
121
  const again = await startMongod(paths, [PACKAGE_ROOT], first.record.port);
77
122
  const client = new MongoClient(again.url);
78
- t.after(async () => {
123
+ paths.teardown = async () => {
79
124
  await client.close();
80
125
  await stopRecorded([again.record]);
81
- });
126
+ };
82
127
  const items = client.db("verify_test").collection("items");
83
128
  const stream = items.watch();
84
129
  assert.equal(await stream.tryNext(), null);
@@ -20,6 +20,9 @@ import {
20
20
  waitForOwnPort,
21
21
  } from "./processes.mjs";
22
22
 
23
+ /** A file name Node runs as a script. */
24
+ const JAVASCRIPT_FILE = /\.[cm]?js$/u;
25
+
23
26
  /**
24
27
  * @typedef {(...args: unknown[]) => unknown} Callable A function whose result is read as `unknown`
25
28
  * @typedef {new (...args: unknown[]) => unknown} Constructor A class whose instances are read as `unknown`
@@ -226,7 +229,9 @@ function mongodOnPath() {
226
229
 
227
230
  /**
228
231
  * The mongod binary: `DMS_CONTROL_MONGOD`, else `mongod` on PATH, else the
229
- * one mongodb-memory-server-core caches (and downloads once).
232
+ * one mongodb-memory-server-core caches (and downloads once). A
233
+ * `DMS_CONTROL_MONGOD` that names a JavaScript file, such as a stand-in,
234
+ * runs on this Node (see {@link startMongod}).
230
235
  *
231
236
  * @param {string[]} from Folders to resolve mongodb-memory-server-core from
232
237
  * @returns {Promise<string>} The binary path
@@ -252,7 +257,9 @@ export async function mongodBinary(from) {
252
257
  * Starts a mongod owned by the run, on `port` or a free one, with its data
253
258
  * under the run folder, as the only member of a replica set, so change
254
259
  * streams work. A mongod that does not become primary is stopped before the
255
- * error is thrown.
260
+ * error is thrown. A binary that is a JavaScript file runs on this Node, as
261
+ * every other process dms-control starts does, since Windows runs no script
262
+ * by its path alone.
256
263
  *
257
264
  * @param {{ mongo: string, logs: string }} paths The run's folders
258
265
  * @param {string[]} from Folders to resolve mongodb-memory-server-core from
@@ -263,10 +270,12 @@ export async function startMongod(paths, from, port) {
263
270
  const binary = await mongodBinary(from);
264
271
  port ??= await freePort();
265
272
  mkdirSync(paths.mongo, { recursive: true });
273
+ const script = JAVASCRIPT_FILE.test(binary);
266
274
  const record = startDetached({
267
275
  name: "mongod",
268
- program: binary,
276
+ program: script ? process.execPath : binary,
269
277
  args: [
278
+ ...(script ? [binary] : []),
270
279
  "--dbpath",
271
280
  paths.mongo,
272
281
  "--port",