From 3bd3c9cc08b974885edb2b7d7b0c7d72100a0192 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Sun, 5 Mar 2023 16:51:06 +0800 Subject: [PATCH] test(napi): tests for custom gc in worker_threads (#1505) --- examples/napi/__test__/worker-thread.spec.ts | 40 +++++++++++++++++++ examples/napi/__test__/worker.js | 41 ++++++++++++++++++-- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/examples/napi/__test__/worker-thread.spec.ts b/examples/napi/__test__/worker-thread.spec.ts index 74423849..11778421 100644 --- a/examples/napi/__test__/worker-thread.spec.ts +++ b/examples/napi/__test__/worker-thread.spec.ts @@ -13,6 +13,7 @@ t('should be able to require in worker thread', async (t) => { Array.from({ length: 100 }).map(() => { const w = new Worker(join(__dirname, 'worker.js')) return new Promise((resolve, reject) => { + w.postMessage({ type: 'require' }) w.on('message', (msg) => { t.is(msg, Animal.withKind(Kind.Cat).whoami() + DEFAULT_COST) resolve() @@ -28,3 +29,42 @@ t('should be able to require in worker thread', async (t) => { }), ) }) + +t('custom GC works on worker_threads', async (t) => { + await Promise.all( + Array.from({ length: 50 }).map(() => + Promise.all([ + new Promise((resolve, reject) => { + const w = new Worker(join(__dirname, 'worker.js')) + w.postMessage({ + type: 'async:buffer', + }) + w.on('message', (msg) => { + t.is(msg, 'done') + resolve(w) + }) + w.on('error', (err) => { + reject(err) + }) + }).then((w) => { + return w.terminate() + }), + new Promise((resolve, reject) => { + const w = new Worker(join(__dirname, 'worker.js')) + w.postMessage({ + type: 'async:arraybuffer', + }) + w.on('message', (msg) => { + t.is(msg, 'done') + resolve(w) + }) + w.on('error', (err) => { + reject(err) + }) + }).then((w) => { + return w.terminate() + }), + ]), + ), + ) +}) diff --git a/examples/napi/__test__/worker.js b/examples/napi/__test__/worker.js index fee47128..392041a5 100644 --- a/examples/napi/__test__/worker.js +++ b/examples/napi/__test__/worker.js @@ -2,6 +2,41 @@ const { parentPort } = require('worker_threads') const native = require('../index') -parentPort.postMessage( - native.Animal.withKind(native.Kind.Cat).whoami() + native.DEFAULT_COST, -) +parentPort.on('message', ({ type }) => { + switch (type) { + case 'require': + parentPort.postMessage( + native.Animal.withKind(native.Kind.Cat).whoami() + native.DEFAULT_COST, + ) + break + case 'async:buffer': + Promise.all( + Array.from({ length: 100 }).map(() => + native.bufferPassThrough(Buffer.from([1, 2, 3])), + ), + ) + .then(() => { + parentPort.postMessage('done') + }) + .catch((e) => { + throw e + }) + break + case 'async:arraybuffer': + Promise.all( + Array.from({ length: 100 }).map(() => + native.arrayBufferPassThrough(Uint8Array.from([1, 2, 3])), + ), + ) + .then(() => { + parentPort.postMessage('done') + }) + .catch((e) => { + throw e + }) + + break + default: + throw new TypeError(`Unknown message type: ${type}`) + } +})