tgrid
Version:
Grid Computing Framework for TypeScript
345 lines • 16.2 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.WorkerServer = void 0;
var tstl_1 = require("tstl");
var Communicator_1 = require("../../components/Communicator");
var once_1 = require("../internal/once");
var ProcessChannel_1 = require("./internal/processes/ProcessChannel");
var ThreadPort_1 = require("./internal/threads/ThreadPort");
/**
* Worker Server.
*
* The `WorkerServer` is a class representing a `Worker` server which communicate
* with client ({@link WorkerConnector}), through the RPC (Remote Procedure Call).
*
* Unlike other servers, `WorkerServer` can accept only one client
* ({@link WorkerConnector}), because the `Worker` is dependent on its parent instance
* (web page, node or parent worker). Thus, `WorkerServer` does not have any acceptor
* and communicates with client (its parent) directly.
*
* To start communication with the client, call the {@link open} method
* with `Provider` instance. After your business, don't forget {@link close closing}
* this `Worker` instance. If the termination is performed by the
* {@link WorkerConnector}, you can wait the closing signal through the
* {@link join} method.
*
* Also, when declaring this `WorkerServer` 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 WorkerConnector} class
* (`Provider` and `Remote` must be reversed).
*
* For reference, the first `Header` type represents an initial data from the
* client after the connection. I recommend utilize it as an activation tool
* for security enhancement. The second generic argument `Provider` represents a
* provider from server to client, and the other `Remote` means a provider from the
* client to server.
*
* @template Header Type of the header containing initial data.
* @template Provider Type of features provided for the client.
* @template Remote Type of features supported by client.
* @author Jeongho Nam - https://github.com/samchon
*/
var WorkerServer = /** @class */ (function (_super) {
__extends(WorkerServer, _super);
/* ----------------------------------------------------------------
CONSTRUCTOR
---------------------------------------------------------------- */
/**
* Default Constructor.
*
* @param type You can specify the worker mode when NodeJS. Default is "thread".
*/
function WorkerServer() {
var _this = _super.call(this, undefined) || this;
_this.channel_ = new tstl_1.Singleton(function () { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// BROWSER CASE
if ((0, tstl_1.is_node)() === false)
return [2 /*return*/, self];
return [4 /*yield*/, ThreadPort_1.ThreadPort.isWorkerThread()];
case 1:
if (!(_b.sent())) return [3 /*break*/, 3];
return [4 /*yield*/, (0, ThreadPort_1.ThreadPort)()];
case 2:
_a = (_b.sent());
return [3 /*break*/, 4];
case 3:
_a = ProcessChannel_1.ProcessChannel;
_b.label = 4;
case 4: return [2 /*return*/, _a];
}
});
}); });
_this.state_ = -1 /* WorkerServer.State.NONE */;
_this.header_ = new tstl_1.Singleton(function () { return __awaiter(_this, void 0, void 0, function () {
var data, wrapper;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.channel_.get()];
case 1:
(_a.sent()).postMessage(0 /* WorkerServer.State.OPENING */);
return [4 /*yield*/, this._Handshake("getHeader")];
case 2:
data = _a.sent();
wrapper = JSON.parse(data);
return [2 /*return*/, wrapper.header];
}
});
}); });
return _this;
}
/**
* Open server with `Provider`.
*
* Open worker server and start communication with the client
* ({@link WorkerConnector}).
*
* Note that, after your business, you should terminate this worker to prevent
* waste of memory leak. Close this worker by yourself ({@link close}) or let
* client to close this worker ({@link WorkerConnector.close}).
*
* @param provider An object providing features for the client.
*/
WorkerServer.prototype.open = function (provider) {
return __awaiter(this, void 0, void 0, function () {
var channel;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!((0, tstl_1.is_node)() === false)) return [3 /*break*/, 1];
if (self.document !== undefined)
throw new Error("Error on WorkerServer.open(): this is not Worker.");
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, this.channel_.get()];
case 2:
if ((_a.sent()).is_worker_server() === false)
throw new Error("Error on WorkerServer.open(): this is not Worker.");
else if (this.state_ !== -1 /* WorkerServer.State.NONE */)
throw new Error("Error on WorkerServer.open(): the server has been opened yet.");
_a.label = 3;
case 3:
// OPEN WORKER
this.state_ = 0 /* WorkerServer.State.OPENING */;
this.provider_ = provider;
// GET HEADERS
return [4 /*yield*/, this.header_.get()];
case 4:
// GET HEADERS
_a.sent();
return [4 /*yield*/, this.channel_.get()];
case 5:
channel = _a.sent();
channel.onmessage = function (evt) { return _this._Handle_message(evt); };
channel.postMessage(1 /* WorkerServer.State.OPEN */);
this.state_ = 1 /* WorkerServer.State.OPEN */;
return [2 /*return*/];
}
});
});
};
/**
* @inheritDoc
*/
WorkerServer.prototype.close = function () {
return __awaiter(this, void 0, void 0, function () {
var error;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
error = this.inspectReady();
if (error)
throw error;
//----
// CLOSE WORKER
//----
this.state_ = 2 /* WorkerServer.State.CLOSING */;
// HANDLERS
return [4 /*yield*/, this.destructor()];
case 1:
// HANDLERS
_a.sent();
// DO CLOSE
setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var channel;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.channel_.get()];
case 1:
channel = _a.sent();
channel.postMessage(2 /* WorkerServer.State.CLOSING */);
channel.close();
return [2 /*return*/];
}
});
}); });
this.state_ = 3 /* WorkerServer.State.CLOSED */;
return [2 /*return*/];
}
});
});
};
Object.defineProperty(WorkerServer.prototype, "state", {
/* ----------------------------------------------------------------
ACCESSORS
---------------------------------------------------------------- */
/**
* @inheritDoc
*/
get: function () {
return this.state_;
},
enumerable: false,
configurable: true
});
/**
* Get header containing initialization data like activation.
*/
WorkerServer.prototype.getHeader = function () {
return this.header_.get();
};
/**
* @hidden
*/
WorkerServer.prototype._Handshake = function (method, timeout, until) {
var _this = this;
return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var completed, expired;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
completed = false;
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;
}
})
.catch(function () { });
return [4 /*yield*/, this.channel_.get()];
case 1:
(_a.sent()).onmessage = (0, once_1.once)(function (evt) {
if (expired === false) {
completed = true;
resolve(evt.data);
}
});
return [2 /*return*/];
}
});
}); });
};
/* ----------------------------------------------------------------
COMMUNICATOR
---------------------------------------------------------------- */
/**
* @hidden
*/
WorkerServer.prototype.sendData = function (invoke) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.channel_.get()];
case 1:
(_a.sent()).postMessage(JSON.stringify(invoke));
return [2 /*return*/];
}
});
});
};
/**
* @hidden
*/
WorkerServer.prototype.inspectReady = function () {
// NO ERROR
if (this.state_ === 1 /* WorkerServer.State.OPEN */)
return null;
// ERROR, ONE OF THEM
else if (this.state_ === -1 /* WorkerServer.State.NONE */)
return new Error("Error on WorkerServer.inspectReady(): server is not opened yet.");
else if (this.state_ === 0 /* WorkerServer.State.OPENING */)
return new Error("Error on WorkerServer.inspectReady(): server is on opening, wait for a sec.");
else if (this.state_ === 2 /* WorkerServer.State.CLOSING */)
return new Error("Error on WorkerServer.inspectReady(): server is on closing.");
// MAY NOT BE OCCURRED
else if (this.state_ === 3 /* WorkerServer.State.CLOSED */)
return new Error("Error on WorkerServer.inspectReady(): the server has been closed.");
else
return new Error("Error on WorkerServer.inspectReady(): unknown error, but not connected.");
};
/**
* @hidden
*/
WorkerServer.prototype._Handle_message = function (evt) {
if (evt.data === 2 /* WorkerServer.State.CLOSING */)
this.close();
else
this.replyData(JSON.parse(evt.data));
};
return WorkerServer;
}(Communicator_1.Communicator));
exports.WorkerServer = WorkerServer;
/**
*
*/
(function (WorkerServer) {
})(WorkerServer || (exports.WorkerServer = WorkerServer = {}));
//# sourceMappingURL=WorkerServer.js.map