@omnitron-dev/testing 0.4.5 → 0.4.6

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 (115) hide show
  1. package/README.md +43 -0
  2. package/dist/async/events.js.map +1 -1
  3. package/dist/async/retry.js.map +1 -1
  4. package/dist/async/wait.js.map +1 -1
  5. package/dist/docker/database-manager.js +13 -15
  6. package/dist/docker/database-manager.js.map +1 -1
  7. package/dist/docker/docker-test-manager.d.ts +12 -3
  8. package/dist/docker/docker-test-manager.js +286 -255
  9. package/dist/docker/docker-test-manager.js.map +1 -1
  10. package/dist/docker/redis-manager.js +68 -94
  11. package/dist/docker/redis-manager.js.map +1 -1
  12. package/dist/docker/types.d.ts +7 -2
  13. package/dist/env.d.ts +11 -0
  14. package/dist/env.js +21 -0
  15. package/dist/env.js.map +1 -0
  16. package/dist/errors.js.map +1 -1
  17. package/dist/helpers/assertions.js +3 -3
  18. package/dist/helpers/assertions.js.map +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/runtime/bun-adapter.d.ts +23 -1
  21. package/dist/runtime/bun-adapter.js +14 -1
  22. package/dist/runtime/bun-adapter.js.map +1 -1
  23. package/dist/runtime/deno-adapter.d.ts +72 -15
  24. package/dist/runtime/deno-adapter.js +93 -78
  25. package/dist/runtime/deno-adapter.js.map +1 -1
  26. package/dist/runtime/node-adapter.d.ts +15 -3
  27. package/dist/runtime/node-adapter.js +1 -1
  28. package/dist/runtime/node-adapter.js.map +1 -1
  29. package/dist/runtime/test-adapter.d.ts +1 -1
  30. package/dist/runtime/test-adapter.js +12 -14
  31. package/dist/runtime/test-adapter.js.map +1 -1
  32. package/dist/titan/database/database-testing.module.d.ts +7 -6
  33. package/dist/titan/database/database-testing.module.js +39 -18
  34. package/dist/titan/database/database-testing.module.js.map +1 -1
  35. package/dist/titan/database/index.d.ts +1 -1
  36. package/dist/titan/database/index.js +1 -1
  37. package/dist/titan/database/index.js.map +1 -1
  38. package/dist/titan/database/test-utilities.d.ts +2 -2
  39. package/dist/titan/database/test-utilities.js +3 -2
  40. package/dist/titan/database/test-utilities.js.map +1 -1
  41. package/dist/titan/index.d.ts +4 -4
  42. package/dist/titan/index.js +3 -3
  43. package/dist/titan/index.js.map +1 -1
  44. package/dist/titan/nexus/mock-provider.js +6 -6
  45. package/dist/titan/nexus/mock-provider.js.map +1 -1
  46. package/dist/titan/nexus/test-container.js +10 -10
  47. package/dist/titan/nexus/test-container.js.map +1 -1
  48. package/dist/titan/nexus/test-utilities.js +9 -9
  49. package/dist/titan/nexus/test-utilities.js.map +1 -1
  50. package/dist/titan/pm/mock-process-spawner.d.ts +4 -3
  51. package/dist/titan/pm/mock-process-spawner.js +33 -14
  52. package/dist/titan/pm/mock-process-spawner.js.map +1 -1
  53. package/dist/titan/pm/mock-spawner.d.ts +2 -1
  54. package/dist/titan/pm/mock-spawner.js +3 -1
  55. package/dist/titan/pm/mock-spawner.js.map +1 -1
  56. package/dist/titan/pm/test-process-manager.d.ts +4 -4
  57. package/dist/titan/pm/test-process-manager.js +7 -3
  58. package/dist/titan/pm/test-process-manager.js.map +1 -1
  59. package/dist/titan/redis-test-utils.d.ts +8 -2
  60. package/dist/titan/redis-test-utils.js +147 -92
  61. package/dist/titan/redis-test-utils.js.map +1 -1
  62. package/dist/titan/test-application.d.ts +1 -1
  63. package/dist/titan/test-application.js +1 -1
  64. package/dist/titan/test-application.js.map +1 -1
  65. package/dist/titan/test-fixtures.js.map +1 -1
  66. package/dist/titan/test-mocks.d.ts +12 -11
  67. package/dist/titan/test-mocks.js +49 -49
  68. package/dist/titan/test-mocks.js.map +1 -1
  69. package/dist/titan/test-module.js.map +1 -1
  70. package/package.json +66 -40
  71. package/src/async/events.ts +1 -1
  72. package/src/docker/a-port-the-network-could-reach.spec.ts +66 -0
  73. package/src/docker/database-manager.ts +13 -15
  74. package/src/docker/docker-orphan-reaper.spec.ts +175 -0
  75. package/src/docker/docker-port-collision.spec.ts +97 -0
  76. package/src/docker/docker-test-manager.spec.ts +122 -0
  77. package/src/docker/docker-test-manager.ts +420 -326
  78. package/src/docker/docker-volume-cleanup.spec.ts +113 -0
  79. package/src/docker/redis-cluster-creation.spec.ts +52 -0
  80. package/src/docker/redis-manager.ts +80 -115
  81. package/src/docker/types.ts +11 -4
  82. package/src/env.spec.ts +20 -0
  83. package/src/env.ts +33 -0
  84. package/src/globals.d.ts +2 -2
  85. package/src/helpers/assertions.ts +3 -3
  86. package/src/index.ts +1 -1
  87. package/src/runtime/adapter-surface.spec.ts +83 -0
  88. package/src/runtime/bun-adapter.ts +36 -5
  89. package/src/runtime/deno-adapter.ts +167 -108
  90. package/src/runtime/node-adapter.ts +5 -5
  91. package/src/runtime/test-adapter.test.ts +1 -1
  92. package/src/runtime/test-adapter.ts +15 -17
  93. package/src/titan/database/database-testing.module.ts +63 -22
  94. package/src/titan/database/index.ts +2 -2
  95. package/src/titan/database/test-utilities.ts +6 -3
  96. package/src/titan/index.ts +8 -1
  97. package/src/titan/nexus/mock-provider.ts +12 -12
  98. package/src/titan/nexus/test-container.ts +12 -12
  99. package/src/titan/nexus/test-utilities.ts +13 -11
  100. package/src/titan/pm/mock-process-spawner.ts +74 -26
  101. package/src/titan/pm/mock-spawner.ts +10 -4
  102. package/src/titan/pm/test-process-manager.ts +26 -9
  103. package/src/titan/redis-test-utils.test.ts +102 -0
  104. package/src/titan/redis-test-utils.ts +191 -109
  105. package/src/titan/test-application.ts +2 -2
  106. package/src/titan/test-fixtures.ts +0 -1
  107. package/src/titan/test-mocks.ts +50 -50
  108. package/runtime/bun.d.ts +0 -2
  109. package/runtime/bun.js +0 -5
  110. package/runtime/bun.ts +0 -7
  111. package/runtime/deno.d.ts +0 -2
  112. package/runtime/deno.js +0 -4
  113. package/runtime/jest.d.ts +0 -2
  114. package/runtime/jest.js +0 -16
  115. package/runtime/jest.ts +0 -7
@@ -1,38 +1,83 @@
1
- import { execSync, execFileSync } from 'child_process';
1
+ import { execSync, execFileSync, execFile } from 'child_process';
2
2
  import { randomBytes } from 'crypto';
3
+ import { hostname } from 'os';
3
4
  import * as net from 'net';
4
5
  import { EventEmitter } from 'events';
6
+ function parseDockerLabels(labels) {
7
+ const out = {};
8
+ for (const pair of labels.split(',')) {
9
+ const eq = pair.indexOf('=');
10
+ if (eq > 0)
11
+ out[pair.slice(0, eq)] = pair.slice(eq + 1);
12
+ }
13
+ return out;
14
+ }
15
+ function dockerHealthCommand(test) {
16
+ if (typeof test === 'string')
17
+ return test;
18
+ const [mode, ...args] = test;
19
+ if (mode === 'CMD-SHELL')
20
+ return args.join(' ');
21
+ const argv = mode === 'CMD' ? args : test;
22
+ return argv.map(arg => "'" + arg.replaceAll("'", "'\\''") + "'").join(' ');
23
+ }
24
+ function pidFromManagerId(managerId) {
25
+ const pid = Number.parseInt(managerId.split('-')[0] ?? '', 10);
26
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
27
+ }
28
+ function isPidAlive(pid) {
29
+ try {
30
+ process.kill(pid, 0);
31
+ return true;
32
+ }
33
+ catch (error) {
34
+ return error.code === 'EPERM';
35
+ }
36
+ }
37
+ function parseDockerTimestamp(createdAt) {
38
+ const m = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(?:\.\d+)? ([+-]\d{2})(\d{2})/.exec(createdAt.trim());
39
+ if (!m)
40
+ return null;
41
+ const parsed = Date.parse(`${m[1]}T${m[2]}${m[3]}:${m[4]}`);
42
+ return Number.isNaN(parsed) ? null : parsed;
43
+ }
5
44
  export class DockerTestManager extends EventEmitter {
45
+ static { this.PORT_COLLISION_RETRIES = 3; }
46
+ static { this.hostId = hostname(); }
47
+ static { this.orphanReapDone = false; }
48
+ static { this.orphanGraceMs = 10 * 60 * 1000; }
6
49
  constructor(options = {}) {
7
50
  super();
8
51
  this.containers = new Map();
9
52
  this.usedPorts = new Set();
10
- this.networks = new Set();
11
- this.cleanupInProgress = false;
53
+ this.networks = new Map();
54
+ this.managerId = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
12
55
  this.dockerPath = options.dockerPath || this.findDockerPath();
13
- const workerId = parseInt(process.env['JEST_WORKER_ID'] || '1', 10);
14
- const basePortOffset = (workerId - 1) * 10000;
15
- this.basePort = options.basePort || 10000 + basePortOffset;
16
- this.maxRetries = options.maxRetries || 20;
17
- this.startupTimeout = options.startupTimeout || 30000;
56
+ const workerId = parseInt(process.env['VITEST_POOL_ID'] || process.env['VITEST_WORKER_ID'] || '1', 10);
57
+ const maxBasePort = 55000;
58
+ const basePortOffset = ((workerId - 1) * 10000) % (maxBasePort - 10000);
59
+ this.basePort = options.basePort || Math.min(10000 + basePortOffset, maxBasePort);
60
+ this.maxRetries = options.maxRetries || 30;
61
+ this.startupTimeout = options.startupTimeout || 60000;
18
62
  this.gracefulShutdownTimeout = options.gracefulShutdownTimeout || 10000;
19
63
  this.maxCleanupRetries = options.maxCleanupRetries || 3;
20
64
  this.cleanup = options.cleanup !== false;
21
65
  this.verbose = options.verbose || false;
22
66
  this.defaultNetwork = options.network;
23
67
  if (this.verbose) {
24
- this.log(`Initialized for Jest worker ${workerId} with port range ${this.basePort}-${this.basePort + 10000}`);
68
+ this.log(`Initialized for Vitest worker ${workerId} with port range ${this.basePort}-${this.basePort + 10000}`);
25
69
  }
26
70
  this.verifyDocker();
27
71
  if (this.cleanup) {
28
72
  process.setMaxListeners(Math.max(20, process.getMaxListeners()));
73
+ this.reapOrphanedResources();
29
74
  process.on('exit', () => this.cleanupSync());
30
75
  process.on('SIGINT', () => {
31
76
  this.log('SIGINT received - initiating graceful shutdown');
32
77
  this.cleanupAllAsync()
33
78
  .then(() => {
34
79
  this.log('Cleanup completed, exiting');
35
- process.exit(0);
80
+ process.exit(130);
36
81
  })
37
82
  .catch((error) => {
38
83
  this.logError('Cleanup failed during SIGINT', error);
@@ -44,7 +89,7 @@ export class DockerTestManager extends EventEmitter {
44
89
  this.cleanupAllAsync()
45
90
  .then(() => {
46
91
  this.log('Cleanup completed, exiting');
47
- process.exit(0);
92
+ process.exit(143);
48
93
  })
49
94
  .catch((error) => {
50
95
  this.logError('Cleanup failed during SIGTERM', error);
@@ -149,9 +194,88 @@ export class DockerTestManager extends EventEmitter {
149
194
  `Visit: https://docs.docker.com/get-docker/`);
150
195
  }
151
196
  }
197
+ reapOrphanedResources() {
198
+ if (DockerTestManager.orphanReapDone)
199
+ return;
200
+ DockerTestManager.orphanReapDone = true;
201
+ try {
202
+ const listed = execFileSync(this.dockerPath, ['ps', '-a', '--filter', 'label=test.cleanup=true', '--format', '{{.ID}}\t{{.CreatedAt}}\t{{.Labels}}'], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
203
+ const orphans = [];
204
+ for (const line of listed ? listed.split('\n') : []) {
205
+ const [id, createdAt, labels] = line.split('\t');
206
+ if (!id || !createdAt || !labels)
207
+ continue;
208
+ if (!this.isOrphaned(labels, createdAt))
209
+ continue;
210
+ orphans.push(id);
211
+ }
212
+ if (orphans.length > 0) {
213
+ this.log(`Reaping ${orphans.length} container(s) left by processes that no longer exist`);
214
+ try {
215
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', ...orphans], { stdio: 'ignore' });
216
+ }
217
+ catch (error) {
218
+ this.logError('Some orphaned containers could not be removed', error);
219
+ }
220
+ }
221
+ this.reapOrphanedNetworks();
222
+ }
223
+ catch (error) {
224
+ this.logError('Could not scan for orphaned test containers', error);
225
+ }
226
+ }
227
+ reapOrphanedNetworks() {
228
+ try {
229
+ const listed = execFileSync(this.dockerPath, ['network', 'ls', '--filter', 'label=test.cleanup=true', '--format', '{{.ID}}\t{{.Labels}}'], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
230
+ const orphans = [];
231
+ for (const line of listed ? listed.split('\n') : []) {
232
+ const [id, labels] = line.split('\t');
233
+ if (!id || !labels)
234
+ continue;
235
+ if (!this.isOrphaned(labels, null))
236
+ continue;
237
+ orphans.push(id);
238
+ }
239
+ if (orphans.length > 0) {
240
+ this.log(`Reaping ${orphans.length} network(s) left by processes that no longer exist`);
241
+ try {
242
+ execFileSync(this.dockerPath, ['network', 'rm', ...orphans], { stdio: 'ignore' });
243
+ }
244
+ catch (error) {
245
+ this.logError('Some orphaned test networks could not be removed', error);
246
+ }
247
+ }
248
+ }
249
+ catch (error) {
250
+ this.logError('Could not scan for orphaned test networks', error);
251
+ }
252
+ }
253
+ isOrphaned(labels, createdAt) {
254
+ const parsed = parseDockerLabels(labels);
255
+ const owner = parsed['test.manager'];
256
+ if (!owner || owner === this.managerId)
257
+ return false;
258
+ const host = parsed['test.host'];
259
+ if (host && host !== DockerTestManager.hostId)
260
+ return false;
261
+ const pid = pidFromManagerId(owner);
262
+ if (pid === null || isPidAlive(pid))
263
+ return false;
264
+ if (createdAt !== null) {
265
+ const created = parseDockerTimestamp(createdAt);
266
+ if (created === null)
267
+ return false;
268
+ if (Date.now() - created < DockerTestManager.orphanGraceMs)
269
+ return false;
270
+ }
271
+ return true;
272
+ }
152
273
  async findAvailablePort() {
274
+ const portRangeSize = Math.min(10000, 65535 - this.basePort);
153
275
  for (let i = 0; i < this.maxRetries; i++) {
154
- const port = this.basePort + Math.floor(Math.random() * 10000);
276
+ const port = this.basePort + Math.floor(Math.random() * portRangeSize);
277
+ if (port >= 65536)
278
+ continue;
155
279
  if (!this.usedPorts.has(port) && (await this.isPortAvailable(port))) {
156
280
  this.usedPorts.add(port);
157
281
  return port;
@@ -190,7 +314,7 @@ export class DockerTestManager extends EventEmitter {
190
314
  const inspectOutput = execFileSync(this.dockerPath, [
191
315
  'inspect',
192
316
  '--format',
193
- '{{.State.Running}}\t{{.State.Status}}\t{{.State.Health.Status}}\t{{.State.ExitCode}}',
317
+ '{{.State.Running}}\t{{.State.Status}}\t{{if .State.Health}}{{.State.Health.Status}}{{end}}\t{{.State.ExitCode}}',
194
318
  name,
195
319
  ], {
196
320
  encoding: 'utf8',
@@ -225,35 +349,57 @@ export class DockerTestManager extends EventEmitter {
225
349
  }
226
350
  }
227
351
  async createContainer(options) {
352
+ const resources = options.resources;
353
+ if (resources?.memoryBytes !== undefined && (!Number.isSafeInteger(resources.memoryBytes) || resources.memoryBytes < 6 * 1024 * 1024))
354
+ throw new RangeError('memoryBytes must be a safe integer of at least 6 MiB');
355
+ if (resources?.cpus !== undefined && (!Number.isFinite(resources.cpus) || resources.cpus <= 0))
356
+ throw new RangeError('cpus must be a finite positive number');
357
+ if (resources?.pidsLimit !== undefined && (!Number.isSafeInteger(resources.pidsLimit) || resources.pidsLimit < 1))
358
+ throw new RangeError('pidsLimit must be a positive safe integer');
228
359
  const id = `test-${randomBytes(8).toString('hex')}`;
229
360
  const name = options.name || `container-${id}`;
230
361
  const host = '127.0.0.1';
231
- try {
232
- execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
233
- this.log(`Removed existing container: ${name}`);
234
- }
235
- catch {
236
- }
362
+ const autoPorts = new Set();
237
363
  const portMappings = new Map();
238
364
  if (options.ports) {
239
365
  for (const [containerPort, hostPort] of Object.entries(options.ports)) {
240
366
  const cPort = parseInt(containerPort);
367
+ if (hostPort === 'auto')
368
+ autoPorts.add(cPort);
241
369
  const hPort = hostPort === 'auto' ? await this.findAvailablePort() : hostPort;
242
370
  portMappings.set(cPort, hPort);
243
371
  }
244
372
  }
245
373
  const dockerArgs = ['run', '-d', '--name', name];
246
- portMappings.forEach((hostPort, containerPort) => {
247
- dockerArgs.push('-p', `${hostPort}:${containerPort}`);
248
- });
374
+ if (resources?.memoryBytes !== undefined)
375
+ dockerArgs.push('--memory', String(resources.memoryBytes));
376
+ if (resources?.cpus !== undefined)
377
+ dockerArgs.push('--cpus', String(resources.cpus));
378
+ if (resources?.pidsLimit !== undefined)
379
+ dockerArgs.push('--pids-limit', String(resources.pidsLimit));
380
+ const portArgsStart = dockerArgs.length;
381
+ const writePortArgs = () => {
382
+ const args = [];
383
+ portMappings.forEach((hostPort, containerPort) => {
384
+ args.push('-p', `127.0.0.1:${hostPort}:${containerPort}`);
385
+ });
386
+ return args;
387
+ };
388
+ dockerArgs.push(...writePortArgs());
389
+ const portArgsLength = dockerArgs.length - portArgsStart;
390
+ const rebuildPortArgs = () => {
391
+ dockerArgs.splice(portArgsStart, portArgsLength, ...writePortArgs());
392
+ };
249
393
  const environment = options.environment || {};
250
394
  for (const [key, value] of Object.entries(environment)) {
251
395
  dockerArgs.push('-e', `${key}=${value}`);
252
396
  }
253
397
  const labels = {
398
+ ...options.labels,
254
399
  'test.id': id,
255
400
  'test.cleanup': 'true',
256
- ...options.labels,
401
+ 'test.manager': this.managerId,
402
+ 'test.host': DockerTestManager.hostId,
257
403
  };
258
404
  for (const [key, value] of Object.entries(labels)) {
259
405
  dockerArgs.push('--label', `${key}=${value}`);
@@ -269,22 +415,7 @@ export class DockerTestManager extends EventEmitter {
269
415
  dockerArgs.push('--network', network);
270
416
  }
271
417
  if (options.healthcheck) {
272
- let healthCmd;
273
- if (Array.isArray(options.healthcheck.test)) {
274
- if (options.healthcheck.test[0] === 'CMD-SHELL') {
275
- healthCmd = options.healthcheck.test.slice(1).join(' ');
276
- }
277
- else if (options.healthcheck.test[0] === 'CMD') {
278
- healthCmd = options.healthcheck.test.slice(1).join(' ');
279
- }
280
- else {
281
- healthCmd = options.healthcheck.test.join(' ');
282
- }
283
- }
284
- else {
285
- healthCmd = options.healthcheck.test;
286
- }
287
- dockerArgs.push('--health-cmd', healthCmd);
418
+ dockerArgs.push('--health-cmd', dockerHealthCommand(options.healthcheck.test));
288
419
  if (options.healthcheck.interval) {
289
420
  dockerArgs.push('--health-interval', options.healthcheck.interval);
290
421
  }
@@ -300,51 +431,56 @@ export class DockerTestManager extends EventEmitter {
300
431
  }
301
432
  dockerArgs.push(options.image);
302
433
  if (options.command) {
303
- dockerArgs.push('sh', '-c', options.command);
304
- }
305
- if (this.verbose) {
306
- console.log(`Starting container ${name}: docker ${dockerArgs.join(' ')}`);
434
+ if (Array.isArray(options.command))
435
+ dockerArgs.push(...options.command);
436
+ else
437
+ dockerArgs.push('sh', '-c', options.command);
307
438
  }
308
- try {
439
+ let containerId;
440
+ for (let attempt = 0;; attempt++) {
309
441
  this.log(`Starting container: ${name}`, { image: options.image });
310
- const result = execFileSync(this.dockerPath, dockerArgs, {
311
- encoding: 'utf8',
312
- stdio: ['pipe', 'pipe', 'pipe'],
313
- });
314
- if (this.verbose && result) {
315
- console.log(result);
316
- }
317
- }
318
- catch (error) {
319
- portMappings.forEach((port) => {
320
- this.usedPorts.delete(port);
442
+ const result = await new Promise(resolve => {
443
+ execFile(this.dockerPath, dockerArgs, { encoding: 'utf8', timeout: this.startupTimeout, maxBuffer: 2 * 1024 * 1024 }, (error, stdout, stderr) => resolve({ status: error ? (typeof error.code === 'number' ? error.code : null) : 0,
444
+ stdout, stderr, ...(error && typeof error.code !== 'number' ? { error } : {}) }));
321
445
  });
322
- const execError = error;
323
- const stderr = execError.stderr ? String(execError.stderr).trim() : '';
324
- const stdout = execError.stdout ? String(execError.stdout).trim() : '';
325
- const message = execError.message || String(error);
326
- if (stderr.includes('already in use') || stderr.includes('name is already') || stderr.includes('Conflict')) {
327
- throw new Error(`Container name conflict: ${name} already exists.\n` +
328
- `Please ensure previous test containers are cleaned up.\n` +
329
- `Stderr: ${stderr}`);
330
- }
331
- throw new Error(`Failed to start container ${name}:\n` +
332
- `Command: docker ${dockerArgs.join(' ')}\n` +
333
- `Exit code: ${execError.status || 'unknown'}\n` +
334
- (stderr ? `Stderr: ${stderr}\n` : '') +
335
- (stdout ? `Stdout: ${stdout}\n` : '') +
336
- (message && !stderr && !stdout ? `Error: ${message}` : ''));
446
+ containerId = (result.stdout ?? '').trim();
447
+ if (result.status === 0 && /^[a-f0-9]{64}$/.test(containerId))
448
+ break;
449
+ portMappings.forEach(port => this.usedPorts.delete(port));
450
+ let diagnostic = (result.stderr ?? '').trim();
451
+ for (const value of Object.values(environment)) {
452
+ if (value)
453
+ diagnostic = diagnostic.replaceAll(value, '[redacted]');
454
+ }
455
+ if (/container name .*already in use|name is already in use/i.test(diagnostic)) {
456
+ throw new Error(`Container name conflict: ${name} already exists`);
457
+ }
458
+ const residue = execFileSync(this.dockerPath, ['ps', '-aq', '--no-trunc',
459
+ '--filter', `label=test.id=${id}`, '--filter', `label=test.manager=${this.managerId}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
460
+ if (/^[a-f0-9]{64}$/.test(residue)) {
461
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', residue], { stdio: 'ignore' });
462
+ }
463
+ if (result.error)
464
+ throw new Error(`Could not execute Docker for ${name}: ${result.error.code ?? 'unknown'}`);
465
+ if (!/port is already allocated|address already in use|Bind for /.test(diagnostic)
466
+ || !autoPorts.size || attempt >= DockerTestManager.PORT_COLLISION_RETRIES) {
467
+ throw new Error(`Failed to start container ${name} (${options.image}), exit ${result.status ?? 'unknown'}: ${diagnostic.slice(0, 2000) || 'Docker did not confirm creation'}`);
468
+ }
469
+ for (const port of autoPorts)
470
+ portMappings.set(port, await this.findAvailablePort());
471
+ rebuildPortArgs();
472
+ this.log(`Host port collision for ${name}, retrying with fresh ports`, { attempt: attempt + 1 });
337
473
  }
338
474
  if (options.waitFor) {
339
475
  try {
340
- await this.waitForContainer(name, options.waitFor);
476
+ await this.waitForContainer(containerId, options.waitFor, portMappings);
341
477
  this.log(`Container ready: ${name}`);
342
478
  }
343
479
  catch (error) {
344
480
  this.logError(`Container ${name} failed to become ready, cleaning up`, error);
345
481
  try {
346
- execFileSync(this.dockerPath, ['stop', '-t', '5', name], { stdio: 'ignore' });
347
- execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
482
+ execFileSync(this.dockerPath, ['stop', '-t', '5', containerId], { stdio: 'ignore' });
483
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', containerId], { stdio: 'ignore' });
348
484
  }
349
485
  catch {
350
486
  }
@@ -382,174 +518,97 @@ export class DockerTestManager extends EventEmitter {
382
518
  networks,
383
519
  createdAt: new Date(),
384
520
  internalIp,
385
- getStatus: async () => this.getContainerStatus(name),
386
- isHealthy: async () => this.isContainerHealthy(name),
521
+ getStatus: async () => this.getContainerStatus(containerId),
522
+ isHealthy: async () => this.isContainerHealthy(containerId),
387
523
  cleanup: async () => {
388
- await this.cleanupContainerWithRetry(name, id, portMappings);
524
+ await this.cleanupContainerWithRetry(containerId, id, portMappings);
389
525
  },
390
526
  };
391
527
  this.containers.set(id, container);
392
528
  return container;
393
529
  }
394
- async cleanupContainerWithRetry(name, id, portMappings) {
395
- this.log(`Starting cleanup for container: ${name}`);
396
- let lastError = null;
397
- for (let attempt = 1; attempt <= this.maxCleanupRetries; attempt++) {
398
- try {
399
- try {
400
- const status = await this.getContainerStatus(name);
401
- if (!status.isRunning) {
402
- this.log(`Container ${name} is not running, force removing`, { attempt });
403
- }
404
- }
405
- catch {
406
- this.log(`Container ${name} doesn't exist, skipping stop`, { attempt });
407
- break;
408
- }
409
- try {
410
- const stopTimeoutSecs = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
411
- this.log(`Stopping container ${name}`, { attempt, timeout: this.gracefulShutdownTimeout });
412
- execFileSync(this.dockerPath, ['stop', '-t', stopTimeoutSecs, name], {
413
- stdio: 'ignore',
414
- timeout: this.gracefulShutdownTimeout + 5000,
415
- });
416
- this.log(`Container stopped: ${name}`, { attempt });
417
- }
418
- catch (error) {
419
- this.logError(`Failed to gracefully stop container ${name}`, error);
420
- }
421
- try {
422
- this.log(`Removing container ${name}`, { attempt });
423
- execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
424
- this.log(`Container removed: ${name}`, { attempt });
425
- lastError = null;
426
- break;
427
- }
428
- catch (error) {
429
- lastError = error instanceof Error ? error : new Error(String(error));
430
- if (attempt === this.maxCleanupRetries) {
431
- throw lastError;
432
- }
433
- await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
434
- }
435
- }
436
- catch (error) {
437
- lastError = error instanceof Error ? error : new Error(String(error));
438
- if (attempt === this.maxCleanupRetries) {
439
- this.logError(`Final cleanup attempt failed for container ${name}`, lastError);
440
- }
441
- else {
442
- this.logError(`Cleanup attempt ${attempt} failed for container ${name}, retrying`, lastError);
443
- await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
444
- }
445
- }
446
- }
530
+ async cleanupContainerWithRetry(containerId, id, portMappings) {
531
+ if (!this.containers.has(id))
532
+ return;
533
+ const seconds = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
447
534
  try {
448
- portMappings.forEach((port) => {
449
- this.usedPorts.delete(port);
450
- this.log(`Released port: ${port}`);
535
+ execFileSync(this.dockerPath, ['stop', '-t', seconds, containerId], {
536
+ stdio: 'ignore', timeout: this.gracefulShutdownTimeout + 5000,
451
537
  });
452
538
  }
453
539
  catch (error) {
454
- this.logError('Failed to release ports', error);
540
+ this.logError(`Could not stop test container ${containerId} gracefully`, error);
455
541
  }
456
- this.containers.delete(id);
457
- this.log(`Container cleanup completed: ${name}`, { attempts: this.maxCleanupRetries });
458
- }
459
- async ensureNetwork(network) {
460
- if (!this.networks.has(network)) {
542
+ for (let attempt = 1;; attempt++) {
461
543
  try {
462
- execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
463
- stdio: 'pipe',
464
- encoding: 'utf8',
465
- });
466
- this.networks.add(network);
467
- this.log(`Created network: ${network}`);
544
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', containerId], { stdio: ['ignore', 'ignore', 'pipe'] });
545
+ break;
468
546
  }
469
547
  catch (error) {
470
- const execError = error;
471
- const stderr = execError.stderr || execError.message || String(error);
472
- if (stderr.includes('already exists') || stderr.includes('network with name')) {
473
- this.log(`Network already exists: ${network}`);
474
- this.networks.add(network);
475
- }
476
- else if (stderr.includes('all predefined address pools have been fully subnetted')) {
477
- this.log('Docker network pool exhausted, attempting cleanup...');
478
- try {
479
- execFileSync(this.dockerPath, ['network', 'prune', '-f'], {
480
- stdio: 'ignore',
481
- });
482
- this.log('Cleaned up unused networks, retrying network creation...');
483
- execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
484
- stdio: 'pipe',
485
- encoding: 'utf8',
486
- });
487
- this.networks.add(network);
488
- this.log(`Created network after cleanup: ${network}`);
489
- }
490
- catch (retryError) {
491
- throw new Error(`Failed to create network ${network} even after cleanup: ${stderr}`);
492
- }
493
- }
494
- else {
495
- throw new Error(`Failed to create network ${network}: ${stderr}`);
496
- }
548
+ if (/no such (container|object)/i.test(String(error.stderr)))
549
+ break;
550
+ if (attempt >= this.maxCleanupRetries)
551
+ throw error;
552
+ await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
497
553
  }
498
554
  }
555
+ portMappings.forEach(port => this.usedPorts.delete(port));
556
+ this.containers.delete(id);
557
+ }
558
+ async ensureNetwork(network) {
559
+ const create = () => {
560
+ const networkId = execFileSync(this.dockerPath, ['network', 'create', network,
561
+ '--label', 'test.cleanup=true', '--label', `test.manager=${this.managerId}`,
562
+ '--label', `test.host=${DockerTestManager.hostId}`], { stdio: 'pipe', encoding: 'utf8' }).trim();
563
+ this.networks.set(network, networkId);
564
+ };
565
+ try {
566
+ create();
567
+ }
568
+ catch (error) {
569
+ const reason = String(error.stderr ?? error);
570
+ if (reason.includes('already exists'))
571
+ return;
572
+ if (!reason.includes('all predefined address pools have been fully subnetted'))
573
+ throw error;
574
+ execFileSync(this.dockerPath, ['network', 'prune', '-f', '--filter', `label=test.manager=${this.managerId}`], { stdio: 'ignore' });
575
+ create();
576
+ }
499
577
  }
500
578
  async removeNetwork(network) {
501
- if (!this.networks.has(network)) {
579
+ const id = this.networks.get(network);
580
+ if (!id)
502
581
  return;
503
- }
504
582
  try {
505
- execFileSync(this.dockerPath, ['network', 'rm', network], {
506
- stdio: 'ignore',
507
- });
508
- this.networks.delete(network);
509
- this.log(`Removed network: ${network}`);
583
+ execFileSync(this.dockerPath, ['network', 'rm', id], { stdio: ['ignore', 'ignore', 'pipe'] });
510
584
  }
511
585
  catch (error) {
512
- this.networks.delete(network);
513
- this.logError(`Failed to remove network ${network}`, error);
586
+ if (!/not found|no such network/i.test(String(error.stderr)))
587
+ throw error;
514
588
  }
589
+ this.networks.delete(network);
515
590
  }
516
- async waitForContainer(name, options) {
591
+ async waitForContainer(name, options, ports) {
517
592
  const startTime = Date.now();
518
593
  const timeout = options?.timeout || this.startupTimeout;
519
594
  let lastError;
520
595
  while (Date.now() - startTime < timeout) {
521
596
  try {
522
597
  const status = await this.getContainerStatus(name);
598
+ if (!status.state)
599
+ throw new Error('Container status is unavailable');
523
600
  if (!status.isRunning) {
524
- throw new Error(`Container exited with status '${status.state}' and exit code ${status.exitCode}. ` +
525
- `Check container logs with 'docker logs ${name}'`);
526
- }
527
- if (options?.healthcheck) {
528
- if (status.health === 'healthy') {
529
- this.log(`Container ${name} is healthy`);
530
- return;
531
- }
532
- if (status.health === 'unhealthy') {
533
- throw new Error(`Container ${name} health check failed. ` + `Check container logs with 'docker logs ${name}'`);
534
- }
535
- if (status.health === 'starting') {
536
- this.log(`Waiting for health check on ${name}...`, { elapsed: Date.now() - startTime });
537
- }
601
+ throw new Error(`Container ${name} exited with status '${status.state}' and exit code ${status.exitCode}`);
538
602
  }
539
- if (options?.port) {
540
- const container = this.containers.get(name);
541
- if (container) {
542
- const hostPort = container.ports.get(options.port);
543
- if (hostPort && (await this.isPortListening('127.0.0.1', hostPort))) {
544
- this.log(`Port ${hostPort} is listening on ${name}`);
545
- return;
546
- }
547
- }
603
+ if (options?.healthcheck && status.health === 'unhealthy') {
604
+ const probes = execFileSync(this.dockerPath, ['inspect', '--format',
605
+ '{{with .State.Health}}{{.FailingStreak}} failed probes{{range .Log}}; exit={{.ExitCode}} at {{.End}}{{end}}{{end}}', name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
606
+ throw new Error(`Container ${name} health check failed after ${Date.now() - startTime} ms (${probes})`);
548
607
  }
549
- if (!options?.healthcheck && !options?.port) {
550
- this.log(`Container ${name} is running`);
608
+ const hostPort = options?.port && ports.get(options.port);
609
+ if ((!options?.healthcheck || status.health === 'healthy') &&
610
+ (!options?.port || (hostPort && await this.isPortListening('127.0.0.1', hostPort))))
551
611
  return;
552
- }
553
612
  lastError = undefined;
554
613
  }
555
614
  catch (error) {
@@ -594,50 +653,22 @@ export class DockerTestManager extends EventEmitter {
594
653
  await container.cleanup();
595
654
  }
596
655
  }
597
- async cleanupAll() {
598
- if (this.cleanupInProgress) {
599
- this.log('Cleanup already in progress, skipping');
600
- return;
601
- }
602
- this.cleanupInProgress = true;
603
- try {
604
- this.log(`Starting cleanup of ${this.containers.size} containers`);
605
- const cleanupPromises = Array.from(this.containers.values()).map((container) => container
606
- .cleanup()
607
- .then(() => {
608
- this.log(`Cleanup succeeded: ${container.name}`);
609
- })
610
- .catch((error) => {
611
- this.logError(`Cleanup failed for ${container.name}`, error);
612
- }));
613
- const results = await Promise.allSettled(cleanupPromises);
614
- const failed = results.filter((r) => r.status === 'rejected').length;
615
- if (failed > 0) {
616
- this.log(`Cleanup completed with ${failed} failures`);
617
- }
618
- else {
619
- this.log('All containers cleaned up successfully');
656
+ cleanupAll() {
657
+ return this.activeCleanup ??= this.cleanupOwnedResources().finally(() => { this.activeCleanup = undefined; });
658
+ }
659
+ async cleanupOwnedResources() {
660
+ const results = await Promise.allSettled(Array.from(this.containers.values(), container => container.cleanup()));
661
+ const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
662
+ for (const network of this.networks.keys()) {
663
+ try {
664
+ await this.removeNetwork(network);
620
665
  }
621
- this.log(`Cleaning up ${this.networks.size} networks`);
622
- const networkArray = Array.from(this.networks);
623
- for (const network of networkArray) {
624
- try {
625
- this.log(`Removing network: ${network}`);
626
- execFileSync(this.dockerPath, ['network', 'rm', network], { stdio: 'ignore' });
627
- this.log(`Network removed: ${network}`);
628
- }
629
- catch (error) {
630
- this.logError(`Failed to remove network ${network}`, error);
631
- }
666
+ catch (error) {
667
+ errors.push(error);
632
668
  }
633
- this.containers.clear();
634
- this.usedPorts.clear();
635
- this.networks.clear();
636
- this.log('Final cleanup completed');
637
- }
638
- finally {
639
- this.cleanupInProgress = false;
640
669
  }
670
+ if (errors.length)
671
+ throw new AggregateError(errors, 'Some Docker test resources could not be removed');
641
672
  }
642
673
  async cleanupAllAsync() {
643
674
  this.log('Initiating graceful cleanup of all test containers');
@@ -661,7 +692,7 @@ export class DockerTestManager extends EventEmitter {
661
692
  }
662
693
  cleanupSyncWindows() {
663
694
  try {
664
- const containerIds = execFileSync(this.dockerPath, ['ps', '-a', '--filter', 'label=test.cleanup=true', '-q'], {
695
+ const containerIds = execFileSync(this.dockerPath, ['ps', '-a', '--filter', `label=test.manager=${this.managerId}`, '-q'], {
665
696
  encoding: 'utf8',
666
697
  stdio: ['pipe', 'pipe', 'ignore'],
667
698
  }).trim();
@@ -678,7 +709,7 @@ export class DockerTestManager extends EventEmitter {
678
709
  catch {
679
710
  }
680
711
  this.log(`Removing container: ${trimmedId}`);
681
- execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
712
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', trimmedId], { stdio: 'ignore' });
682
713
  this.log(`Container removed: ${trimmedId}`);
683
714
  }
684
715
  catch (error) {
@@ -687,7 +718,7 @@ export class DockerTestManager extends EventEmitter {
687
718
  }
688
719
  }
689
720
  try {
690
- const networkIds = execFileSync(this.dockerPath, ['network', 'ls', '--filter', 'label=test.cleanup=true', '-q'], {
721
+ const networkIds = execFileSync(this.dockerPath, ['network', 'ls', '--filter', `label=test.manager=${this.managerId}`, '-q'], {
691
722
  encoding: 'utf8',
692
723
  stdio: ['pipe', 'pipe', 'ignore'],
693
724
  }).trim();
@@ -716,7 +747,7 @@ export class DockerTestManager extends EventEmitter {
716
747
  }
717
748
  cleanupSyncUnix() {
718
749
  try {
719
- const containerCmd = `"${this.dockerPath}" ps -a --filter "label=test.cleanup=true" -q`;
750
+ const containerCmd = `"${this.dockerPath}" ps -a --filter "label=test.manager=${this.managerId}" -q`;
720
751
  try {
721
752
  const ids = execSync(containerCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
722
753
  if (ids) {
@@ -732,7 +763,7 @@ export class DockerTestManager extends EventEmitter {
732
763
  catch {
733
764
  }
734
765
  this.log(`Removing container: ${trimmedId}`);
735
- execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
766
+ execFileSync(this.dockerPath, ['rm', '-f', '-v', trimmedId], { stdio: 'ignore' });
736
767
  this.log(`Container removed: ${trimmedId}`);
737
768
  }
738
769
  catch (error) {
@@ -745,7 +776,7 @@ export class DockerTestManager extends EventEmitter {
745
776
  this.logError('Failed to cleanup containers', error);
746
777
  }
747
778
  try {
748
- const networkCmd = `"${this.dockerPath}" network ls --filter "label=test.cleanup=true" -q`;
779
+ const networkCmd = `"${this.dockerPath}" network ls --filter "label=test.manager=${this.managerId}" -q`;
749
780
  const ids = execSync(networkCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
750
781
  if (ids) {
751
782
  const networkIds = ids.split('\n').filter((id) => id.trim());
@@ -766,7 +797,7 @@ export class DockerTestManager extends EventEmitter {
766
797
  this.logError('Failed to cleanup networks', error);
767
798
  }
768
799
  try {
769
- const volumeCmd = `"${this.dockerPath}" volume ls --filter "label=test.cleanup=true" -q`;
800
+ const volumeCmd = `"${this.dockerPath}" volume ls --filter "label=test.manager=${this.managerId}" -q`;
770
801
  const ids = execSync(volumeCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
771
802
  if (ids) {
772
803
  const volumeIds = ids.split('\n').filter((id) => id.trim());