UNPKG

tgrid

Version:

Grid Computing Framework for TypeScript

384 lines 17 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.WebSocketAcceptor = void 0; var tstl_1 = require("tstl"); var AcceptorBase_1 = require("../internal/AcceptorBase"); var WebSocketError_1 = require("./WebSocketError"); /** * Web Socket Acceptor. * * - available only in the NodeJS. * * The `WebSocketAcceptor` is a communicator class interacting with the remote * {@link WebSocketConnector websocket client} through RPC (Remote Procedure Call), * created by the {@link WebSocketServer} class whenever a remote client * connects to the websocket server. * * When a remote client connects to the {@link WebSocketServer websocket server}, * so that a new `WebSocketAcceptor` instance being created, you can determine * whether to {@link accept} the client's connection or {@link reject not}, * reading the {@link header} and {@link path} properties. If you've decided to * accept the connection, call the {@link accept} method with `Provider` instance. * Otherwise, reject it through the {@link reject} method. * * After {@link accept accepting} the connection, don't forget to * {@link close closing} the connection after your business has been completed * to clean up the resources. Otherwise the closing must be performed by the remote * client, you can wait the remote client's closing signal by the {@link join} method. * * Also, when declaring this {@link WebSocketAcceptor} type, you have to define three * generic arguments; `Header`, `Provider` and `Remote`. Those generic arguments must * be same with the ones defined in the {@link WebSocketServer} class. * * 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 server to client, and the other `Remote` means a provider from the * remote client to server. * * @template Header Type of the header containing initial data. * @template Provider Type of features provided for the remote client. * @template Remote Type of features provided by remote client. * @author Jeongho Nam - https://github.com/samchon */ var WebSocketAcceptor = /** @class */ (function (_super) { __extends(WebSocketAcceptor, _super); /** * @hidden */ function WebSocketAcceptor(request, socket, header) { var _this = _super.call(this, header) || this; _this.request_ = request; _this.socket_ = socket; return _this; } /* ---------------------------------------------------------------- CONSTRUCTORS ---------------------------------------------------------------- */ /** * Upgrade to WebSocket protocol. * * If you've not opened websocket server from {@link WebSocketServer}, you can * still compose the `WebSocketAcceptor` instance by yourself, by upgrading * the HTTP connection to the websocket protocol. * * For reference, this `upgrade()` method is useful when you're planning to * make a server supporting both HTTP and WebSocket protocols, and * distinguishing the protocol by the path of URL. * * - ex) [NestJS `@WebSocketRoute()` case](https://nestia.io/docs/core/WebSocketRoute/) * * @param request HTTP incoming message. * @param socket WebSocket instance * @param handler A callback function after the connection has been established. */ WebSocketAcceptor.upgrade = function (request, socket, handler) { var _this = this; socket.once("message", function (data) { return __awaiter(_this, void 0, void 0, function () { var wrapper, acceptor, exp_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(typeof data !== "string")) return [3 /*break*/, 1]; socket.close(); return [3 /*break*/, 5]; case 1: _a.trys.push([1, 4, , 5]); wrapper = JSON.parse(data); acceptor = new WebSocketAcceptor(request, socket, wrapper.header); if (!(handler !== undefined)) return [3 /*break*/, 3]; return [4 /*yield*/, handler(acceptor)]; case 2: _a.sent(); _a.label = 3; case 3: return [3 /*break*/, 5]; case 4: exp_1 = _a.sent(); socket.close(); return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }); }; /** * @inheritDoc */ WebSocketAcceptor.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 /* WebSocketAcceptor.State.CLOSING */; if (code === 1000) this.socket_.close(); else this.socket_.close(code, reason); // state would be closed in destructor() via _Handle_close() return [4 /*yield*/, ret]; case 1: // state would be closed in destructor() via _Handle_close() _a.sent(); return [2 /*return*/]; } }); }); }; /** * @hidden */ WebSocketAcceptor.prototype.destructor = function (error) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, _super.prototype.destructor.call(this, error)]; case 1: _a.sent(); this.state_ = 3 /* WebSocketAcceptor.State.CLOSED */; return [2 /*return*/]; } }); }); }; Object.defineProperty(WebSocketAcceptor.prototype, "ip", { /* ---------------------------------------------------------------- ACCESSORS ---------------------------------------------------------------- */ /** * IP Address of client. */ get: function () { return this.request_.connection.remoteAddress; }, enumerable: false, configurable: true }); Object.defineProperty(WebSocketAcceptor.prototype, "path", { /** * Path of client has connected. */ get: function () { return this.request_.url; }, enumerable: false, configurable: true }); Object.defineProperty(WebSocketAcceptor.prototype, "state", { /** * Get state. * * Get current state of connection state with the remote client. * * List of values are such like below: * * - `REJECTING`: The {@link WebSocketAcceptor.reject} method is on running. * - `NONE`: The {@link WebSocketAcceptor} instance is newly created, but did nothing yet. * - `ACCEPTING`: The {@link WebSocketAcceptor.accept} method is on running. * - `OPEN`: The connection is online. * - `CLOSING`: The {@link WebSocketAcceptor.close} method is on running. * - `CLOSED`: The connection is offline. */ get: function () { return this.state_; }, enumerable: false, configurable: true }); /* ---------------------------------------------------------------- HANDSHAKES ---------------------------------------------------------------- */ /** * @inheritDoc */ WebSocketAcceptor.prototype.accept = function (provider) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { // VALIDATION if (this.state_ !== -1 /* WebSocketAcceptor.State.NONE */) throw new Error("Error on WebSocketAcceptor.accept(): you've already accepted (or rejected) the connection."); // PREPARE ASSETS this.state_ = 0 /* WebSocketAcceptor.State.ACCEPTING */; this.provider_ = provider; // REGISTER EVENTS this.socket_.on("message", this._Handle_message.bind(this)); this.socket_.on("close", this._Handle_close.bind(this)); this.socket_.send(1 /* WebSocketAcceptor.State.OPEN */.toString()); // FINISHED this.state_ = 1 /* WebSocketAcceptor.State.OPEN */; return [2 /*return*/]; }); }); }; /** * Reject connection. * * Reject without acceptance, any interaction. The connection would be closed immediately. * * @param status Status code. * @param reason Detailed reason to reject. */ WebSocketAcceptor.prototype.reject = function (status, reason) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // VALIDATION if (this.state_ !== -1 /* WebSocketAcceptor.State.NONE */) throw new Error("Error on WebSocketAcceptor.reject(): you've already accepted (or rejected) the connection."); // SEND CLOSING FRAME this.state_ = -2 /* WebSocketAcceptor.State.REJECTING */; this.socket_.close(status, reason); // FINALIZATION return [4 /*yield*/, this.destructor()]; case 1: // FINALIZATION _a.sent(); return [2 /*return*/]; } }); }); }; /* ---------------------------------------------------------------- COMMUNICATOR ---------------------------------------------------------------- */ /** * Ping to the remote client. * * Send a ping message to the remote client repeatedly. * * The ping message would be sent every internal milliseconds, until the * connection be disconnected. The remote client will reply with a pong * message, so that the connection would be alive until be explicitly * disconnected. * * @param ms Interval milliseconds * @throws Error when the connection is not accepted. */ WebSocketAcceptor.prototype.ping = function (ms) { var _this = this; // TEST CONDITION var error = this.inspectReady("close"); if (error) throw error; (function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(this.state_ === 1 /* WebSocketAcceptor.State.OPEN */)) return [3 /*break*/, 2]; return [4 /*yield*/, (0, tstl_1.sleep_for)(ms)]; case 1: _a.sent(); try { this.socket_.ping(); } catch (_b) { } return [3 /*break*/, 0]; case 2: return [2 /*return*/]; } }); }); })().catch(function () { }); }; /** * @hidden */ WebSocketAcceptor.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 */ WebSocketAcceptor.prototype._Handle_message = function (data) { if (typeof data === "string") { var invoke = JSON.parse(data); this.replyData(invoke); } }; /** * @hidden */ WebSocketAcceptor.prototype._Handle_close = function (code, reason) { return __awaiter(this, void 0, void 0, function () { var error; return __generator(this, function (_a) { switch (_a.label) { case 0: error = code !== 100 ? new WebSocketError_1.WebSocketError(code, reason) : undefined; return [4 /*yield*/, this.destructor(error)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return WebSocketAcceptor; }(AcceptorBase_1.AcceptorBase)); exports.WebSocketAcceptor = WebSocketAcceptor; /** * */ (function (WebSocketAcceptor) { })(WebSocketAcceptor || (exports.WebSocketAcceptor = WebSocketAcceptor = {})); //# sourceMappingURL=WebSocketAcceptor.js.map