mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-10-02 21:33:52 +02:00
Fix Webpack erroring with worker_threads import, unref Worker so process can terminate
This commit is contained in:
@@ -10,13 +10,51 @@ import { assert, type WorkerCommand, type WorkerResponse, type WorkerResponseDat
|
||||
// @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
|
||||
import createWorker from './codec.worker';
|
||||
|
||||
let workerPromise: Promise<Worker> | null;
|
||||
type ExtendedWorker = Worker & {
|
||||
ref?: () => void;
|
||||
unref?: () => void;
|
||||
};
|
||||
|
||||
let workerPromise: Promise<ExtendedWorker> | null;
|
||||
let nextMessageId = 0;
|
||||
const pendingMessages = new Map<number, {
|
||||
resolve: (value: WorkerResponseData) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}>();
|
||||
|
||||
let refCount = 0;
|
||||
let keepAliveInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
export const refWorker = async () => {
|
||||
refCount++;
|
||||
if (refCount === 1) {
|
||||
keepAliveInterval = setInterval(() => {}, 2 ** 31 - 1);
|
||||
const worker = await ensureWorker();
|
||||
worker.ref?.();
|
||||
}
|
||||
};
|
||||
|
||||
export const unrefWorker = async () => {
|
||||
refCount--;
|
||||
if (refCount === 0) {
|
||||
if (keepAliveInterval !== null) {
|
||||
clearInterval(keepAliveInterval);
|
||||
keepAliveInterval = null;
|
||||
}
|
||||
|
||||
const worker = await workerPromise;
|
||||
if (worker) {
|
||||
if (worker.unref) {
|
||||
worker.unref(); // If we don't do this, then the Node process never terminates by itself
|
||||
} else if (typeof window === 'undefined') {
|
||||
// Non-browser environment without unref - terminate instead
|
||||
worker.terminate();
|
||||
workerPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const sendCommand = async <T extends string>(
|
||||
command: WorkerCommand & { type: T },
|
||||
transferables?: Transferable[],
|
||||
@@ -41,7 +79,8 @@ export const sendCommand = async <T extends string>(
|
||||
const ensureWorker = () => {
|
||||
return workerPromise ??= (async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
const worker = (await createWorker()) as Worker;
|
||||
const worker = (await createWorker()) as ExtendedWorker;
|
||||
worker.unref?.(); // Start unreffed
|
||||
|
||||
const onMessage = (data: WorkerResponse) => {
|
||||
const pending = pendingMessages.get(data.id);
|
||||
|
||||
Reference in New Issue
Block a user