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
4 changes: 4 additions & 0 deletions docker-run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/bash
NODE_VERSION=${NODE_VERSION:-21.7.1}
# easily run node commands through docker
docker run --user $(id -u):$(id -g) --rm -it -v .:/app -w /app --env-file <(env) "node:${NODE_VERSION}-alpine" "$@"
12 changes: 12 additions & 0 deletions src/CreateThreadosaurus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ import { extname } from 'path';
import TrackedPromise from './TrackedPromise';
import { Expect } from './Expect';

const FORCE_EXIT_MESSAGE = 'force_exit';

export function CreateThreadosaurus<T extends Threadosaurus>(
ClassRef: new (...args: unknown[]) => T,
maxRunTimeMs: number = 0,
forceTerminate: boolean = false,
) {
const instance = new ClassRef();
if (typeof instance.get__filename !== 'function') {
Expand Down Expand Up @@ -44,6 +47,9 @@ export function CreateThreadosaurus<T extends Threadosaurus>(
}
try {
weAreTerminating = true;
if (forceTerminate) {
worker.postMessage(FORCE_EXIT_MESSAGE);
}
await worker.terminate();
} catch {
//ignore
Expand Down Expand Up @@ -91,6 +97,12 @@ if (!isMainThread) {
// this is not intended for this class
return;
}
parentPort?.on('message', (message: string) => {
if (message === FORCE_EXIT_MESSAGE) {
process.exit(-1);
}
});

let filename = input.filename;

if (!extname(filename)) {
Expand Down
6 changes: 6 additions & 0 deletions test/SampleClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ export default class SampleClass implements Threadosaurus {
return new Promise((resolve) => setTimeout(resolve, 1000));
}

infinite(): Promise<void> {
while (true) {
/* empty */
}
}

async exit(code: number): Promise<void> {
process.exit(code);
}
Expand Down
9 changes: 9 additions & 0 deletions test/create-threadosaurus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ describe('CreateThreadosaurus', () => {
expect(String(e)).toEqual('Error: CreateThreadosaurus execution timed out');
}
});
it('test timeout with forced terminate', async () => {
const worker = CreateThreadosaurus(SampleClass, 100, true);
try {
await worker.infinite();
fail('this should fail');
} catch (e) {
expect(String(e)).toEqual('Error: CreateThreadosaurus execution timed out');
}
});
it('test missing get__filename', async () => {
try {
class AnyClass {}
Expand Down
Loading