node/test/parallel/test-worker-message-transfer-port-mark-as-untransferable.js
Chengzhong Wu 64549731b6
src: throw DataCloneError on transfering untransferable objects
The HTML StructuredSerializeWithTransfer algorithm defines that when
an untransferable object is in the transfer list, a DataCloneError is
thrown.
An array buffer that is already transferred is also considered as
untransferable.

PR-URL: https://github.com/nodejs/node/pull/47604
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
2023-05-05 11:22:42 +00:00

60 lines
1.5 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { MessageChannel, markAsUntransferable, isMarkedAsUntransferable } = require('worker_threads');
{
const ab = new ArrayBuffer(8);
markAsUntransferable(ab);
assert.ok(isMarkedAsUntransferable(ab));
assert.strictEqual(ab.byteLength, 8);
const { port1 } = new MessageChannel();
assert.throws(() => port1.postMessage(ab, [ ab ]), {
code: 25,
name: 'DataCloneError',
});
assert.strictEqual(ab.byteLength, 8); // The AB is not detached.
}
{
const channel1 = new MessageChannel();
const channel2 = new MessageChannel();
markAsUntransferable(channel2.port1);
assert.ok(isMarkedAsUntransferable(channel2.port1));
assert.throws(() => {
channel1.port1.postMessage(channel2.port1, [ channel2.port1 ]);
}, {
code: 25,
name: 'DataCloneError',
});
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.
assert.ok(!isMarkedAsUntransferable(value));
}
for (const value of [[], {}]) {
markAsUntransferable(value);
assert.ok(isMarkedAsUntransferable(value));
}
}
{
// Verifies that the mark is not inherited.
class Foo {}
markAsUntransferable(Foo.prototype);
assert.ok(isMarkedAsUntransferable(Foo.prototype));
const foo = new Foo();
assert.ok(!isMarkedAsUntransferable(foo));
}