Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions src/test/common/testResources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
interface Release {
name: string;
release: () => unknown;
}

/** Own test resources in dependency order, including partially acquired fixtures. */
export class TestResources<Phase extends string> {
private readonly releases = new Map<Phase, Release[]>();
private disposal?: Promise<void>;

constructor(
private readonly phases: readonly Phase[],
private readonly timeoutMs = 15000,
private readonly budgetMs = 50000,
) {}

add(phase: Phase, name: string, release: () => unknown): void {
const entries = this.releases.get(phase) ?? [];
entries.push({ name, release });
this.releases.set(phase, entries);
}

/** Runs once, retaining original errors alongside resource-release failures. */
dispose(originalErrors: readonly unknown[] = []): Promise<void> {
return (this.disposal ??= this.releaseAll(originalErrors));
}

private async releaseAll(originalErrors: readonly unknown[]): Promise<void> {
const errors = [...originalErrors];
const deadline = Date.now() + this.budgetMs;
for (const phase of this.phases) {
const entries = this.releases.get(phase);
// Discovery tasks may register individual resources in this phase.
while (entries?.length) {
const batch = entries.splice(0);
const results = await Promise.allSettled(
batch.map(({ release }) => {
let timer: ReturnType<typeof setTimeout>;
// Invoke through a promise so synchronous throws cannot skip siblings.
const operation = Promise.resolve().then(release);
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(
() =>
reject(
new Error(
'Cleanup timed out; operation may still be running',
),
),
Math.max(0, Math.min(this.timeoutMs, deadline - Date.now())),
);
});
// The race observes late rejections too; timing out does not cancel work.
return Promise.race([operation, timeout]).finally(() =>
clearTimeout(timer),
);
}),
);
results.forEach((result, index) => {
if (result.status === 'rejected') {
errors.push(
new Error(`Cleanup [${phase}] ${batch[index].name}`, {
cause: result.reason as unknown,
}),
);
}
});
}
}
if (errors.length) {
// Mocha's reporter need not expand AggregateError.errors or Error.cause.
// Include resource names and reasons in the visible message as well.
const describe = (error: unknown): string => {
if (error instanceof AggregateError) {
return `${error.message}: ${(error.errors as unknown[]).map(describe).join('; ')}`;
}
if (error instanceof Error) {
return error.cause === undefined
? error.message
: `${error.message}: ${describe(error.cause)}`;
}
return String(error);
};
throw new AggregateError(
errors,
`Test resource cleanup failed:\n${errors.map(describe).join('\n')}`,
);
}
}
}
64 changes: 64 additions & 0 deletions src/test/node/testResources.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestResources } from '../common/testResources';

suite('Test resource cleanup', () => {
test('aggregates sync and async failures, retains the original failure and continues in order', async () => {
const resources = new TestResources(['stop', 'remove']);
const original = new Error('setup failed');
const sync = new Error('sync stop failed');
const asyncError = new Error('async stop failed');
const calls: string[] = [];
resources.add('stop', 'sync resource', () => {
calls.push('sync');
throw sync;
});
resources.add('stop', 'async resource', () => Promise.reject(asyncError));
resources.add('stop', 'discover healthy resource', () => {
resources.add('stop', 'healthy resource', () => {
calls.push('healthy');
});
});
resources.add('remove', 'directory', () => {
calls.push('remove');
});
await assert.rejects(resources.dispose([original]), (error: unknown) => {
assert.ok(error instanceof AggregateError);
assert.strictEqual(error.errors[0], original);
assert.match(error.message, /Cleanup \[stop\] sync resource: sync stop failed/);
const failures = error.errors.slice(1) as Error[];
assert.deepStrictEqual(
failures.map((failure) => failure.cause),
[sync, asyncError],
);
assert.deepStrictEqual(
failures.map((failure) => failure.message),
['Cleanup [stop] sync resource', 'Cleanup [stop] async resource'],
);
return true;
});
assert.deepStrictEqual(calls, ['sync', 'healthy', 'remove']);
});

test('bounds a stuck release and still attempts the next phase', async () => {
const clock = sinon.useFakeTimers();
try {
const resources = new TestResources(['stop', 'remove'], 10, 20);
let removed = false;
resources.add('stop', 'stuck resource', () => new Promise(() => undefined));
resources.add('remove', 'directory', () => {
removed = true;
});
const result = assert.rejects(resources.dispose(), (error: unknown) => {
assert.ok(error instanceof AggregateError);
assert.match((error.errors[0] as Error).message, /\[stop\] stuck resource/);
return true;
});
await clock.tickAsync(10);
await result;
assert.ok(removed);
} finally {
clock.restore();
}
});
});
Loading
Loading