UNPKG

physical-node

Version:

virtual physical network infrastructure layer for node

277 lines 12.6 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(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 (_) 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 }); var promiseRequest_1 = require("./promiseRequest"); var config_1 = require("../config"); var WebSocket = require("ws"); var net = require("net"); var crypto = require("crypto"); var State; (function (State) { State[State["EMPTY"] = 0] = "EMPTY"; State[State["INITIATED"] = 1] = "INITIATED"; State[State["RESPONDED"] = 2] = "RESPONDED"; State[State["FINALIZING"] = 3] = "FINALIZING"; State[State["OPEN"] = 4] = "OPEN"; State[State["CLOSED"] = 5] = "CLOSED"; })(State || (State = {})); var PhysicalNode = /** @class */ (function () { function PhysicalNode() { this.key = crypto.randomBytes(config_1.config.keyLength).toString('hex'); this.state = State.EMPTY; this.onMessage = function (str) { console.warn("onmessage not set!"); }; this.onOpen = function () { console.warn("onOpen not set!"); }; this.onClose = function () { console.warn("onClose not set!"); }; this.socket = null; } PhysicalNode.prototype.close = function () { if (this.state != State.CLOSED) this.onClose(); this.state = State.CLOSED; delete PhysicalNode.pendingConnections[this.key]; try { this.socket && this.socket.close(); } catch (e) { if (e.message === 'WebSocket was closed before the connection was established') { //allowed } else { throw e; } } }; PhysicalNode.prototype.open = function (ack) { if (this.state != State.INITIATED) throw ("wrong state exception"); this.state = State.FINALIZING; if (ack.protocol !== "WebSocket-Consumer") console.error("peer failed to honor contract"); if (!this.socket) { this.buildConnectionHandler(config_1.config.pendingConnectionTimeout, true); } else { this.openFinalizeHandshake(); } }; PhysicalNode.prototype.openFinalizeHandshake = function () { this.socket.send("RFT"); // ready for transmission this.state = State.OPEN; this.onOpen(); }; PhysicalNode.prototype.buildURI = function () { var self = this; return Promise.all([PhysicalNode.host, PhysicalNode.port]).then(function (res) { return "ws://" + res[0] + ":" + res[1] + "/" + self.key; }); }; PhysicalNode.prototype.buildConnectionHandler = function (timeout, override) { if (timeout === void 0) { timeout = 0; } if (override === void 0) { override = false; } var self = this; if (!override && PhysicalNode.pendingConnections[self.key]) throw ("key already in use"); PhysicalNode.pendingConnections[self.key] = function (ws) { self.socket = ws; self.socket.on('message', function (message) { self.onMessage(message); }); delete PhysicalNode.pendingConnections[self.key]; self.peerReady(); }; if (timeout) setTimeout(function () { if (PhysicalNode.pendingConnections[self.key]) self.close(); }, timeout); }; PhysicalNode.prototype.peerReady = function () { switch (this.state) { case State.CLOSED: this.socket.close(); break; case State.INITIATED: break; //this is fine. check in open if socket is avaolable case State.RESPONDED: break; case State.FINALIZING: this.openFinalizeHandshake(); break; default: console.error("Peer ready but bad state: " + this.state); } }; PhysicalNode.prototype.request = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (this.state != State.EMPTY) throw ("wrong state exception"); this.state = State.INITIATED; this.buildConnectionHandler(); _a = { author: "physical-node", supported: ["WebSocket-Provider", "WebSocket-Consumer"] }; return [4 /*yield*/, this.buildURI()]; case 1: return [2 /*return*/, (_a.body = [_b.sent(), ""], _a)]; } }); }); }; PhysicalNode.prototype.connectToWebSocket = function (url) { return __awaiter(this, void 0, void 0, function () { var self, split, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: self = this; _b = (_a = url).split; return [4 /*yield*/, PhysicalNode.host]; case 1: split = _b.apply(_a, [_c.sent()]); if (split.length == 2) url = split[0] + "127.0.0.1" + split[1]; this.socket = new WebSocket(url); this.socket.onmessage = function (event) { if (event.data == "RFT") { self.socket.onmessage = function (event2) { self.onMessage(event2.data); }; self.state = State.OPEN; self.onOpen(); } else { console.error("peer failed to honor contract"); console.error("out of state message: " + event.data); self.close(); } }; this.socket.onopen = function () { return console.log("opening socket"); }; this.socket.onclose = function () { return self.close(); }; return [2 /*return*/]; } }); }); }; PhysicalNode.prototype.respond = function (synq) { return __awaiter(this, void 0, void 0, function () { var url, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (this.state != State.EMPTY) throw ("wrong state exception"); this.state = State.RESPONDED; if (!synq.supported.includes("WebSocket-Provider")) return [3 /*break*/, 2]; url = synq.body[synq.supported.indexOf("WebSocket-Provider")]; return [4 /*yield*/, this.connectToWebSocket(url)]; case 1: _b.sent(); //could be run asynchronously return [2 /*return*/, { author: "physical-node", protocol: "WebSocket-Consumer", body: [""] }]; case 2: if (!synq.supported.includes("WebSocket-Consumer")) return [3 /*break*/, 4]; this.buildConnectionHandler(); _a = { author: "physical-node", protocol: "WebSocket-Provider" }; return [4 /*yield*/, this.buildURI()]; case 3: return [2 /*return*/, (_a.body = [_b.sent()], _a)]; case 4: throw "No Compatible Protocol"; } }); }); }; PhysicalNode.prototype.send = function (message) { if (this.state != State.OPEN) throw ("connection not open"); try { this.socket.send(message); } catch (e) { this.close(); throw ("failed to send message"); } }; PhysicalNode.prototype.setOnClose = function (f) { this.onClose = f; }; PhysicalNode.prototype.setOnMessage = function (f) { this.onMessage = f; }; PhysicalNode.prototype.setOnOpen = function (f) { this.onOpen = f; }; /** * initialize the webserver and handle incoming connections. * @param port * @private */ PhysicalNode.__init = function (port) { if (port === void 0) { port = 0; } if (PhysicalNode.initialized) throw "Already Initialized"; PhysicalNode.initialized = true; PhysicalNode.host = promiseRequest_1.promiseRequest("https://api.ipify.org"); var server = net.createServer(); PhysicalNode.port = Promise.resolve(config_1.config.port); PhysicalNode.server = new WebSocket.Server({ port: config_1.config.port }); //find the instance associated with the socket PhysicalNode.server.on('connection', function (ws, req) { var key = req.url.slice(1); var callback = key ? PhysicalNode.pendingConnections[key] : undefined; if (!callback) { ws.close(); // key not found return; } delete PhysicalNode.pendingConnections[key]; callback(ws); }); }; PhysicalNode.initialized = false; PhysicalNode.pendingConnections = []; return PhysicalNode; }()); exports.PhysicalNode = PhysicalNode; PhysicalNode.__init(); //# sourceMappingURL=PhysicalNode.js.map