node/test/parallel/test-worker-message-transfer-port-mark-as-untransferable.js
Anna Henningsen 88fb5a5c79
worker: add public method for marking objects as untransferable
We currently mark a number of `ArrayBuffer`s as not transferable,
including the `Buffer` pool and ones with finalizers provided
by C++ addons.

There is no good reason to assume that userland code might not
encounter similar problems, for example when doing `ArrayBuffer`
pooling similar to ours. Therefore, provide an API that lets
userland code also mark objects as not transferable.

PR-URL: https://github.com/nodejs/node/pull/33979
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Gus Caplan <me@gus.host>
2020-06-25 08:33:29 -07:00

38 lines
1005 B
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { MessageChannel, markAsUntransferable } = require('worker_threads');
{
const ab = new ArrayBuffer(8);
markAsUntransferable(ab);
assert.strictEqual(ab.byteLength, 8);
const { port1, port2 } = new MessageChannel();
port1.postMessage(ab, [ ab ]);
assert.strictEqual(ab.byteLength, 8); // The AB is not detached.
port2.once('message', common.mustCall());
}
{
const channel1 = new MessageChannel();
const channel2 = new MessageChannel();
markAsUntransferable(channel2.port1);
assert.throws(() => {
channel1.port1.postMessage(channel2.port1, [ channel2.port1 ]);
}, /was found in message but not listed in transferList/);
channel2.port1.postMessage('still works, not closed/transferred');
channel2.port2.once('message', common.mustCall());
}
{
for (const value of [0, null, false, true, undefined, [], {}]) {
markAsUntransferable(value); // Has no visible effect.
}
}