UNPKG

tgrid

Version:

Grid Computing Framework for TypeScript

334 lines 15.8 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SharedWorkerConnector = void 0; var tstl_1 = require("tstl"); var ConnectorBase_1 = require("../internal/ConnectorBase"); var IHeaderWrapper_1 = require("../internal/IHeaderWrapper"); var once_1 = require("../internal/once"); var WebWorkerCompiler_1 = require("./internal/WebWorkerCompiler"); /** * SharedWorker Connector * * - available only in the Web Browser. * * The `SharedWorkerConnector` is a communicator class which connects to an * `SharedWorker` instance, and interacts with it through RFC (Remote Function Call) * concept. * * You can connect to the {@link SharedWorkerServer} using {@link connect} method. * The interaction would be started if the server accepts your connection by calling * the {@link SharedWorkerAcceptor.accept} method. If the remote server rejects your * connection through {@link SharedWorkerAcceptor.reject} method, the exception * would be thrown. * * After the connection, don't forget to {@link closing} the connection, if your * business logics have been completed, to clean up the resources. Otherwise, the * closing must be performed by the remote shared worker server, you can wait the * remote server's closing signal through the {@link join} method. * * Also, when declaring this `SharedWorkerConnector` type, you've to define three * generic arguments; `Header`, `Provider` and `Remote`. Those generic arguments must * be same with the ones defined in the target {@link WebSocketServer} and * {@link SharedWorkerAcceptor} classes (`Provider` and `Remote` must be reversed). * * For reference, the first `Header` type represents an initial data from the * remote client after the connection. I recommend utilize it as an activation tool * for security enhancement. The second generic argument `Provider` represents a * provider from client to server, and the other `Remote` means a provider from the * remote server to client. * * @template Header Type of the header containing initial data. * @template Provider Type of features provided for the remote server. * @template Remote Type of features supported by remote server. */ var SharedWorkerConnector = /** @class */ (function (_super) { __extends(SharedWorkerConnector, _super); function SharedWorkerConnector() { return _super !== null && _super.apply(this, arguments) || this; } /* ---------------------------------------------------------------- CONNECTIONS ---------------------------------------------------------------- */ /** * Connect to remote server. * * The {@link connect}() method tries to connect an `SharedWorker` instance. If the * `SharedWorker` instance is not created yet, the `SharedWorker` instance would be newly * created. After the creation, the `SharedWorker` program must open that server using * the {@link SharedWorkerServer.open}() method. * * After you business has been completed, you've to close the `SharedWorker` using one of * them below. If you don't close that, vulnerable memory usage and communication channel * would not be destroyed and it may cause the memory leak: * * - {@link close}() * - {@link ShareDWorkerAcceptor.close}() * - {@link SharedWorkerServer.close}() * * @param jsFile JS File to be {@link SharedWorkerServer}. * @param options Detailed options like timeout. */ SharedWorkerConnector.prototype.connect = function (jsFile_1) { return __awaiter(this, arguments, void 0, function (jsFile, options) { var at, worker, last, reject, exp_1; if (options === void 0) { options = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: // TEST CONDITION if (this.port_ && this.state_ !== 3 /* SharedWorkerConnector.State.CLOSED */) { if (this.state_ === 0 /* SharedWorkerConnector.State.CONNECTING */) throw new Error("Error on SharedWorkerConnector.connect(): on connecting."); else if (this.state_ === 1 /* SharedWorkerConnector.State.OPEN */) throw new Error("Error on SharedWorkerConnector.connect(): already connected."); else throw new Error("Error on SharedWorkerConnector.connect(): closing."); } at = options.timeout !== undefined ? new Date(Date.now() + options.timeout) : undefined; // SET CURRENT STATE this.state_ = 0 /* SharedWorkerConnector.State.CONNECTING */; _a.label = 1; case 1: _a.trys.push([1, 4, , 5]); worker = new SharedWorker(jsFile); this.port_ = worker.port; return [4 /*yield*/, this._Handshake(options.timeout, at)]; case 2: // WAIT THE WORKER TO BE READY if ((_a.sent()) !== 0 /* SharedWorkerConnector.State.CONNECTING */) throw new Error("Error on SharedWorkerConnector.connect(): target shared-worker may not be opened by TGrid. It's not following the TGrid's own handshake rule when connecting."); // SEND HEADERS this.port_.postMessage(JSON.stringify(IHeaderWrapper_1.IHeaderWrapper.wrap(this.header))); return [4 /*yield*/, this._Handshake(options.timeout, at)]; case 3: last = _a.sent(); if (last === 1 /* SharedWorkerConnector.State.OPEN */) { // ACCEPTED this.state_ = 1 /* SharedWorkerConnector.State.OPEN */; this.port_.onmessage = this._Handle_message.bind(this); this.port_.onmessageerror = function () { }; } else { reject = null; try { reject = JSON.parse(last); } catch (_b) { } if (reject && reject.name === "reject" && typeof reject.message === "string") throw new Error(reject.message); else throw new Error("Error on SharedWorkerConnector.connect(): target shared-worker may not be opened by TGrid. It's not following the TGrid's own handshake rule."); } return [3 /*break*/, 5]; case 4: exp_1 = _a.sent(); try { if (this.port_) this.port_.close(); } catch (_c) { } this.state_ = -1 /* SharedWorkerConnector.State.NONE */; throw exp_1; case 5: return [2 /*return*/]; } }); }); }; /** * @hidden */ SharedWorkerConnector.prototype._Handshake = function (timeout, at) { var _this = this; return new Promise(function (resolve, reject) { var completed = false; var expired = false; if (at !== undefined) (0, tstl_1.sleep_until)(at).then(function () { if (completed === false) { reject(new Error("Error on SharedWorkerConnector.connect(): target shared-worker is not sending handshake data over ".concat(timeout, " milliseconds."))); expired = true; } }); _this.port_.onmessage = (0, once_1.once)(function (evt) { if (expired === false) { completed = true; resolve(evt.data); } }); }); }; /** * @inheritDoc */ SharedWorkerConnector.prototype.close = function () { return __awaiter(this, void 0, void 0, function () { var error, ret; return __generator(this, function (_a) { switch (_a.label) { case 0: error = this.inspectReady("close"); if (error) throw error; ret = this.join(); // REQUEST CLOSE TO SERVER this.state_ = 2 /* SharedWorkerConnector.State.CLOSING */; this.port_.postMessage(2 /* SharedWorkerConnector.State.CLOSING */); // LAZY RETURN return [4 /*yield*/, ret]; case 1: // LAZY RETURN _a.sent(); return [2 /*return*/]; } }); }); }; /* ---------------------------------------------------------------- COMMUNICATOR ---------------------------------------------------------------- */ /** * @hidden */ SharedWorkerConnector.prototype.sendData = function (invoke) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.port_.postMessage(JSON.stringify(invoke)); return [2 /*return*/]; }); }); }; /** * @hidden */ SharedWorkerConnector.prototype._Handle_message = function (evt) { if (evt.data === 2 /* SharedWorkerConnector.State.CLOSING */) this._Handle_close(); // RFC OR REJECT else { var data = JSON.parse(evt.data); this.replyData(data); } }; /** * @hidden */ SharedWorkerConnector.prototype._Handle_close = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.destructor()]; case 1: _a.sent(); this.state_ = 3 /* SharedWorkerConnector.State.CLOSED */; return [2 /*return*/]; } }); }); }; return SharedWorkerConnector; }(ConnectorBase_1.ConnectorBase)); exports.SharedWorkerConnector = SharedWorkerConnector; /** * */ (function (SharedWorkerConnector) { /** * Compile JS source code. * * @param content Source code * @return Temporary URL. */ function compile(content) { return __awaiter(this, void 0, void 0, function () { var compile; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, WebWorkerCompiler_1.WebWorkerCompiler)()]; case 1: compile = (_a.sent()).compile; return [2 /*return*/, compile(content)]; } }); }); } SharedWorkerConnector.compile = compile; /** * Remove compiled JS file. * * @param url Temporary URL. */ function remove(url) { return __awaiter(this, void 0, void 0, function () { var remove; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, WebWorkerCompiler_1.WebWorkerCompiler)()]; case 1: remove = (_a.sent()).remove; return [4 /*yield*/, remove(url)]; case 2: _a.sent(); return [2 /*return*/]; } }); }); } SharedWorkerConnector.remove = remove; })(SharedWorkerConnector || (exports.SharedWorkerConnector = SharedWorkerConnector = {})); //# sourceMappingURL=SharedWorkerConnector.js.map