vitecompose 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +180 -2
- package/dist/core/index.d.mts +4 -0
- package/dist/core/index.mjs +3 -0
- package/dist/duration-BRZrZK6s.mjs +13 -0
- package/dist/index.d.mts +62 -0
- package/dist/index.mjs +144 -0
- package/dist/node.d.mts +108 -0
- package/dist/node.mjs +587 -0
- package/dist/provided-CnoC64M0.d.mts +8 -0
- package/dist/scope-B1yisv2y.d.mts +292 -0
- package/dist/scope-BT1dmBGo.mjs +670 -0
- package/dist/state-B-aMt5sE.mjs +152 -0
- package/package.json +51 -4
package/dist/node.mjs
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import { _ as runChecked, a as createComposeClient, h as killOwnedChildren, i as composeBaseArgs, n as createScope } from "./scope-BT1dmBGo.mjs";
|
|
2
|
+
import { t as formatDuration } from "./duration-BRZrZK6s.mjs";
|
|
3
|
+
import { t as createStackStateStore } from "./state-B-aMt5sE.mjs";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { setTimeout } from "node:timers/promises";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
9
|
+
import { hostname, tmpdir } from "node:os";
|
|
10
|
+
import { globSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
11
|
+
import { styleText } from "node:util";
|
|
12
|
+
import { DefaultReporter } from "vitest/node";
|
|
13
|
+
// src/stack/docker.ts
|
|
14
|
+
const MANAGED_LABEL = "com.vitecompose.managed";
|
|
15
|
+
const LIFECYCLE_LABEL = "com.vitecompose.lifecycle";
|
|
16
|
+
const DOCKER_TIMEOUT_MS = 3e4;
|
|
17
|
+
const parseLabelsString = (raw) => {
|
|
18
|
+
const out = {};
|
|
19
|
+
for (const pair of raw.split(",")) {
|
|
20
|
+
const idx = pair.indexOf("=");
|
|
21
|
+
if (idx > 0) out[pair.slice(0, idx).trim()] = pair.slice(idx + 1).trim();
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Inspects Docker for containers belonging to `projectName`.
|
|
27
|
+
* Returns `null` if no containers exist. If any container lacks vitecompose's ownership label,
|
|
28
|
+
* `lifecycle` is `undefined` so `decideExistingStack` refuses to touch it.
|
|
29
|
+
*/
|
|
30
|
+
const findExistingProject = async (projectName) => {
|
|
31
|
+
const { stdout } = await runChecked("docker", [
|
|
32
|
+
"ps",
|
|
33
|
+
"-a",
|
|
34
|
+
"--filter",
|
|
35
|
+
`label=com.docker.compose.project=${projectName}`,
|
|
36
|
+
"--format",
|
|
37
|
+
"{{.Labels}}"
|
|
38
|
+
], { timeoutMs: DOCKER_TIMEOUT_MS });
|
|
39
|
+
const lines = stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
40
|
+
if (lines.length === 0) return null;
|
|
41
|
+
let detectedLifecycle;
|
|
42
|
+
for (const line of lines) {
|
|
43
|
+
const labels = parseLabelsString(line);
|
|
44
|
+
if (labels["com.vitecompose.managed"] !== "true") return {
|
|
45
|
+
name: projectName,
|
|
46
|
+
lifecycle: void 0,
|
|
47
|
+
containerCount: lines.length
|
|
48
|
+
};
|
|
49
|
+
const lifecycle = labels[LIFECYCLE_LABEL];
|
|
50
|
+
if (lifecycle !== "reuse" && lifecycle !== "fresh") return {
|
|
51
|
+
name: projectName,
|
|
52
|
+
lifecycle: void 0,
|
|
53
|
+
containerCount: lines.length
|
|
54
|
+
};
|
|
55
|
+
if (detectedLifecycle && detectedLifecycle !== lifecycle) return {
|
|
56
|
+
name: projectName,
|
|
57
|
+
lifecycle: void 0,
|
|
58
|
+
containerCount: lines.length
|
|
59
|
+
};
|
|
60
|
+
detectedLifecycle = lifecycle;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
name: projectName,
|
|
64
|
+
lifecycle: detectedLifecycle,
|
|
65
|
+
containerCount: lines.length
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/** Lists every service declared in the given Compose file(s), including services under profiles. */
|
|
69
|
+
const listComposeServices = async (composeFiles, cwd, envFile) => {
|
|
70
|
+
const args = ["compose"];
|
|
71
|
+
for (const file of composeFiles) args.push("--file", file);
|
|
72
|
+
if (envFile) args.push("--env-file", envFile);
|
|
73
|
+
args.push("--profile", "*", "config", "--services");
|
|
74
|
+
const { stdout } = await runChecked("docker", args, {
|
|
75
|
+
cwd,
|
|
76
|
+
timeoutMs: DOCKER_TIMEOUT_MS
|
|
77
|
+
});
|
|
78
|
+
return stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
79
|
+
};
|
|
80
|
+
/** Generates a Compose override YAML that stamps every declared service with vitecompose ownership labels. */
|
|
81
|
+
const buildOwnershipOverrideYaml = (services, lifecycle) => {
|
|
82
|
+
if (services.length === 0) return "services: {}\n";
|
|
83
|
+
const lines = ["services:"];
|
|
84
|
+
for (const service of services) {
|
|
85
|
+
lines.push(` ${JSON.stringify(service)}:`);
|
|
86
|
+
lines.push(" labels:");
|
|
87
|
+
lines.push(` ${MANAGED_LABEL}: "true"`);
|
|
88
|
+
lines.push(` ${LIFECYCLE_LABEL}: "${lifecycle}"`);
|
|
89
|
+
}
|
|
90
|
+
return `${lines.join("\n")}\n`;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Tears down a fresh project in a detached background process when Vitest is interrupted by SIGINT/SIGTERM,
|
|
94
|
+
* because Vitest does not wait for async global teardown on signals.
|
|
95
|
+
*/
|
|
96
|
+
const deleteProjectDetached = (target, stateDir) => {
|
|
97
|
+
const script = `docker ${[
|
|
98
|
+
...composeBaseArgs(target),
|
|
99
|
+
"--profile",
|
|
100
|
+
"*",
|
|
101
|
+
"down",
|
|
102
|
+
"--volumes",
|
|
103
|
+
"--remove-orphans"
|
|
104
|
+
].map((arg) => JSON.stringify(arg)).join(" ")} >/dev/null 2>&1; rm -rf ${JSON.stringify(stateDir)}`;
|
|
105
|
+
spawn("sh", ["-c", script], {
|
|
106
|
+
cwd: target.cwd,
|
|
107
|
+
detached: true,
|
|
108
|
+
stdio: "ignore"
|
|
109
|
+
}).unref();
|
|
110
|
+
};
|
|
111
|
+
// src/stack/lock.ts
|
|
112
|
+
/** A holder on this machine whose process is gone is stale at once, so a killed run need not wait for expiry. */
|
|
113
|
+
const isLockLive = (lock, environment) => {
|
|
114
|
+
if (!lock || lock.expiresAt <= environment.now) return false;
|
|
115
|
+
return lock.hostname !== environment.hostname || environment.isProcessAlive(lock.pid);
|
|
116
|
+
};
|
|
117
|
+
const isProcessAlive = (pid) => {
|
|
118
|
+
try {
|
|
119
|
+
process.kill(pid, 0);
|
|
120
|
+
return true;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
return error.code === "EPERM";
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
/** What to do about a Compose project that already has this name. Deletion needs proof that it is ours and idle. */
|
|
126
|
+
const decideExistingStack = (input) => {
|
|
127
|
+
const { name, lifecycle, wantReuse, lockLive, unusableReason } = input;
|
|
128
|
+
const deleteHint = `To remove it: docker compose -p ${name} down -v --remove-orphans`;
|
|
129
|
+
if (!lifecycle) return {
|
|
130
|
+
action: "refuse",
|
|
131
|
+
message: `Docker Compose project "${name}" exists but was not created by vitecompose, so it will not be used or deleted. ${deleteHint}`
|
|
132
|
+
};
|
|
133
|
+
if (lockLive) return { action: "busy" };
|
|
134
|
+
if (lifecycle === "fresh") return { action: "replace" };
|
|
135
|
+
if (!wantReuse) return {
|
|
136
|
+
action: "refuse",
|
|
137
|
+
message: `Docker Compose project "${name}" is a kept stack, and this run asked for a fresh one, so it will not be deleted. ${deleteHint}`
|
|
138
|
+
};
|
|
139
|
+
if (unusableReason) return {
|
|
140
|
+
action: "refuse",
|
|
141
|
+
message: `Docker Compose project "${name}" is marked unusable: ${unusableReason}. ${deleteHint}`
|
|
142
|
+
};
|
|
143
|
+
return { action: "reuse" };
|
|
144
|
+
};
|
|
145
|
+
// src/stack/environment-plan.ts
|
|
146
|
+
/** Stages run in declaration order, so a dependency has to be declared first. */
|
|
147
|
+
const validateStages = (stages, imageNames) => {
|
|
148
|
+
const seen = /* @__PURE__ */ new Set();
|
|
149
|
+
for (const stage of stages) {
|
|
150
|
+
if (seen.has(stage.name)) throw new Error(`Stage "${stage.name}" is declared twice`);
|
|
151
|
+
for (const dependency of stage.dependsOn ?? []) if (!seen.has(dependency)) throw new Error(`Stage "${stage.name}" depends on "${dependency}", which must be declared before it`);
|
|
152
|
+
for (const image of stage.images ?? []) if (!imageNames.includes(image)) throw new Error(`Stage "${stage.name}" uses image "${image}", which is not declared`);
|
|
153
|
+
seen.add(stage.name);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
/** Decides what to run and why. A stage also runs when anything it depends on runs. */
|
|
157
|
+
const planStages = (stages, fingerprints, recorded, { force = false } = {}) => {
|
|
158
|
+
const running = /* @__PURE__ */ new Set();
|
|
159
|
+
return stages.map(({ name, dependsOn = [] }) => {
|
|
160
|
+
const decide = () => {
|
|
161
|
+
if (force) return {
|
|
162
|
+
run: true,
|
|
163
|
+
reason: "a rebuild was requested"
|
|
164
|
+
};
|
|
165
|
+
if (recorded[name] === void 0) return {
|
|
166
|
+
run: true,
|
|
167
|
+
reason: "it has not completed on this stack"
|
|
168
|
+
};
|
|
169
|
+
if (recorded[name] !== fingerprints[name]) return {
|
|
170
|
+
run: true,
|
|
171
|
+
reason: "its inputs changed"
|
|
172
|
+
};
|
|
173
|
+
const dependency = dependsOn.find((candidate) => running.has(candidate));
|
|
174
|
+
if (dependency) return {
|
|
175
|
+
run: true,
|
|
176
|
+
reason: `it depends on ${dependency}, which is running`
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
run: false,
|
|
180
|
+
reason: "unchanged"
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
const decision = decide();
|
|
184
|
+
if (decision.run) running.add(name);
|
|
185
|
+
return {
|
|
186
|
+
name,
|
|
187
|
+
...decision
|
|
188
|
+
};
|
|
189
|
+
});
|
|
190
|
+
};
|
|
191
|
+
const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
|
|
192
|
+
"node_modules",
|
|
193
|
+
".git",
|
|
194
|
+
"dist"
|
|
195
|
+
]);
|
|
196
|
+
const filesUnder = (path) => {
|
|
197
|
+
if (statSync(path).isFile()) return [path];
|
|
198
|
+
return readdirSync(path, { withFileTypes: true }).flatMap((entry) => {
|
|
199
|
+
if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) return [];
|
|
200
|
+
return filesUnder(join(path, entry.name));
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Hashes file contents and paths relative to `rootDir`, so moving the checkout changes nothing.
|
|
205
|
+
* A pattern matching no file is an error, because a typo would silently mean "never changes".
|
|
206
|
+
*/
|
|
207
|
+
const fingerprintFiles = (rootDir, patterns) => patterns.flatMap((pattern) => {
|
|
208
|
+
const matches = globSync(pattern, { cwd: rootDir }).map((match) => resolve(rootDir, match));
|
|
209
|
+
if (matches.length === 0) throw new Error(`Nothing in ${rootDir} matches "${pattern}"`);
|
|
210
|
+
return matches.flatMap(filesUnder).toSorted().map((file) => `${relative(rootDir, file)}:${createHash("sha256").update(readFileSync(file)).digest("hex")}`);
|
|
211
|
+
});
|
|
212
|
+
const hashParts = (parts) => createHash("sha256").update(parts.join("\n")).digest("hex");
|
|
213
|
+
// src/vitest/environment.ts
|
|
214
|
+
const log$1 = (message) => console.log(`[vitecompose] ${message}`);
|
|
215
|
+
const elapsed = (startedAt) => formatDuration(Date.now() - startedAt);
|
|
216
|
+
const BUILD_TIMEOUT_MS = 9e5;
|
|
217
|
+
const INSPECT_TIMEOUT_MS = 6e4;
|
|
218
|
+
const WAIT_TIMEOUT_MS = 18e4;
|
|
219
|
+
const imageRef = ({ name, tag = "local" }) => `${name}:${tag}`;
|
|
220
|
+
/** Always asks Docker, because its layer cache is the only exact answer to whether an image changed. */
|
|
221
|
+
const buildImage = async (image, rootDir) => {
|
|
222
|
+
const startedAt = Date.now();
|
|
223
|
+
const ref = imageRef(image);
|
|
224
|
+
const args = [
|
|
225
|
+
"build",
|
|
226
|
+
"--file",
|
|
227
|
+
resolve(rootDir, image.dockerfile),
|
|
228
|
+
"--tag",
|
|
229
|
+
ref
|
|
230
|
+
];
|
|
231
|
+
if (image.target) args.push("--target", image.target);
|
|
232
|
+
for (const [key, value] of Object.entries(image.buildArgs ?? {})) args.push("--build-arg", `${key}=${value}`);
|
|
233
|
+
args.push(resolve(rootDir, image.context));
|
|
234
|
+
await runChecked("docker", args, {
|
|
235
|
+
cwd: rootDir,
|
|
236
|
+
timeoutMs: BUILD_TIMEOUT_MS
|
|
237
|
+
});
|
|
238
|
+
const { stdout } = await runChecked("docker", [
|
|
239
|
+
"image",
|
|
240
|
+
"inspect",
|
|
241
|
+
"--format",
|
|
242
|
+
"{{json .RootFS.Layers}}|{{json .Config}}",
|
|
243
|
+
ref
|
|
244
|
+
], { timeoutMs: INSPECT_TIMEOUT_MS });
|
|
245
|
+
log$1(`image ${ref} checked in ${elapsed(startedAt)}`);
|
|
246
|
+
return hashParts([stdout.trim()]);
|
|
247
|
+
};
|
|
248
|
+
const runStage = async (stage, context, forceRecreate) => {
|
|
249
|
+
const { compose } = context;
|
|
250
|
+
if (stage.services && stage.services.length > 0) await compose.up({
|
|
251
|
+
services: stage.services,
|
|
252
|
+
profiles: stage.profiles,
|
|
253
|
+
build: stage.build,
|
|
254
|
+
forceRecreate
|
|
255
|
+
});
|
|
256
|
+
const waitTargets = stage.waitFor ?? stage.services ?? [];
|
|
257
|
+
for (const service of waitTargets) await compose.waitForHealthy(service, { timeoutMs: WAIT_TIMEOUT_MS });
|
|
258
|
+
await stage.run?.(context);
|
|
259
|
+
};
|
|
260
|
+
const hashComposeFiles = (rootDir, files) => files.toSorted().map((file) => `${relative(rootDir, file)}:${createHash("sha256").update(readFileSync(file)).digest("hex")}`);
|
|
261
|
+
const stageFingerprint = (stage, rootDir, userComposeFiles, imageIds) => {
|
|
262
|
+
const shape = {
|
|
263
|
+
services: stage.services ?? [],
|
|
264
|
+
profiles: stage.profiles ?? [],
|
|
265
|
+
waitFor: stage.waitFor ?? [],
|
|
266
|
+
build: Boolean(stage.build)
|
|
267
|
+
};
|
|
268
|
+
return hashParts([
|
|
269
|
+
JSON.stringify(shape),
|
|
270
|
+
...(stage.images ?? []).map((name) => `${name}:${imageIds[name]}`),
|
|
271
|
+
...fingerprintFiles(rootDir, stage.inputs ?? []),
|
|
272
|
+
...stage.services && stage.services.length > 0 ? hashComposeFiles(rootDir, userComposeFiles) : []
|
|
273
|
+
]);
|
|
274
|
+
};
|
|
275
|
+
/** Brings the Compose stack to the declared state, doing only the work that the declaration's inputs call for. */
|
|
276
|
+
const prepareEnvironment = async (spec, input) => {
|
|
277
|
+
const { compose, target, userComposeFiles, store } = input;
|
|
278
|
+
const rootDir = resolve(input.vitestRoot, spec.rootDir ?? ".");
|
|
279
|
+
const images = spec.images ?? [];
|
|
280
|
+
validateStages(spec.stages, images.map((image) => image.name));
|
|
281
|
+
const force = process.env.VITECOMPOSE_REBUILD === "1";
|
|
282
|
+
const startedAt = Date.now();
|
|
283
|
+
const built = await Promise.all(images.map(async (image) => [image, await buildImage(image, rootDir)]));
|
|
284
|
+
const imageIds = Object.fromEntries(built.map(([image, id]) => [image.name, id]));
|
|
285
|
+
const recorded = await store.readEnvironment();
|
|
286
|
+
for (const [image, id] of built) if (force || recorded.images[image.name] !== id) await store.recordImage(image.name, id);
|
|
287
|
+
const existingContainers = await compose.ps({ all: true });
|
|
288
|
+
const existingServices = new Set(existingContainers.map((container) => container.service));
|
|
289
|
+
const runningServices = new Set(existingContainers.filter((container) => container.state === "running").map((container) => container.service));
|
|
290
|
+
const recordedStages = { ...recorded.stages };
|
|
291
|
+
for (const stage of spec.stages) if ((stage.services ?? []).some((service) => !existingServices.has(service))) delete recordedStages[stage.name];
|
|
292
|
+
const fingerprints = Object.fromEntries(spec.stages.map((stage) => [stage.name, stageFingerprint(stage, rootDir, userComposeFiles, imageIds)]));
|
|
293
|
+
const decisions = planStages(spec.stages, fingerprints, recordedStages, { force });
|
|
294
|
+
for (const decision of decisions) if (decision.run) await store.recordStage(decision.name, void 0);
|
|
295
|
+
const context = {
|
|
296
|
+
compose,
|
|
297
|
+
target,
|
|
298
|
+
rootDir
|
|
299
|
+
};
|
|
300
|
+
for (const [index, stage] of spec.stages.entries()) {
|
|
301
|
+
const decision = decisions[index];
|
|
302
|
+
if (!decision.run) {
|
|
303
|
+
const missingServices = (stage.services ?? []).filter((service) => !runningServices.has(service));
|
|
304
|
+
if (missingServices.length > 0) {
|
|
305
|
+
log$1(`stage ${stage.name}: restarting stopped services (${missingServices.join(", ")})`);
|
|
306
|
+
await compose.up({
|
|
307
|
+
services: missingServices,
|
|
308
|
+
profiles: stage.profiles
|
|
309
|
+
});
|
|
310
|
+
for (const service of stage.waitFor ?? missingServices) await compose.waitForHealthy(service, { timeoutMs: WAIT_TIMEOUT_MS });
|
|
311
|
+
for (const service of missingServices) runningServices.add(service);
|
|
312
|
+
} else log$1(`stage ${stage.name}: skipped, ${decision.reason}`);
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
log$1(`stage ${stage.name}: running, because ${decision.reason}`);
|
|
316
|
+
const stageStartedAt = Date.now();
|
|
317
|
+
await runStage(stage, context, true);
|
|
318
|
+
for (const service of stage.services ?? []) runningServices.add(service);
|
|
319
|
+
await store.recordStage(stage.name, fingerprints[stage.name]);
|
|
320
|
+
log$1(`stage ${stage.name}: done in ${elapsed(stageStartedAt)}`);
|
|
321
|
+
}
|
|
322
|
+
log$1(`environment ready in ${elapsed(startedAt)}`);
|
|
323
|
+
};
|
|
324
|
+
// src/vitest/global-setup.ts
|
|
325
|
+
const LOCK_TTL_MS = 6e4;
|
|
326
|
+
const HEARTBEAT_MS = 15e3;
|
|
327
|
+
const LOCK_POLL_MS = 2e3;
|
|
328
|
+
const MARKER = "vitecompose";
|
|
329
|
+
const log = (message) => console.log(`[vitecompose] ${message}`);
|
|
330
|
+
/** `vitest list` runs global setup even though it only collects tests, and collecting needs no stack. */
|
|
331
|
+
const isListCommand = () => process.argv.slice(2)[0] === "list";
|
|
332
|
+
const lockEnvironment = () => ({
|
|
333
|
+
now: Date.now(),
|
|
334
|
+
hostname: hostname(),
|
|
335
|
+
isProcessAlive
|
|
336
|
+
});
|
|
337
|
+
const lockIsLive = (lock) => isLockLive(lock, lockEnvironment());
|
|
338
|
+
const describeLock = (lock) => lock ? `process ${lock.pid} on ${lock.hostname}` : "another run";
|
|
339
|
+
/** Deterministic per project name, so a later run can find and clean up after a killed one. */
|
|
340
|
+
const privateDirectory = (name) => join(tmpdir(), "vitecompose", name);
|
|
341
|
+
const sanitizeProjectName = (name) => {
|
|
342
|
+
const cleaned = name.trim().toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+/, "");
|
|
343
|
+
if (!cleaned) throw new Error(`Invalid Docker Compose project name: "${name}"`);
|
|
344
|
+
return cleaned;
|
|
345
|
+
};
|
|
346
|
+
const readStateIfReachable = async (store) => {
|
|
347
|
+
try {
|
|
348
|
+
return await store.read();
|
|
349
|
+
} catch {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
/** Provisions the Docker Compose stack for a run and cleans up after it. Use as default export of a globalSetup file. */
|
|
354
|
+
const defineComposeGlobalSetup = (options) => async (project) => {
|
|
355
|
+
if (isListCommand()) return;
|
|
356
|
+
const vitestRoot = project.config.root;
|
|
357
|
+
const rawName = process.env.VITECOMPOSE_PROJECT?.trim() || options.stack.name;
|
|
358
|
+
const projectName = sanitizeProjectName(rawName);
|
|
359
|
+
const wantReuse = options.stack.reuse ?? false;
|
|
360
|
+
const lifecycle = wantReuse ? "reuse" : "fresh";
|
|
361
|
+
const lockWaitMs = options.lockWaitMs ?? 0;
|
|
362
|
+
const rawFiles = Array.isArray(options.stack.composeFile) ? [...options.stack.composeFile] : [options.stack.composeFile];
|
|
363
|
+
if (rawFiles.length === 0) throw new Error("stack.composeFile must specify at least one Compose file");
|
|
364
|
+
const userComposeFiles = rawFiles.map((file) => resolve(vitestRoot, file));
|
|
365
|
+
const cwd = options.stack.cwd ? resolve(vitestRoot, options.stack.cwd) : dirname(userComposeFiles[0]);
|
|
366
|
+
const envFile = options.stack.envFile ? resolve(vitestRoot, options.stack.envFile) : void 0;
|
|
367
|
+
const stateDir = privateDirectory(projectName);
|
|
368
|
+
const overridePath = join(stateDir, "vitecompose.override.yaml");
|
|
369
|
+
const target = {
|
|
370
|
+
projectName,
|
|
371
|
+
composeFiles: [...userComposeFiles, overridePath],
|
|
372
|
+
cwd,
|
|
373
|
+
envFile
|
|
374
|
+
};
|
|
375
|
+
const store = createStackStateStore(stateDir);
|
|
376
|
+
const holder = randomUUID();
|
|
377
|
+
const scope = createScope();
|
|
378
|
+
let owned;
|
|
379
|
+
let lockHeld = false;
|
|
380
|
+
let heartbeat;
|
|
381
|
+
const onSignal = (signal) => {
|
|
382
|
+
removeSignalHandlers();
|
|
383
|
+
killOwnedChildren();
|
|
384
|
+
if (owned) {
|
|
385
|
+
log(`interrupted, tearing down Compose stack ${owned.target.projectName} in the background`);
|
|
386
|
+
deleteProjectDetached(owned.target, owned.stateDir);
|
|
387
|
+
}
|
|
388
|
+
process.kill(process.pid, signal);
|
|
389
|
+
};
|
|
390
|
+
const removeSignalHandlers = () => {
|
|
391
|
+
process.off("SIGINT", onSignal);
|
|
392
|
+
process.off("SIGTERM", onSignal);
|
|
393
|
+
};
|
|
394
|
+
process.on("SIGINT", onSignal);
|
|
395
|
+
process.on("SIGTERM", onSignal);
|
|
396
|
+
const teardown = async () => {
|
|
397
|
+
clearInterval(heartbeat);
|
|
398
|
+
const errors = [];
|
|
399
|
+
await scope.dispose().catch((error) => errors.push(error));
|
|
400
|
+
if (lockHeld && !owned) await store.releaseLock(holder).catch((error) => errors.push(error));
|
|
401
|
+
if (owned) {
|
|
402
|
+
if (process.env.VITECOMPOSE_KEEP_ON_FAILURE === "1") {
|
|
403
|
+
const state = await readStateIfReachable(store);
|
|
404
|
+
if (state?.hadFailure || state?.unusable) {
|
|
405
|
+
log(`kept stack ${owned.target.projectName} because a test failed. The next run removes it. Inspect with:\n docker compose -p ${owned.target.projectName} ps`);
|
|
406
|
+
await store.releaseLock(holder).catch((error) => errors.push(error));
|
|
407
|
+
removeSignalHandlers();
|
|
408
|
+
if (errors.length > 0) throw new AggregateError(errors, `vitecompose teardown failed: ${errors.map(String).join("; ")}`);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
log(`tearing down Compose stack ${owned.target.projectName}`);
|
|
413
|
+
await createComposeClient(owned.target, { rootDir: vitestRoot }).down({
|
|
414
|
+
volumes: true,
|
|
415
|
+
removeOrphans: true,
|
|
416
|
+
profiles: ["*"]
|
|
417
|
+
}).catch((error) => errors.push(error));
|
|
418
|
+
await rm(owned.stateDir, {
|
|
419
|
+
recursive: true,
|
|
420
|
+
force: true
|
|
421
|
+
}).catch((error) => errors.push(error));
|
|
422
|
+
}
|
|
423
|
+
removeSignalHandlers();
|
|
424
|
+
if (errors.length > 0) throw new AggregateError(errors, `vitecompose teardown failed: ${errors.map(String).join("; ")}`);
|
|
425
|
+
};
|
|
426
|
+
try {
|
|
427
|
+
const deadline = Date.now() + lockWaitMs;
|
|
428
|
+
let reusing = false;
|
|
429
|
+
while (true) {
|
|
430
|
+
const existing = await findExistingProject(projectName);
|
|
431
|
+
if (!existing) break;
|
|
432
|
+
const state = await readStateIfReachable(store);
|
|
433
|
+
const decision = decideExistingStack({
|
|
434
|
+
name: projectName,
|
|
435
|
+
lifecycle: existing.lifecycle,
|
|
436
|
+
wantReuse,
|
|
437
|
+
lockLive: lockIsLive(state?.lock),
|
|
438
|
+
unusableReason: state?.unusable
|
|
439
|
+
});
|
|
440
|
+
if (decision.action === "refuse") throw new Error(decision.message);
|
|
441
|
+
if (decision.action === "reuse") {
|
|
442
|
+
log(`reusing Compose stack ${projectName}`);
|
|
443
|
+
reusing = true;
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
if (decision.action === "replace") {
|
|
447
|
+
log(`replacing Compose stack ${projectName} left over from an interrupted run`);
|
|
448
|
+
await createComposeClient({
|
|
449
|
+
projectName,
|
|
450
|
+
composeFiles: userComposeFiles,
|
|
451
|
+
cwd,
|
|
452
|
+
envFile
|
|
453
|
+
}, { rootDir: vitestRoot }).down({
|
|
454
|
+
volumes: true,
|
|
455
|
+
removeOrphans: true,
|
|
456
|
+
profiles: ["*"]
|
|
457
|
+
});
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
if (Date.now() >= deadline) throw new Error(`Docker Compose stack "${projectName}" is in use by ${describeLock(state?.lock)}`);
|
|
461
|
+
await setTimeout(LOCK_POLL_MS);
|
|
462
|
+
}
|
|
463
|
+
await mkdir(stateDir, {
|
|
464
|
+
recursive: true,
|
|
465
|
+
mode: 448
|
|
466
|
+
});
|
|
467
|
+
const declaredServices = await listComposeServices(userComposeFiles, cwd, envFile);
|
|
468
|
+
await writeFile(overridePath, buildOwnershipOverrideYaml(declaredServices, lifecycle), { mode: 384 });
|
|
469
|
+
await store.initialize(MARKER, lifecycle);
|
|
470
|
+
const lockDeadline = Date.now() + lockWaitMs;
|
|
471
|
+
while (true) {
|
|
472
|
+
const blocker = await store.acquireLock({
|
|
473
|
+
holder,
|
|
474
|
+
hostname: hostname(),
|
|
475
|
+
pid: process.pid,
|
|
476
|
+
expiresAt: Date.now() + LOCK_TTL_MS
|
|
477
|
+
}, lockIsLive);
|
|
478
|
+
if (!blocker) break;
|
|
479
|
+
if (Date.now() >= lockDeadline) throw new Error(`The Compose stack "${projectName}" is in use by ${describeLock(blocker)}`);
|
|
480
|
+
await setTimeout(LOCK_POLL_MS);
|
|
481
|
+
}
|
|
482
|
+
lockHeld = true;
|
|
483
|
+
await store.clearFailed();
|
|
484
|
+
if (!reusing) {
|
|
485
|
+
await store.clearEnvironment();
|
|
486
|
+
await store.clearUnusable();
|
|
487
|
+
}
|
|
488
|
+
heartbeat = setInterval(() => {
|
|
489
|
+
store.renewLock(holder, Date.now() + LOCK_TTL_MS).catch((error) => {
|
|
490
|
+
console.error(`[vitecompose] could not renew the run lock: ${String(error)}`);
|
|
491
|
+
});
|
|
492
|
+
}, HEARTBEAT_MS);
|
|
493
|
+
heartbeat.unref();
|
|
494
|
+
if (!wantReuse) owned = {
|
|
495
|
+
target,
|
|
496
|
+
stateDir
|
|
497
|
+
};
|
|
498
|
+
project.provide("vitecomposeTarget", target);
|
|
499
|
+
project.provide("vitecomposeRoot", vitestRoot);
|
|
500
|
+
project.provide("vitecomposeStateDir", stateDir);
|
|
501
|
+
const compose = createComposeClient(target, {
|
|
502
|
+
rootDir: vitestRoot,
|
|
503
|
+
onEnvironmentDamaged: (reason) => store.markUnusable(reason)
|
|
504
|
+
});
|
|
505
|
+
if (options.environment) await prepareEnvironment(options.environment, {
|
|
506
|
+
vitestRoot,
|
|
507
|
+
compose,
|
|
508
|
+
target,
|
|
509
|
+
userComposeFiles,
|
|
510
|
+
store
|
|
511
|
+
});
|
|
512
|
+
else {
|
|
513
|
+
const startedAt = Date.now();
|
|
514
|
+
if (!reusing) log(`starting Compose stack ${projectName}`);
|
|
515
|
+
await compose.up({
|
|
516
|
+
services: options.stack.services,
|
|
517
|
+
profiles: options.stack.profiles,
|
|
518
|
+
build: options.stack.build || process.env.VITECOMPOSE_REBUILD === "1",
|
|
519
|
+
forceRecreate: process.env.VITECOMPOSE_REBUILD === "1",
|
|
520
|
+
wait: options.stack.wait ?? true
|
|
521
|
+
});
|
|
522
|
+
log(`stack ${projectName} ready in ${formatDuration(Date.now() - startedAt)}`);
|
|
523
|
+
}
|
|
524
|
+
log(`inspect the stack with: docker compose -p ${projectName} ps`);
|
|
525
|
+
if (options.setup) await options.setup({
|
|
526
|
+
compose,
|
|
527
|
+
target,
|
|
528
|
+
scope,
|
|
529
|
+
provide: (key, value) => project.provide(key, value)
|
|
530
|
+
});
|
|
531
|
+
} catch (error) {
|
|
532
|
+
await teardown().catch((teardownError) => {
|
|
533
|
+
console.error(`[vitecompose] cleanup after failed setup also failed: ${String(teardownError)}`);
|
|
534
|
+
});
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
return teardown;
|
|
538
|
+
};
|
|
539
|
+
// src/vitest/require-matching-tests.ts
|
|
540
|
+
/**
|
|
541
|
+
* Vitest exits 0 when `-t` matches nothing, so a typo in a filter looks like a pass after a full provision.
|
|
542
|
+
* This reporter fails that run. Runs without a name filter are unaffected, so a suite that is
|
|
543
|
+
* entirely `test.skip` still passes.
|
|
544
|
+
*/
|
|
545
|
+
var RequireMatchingTests = class {
|
|
546
|
+
vitest;
|
|
547
|
+
onInit(vitest) {
|
|
548
|
+
this.vitest = vitest;
|
|
549
|
+
}
|
|
550
|
+
onTestRunEnd(testModules) {
|
|
551
|
+
const pattern = this.vitest?.config.testNamePattern;
|
|
552
|
+
if (!pattern || testModules.length === 0) return;
|
|
553
|
+
if (!testModules.some((testModule) => [...testModule.children.allTests()].some((testCase) => testCase.result().state !== "skipped"))) {
|
|
554
|
+
console.error(`[vitecompose] no test matched the name filter ${String(pattern)}`);
|
|
555
|
+
process.exitCode = 1;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
// src/vitest/compose-reporter.ts
|
|
560
|
+
/**
|
|
561
|
+
* Vitest's default output, with times people can read at a glance: `38.2s` instead of `38196ms`.
|
|
562
|
+
* It also fails a run whose `-t` filter matched nothing, like `RequireMatchingTests`.
|
|
563
|
+
*/
|
|
564
|
+
var ComposeReporter = class extends DefaultReporter {
|
|
565
|
+
filterCheck = new RequireMatchingTests();
|
|
566
|
+
startedAt = Date.now();
|
|
567
|
+
constructor(...args) {
|
|
568
|
+
super(...args);
|
|
569
|
+
Object.assign(this, { getDurationPrefix: (task) => {
|
|
570
|
+
const duration = task.result?.duration;
|
|
571
|
+
if (duration == null) return "";
|
|
572
|
+
const slow = duration > this.ctx.config.slowTestThreshold;
|
|
573
|
+
return ` ${styleText(slow ? "yellow" : "green", formatDuration(duration))}`;
|
|
574
|
+
} });
|
|
575
|
+
}
|
|
576
|
+
onInit(vitest) {
|
|
577
|
+
super.onInit(vitest);
|
|
578
|
+
this.filterCheck.onInit(vitest);
|
|
579
|
+
this.startedAt = Date.now();
|
|
580
|
+
}
|
|
581
|
+
onTestRunEnd(...args) {
|
|
582
|
+
super.onTestRunEnd(...args);
|
|
583
|
+
this.log(`${styleText("dim", " Total")} ${formatDuration(Date.now() - this.startedAt)}`);
|
|
584
|
+
this.filterCheck.onTestRunEnd(args[0]);
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
export { ComposeReporter, RequireMatchingTests, defineComposeGlobalSetup };
|