@vscode/sync-api-common
Version:
An RPC implementation between Web and NodeJS workers that works sync
57 lines (55 loc) • 2.44 kB
JavaScript
;
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cancellation = void 0;
var Cancellation;
(function (Cancellation) {
/**
* Adds cancellation data to a message. Such a message is usually send via
* `MessagePort.postMessage` to another web worker using a *asynchronous*
* message channel. The function is therefore called on the sending side
* of a message.
*
* The cancellation data is stored using the property `$cancellationData`
* on the provided message object.
*
* @param message The message to add cancellation data to.
* @returns A function when called cancels the message.
*/
function addData(message) {
if (message.$cancellationData !== undefined) {
throw new Error(`Message already has a property $cancellationData`);
}
const data = new SharedArrayBuffer(4);
const typedArray = new Int32Array(data, 0, 1);
typedArray[0] = 0;
message.$cancellationData = data;
return () => {
Atomics.store(typedArray, 0, 1);
};
}
Cancellation.addData = addData;
/**
* Return for the given message a function that if call indicates whether
* the message got canceled or not. The necessary cancellation data is
* expected to be stored under the property `$cancellationData` and must
* be of type `SharedArrayBuffer`. The function is usually called on the
* receiving side of a message.
* @param message The given message.
* @returns a function to check if the message got canceled.
*/
function retrieveCheck(message) {
const candidate = message;
if (!(candidate.$cancellationData instanceof SharedArrayBuffer)) {
return () => false;
}
const typedArray = new Int32Array(candidate.$cancellationData, 0, 1);
return () => {
return Atomics.load(typedArray, 0) === 1;
};
}
Cancellation.retrieveCheck = retrieveCheck;
})(Cancellation || (exports.Cancellation = Cancellation = {}));