Skip to content

Commit

Permalink
fix: Handle errors emitted within worker threads (#270)
Browse files Browse the repository at this point in the history
Uncaught errors thrown within the worker will kill the entire
application. This PR handles this by listening for these errors and
terminating the thread if they arise.
  • Loading branch information
morgsmccauley authored Oct 6, 2023
1 parent ebadd12 commit 29e77c3
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion runner/src/stream-handler/stream-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default class StreamHandler {
private readonly worker?: Worker;

constructor (
streamKey: string
public readonly streamKey: string
) {
if (isMainThread) {
this.worker = new Worker(path.join(__dirname, 'worker.js'), {
Expand All @@ -19,11 +19,19 @@ export default class StreamHandler {
});

this.worker.on('message', this.handleMessage);
this.worker.on('error', this.handleError);
} else {
throw new Error('StreamHandler should not be instantiated in a worker thread');
}
}

private handleError (error: Error): void {
console.log(`Encountered error processing stream: ${this.streamKey}, terminating thread`, error);
this.worker?.terminate().catch(() => {
console.log(`Failed to terminate thread for stream: ${this.streamKey}`);
});
}

private handleMessage (message: Message): void {
if (METRICS[message.type] instanceof Gauge) {
(METRICS[message.type] as Gauge).labels(message.labels).set(message.value);
Expand Down

0 comments on commit 29e77c3

Please sign in to comment.