tgrid
Version:
Grid Computing Framework for TypeScript
380 lines • 18 kB
JavaScript
"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.WorkerConnector = 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 NodeWorkerCompiler_1 = require("./internal/NodeWorkerCompiler");
var WebWorkerCompiler_1 = require("./internal/WebWorkerCompiler");
/**
* Worker Connector.
*
* The `WorkerConnector` is a communicator class, which creates an `Worker` instance
* and interacts with it through RPC (Remote Procedure Call). In other words,
* `WorkerConnector` considers the `Worker` instance as a remote server accepting
* only one client; {@link WorkerServer}.
*
* You can create an `Worker` instance with {@link connect} or {@link compile} method.
* The {@link connect} method just opens an existing JS (or TS) file, and
* {@link compile} method writes a temporary JS (TS) file, and connects to it.
* Anyway, the `Worker` instanced program must open the {@link WorkerServer}.
*
* By the way, don't forget {@link close closing} the worker to clean up the resources.
* If the closing be performed by {@link WorkerServer}, you can wait
* the worker server closing through the {@link join} method.
*
* Also, when declaring this `WorkerConnector` 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 WorkerServer} class
* (`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.
* @author Jeongho Nam - https://github.com/samchon
*/
var WorkerConnector = /** @class */ (function (_super) {
__extends(WorkerConnector, _super);
/**
* Initializer Constructor.
*
* For reference, you're planning to run a bundled JavaScript file,
* and you're using the NodeJS environment, you can't use the `"thread"`
* mode. You've to use the `"process"` mode instead.
*
* @param header An object containing initialization data like activation.
* @param provider An object providing features for remote system.
* @param type You can specify the worker mode when NodeJS. Default is "process".
*/
function WorkerConnector(header, provider, type) {
var _this = _super.call(this, header, provider) || this;
_this.compiler_ = new tstl_1.Singleton(function () {
return (0, tstl_1.is_node)() ? (0, NodeWorkerCompiler_1.NodeWorkerCompiler)(type !== null && type !== void 0 ? type : "process") : (0, WebWorkerCompiler_1.WebWorkerCompiler)();
});
return _this;
}
/* ----------------------------------------------------------------
CONNECTIONS
---------------------------------------------------------------- */
/**
* Compile server and connect to there.
*
* The {@link compile} method tries compile JS source code, creates `Worker` instance
* with that code connects to the `Worker`. To complete the compilation and connection,
* the `Worker` program must open that server using the {@link WorkerServer.open}()
* method.
*
* Note that, after your business has been completed, you've to close the `Worker` using
* {@link close}() or {@link WorkerServer.close}(). If you don't close that, vulnerable
* memory usage and communication channel would not be destroyed and it may cause the
* memory leak.
*
* @param content JS Source code to compile.
* @param options Detailed options like timeout.
*/
WorkerConnector.prototype.compile = function (content_1) {
return __awaiter(this, arguments, void 0, function (content, options) {
var compiler, path, error, exp_1;
if (options === void 0) { options = {}; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
//----
// PRELIMINARIES
//----
// TEST CONDITION
this._Test_connection("compile");
return [4 /*yield*/, this.compiler_.get()];
case 1:
compiler = _a.sent();
return [4 /*yield*/, compiler.compile(content)];
case 2:
path = _a.sent();
error = null;
_a.label = 3;
case 3:
_a.trys.push([3, 5, , 6]);
return [4 /*yield*/, this._Connect("compile", path, options)];
case 4:
_a.sent();
return [3 /*break*/, 6];
case 5:
exp_1 = _a.sent();
error = exp_1;
return [3 /*break*/, 6];
case 6:
// REMOVE THE TEMPORARY FILE
return [4 /*yield*/, compiler.remove(path)];
case 7:
// REMOVE THE TEMPORARY FILE
_a.sent();
// LAZY THROWING
if (error !== null)
throw error;
return [2 /*return*/];
}
});
});
};
/**
* Connect to server.
*
* The {@link connect}() method tries to create an `Worker` instance and connect to the
* `Worker`. To complete the connection, the `Worker` program must open that server using
* the {@link WorkerServer.open}() method.
*
* Note that, after your business has been completed, you've to close the `Worker` using
* {@link close}() or {@link WorkerServer.close}(). If you don't close that, vulnerable
* memory usage and communication channel would not be destroyed and it may cause the
* memory leak.
*
* @param jsFile JS File to be {@link WorkerServer}.
* @param options Detailed options like timeout.
*/
WorkerConnector.prototype.connect = function (jsFile_1) {
return __awaiter(this, arguments, void 0, function (jsFile, options) {
if (options === void 0) { options = {}; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// TEST CONDITION
this._Test_connection("connect");
// DO CONNECT
return [4 /*yield*/, this._Connect("connect", jsFile, options)];
case 1:
// DO CONNECT
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* @hidden
*/
WorkerConnector.prototype._Test_connection = function (method) {
if (this.worker_ && this.state !== 3 /* WorkerConnector.State.CLOSED */) {
if (this.state_ === 0 /* WorkerConnector.State.CONNECTING */)
throw new Error("Error on WorkerConnector.".concat(method, "(): on connecting."));
else if (this.state_ === 1 /* WorkerConnector.State.OPEN */)
throw new Error("Error on WorkerConnector.".concat(method, "(): already connected."));
else
throw new Error("Error on WorkerConnector.".concat(method, "(): closing."));
}
};
/**
* @hidden
*/
WorkerConnector.prototype._Connect = function (method, jsFile, options) {
return __awaiter(this, void 0, void 0, function () {
var at, compiler, _a, exp_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
at = options.timeout !== undefined
? new Date(Date.now() + options.timeout)
: undefined;
// SET CURRENT STATE
this.state_ = 0 /* WorkerConnector.State.CONNECTING */;
_b.label = 1;
case 1:
_b.trys.push([1, 6, , 7]);
return [4 /*yield*/, this.compiler_.get()];
case 2:
compiler = _b.sent();
_a = this;
return [4 /*yield*/, compiler.execute(jsFile, (0, tstl_1.is_node)() === true ? options : undefined)];
case 3:
_a.worker_ = _b.sent();
return [4 /*yield*/, this._Handshake(method, options.timeout, at)];
case 4:
// WAIT THE WORKER TO BE READY
if ((_b.sent()) !==
0 /* WorkerConnector.State.CONNECTING */)
throw new Error("Error on WorkerConnector.".concat(method, "(): target worker may not be opened by TGrid. It's not following the TGrid's own handshake rule when connecting."));
// SEND HEADERS
this.worker_.postMessage(JSON.stringify(IHeaderWrapper_1.IHeaderWrapper.wrap(this.header)));
return [4 /*yield*/, this._Handshake(method, options.timeout, at)];
case 5:
// WAIT COMPLETION
if ((_b.sent()) !==
1 /* WorkerConnector.State.OPEN */)
throw new Error("Error on WorkerConnector.".concat(method, "(): target worker may not be opened by TGrid. It's not following the TGrid's own handshake rule when connected."));
// SUCCESS
this.state_ = 1 /* WorkerConnector.State.OPEN */;
this.worker_.onmessage = this._Handle_message.bind(this);
return [3 /*break*/, 7];
case 6:
exp_2 = _b.sent();
try {
if (this.worker_)
this.worker_.terminate();
}
catch (_c) { }
this.state_ = -1 /* WorkerConnector.State.NONE */;
throw exp_2;
case 7: return [2 /*return*/];
}
});
});
};
/**
* @hidden
*/
WorkerConnector.prototype._Handshake = function (method, timeout, until) {
var _this = this;
return new Promise(function (resolve, reject) {
/* eslint-disable */
var completed = false;
/* eslint-disable */
var expired = false;
if (until !== undefined)
(0, tstl_1.sleep_until)(until).then(function () {
if (completed === false) {
reject(new Error("Error on WorkerConnector.".concat(method, "(): target worker is not sending handshake data over ").concat(timeout, " milliseconds.")));
expired = true;
}
});
_this.worker_.onmessage = (0, once_1.once)(function (evt) {
if (expired === false) {
completed = true;
resolve(evt.data);
}
});
});
};
/**
* @inheritDoc
*/
WorkerConnector.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 /* WorkerConnector.State.CLOSING */;
this.worker_.postMessage(2 /* WorkerConnector.State.CLOSING */);
// LAZY RETURN
return [4 /*yield*/, ret];
case 1:
// LAZY RETURN
_a.sent();
return [2 /*return*/];
}
});
});
};
/* ----------------------------------------------------------------
COMMUNICATOR
---------------------------------------------------------------- */
/**
* @hidden
*/
WorkerConnector.prototype.sendData = function (invoke) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.worker_.postMessage(JSON.stringify(invoke));
return [2 /*return*/];
});
});
};
/**
* @hidden
*/
WorkerConnector.prototype._Handle_message = function (evt) {
if (evt.data === 2 /* WorkerConnector.State.CLOSING */)
this._Handle_close().catch(function () { });
else
this.replyData(JSON.parse(evt.data));
};
/**
* @hidden
*/
WorkerConnector.prototype._Handle_close = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// STATE & PROMISE RETURN
return [4 /*yield*/, this.destructor()];
case 1:
// STATE & PROMISE RETURN
_a.sent();
this.state_ = 3 /* WorkerConnector.State.CLOSED */;
return [2 /*return*/];
}
});
});
};
return WorkerConnector;
}(ConnectorBase_1.ConnectorBase));
exports.WorkerConnector = WorkerConnector;
/**
*
*/
(function (WorkerConnector) {
})(WorkerConnector || (exports.WorkerConnector = WorkerConnector = {}));
//# sourceMappingURL=WorkerConnector.js.map