DittoPglite: prevent starting PGlite instances in worker threads

This commit is contained in:
Alex Gleason
2024-09-25 14:31:01 -05:00
parent 606aeb3236
commit 350671db47
3 changed files with 52 additions and 6 deletions

30
src/utils/worker.test.ts Normal file
View File

@@ -0,0 +1,30 @@
import { assertEquals } from '@std/assert';
import { isWorker } from '@/utils/worker.ts';
Deno.test('isWorker from the main thread returns false', () => {
assertEquals(isWorker(), false);
});
Deno.test('isWorker from a worker thread returns true', async () => {
const script = `
import { isWorker } from '@/utils/worker.ts';
postMessage(isWorker());
self.close();
`;
const worker = new Worker(
URL.createObjectURL(new Blob([script], { type: 'application/javascript' })),
{ type: 'module' },
);
const result = await new Promise<boolean>((resolve) => {
worker.onmessage = (e) => {
resolve(e.data);
};
});
worker.terminate();
assertEquals(result, true);
});

9
src/utils/worker.ts Normal file
View File

@@ -0,0 +1,9 @@
/**
* Detect if this thread is running in a Worker context.
*
* https://stackoverflow.com/a/18002694
*/
export function isWorker(): boolean {
// @ts-ignore This is fine.
return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
}