UNPKG

tgrid

Version:

Grid Computing Framework for TypeScript

349 lines 16.6 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.WebSocketConnector = 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 WebSocketError_1 = require("./WebSocketError"); var WebSocketPolyfill_1 = require("./internal/WebSocketPolyfill"); /** * Web Socket Connector. * * The `WebSocketConnector` is a communicator class which connects to a * {@link WebSocketServer websocket server}, and interacts with it through RPC * (Remote Procedure Call) concept. * * You can connect to the websocket server using {@link connect} method. The * interaction would be started if the server accepts your connection by calling * the {@link WebSocketAcceptor.accept} method. If the remote server rejects your * connection through {@link WebSocketAcceptor.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 websocket server, you can wait the * remote server's closing signal through the {@link join} method. * * Also, when declaring this `WebSocketConnector` 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 WebSocketAcceptor} 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. * @author Jeongho Nam - https://github.com/samchon */ var WebSocketConnector = /** @class */ (function (_super) { __extends(WebSocketConnector, _super); function WebSocketConnector() { return _super !== null && _super.apply(this, arguments) || this; } /* ---------------------------------------------------------------- CONNECTION ---------------------------------------------------------------- */ /** * Connect to remote websocket server. * * Try connection to the remote websocket server with its address and waiting for the * server to accept the trial. If the server rejects your connection, then exception * would be thrown (in *Promise.catch*, as `WebSocketError`). * * After the connection and your business has been completed, don't forget to closing the * connection in time to prevent waste of the server resource. * * @param url URL address to connect. * @param options Detailed options like timeout. */ WebSocketConnector.prototype.connect = function (url_1) { return __awaiter(this, arguments, void 0, function (url, options) { var factory, _a, exp_1; if (options === void 0) { options = {}; } return __generator(this, function (_b) { switch (_b.label) { case 0: // TEST CONDITION if (this.socket_ && this.state !== 3 /* WebSocketConnector.State.CLOSED */) if (this.socket_.readyState === 0 /* WebSocketConnector.State.CONNECTING */) throw new Error("Error on WebSocketConnector.connect(): already connecting."); else if (this.socket_.readyState === 1 /* WebSocketConnector.State.OPEN */) throw new Error("Error on WebSocketConnector.connect(): already connected."); else throw new Error("Error on WebSocketConnector.connect(): already closing."); //---- // CONNECTION //---- // PREPARE ASSETS this.state_ = 0 /* WebSocketConnector.State.CONNECTING */; _b.label = 1; case 1: _b.trys.push([1, 7, , 8]); if (!(0, tstl_1.is_node)()) return [3 /*break*/, 3]; return [4 /*yield*/, (0, WebSocketPolyfill_1.WebSocketPolyfill)()]; case 2: _a = (_b.sent()); return [3 /*break*/, 4]; case 3: _a = self.WebSocket; _b.label = 4; case 4: factory = _a; this.socket_ = new factory(url); return [4 /*yield*/, this._Wait_connection()]; case 5: _b.sent(); // SEND HEADERS this.socket_.send(JSON.stringify(IHeaderWrapper_1.IHeaderWrapper.wrap(this.header))); return [4 /*yield*/, this._Handshake(options.timeout)]; case 6: // PROMISED HANDSHAKE if ((_b.sent()) !== 1 /* WebSocketConnector.State.OPEN */.toString()) throw new WebSocketError_1.WebSocketError(1008, "Error on WebSocketConnector.connect(): target server may not be opened by TGrid. It's not following the TGrid's own handshake rule."); // SUCCESS this.state_ = 1 /* WebSocketConnector.State.OPEN */; { this.socket_.onmessage = this._Handle_message.bind(this); this.socket_.onclose = this._Handle_close.bind(this); this.socket_.onerror = function () { }; } return [3 /*break*/, 8]; case 7: exp_1 = _b.sent(); this.state_ = -1 /* WebSocketConnector.State.NONE */; if (this.socket_ && this.socket_.readyState === 1 /* WebSocketConnector.State.OPEN */) { this.socket_.onclose = function () { }; this.socket_.close(); } throw exp_1; case 8: return [2 /*return*/]; } }); }); }; /** * @hidden */ WebSocketConnector.prototype._Wait_connection = function () { var _this = this; return new Promise(function (resolve, reject) { _this.socket_.onopen = function () { return resolve(_this.socket_); }; _this.socket_.onclose = (0, once_1.once)(function (evt) { reject(new WebSocketError_1.WebSocketError(evt.code, evt.reason)); }); _this.socket_.onerror = (0, once_1.once)(function (evt) { var _a; reject(new WebSocketError_1.WebSocketError(1006, "Error on WebSocketConnector.connect(): ".concat((_a = evt === null || evt === void 0 ? void 0 : evt.message) !== null && _a !== void 0 ? _a : "connection refused."))); }); }); }; /** * @inheritDoc */ WebSocketConnector.prototype.close = function (code, reason) { 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(); // DO CLOSE this.state_ = 2 /* WebSocketConnector.State.CLOSING */; this.socket_.close(code, reason); // LAZY RETURN return [4 /*yield*/, ret]; case 1: // LAZY RETURN _a.sent(); return [2 /*return*/]; } }); }); }; /** * @hidden */ WebSocketConnector.prototype._Handshake = function (timeout) { var _this = this; return new Promise(function (resolve, reject) { /* eslint-disable */ var completed = false; /* eslint-disable */ var expired = false; // TIMEOUT if (timeout !== undefined) (0, tstl_1.sleep_for)(timeout).then(function () { if (completed === false) { reject(new WebSocketError_1.WebSocketError(1008, "Error on WebSocketConnector.connect(): target server is not sending handshake data over ".concat(timeout, " milliseconds."))); expired = true; } }); // EVENT LISTENERS _this.socket_.onmessage = (0, once_1.once)(function (evt) { if (expired === false) { completed = true; resolve(evt.data); } }); _this.socket_.onclose = (0, once_1.once)(function (evt) { if (expired === false) { completed = true; reject(new WebSocketError_1.WebSocketError(evt.code, evt.reason)); } }); _this.socket_.onerror = (0, once_1.once)(function () { if (expired === false) { completed = true; reject(new WebSocketError_1.WebSocketError(1006, "Error on WebSocketConnector.connect(): connection refused.")); } }); }); }; Object.defineProperty(WebSocketConnector.prototype, "url", { /* ---------------------------------------------------------------- ACCESSORS ---------------------------------------------------------------- */ /** * Connection URL. */ get: function () { return this.socket_ ? this.socket_.url : undefined; }, enumerable: false, configurable: true }); Object.defineProperty(WebSocketConnector.prototype, "state", { /** * Get state. * * Get current state of connection state with the websocket server. * * List of values are such like below: * * - `NONE`: The {@link WebSocketConnector} instance is newly created, but did nothing yet. * - `CONNECTING`: The {@link WebSocketConnector.connect} method is on running. * - `OPEN`: The connection is online. * - `CLOSING`: The {@link WebSocketConnector.close} method is on running. * - `CLOSED`: The connection is offline. */ get: function () { return this.state_; }, enumerable: false, configurable: true }); /* ---------------------------------------------------------------- COMMUNICATOR ---------------------------------------------------------------- */ /** * @hidden */ WebSocketConnector.prototype.sendData = function (invoke) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.socket_.send(JSON.stringify(invoke)); return [2 /*return*/]; }); }); }; /** * @hidden */ WebSocketConnector.prototype._Handle_message = function (evt) { if (typeof evt.data === "string") { var invoke = JSON.parse(evt.data); this.replyData(invoke); } }; /** * @hidden */ WebSocketConnector.prototype._Handle_close = function (event) { return __awaiter(this, void 0, void 0, function () { var error; return __generator(this, function (_a) { switch (_a.label) { case 0: error = !event.code || event.code !== 1000 ? new WebSocketError_1.WebSocketError(event.code, event.reason) : undefined; this.state_ = 3 /* WebSocketConnector.State.CLOSED */; return [4 /*yield*/, this.destructor(error)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return WebSocketConnector; }(ConnectorBase_1.ConnectorBase)); exports.WebSocketConnector = WebSocketConnector; /** * */ (function (WebSocketConnector) { })(WebSocketConnector || (exports.WebSocketConnector = WebSocketConnector = {})); //# sourceMappingURL=WebSocketConnector.js.map