IPC removed, replaced by WS

This commit is contained in:
Luis Fernando Molina committed 2020-04-06 08:33:07 +02:00
1 parent ba4217fb24
commit 656c193511
503 files changed
+28128 -34498

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
#PORT NUMBERS: If any of these ports are already in use by a different app, please pick a new number between 1 and 50000.
WEB_SERVER_PORT=34247
WEB_SOCKETS_PORT=8080
WEB_SOCKETS_SERVER_PORT=8080
# TASK MANAGER VARIABLES:
@@ -8,3 +8,5 @@ WRITE_LOGS_TO_FILES=true
BOTS_PATH=../Legacy-Code
LOG_PATH=../Log-Files
WEB_SOCKETS_SERVER_PORT=8080
+222
View File
@@ -0,0 +1,222 @@
exports.newEventsServer = function newEventsServer() {
const MODULE = "Events Server"
const LOG_INFO = false
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run,
onMessage: onMessage
}
let eventHandlers = new Map()
let counter = 0
return thisObject
function finalize() {
}
function initialize() {
}
function onMessage(data, callbackFunction) {
try {
let command = JSON.parse(data)
switch (command.action) {
case "greetings": {
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "createEventHandler": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/*
We will only create event handlers which were not created before. Remember that someone trying to listen events
at an event handler that does not exist, will create that eventhandler, so it is possible that the emitter
when trying to create the event handler in fact was late and the event handler is already there if the listener
arrived here first. An event handler created with this method is not destroyed if there are no listeners or they
all leave.
*/
eventHandler = newEventHandler()
eventHandler.deleteWhenAllListenersAreGone = false
eventHandlers.set(command.eventHandlerName, eventHandler)
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "deleteEventHandler": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler !== undefined) {
/*
We will only delete event handlers which have noone listening, allowing a listener to continue listening even
when the event emitter is gone, asuming that it could come back at some point in time and resume emitting.
*/
if (eventHandler.listeners.length === 0) {
eventHandlers.delete(command.eventHandlerName)
} else {
eventHandler.deleteWhenAllListenersAreGone = true
}
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "listenToEvent": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/*
We will create event handlers which were not created before if a listener tries to listen to a handler that does noet
exist before the emitter comes and create it. This is to aviod syncronization problems and also problems with emitters life
cycles with higher frecuency that the ones of listeners. Created in this way, event handlers are marked for deletion if
all listeners stop listening at one point in time.
*/
eventHandler = newEventHandler()
eventHandler.deleteWhenAllListenersAreGone = true
eventHandlers.set(command.eventHandlerName, eventHandler)
}
eventSubscriptionId = eventHandler.listenToEvent(command.eventHandlerName, command.eventType, command.callerId, handlerFunction, command.extraData)
function handlerFunction(event, extraData) {
let outputData = {
action: 'Event Raised',
eventHandlerName: command.eventHandlerName,
eventType: command.eventType,
event: event,
callerId: command.callerId,
extraData: extraData
}
callbackFunction(JSON.stringify(outputData))
}
let response = {
result: global.DEFAULT_OK_RESPONSE.result,
message: global.DEFAULT_OK_RESPONSE.message,
eventSubscriptionId: eventSubscriptionId
}
sendResponse(response)
return
}
case "stopListening": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/* If the event handler does not exist anymore, then there is no need to perform further actiions. */
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
eventHandler.stopListening(command.eventHandlerName, command.eventType, command.callerId, command.eventSubscriptionId)
/*
We check here if there are no more listeners and the event handler original emmiter is also gone, then we need to delete
this event handlers since chances are that is not needed anymore.
*/
if (eventHandler.listeners.length === 0 && eventHandler.deleteWhenAllListenersAreGone === true) {
eventHandlers.delete(command.eventHandlerName)
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "raiseEvent": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
eventHandler = newEventHandler()
eventHandlers.set(command.eventHandlerName, eventHandler)
/* No matter if it is the listener or the emiter the one that acts first, if an event handler does not exist we just create it acan keep it there. */
}
//console.log("[INFO] BackendServers -> Events Server -> Raising Event " + command.eventHandlerName + " " + command.eventType)
eventHandler.raiseEvent(command.eventType, command.event)
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
}
console.log("[WARN] BackendServers -> Events Server -> onMessage -> Unknown Command Received:" + data)
function sendResponse(message) {
if (command.callerId !== undefined) {
message.callerId = command.callerId
}
message.action = 'Event Server Response'
callbackFunction(JSON.stringify(message))
}
} catch (err) {
console.log("[ERROR] BackendServers -> Events Server -> onMessage -> Bad Command Received:" + data)
console.log("[ERROR] BackendServers -> Events Server -> onMessage -> An Error Happened:" + err.stack)
}
}
function run() {
console.log('Events Server Started.')
}
function newEventHandler() {
let thisObject = {
name: undefined, // This is for debugging purposes only.
deleteWhenAllListenersAreGone: false,
listeners: [], // Here we store all the functions we will call when an event is raiseed.
listenToEvent: listenToEvent,
stopListening: stopListening,
raiseEvent: raiseEvent,
finalize: finalize
}
return thisObject
function finalize() {
thisObject.listeners = []
}
function listenToEvent(eventHandlerName, eventType, callerId, handler, extraData) {
let eventSubscriptionId = Math.trunc(Math.random() * 1000000)
thisObject.listeners.push([eventHandlerName, eventType, callerId, handler, extraData, eventSubscriptionId])
return eventSubscriptionId
}
function stopListening(eventHandlerName, eventType, callerId, eventSubscriptionId) {
if (eventSubscriptionId !== undefined) {
for (let i = 0; i < thisObject.listeners.length; i++) {
if (eventSubscriptionId === thisObject.listeners[i][5]) {
thisObject.listeners.splice(i, 1)
return
}
}
}
if (eventHandlerName !== undefined && eventType !== undefined && callerId !== undefined) {
for (let i = 0; i < thisObject.listeners.length; i++) {
if (eventHandlerName === thisObject.listeners[i][0] && eventType === thisObject.listeners[i][1] && callerId === thisObject.listeners[i][2]) {
thisObject.listeners.splice(i, 1)
return
}
}
}
}
function raiseEvent(eventType, event) {
for (let i = 0; i < thisObject.listeners.length; i++) {
/* We will execute all the functions listening to this event type. */
if (thisObject.listeners[i][1] === eventType) {
let handler = thisObject.listeners[i][3]
let extraData = thisObject.listeners[i][4]
handler(event, extraData)
}
}
}
}
}
@@ -1,28 +1,27 @@
{
"_from": "child_process",
"_from": "child_process@^1.0.2",
"_id": "child_process@1.0.2",
"_inBundle": false,
"_integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o=",
"_location": "/child_process",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"type": "range",
"registry": true,
"raw": "child_process",
"raw": "child_process@^1.0.2",
"name": "child_process",
"escapedName": "child_process",
"rawSpec": "",
"rawSpec": "^1.0.2",
"saveSpec": null,
"fetchSpec": "latest"
"fetchSpec": "^1.0.2"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz",
"_shasum": "b1f7e7fc73d25e7fd1d455adc94e143830182b5a",
"_spec": "child_process",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServer",
"_spec": "child_process@^1.0.2",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServers",
"author": "",
"bugs": {
"url": "https://github.com/npm/security-holder/issues"
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,28 +1,27 @@
{
"_from": "dotenv",
"_from": "dotenv@^8.2.0",
"_id": "dotenv@8.2.0",
"_inBundle": false,
"_integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw==",
"_location": "/dotenv",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"type": "range",
"registry": true,
"raw": "dotenv",
"raw": "dotenv@^8.2.0",
"name": "dotenv",
"escapedName": "dotenv",
"rawSpec": "",
"rawSpec": "^8.2.0",
"saveSpec": null,
"fetchSpec": "latest"
"fetchSpec": "^8.2.0"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz",
"_shasum": "97e619259ada750eea3e4ea3e26bceea5424b16a",
"_spec": "dotenv",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\WebSocketsServer",
"_spec": "dotenv@^8.2.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServers",
"bugs": {
"url": "https://github.com/motdotla/dotenv/issues"
},
File renamed without changes.
File renamed without changes.
@@ -19,10 +19,12 @@ function concat(list, totalLength) {
for (let i = 0; i < list.length; i++) {
const buf = list[i];
buf.copy(target, offset);
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength) return target.slice(0, offset);
return target;
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
+54
View File
@@ -0,0 +1,54 @@
'use strict';
const kDone = Symbol('kDone');
const kRun = Symbol('kRun');
/**
* A very simple job queue with adjustable concurrency. Adapted from
* https://github.com/STRML/async-limiter
*/
class Limiter {
/**
* Creates a new `Limiter`.
*
* @param {Number} concurrency The maximum number of jobs allowed to run
* concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
}
module.exports = Limiter;
@@ -1,14 +1,12 @@
'use strict';
const Limiter = require('async-limiter');
const zlib = require('zlib');
const bufferUtil = require('./buffer-util');
const Limiter = require('./limiter');
const { kStatusCode, NOOP } = require('./constants');
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const EMPTY_BLOCK = Buffer.from([0x00]);
const kPerMessageDeflate = Symbol('permessage-deflate');
const kTotalLength = Symbol('total-length');
const kCallback = Symbol('callback');
@@ -66,7 +64,7 @@ class PerMessageDeflate {
this._options.concurrencyLimit !== undefined
? this._options.concurrencyLimit
: 10;
zlibLimiter = new Limiter({ concurrency });
zlibLimiter = new Limiter(concurrency);
}
}
@@ -133,12 +131,18 @@ class PerMessageDeflate {
}
if (this._deflate) {
if (this._deflate[kCallback]) {
this._deflate[kCallback]();
}
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
'The deflate stream was closed while data was being processed'
)
);
}
}
}
@@ -288,7 +292,7 @@ class PerMessageDeflate {
}
/**
* Decompress data. Concurrency limited by async-limiter.
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
@@ -296,7 +300,7 @@ class PerMessageDeflate {
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.push((done) => {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err, result) => {
done();
callback(err, result);
@@ -305,7 +309,7 @@ class PerMessageDeflate {
}
/**
* Compress data. Concurrency limited by async-limiter.
* Compress data. Concurrency limited.
*
* @param {Buffer} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
@@ -313,12 +317,10 @@ class PerMessageDeflate {
* @public
*/
compress(data, fin, callback) {
zlibLimiter.push((done) => {
zlibLimiter.add((done) => {
this._compress(data, fin, (err, result) => {
done();
if (err || result) {
callback(err, result);
}
callback(err, result);
});
});
}
@@ -393,11 +395,6 @@ class PerMessageDeflate {
* @private
*/
_compress(data, fin, callback) {
if (!data || data.length === 0) {
process.nextTick(callback, null, EMPTY_BLOCK);
return;
}
const endpoint = this._isServer ? 'server' : 'client';
if (!this._deflate) {
@@ -431,10 +428,7 @@ class PerMessageDeflate {
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
//
// This `if` statement is only needed for Node.js < 10.0.0 because as of
// commit https://github.com/nodejs/node/commit/5e3f5164, the flush
// callback is no longer called if the deflate stream is closed while
// data is being processed.
// The deflate stream was closed while data was being processed.
//
return;
}
@@ -30,14 +30,17 @@ class Receiver extends Writable {
*
* @param {String} binaryType The type for binary data
* @param {Object} extensions An object containing the negotiated extensions
* @param {Boolean} isServer Specifies whether to operate in client or server
* mode
* @param {Number} maxPayload The maximum allowed message length
*/
constructor(binaryType, extensions, maxPayload) {
constructor(binaryType, extensions, isServer, maxPayload) {
super();
this._binaryType = binaryType || BINARY_TYPES[0];
this[kWebSocket] = undefined;
this._extensions = extensions || {};
this._isServer = !!isServer;
this._maxPayload = maxPayload | 0;
this._bufferedBytes = 0;
@@ -96,11 +99,12 @@ class Receiver extends Writable {
do {
const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) {
this._buffers.shift().copy(dst, dst.length - n);
dst.set(this._buffers.shift(), offset);
} else {
buf.copy(dst, dst.length - n, 0, n);
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
this._buffers[0] = buf.slice(n);
}
@@ -224,6 +228,16 @@ class Receiver extends Writable {
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 0x80) === 0x80;
if (this._isServer) {
if (!this._masked) {
this._loop = false;
return error(RangeError, 'MASK must be set', true, 1002);
}
} else if (this._masked) {
this._loop = false;
return error(RangeError, 'MASK must be clear', true, 1002);
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else return this.haveLength();
@@ -110,7 +110,13 @@ class Sender {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError('The message must not be greater than 123 bytes');
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
buf.write(data, 2);
}
@@ -154,6 +160,10 @@ class Sender {
ping(data, mask, cb) {
const buf = toBuffer(data);
if (buf.length > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
if (this._deflating) {
this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);
} else {
@@ -194,6 +204,10 @@ class Sender {
pong(data, mask, cb) {
const buf = toBuffer(data);
if (buf.length > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
if (this._deflating) {
this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);
} else {
@@ -306,6 +320,22 @@ class Sender {
this._deflating = true;
perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while data was being compressed'
);
if (typeof cb === 'function') cb(err);
for (let i = 0; i < this._queue.length; i++) {
const callback = this._queue[i][4];
if (typeof callback === 'function') callback(err);
}
return;
}
this._deflating = false;
options.readOnly = false;
this.sendFrame(Sender.frame(buf, options), cb);
@@ -67,7 +67,6 @@ function createWebSocketStream(ws, options) {
autoDestroy: false,
emitClose: false,
objectMode: false,
readableObjectMode: false,
writableObjectMode: false
});
@@ -79,6 +78,8 @@ function createWebSocketStream(ws, options) {
});
ws.once('error', function error(err) {
if (duplex.destroyed) return;
duplex.destroy(err);
});
@@ -95,8 +96,15 @@ function createWebSocketStream(ws, options) {
return;
}
ws.once('close', function close() {
let called = false;
ws.once('error', function error(err) {
called = true;
callback(err);
});
ws.once('close', function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
ws.terminate();
@@ -110,6 +118,12 @@ function createWebSocketStream(ws, options) {
return;
}
// If the value of the `_socket` property is `null` it means that `ws` is a
// client websocket and the handshake failed. In fact, when this happens, a
// socket is never assigned to the websocket. Wait for the `'error'` event
// that will be emitted by the websocket.
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
if (duplex._readableState.endEmitted) duplex.destroy();
callback();
@@ -117,7 +131,7 @@ function createWebSocketStream(ws, options) {
ws._socket.once('finish', function finish() {
// `duplex` is not destroyed here because the `'end'` event will be
// emitted on `duplex` after this `'finish'` event. The EOF signaling
// `null` chunk is, in fact, pushed when the WebSocket emits `'close'`.
// `null` chunk is, in fact, pushed when the websocket emits `'close'`.
callback();
});
ws.close();
@@ -21,7 +21,7 @@ try {
exports.isValidStatusCode = (code) => {
return (
(code >= 1000 &&
code <= 1013 &&
code <= 1014 &&
code !== 1004 &&
code !== 1005 &&
code !== 1006) ||
@@ -141,6 +141,7 @@ class WebSocket extends EventEmitter {
const receiver = new Receiver(
this._binaryType,
this._extensions,
this._isServer,
maxPayload
);
@@ -178,9 +179,8 @@ class WebSocket extends EventEmitter {
* @private
*/
emitClose() {
this.readyState = WebSocket.CLOSED;
if (!this._socket) {
this.readyState = WebSocket.CLOSED;
this.emit('close', this._closeCode, this._closeMessage);
return;
}
@@ -190,6 +190,7 @@ class WebSocket extends EventEmitter {
}
this._receiver.removeAllListeners();
this.readyState = WebSocket.CLOSED;
this.emit('close', this._closeCode, this._closeMessage);
}
@@ -1,28 +1,27 @@
{
"_from": "ws",
"_id": "ws@7.1.2",
"_from": "ws@^7.1.2",
"_id": "ws@7.2.3",
"_inBundle": false,
"_integrity": "sha512-gftXq3XI81cJCgkUiAVixA0raD9IVmXqsylCrjRygw4+UOOGzPoxnQ6r/CnVL9i+mDncJo94tSkyrtuuQVBmrg==",
"_integrity": "sha512-HTDl9G9hbkNDk98naoR/cHDws7+EyYMOdL1BmjsZXRUjf7d+MficC4B7HLUPlSiho0vg+CWKrGIt/VJBd1xunQ==",
"_location": "/ws",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"type": "range",
"registry": true,
"raw": "ws",
"raw": "ws@^7.1.2",
"name": "ws",
"escapedName": "ws",
"rawSpec": "",
"rawSpec": "^7.1.2",
"saveSpec": null,
"fetchSpec": "latest"
"fetchSpec": "^7.1.2"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/ws/-/ws-7.1.2.tgz",
"_shasum": "c672d1629de8bb27a9699eb599be47aeeedd8f73",
"_spec": "ws",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\WebSockets-Server",
"_resolved": "https://registry.npmjs.org/ws/-/ws-7.2.3.tgz",
"_shasum": "a5411e1fb04d5ed0efee76d26d5c46d830c39b46",
"_spec": "ws@^7.1.2",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServers",
"author": {
"name": "Einar Otto Stangvik",
"email": "einaros@gmail.com",
@@ -33,9 +32,6 @@
"url": "https://github.com/websockets/ws/issues"
},
"bundleDependencies": false,
"dependencies": {
"async-limiter": "^1.0.0"
},
"deprecated": false,
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"devDependencies": {
@@ -45,11 +41,14 @@
"eslint": "^6.0.0",
"eslint-config-prettier": "^6.0.0",
"eslint-plugin-prettier": "^3.0.1",
"mocha": "^6.1.3",
"nyc": "^14.0.0",
"mocha": "^7.0.0",
"nyc": "^15.0.0",
"prettier": "^1.17.0",
"utf-8-validate": "^5.0.2"
},
"engines": {
"node": ">=8.3.0"
},
"files": [
"browser.js",
"index.js",
@@ -73,6 +72,18 @@
"license": "MIT",
"main": "index.js",
"name": "ws",
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/ws.git"
@@ -82,5 +93,5 @@
"lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"",
"test": "npm run lint && nyc --reporter=html --reporter=text mocha --throw-deprecation test/*.test.js"
},
"version": "7.1.2"
"version": "7.2.3"
}
+23
View File
@@ -0,0 +1,23 @@
{
"name": "backend-server",
"version": "0.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"child_process": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/child_process/-/child_process-1.0.2.tgz",
"integrity": "sha1-sffn/HPSXn/R1FWtyU4UODAYK1o="
},
"dotenv": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz",
"integrity": "sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw=="
},
"ws": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.2.3.tgz",
"integrity": "sha512-HTDl9G9hbkNDk98naoR/cHDws7+EyYMOdL1BmjsZXRUjf7d+MficC4B7HLUPlSiho0vg+CWKrGIt/VJBd1xunQ=="
}
}
}
@@ -8,7 +8,7 @@
},
"dependencies": {
"child_process": "^1.0.2",
"dotenv": "^8.1.0",
"node-ipc": "^9.1.1"
"dotenv": "^8.2.0",
"ws": "^7.1.2"
}
}
+49
View File
@@ -0,0 +1,49 @@
process.on('uncaughtException', function (err) {
if (err.message.indexOf("EADDRINUSE") > 0) {
console.log("Superalgos Backend Server cannot be started. Reason: the port " + port + " is already in use by another application.")
return
}
console.log('[ERROR] Backend Server -> server -> uncaughtException -> err.message = ' + err.message)
console.log('[ERROR] Backend Server -> server -> uncaughtException -> err.stack = ' + err.stack)
process.exit(1)
})
process.on('unhandledRejection', (reason, p) => {
console.log('[ERROR] Backend Server -> server -> unhandledRejection -> reason = ' + JSON.stringify(reason))
console.log('[ERROR] Backend Server -> server -> unhandledRejection -> p = ' + JSON.stringify(p))
process.exit(1)
})
/* Callbacks default responses. */
global.DEFAULT_OK_RESPONSE = {
result: "Ok",
message: "Operation Succeeded"
};
global.DEFAULT_FAIL_RESPONSE = {
result: "Fail",
message: "Operation Failed"
};
let EVENTS_SERVER = require('./eventsServer.js');
let WEB_SOCKETS_SERVER = require('./webSocketsServer.js');
let TASK_MANAGER_SERVER = require('./taskManagerServer.js');
try {
EVENTS_SERVER = EVENTS_SERVER.newEventsServer()
EVENTS_SERVER.initialize()
EVENTS_SERVER.run()
WEB_SOCKETS_SERVER = WEB_SOCKETS_SERVER.newWebSocketsServer(EVENTS_SERVER)
WEB_SOCKETS_SERVER.initialize()
WEB_SOCKETS_SERVER.run()
TASK_MANAGER_SERVER = TASK_MANAGER_SERVER.newTaskManagerServer(WEB_SOCKETS_SERVER, EVENTS_SERVER)
TASK_MANAGER_SERVER.initialize()
TASK_MANAGER_SERVER.run()
} catch (err) {
console.log('[ERROR] BackendServers -> Task Manager -> server -> Error = ' + err.stack)
}
+295
View File
@@ -0,0 +1,295 @@
exports.newTaskManagerServer = function newTaskManagerServer(WEB_SOCKETS_SERVER, EVENTS_SERVER) {
const MODULE = "Task Manager Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
/*
This server creates and destroys Task Servers according to what is going on at the UI. Each of these created servers will do their own
work. The responsibility of this server is to manage those children processes in order to be in sync with what the end user want and is defining
at the user interface.
*/
const { fork } = require('child_process')
require('dotenv').config()
tasks = new Map()
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
/*
Here we will create an Event Handler for this server. After that we will listen to events happening here. Elements of the UI will raise events here,
as a way to communicate what is going on with the user interacting with UI components. That is the way this server will know for example when a new
task needs to be created or destroyed.
*/
let eventsServerClient = newEventsServerClient()
eventsServerClient.createEventHandler('Task Manager')
eventsServerClient.listenToEvent('Task Manager', 'Run Task', undefined, undefined, undefined, runTask)
eventsServerClient.listenToEvent('Task Manager', 'Stop Task', undefined, undefined, undefined, stopTask)
console.log('Task Manager Server Started.')
function runTask(message) {
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Entering function.')
if (message.event === undefined) {
console.log('[WARN] BackendServers -> Task Manager Server -> runTask -> Message Received Without Event -> message = ' + JSON.stringify(message))
return
}
if (message.event.taskId === undefined) {
console.log('[WARN] BackendServers -> Task Manager Server -> runTask -> Message Received Without taskId -> message = ' + JSON.stringify(message))
return
}
if (message.event.definition === undefined) {
console.log('[WARN] BackendServers -> Task Manager Server -> runTask -> Message Received Without Definition -> message = ' + JSON.stringify(message))
return
}
if (tasks.get(message.event.taskId) !== undefined) {
//console.log('[WARN] BackendServers -> Task Manager Server -> runTask -> Task Already Running -> taskId = ' + message.event.taskId)
return
}
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Task Name = ' + message.event.taskName)
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Task Id = ' + message.event.taskId)
let path = process.env.TASK_SERVER_PATH + '/server.js'
/* Workarround to avoid having the same debug port at the forked process which makes it crash. */
for (let i = 0; i < process.execArgv.length; i++) {
let argument = process.execArgv[i]
if (argument.indexOf('--inspect') > -1) {
process.execArgv[i] = ''
}
}
/* Forking this process. */
let task = {
childProcess: fork(path, [message.event.taskId], { stdio: 'inherit' }),
id: message.event.taskId,
name: message.event.taskName
}
tasks.set(message.event.taskId, task)
task.childProcess.on('error', (err) => {
console.log('[ERROR] BackendServers -> Task Manager Server -> runTask -> Problem with Task Name = ' + task.name)
console.log('[ERROR] BackendServers -> Task Manager Server -> runTask -> Problem with Task Id = ' + task.id)
console.log(`[ERROR] BackendServers -> Task Manager Server -> runTask -> Task Manager exited with error ${err}`)
})
task.childProcess.on('close', (code, signal) => {
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Task Terminated. -> Task Name = ' + task.name)
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Task Terminated. -> Task Id = ' + task.id)
tasks.delete(task.id)
})
eventsServerClient.listenToEvent('Task Manager - ' + message.event.taskId, 'Nodejs Process Ready for Task', undefined, undefined, undefined, sendStartingEvent)
function sendStartingEvent() {
//console.log('[INFO] BackendServers -> Task Manager Server -> runTask -> Emitting Event -> key = ' + 'Task Server - ' + task.id)
eventsServerClient.raiseEvent('Task Server - ' + task.id, 'Run Task', message.event)
}
}
function stopTask(message) {
//console.log('[INFO] BackendServers -> Task Manager Server -> stopTask -> Entering function.')
if (message.event === undefined) {
console.log('[WARN] BackendServers -> Task Manager Server -> stopTask -> Message Received Without Event -> message = ' + JSON.stringify(message))
return
}
if (message.event.taskId === undefined) {
console.log('[WARN] BackendServers -> Task Manager Server -> stopTask -> Message Received Without taskId -> message = ' + JSON.stringify(message))
return
}
//console.log('[INFO] BackendServers -> Task Manager Server -> stopTask -> Task Name = ' + message.event.taskName)
//console.log('[INFO] BackendServers -> Task Manager Server -> stopTask -> Task Id = ' + message.event.taskId)
let task = tasks.get(message.event.taskId)
if (task) {
task.childProcess.send('Stop this Task');
//console.log('[INFO] BackendServers -> Task Manager Server -> stopTask -> Child Process instructed to finish.')
} else {
console.log('[WARN] BackendServers -> Task Manager Server -> stopTask -> Cannot delete Task that does not exist.')
}
}
}
function newEventsServerClient() {
let thisObject = {
initialize: initialize,
finalize: finalize,
createEventHandler: createEventHandler,
deleteEventHandler: deleteEventHandler,
listenToEvent: listenToEvent,
stopListening: stopListening,
raiseEvent: raiseEvent,
onMessage: onMessage
}
let eventListeners = new Map()
let responseWaiters = new Map()
return thisObject
function finalize() {
/* Before disconnecting we will forze all eventListeners to stop listening. */
const eventListenersArray = [...eventListeners.values()]
for (let i = 0; i < eventListenersArray.length; i++) {
let handler = eventListenersArray[i]
let eventCommand = {
action: 'stopListening',
eventHandlerName: handler.eventHandlerName,
eventType: handler.eventType,
callerId: handler.callerId
}
sendCommand(eventCommand)
}
}
function initialize() {
}
function onMessage(data) {
try {
let message = JSON.parse(data)
if (message.action === 'Event Raised') {
let key
if (message.callerId) {
key = message.eventHandlerName + '-' + message.eventType + '-' + message.callerId
} else {
key = message.eventHandlerName + '-' + message.eventType
}
let handler = eventListeners.get(key)
if (handler) {
handler.callBack(message)
} else {
console.log(key + ' not found so could not deliver event raised.')
console.log(' Message = ' + data)
}
return
}
if (message.action === 'Event Server Response') {
let handler = responseWaiters.get(message.callerId)
if (handler) {
handler(message)
}
return
}
} catch (err) {
console.log('[ERROR] BackendServers -> Task Manager Server -> onMessage -> Error Receiving Message from Events Server -> data = ' + JSON.stringify(data))
console.log('[ERROR] BackendServers -> Task Manager Server -> onMessage -> Error Receiving Message from Events Server -> error = ' + err.stack)
}
}
function sendCommand(command, responseCallBack, eventsCallBack) {
try {
if (command.action === 'listenToEvent') {
let key
if (command.callerId) {
key = command.eventHandlerName + '-' + command.eventType + '-' + command.callerId
} else {
key = command.eventHandlerName + '-' + command.eventType
}
let handler = {
eventHandlerName: command.eventHandlerName,
eventType: command.eventType,
callerId: command.callerId,
callBack: eventsCallBack
}
eventListeners.set(key, handler)
}
if (command.callerId && responseCallBack) {
responseWaiters.set(command.callerId, responseCallBack)
}
EVENTS_SERVER.onMessage(JSON.stringify(command), thisObject.onMessage)
} catch (err) {
console.log('[ERROR] BackendServers -> Task Manager Server -> sendCommand -> Error Sending Command to Events Server -> command = ' + JSON.stringify(command))
console.log('[ERROR] BackendServers -> Task Manager Server -> sendCommand -> Error Sending Command to Events Server -> error = ' + err.stack)
}
}
function createEventHandler(eventHandlerName, callerId, responseCallBack) {
let eventCommand = {
action: 'createEventHandler',
eventHandlerName: eventHandlerName,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function deleteEventHandler(eventHandlerName, callerId, responseCallBack) {
let eventCommand = {
action: 'deleteEventHandler',
eventHandlerName: eventHandlerName,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function listenToEvent(eventHandlerName, eventType, extraData, callerId, responseCallBack, eventsCallBack) {
let eventCommand = {
action: 'listenToEvent',
eventHandlerName: eventHandlerName,
eventType: eventType,
extraData: extraData,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack, eventsCallBack)
}
function stopListening(eventHandlerName, eventType, eventSubscriptionId, callerId, responseCallBack) {
/* User either needs to specify a valid eventSubscriptionId OR the 3 params: eventHandlerName, eventType, callerId which were used when start listening to events. */
let eventCommand = {
action: 'stopListening',
eventHandlerName: eventHandlerName,
eventType: eventType,
eventSubscriptionId: eventSubscriptionId,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function raiseEvent(eventHandlerName, eventType, event, callerId, responseCallBack) {
let eventCommand = {
action: 'raiseEvent',
eventHandlerName: eventHandlerName,
eventType: eventType,
event: event,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
}
}
+112
View File
@@ -0,0 +1,112 @@
exports.newWebSocketsServer = function newWebSocketsServer(EVENTS_SERVER) {
const MODULE = "Web Sockets Server"
const LOG_INFO = false
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
require('dotenv').config()
const WEB_SOCKET = require('ws')
let socketServer
let port = process.env.WEB_SOCKETS_SERVER_PORT
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
setUpWebSocketServer()
}
function setUpWebSocketServer() {
try {
socketServer = new WEB_SOCKET.Server({ port: port })
socketServer.on('connection', onConnection)
function onConnection(socket) {
let lastNonce = -1
if (LOG_INFO === true) {
console.log('New Websocket Connection.')
}
socket.on('message', onMenssage)
function onMenssage(message){
try {
if (LOG_INFO === true) {
console.log('Message Received: ' + message)
}
let messageArray = message.split('|')
let origin = messageArray[0]
let nonce = messageArray[1]
let messageToEventServer = messageArray[2]
if (origin === 'Web Browser') {
if (isNaN(nonce) || nonce === "") {
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce is not a Number. message = ' + message)
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce is not a Number. nonce = ' + nonce)
return
}
if (nonce === "1") { // this happens once the browser is restarted, and the server is running since a previous session.
lastNonce = 0
}
if (Number(nonce) < Number(lastNonce)) {
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. message = ' + message)
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. nonce = ' + nonce)
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. lastNonce = ' + lastNonce)
return
}
lastNonce = nonce
try {
let jsonCheck = JSON.parse(messageToEventServer)
} catch (err) {
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Message received from the browser is not a valid JSON. message = ' + message)
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Message received from the browser is not a valid JSON. messageToEventServer = ' + messageToEventServer)
return
}
let acknowledgeMessage = {
action: 'Acknowledge',
nonce: nonce
}
socket.send(JSON.stringify(acknowledgeMessage))
}
EVENTS_SERVER.onMessage(messageToEventServer, onResponse)
function onResponse(message) {
socket.send(message)
}
} catch (err) {
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. err = ' + err.stack)
}
}
}
console.log('Web Sockets Server Started.')
} catch (err) {
console.log('[ERROR] BackendServers -> Web Sockets Server -> run -> setUpWebSocketServer -> err.message = ' + err.message)
}
}
}
+1 -1
View File
@@ -131,7 +131,7 @@ function newCanvas () {
thisObject.animation = animation
/* Low Level Infraestructure First */
animation.addCallBackFunction('System Event Handler Physics', systemEventHandler.physics)
animation.addCallBackFunction('System Event Handler Physics', eventsServerClient.physics)
/* Spcaces Physics */
animation.addCallBackFunction('CockpitSpace Physics', thisObject.cockpitSpace.physics)
@@ -65,7 +65,7 @@ function newSessionFunctions () {
tradingSystem: JSON.stringify(tradingSystem)
}
systemEventHandler.raiseEvent(key, 'Run Session', event)
eventsServerClient.raiseEvent(key, 'Run Session', event)
if (node.payload.parentNode.payload.parentNode.payload.parentNode.payload.parentNode === undefined) {
callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE)
@@ -75,7 +75,7 @@ function newSessionFunctions () {
function stopSession (node, functionLibraryProtocolNode, callBackFunction) {
let key = node.name + '-' + node.type + '-' + node.id
systemEventHandler.raiseEvent(key, 'Stop Session')
eventsServerClient.raiseEvent(key, 'Stop Session')
node.payload.uiObject.stop(callBackFunction)
}
@@ -68,12 +68,12 @@ function newTaskFunctions () {
if (node.payload.parentNode === undefined) {
callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE)
systemEventHandler.raiseEvent('Task Server', 'Debug Task Started', event)
eventsServerClient.raiseEvent('Task Server', 'Debug Task Started', event)
return
}
node.payload.uiObject.run(callBackFunction)
systemEventHandler.raiseEvent('Task Manager', 'Run Task', event)
eventsServerClient.raiseEvent('Task Manager', 'Run Task', event)
}
function stopTask (node, functionLibraryProtocolNode, callBackFunction) {
@@ -83,7 +83,7 @@ function newTaskFunctions () {
}
node.payload.uiObject.stop(callBackFunction)
systemEventHandler.raiseEvent('Task Manager', 'Stop Task', event)
eventsServerClient.raiseEvent('Task Manager', 'Stop Task', event)
if (node.bot === undefined) { return }
if (node.bot.processes.length === 0) { return }
@@ -32,7 +32,7 @@ function newCircularProgressBar () {
function finalize () {
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
if (eventSubscriptionIdHeartbeat !== undefined) {
systemEventHandler.stopListening(key, eventSubscriptionIdHeartbeat)
eventsServerClient.stopListening(key, eventSubscriptionIdHeartbeat)
}
thisObject.container = undefined
@@ -48,7 +48,7 @@ function newCircularProgressBar () {
}
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
systemEventHandler.listenToEvent(key, 'Heartbeat', undefined, key, onResponse, onHeartBeat)
eventsServerClient.listenToEvent(key, 'Heartbeat', undefined, key, onResponse, onHeartBeat)
function onResponse (message) {
eventSubscriptionIdHeartbeat = message.eventSubscriptionId
+5 -5
View File
@@ -122,10 +122,10 @@ function newUiObject () {
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
if (eventSubscriptionIdOnRunning !== undefined) {
systemEventHandler.stopListening(key, eventSubscriptionIdOnRunning, 'UiObject')
eventsServerClient.stopListening(key, eventSubscriptionIdOnRunning, 'UiObject')
}
if (eventSubscriptionIdOnStopped !== undefined) {
systemEventHandler.stopListening(key, eventSubscriptionIdOnStopped, 'UiObject')
eventsServerClient.stopListening(key, eventSubscriptionIdOnStopped, 'UiObject')
}
thisObject.container.eventHandler.stopListening(selfFocusEventSubscriptionId)
@@ -759,7 +759,7 @@ function newUiObject () {
/* We will wait to hear the Running event in order to confirm the execution was really started */
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
systemEventHandler.listenToEvent(key, 'Running', undefined, 'UiObject', onResponse, onRunning)
eventsServerClient.listenToEvent(key, 'Running', undefined, 'UiObject', onResponse, onRunning)
onRunningCallBackFunction = callBackFunction
@@ -771,7 +771,7 @@ function newUiObject () {
if (thisObject.payload === undefined) { return }
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
systemEventHandler.stopListening(key, eventSubscriptionIdOnRunning, 'UiObject')
eventsServerClient.stopListening(key, eventSubscriptionIdOnRunning, 'UiObject')
thisObject.isRunning = true
@@ -801,7 +801,7 @@ function newUiObject () {
function stop (callBackFunction, event) {
/* We will wait to the event that the execution was terminated in order to call back the menu item */
let key = thisObject.payload.node.name + '-' + thisObject.payload.node.type + '-' + thisObject.payload.node.id
systemEventHandler.listenToEvent(key, 'Stopped', undefined, 'UiObject', onResponse, onStopped)
eventsServerClient.listenToEvent(key, 'Stopped', undefined, 'UiObject', onResponse, onStopped)
function onResponse (message) {
eventSubscriptionIdOnStopped = message.eventSubscriptionId
+3 -3
View File
@@ -1,6 +1,6 @@
let canvas
let markets
let systemEventHandler
let eventsServerClient
let APP_SCHEMA_MAP = new Map()
let APP_SCHEMA_ARRAY = []
@@ -24,8 +24,8 @@ function newDashboard () {
try {
setBrowserEvents()
systemEventHandler = newSystemEventHandler()
systemEventHandler.initialize(setUpAppSchema)
eventsServerClient = newEventsServerClient()
eventsServerClient.initialize(setUpAppSchema)
function setUpAppSchema () {
APP_SCHEMA_ARRAY = getAppSchema()
+2 -5
View File
@@ -1,5 +1,5 @@
function newSystemEventHandler () {
function newEventsServerClient () {
/* Web Sockets Connection */
const MODULE_NAME = 'System Event Handler'
@@ -71,7 +71,7 @@ function newSystemEventHandler () {
commandsWaitingConfirmation.set(stringNonce, command)
commandsSentByTimestamp.set(stringNonce, timestamp)
let messageToWebSocketServer = stringNonce + '->' + JSON.stringify(command)
let messageToWebSocketServer = 'Web Browser|' + stringNonce + '|' + JSON.stringify(command)
WEB_SOCKETS_CONNECTION.send(messageToWebSocketServer)
}
@@ -164,9 +164,6 @@ function newSystemEventHandler () {
function setuptWebSockets (callBackFunction) {
try {
WEB_SOCKETS_CONNECTION = new WebSocket(WEB_SOCKETS_URL)
WEB_SOCKETS_CONNECTION.onopen = () => {
console.log('Websocket connection opened.')
}
WEB_SOCKETS_CONNECTION.onerror = error => {
console.log('WebSocket error:' + JSON.stringify(error))
}
-74
View File
@@ -1,74 +0,0 @@
function Stack(){
Object.defineProperties(
this,
{
add:{
enumerable:true,
writable:false,
value:addToStack
},
next:{
enumerable:true,
writable:false,
value:run
},
clear:{
enumerable:true,
writable:false,
value:clearStack
},
contents:{
enumerable:false,
get:getStack,
set:setStack
},
autoRun:{
enumerable:true,
writable:true,
value:true
},
stop:{
enumerable:true,
writable:true,
value:false
}
}
);
var stack=[];
var running=false;
var stop=false;
function clearStack(){
stack=[];
return stack;
}
function getStack(){
return stack;
}
function setStack(val){
stack=val;
return stack;
}
function addToStack(){
for(var i in arguments){
stack.unshift(arguments[i]);
}
if(!running && !this.stop && this.autoRun){
this.next();
}
}
function run(){
running=true;
if(stack.length<1 || this.stop){
running=false;
return;
}
stack.shift().bind(this)();
}
}
-18
View File
@@ -1,18 +0,0 @@
var Stack=require('../stack');
//create a new Stack instance
var stack=new Stack;
stack.autoRun=false;
for(var i=0; i<50; i++){
//add a bunch of stuff to the stack
stack.add(makeRequest.bind(stack,i));
}
stack.next();
function makeRequest(index){
//do stuff
console.log(`making LIFO request ${index}`);
this.next();
}
-59
View File
@@ -1,59 +0,0 @@
{
"_from": "easy-stack@^1.0.0",
"_id": "easy-stack@1.0.0",
"_inBundle": false,
"_integrity": "sha1-EskbMIWjfwuqM26UhurEv5Tj54g=",
"_location": "/easy-stack",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "easy-stack@^1.0.0",
"name": "easy-stack",
"escapedName": "easy-stack",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/js-queue"
],
"_resolved": "https://registry.npmjs.org/easy-stack/-/easy-stack-1.0.0.tgz",
"_shasum": "12c91b3085a37f0baa336e9486eac4bf94e3e788",
"_spec": "easy-stack@^1.0.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\Events-Server\\node_modules\\js-queue",
"author": {
"name": "Brandon Nozaki Miller"
},
"bugs": {
"url": "https://github.com/RIAEvangelist/easy-stack/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Simple JS stack with auto run for node and browsers",
"engines": {
"node": ">=6.0.0"
},
"homepage": "https://github.com/RIAEvangelist/easy-stack#readme",
"keywords": [
"stack",
"node",
"js",
"auto",
"run",
"execute",
"browser",
"react"
],
"license": "DBAD",
"main": "stack.js",
"name": "easy-stack",
"repository": {
"type": "git",
"url": "git+https://github.com/RIAEvangelist/easy-stack.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "1.0.0"
}
-39
View File
@@ -1,39 +0,0 @@
class Stack{
constructor(){
this.stack=[];
this.autoRun=true;
this.running=false;
this.stop=false;
}
clear(){
this.stack=[];
return this.stack;
}
contents(val){
if(val){
this.stack=val;
}
return this.stack;
}
add(...callbacks){
this.stack.push(...callbacks);
if(!this.running && !this.stop && this.autoRun){
this.next();
}
}
next(){
this.running=true;
if(this.stack.length<1 || this.stop){
this.running=false;
return;
}
this.stack.pop().bind(this)();
}
}
module.exports=Stack;
-28
View File
@@ -1,28 +0,0 @@
{
"name": "event-pubsub",
"description": "Super light and fast Extensible PubSub events and EventEmitters for Node and the browser with support for ES6 by default, and ES5 versions for older verions of node and older IE/Safari versions. Easy for any developer level. No frills, just high speed pubsub events!",
"main": "event-pubsub.js",
"authors": [
"Brandon Nozaki Miller"
],
"license": "DBAD",
"keywords": [
"event",
"events",
"pubsub",
"node",
"browser"
],
"homepage": "https://github.com/RIAEvangelist/event-pubsub",
"moduleType": [
"globals",
"node"
],
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
-143
View File
@@ -1,143 +0,0 @@
'use strict';
function EventPubSub() {
this._events_={};
this.publish=this.trigger=this.emit=emit;
this.subscribe=this.on=on;
this.once=once;
this.unSubscribe=this.off=off;
this.emit$=emit$;
function on(type,handler,once){
if(!handler){
throw new ReferenceError('handler not defined.');
}
if(!this._events_[type]){
this._events_[type]=[];
}
if(once){
handler._once_ = once;
}
this._events_[type].push(handler);
return this;
}
function once(type,handler){
return this.on(type, handler, true);
}
function off(type,handler){
if(!this._events_[type]){
return this;
}
if(!handler){
throw new ReferenceError('handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler');
}
if(handler=='*'){
delete this._events_[type];
return this;
}
var handlers=this._events_[type];
while(handlers.includes(handler)){
handlers.splice(
handlers.indexOf(handler),
1
);
}
if(handlers.length<1){
delete this._events_[type];
}
return this;
}
function emit(type){
this.emit$.apply(this, arguments);
if(!this._events_[type]){
return this;
}
arguments.splice=Array.prototype.splice;
arguments.splice(0,1);
var handlers=this._events_[type];
var onceHandled=[];
for(var i in handlers){
var handler=handlers[i];
handler.apply(this, arguments);
if(handler._once_){
onceHandled.push(handler);
}
}
for(var i in onceHandled){
this.off(
type,
onceHandled[i]
);
}
return this;
}
function emit$(type, args){
if(!this._events_['*']){
return this;
}
var catchAll=this._events_['*'];
args.shift=Array.prototype.shift;
args.shift(type);
for(var handler of catchAll){
handler.apply(this, args);
}
return this;
}
return this;
}
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
module.exports=EventPubSub;
-99
View File
@@ -1,99 +0,0 @@
'use strict';
class EventPubSub {
constructor( scope ) {
this._events_ = {};
this.publish = this.trigger = this.emit;
this.subscribe = this.on;
this.unSubscribe = this.off;
}
on( type, handler, once ) {
if ( !handler ) {
throw new ReferenceError( 'handler not defined.' );
}
if ( !this._events_[ type ] ) {
this._events_[ type ] = [];
}
if(once){
handler._once_ = once;
}
this._events_[ type ].push( handler );
return this;
}
once( type, handler ) {
return this.on( type, handler, true );
}
off( type, handler ) {
if ( !this._events_[ type ] ) {
return this;
}
if ( !handler ) {
throw new ReferenceError( 'handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler' );
}
if ( handler == '*' ) {
delete this._events_[ type ];
return this;
}
const handlers = this._events_[ type ];
while ( handlers.includes( handler ) ) {
handlers.splice(
handlers.indexOf( handler ),
1
);
}
if ( handlers.length < 1 ) {
delete this._events_[ type ];
}
return this;
}
emit( type, ...args ) {
if ( !this._events_[ type ] ) {
return this.emit$( type, ...args );
}
const handlers = this._events_[ type ];
const onceHandled=[];
for ( let handler of handlers ) {
handler.apply( this, args );
if(handler._once_){
onceHandled.push(handler);
}
}
for(let handler of onceHandled){
this.off(type,handler);
}
return this.emit$( type, ...args );
}
emit$( type, ...args ) {
if ( !this._events_[ '*' ] ) {
return this;
}
const catchAll = this._events_[ '*' ];
for ( let handler of catchAll ) {
handler.call( this, type, ...args );
}
return this;
}
}
module.exports = EventPubSub;
-141
View File
@@ -1,141 +0,0 @@
'use strict';
window.EventPubSub=function EventPubSub() {
this._events_={};
this.publish=this.trigger=this.emit=emit;
this.subscribe=this.on=on;
this.once=once;
this.unSubscribe=this.off=off;
this.emit$=emit$;
function on(type,handler,once){
if(!handler){
throw new ReferenceError('handler not defined.');
}
if(!this._events_[type]){
this._events_[type]=[];
}
if(once){
handler._once_ = once;
}
this._events_[type].push(handler);
return this;
}
function once(type,handler){
return this.on(type, handler, true);
}
function off(type,handler){
if(!this._events_[type]){
return this;
}
if(!handler){
throw new ReferenceError('handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler');
}
if(handler=='*'){
delete this._events_[type];
return this;
}
var handlers=this._events_[type];
while(handlers.includes(handler)){
handlers.splice(
handlers.indexOf(handler),
1
);
}
if(handlers.length<1){
delete this._events_[type];
}
return this;
}
function emit(type){
this.emit$.apply(this, arguments);
if(!this._events_[type]){
return this;
}
arguments.splice=Array.prototype.splice;
arguments.splice(0,1);
var handlers=this._events_[type];
var onceHandled=[];
for(var i in handlers){
var handler=handlers[i];
handler.apply(this, arguments);
if(handler._once_){
onceHandled.push(handler);
}
}
for(var i in onceHandled){
this.off(
type,
onceHandled[i]
);
}
return this;
}
function emit$(type, args){
if(!this._events_['*']){
return this;
}
var catchAll=this._events_['*'];
args.shift=Array.prototype.shift;
args.shift(type);
for(var handler of catchAll){
handler.apply(this, args);
}
return this;
}
return this;
}
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
-130
View File
@@ -1,130 +0,0 @@
'use strict';
window.EventPubSub=class EventPubSub {
constructor( scope ) {
this._events_ = {};
this.publish = this.trigger = this.emit;
this.subscribe = this.on;
this.unSubscribe = this.off;
}
on( type, handler, once ) {
if ( !handler ) {
throw new ReferenceError( 'handler not defined.' );
}
if ( !this._events_[ type ] ) {
this._events_[ type ] = [];
}
if(once){
handler._once_ = once;
}
this._events_[ type ].push( handler );
return this;
}
once( type, handler ) {
return this.on( type, handler, true );
}
off( type, handler ) {
if ( !this._events_[ type ] ) {
return this;
}
if ( !handler ) {
throw new ReferenceError( 'handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler' );
}
if ( handler == '*' ) {
delete this._events_[ type ];
return this;
}
const handlers = this._events_[ type ];
while ( handlers.includes( handler ) ) {
handlers.splice(
handlers.indexOf( handler ),
1
);
}
if ( handlers.length < 1 ) {
delete this._events_[ type ];
}
return this;
}
emit( type, ...args ) {
if ( !this._events_[ type ] ) {
return this.emit$( type, ...args );
}
const handlers = this._events_[ type ];
const onceHandled=[];
for ( let handler of handlers ) {
handler.apply( this, args );
if(handler._once_){
onceHandled.push(handler);
}
}
for(let handler of onceHandled){
this.off(type,handler);
}
return this.emit$( type, ...args );
}
emit$( type, ...args ) {
if ( !this._events_[ '*' ] ) {
return this;
}
const catchAll = this._events_[ '*' ];
for ( let handler of catchAll ) {
handler.call( this, type, ...args );
}
return this;
}
}
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
-8
View File
@@ -1,8 +0,0 @@
'use strict';
let EventPubSub = require('./es5');
if(process.version[1]>5){
EventPubSub = require('./es6');
}
module.exports=EventPubSub;
-59
View File
@@ -1,59 +0,0 @@
{
"_from": "event-pubsub@4.3.0",
"_id": "event-pubsub@4.3.0",
"_inBundle": false,
"_integrity": "sha512-z7IyloorXvKbFx9Bpie2+vMJKKx1fH1EN5yiTfp8CiLOTptSYy1g8H4yDpGlEdshL1PBiFtBHepF2cNsqeEeFQ==",
"_location": "/event-pubsub",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "event-pubsub@4.3.0",
"name": "event-pubsub",
"escapedName": "event-pubsub",
"rawSpec": "4.3.0",
"saveSpec": null,
"fetchSpec": "4.3.0"
},
"_requiredBy": [
"/node-ipc"
],
"_resolved": "https://registry.npmjs.org/event-pubsub/-/event-pubsub-4.3.0.tgz",
"_shasum": "f68d816bc29f1ec02c539dc58c8dd40ce72cb36e",
"_spec": "event-pubsub@4.3.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\Events-Server\\node_modules\\node-ipc",
"author": {
"name": "Brandon Nozaki Miller"
},
"bugs": {
"url": "https://github.com/RIAEvangelist/event-pubsub/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Super light and fast Extensible PubSub events and EventEmitters for Node and the browser with support for ES6 by default, and ES5 versions for older verions of node and older IE/Safari versions. Easy for any developer level. No frills, just high speed pubsub events!",
"directories": {
"example": "examples"
},
"engines": {
"node": ">=4.0.0"
},
"homepage": "https://github.com/RIAEvangelist/event-pubsub",
"keywords": [
"event",
"events",
"pubsub",
"node",
"browser"
],
"license": "Unlicense",
"main": "event-pubsub.js",
"name": "event-pubsub",
"repository": {
"type": "git",
"url": "git+https://github.com/RIAEvangelist/event-pubsub.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "4.3.0"
}
-71
View File
@@ -1,71 +0,0 @@
function Message() {
Object.defineProperties(
this, {
data: {
enumerable: true,
get: getData,
set: setData
},
type: {
enumerable: true,
get: getType,
set: setType
},
load:{
enumarable:true,
writable:false,
value:parse
},
JSON: {
enumerable: true,
get: getJSON
}
}
);
var type = '';
var data = {};
function getType() {
return type;
}
function getData() {
return data;
}
function getJSON() {
return JSON.stringify(
{
type: type,
data: data
}
);
}
function setType(value) {
type = value;
}
function setData(value) {
data = value;
}
function parse(message){
try{
var message=JSON.parse(message);
type=message.type;
data=message.data;
}catch(err){
var badMessage=message;
type='error',
data={
message:'Invalid JSON response format',
err:err,
response:badMessage
}
}
}
}
module.exports=Message;
-75
View File
@@ -1,75 +0,0 @@
(
function(){
function Message() {
Object.defineProperties(
this, {
data: {
enumerable: true,
get: getData,
set: setData
},
type: {
enumerable: true,
get: getType,
set: setType
},
load:{
enumarable:true,
writable:false,
value:parse
},
JSON: {
enumerable: true,
get: getJSON
}
}
);
var type = '';
var data = {};
function getType() {
return type;
}
function getData() {
return data;
}
function getJSON() {
return JSON.stringify(
{
type: type,
data: data
}
);
}
function setType(value) {
type = value;
}
function setData(value) {
data = value;
}
function parse(message){
try{
var message=JSON.parse(message);
type=message.type;
data=message.data;
}catch(err){
var badMessage=message;
type='error',
data={
message:'Invalid JSON response format',
err:err,
response:badMessage
}
}
}
}
window.message=Message;
}
)();
-81
View File
@@ -1,81 +0,0 @@
{
"_from": "js-message@1.0.5",
"_id": "js-message@1.0.5",
"_inBundle": false,
"_integrity": "sha1-IwDSSxrwjondCVvBpMnJz8uJLRU=",
"_location": "/js-message",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "js-message@1.0.5",
"name": "js-message",
"escapedName": "js-message",
"rawSpec": "1.0.5",
"saveSpec": null,
"fetchSpec": "1.0.5"
},
"_requiredBy": [
"/node-ipc"
],
"_resolved": "https://registry.npmjs.org/js-message/-/js-message-1.0.5.tgz",
"_shasum": "2300d24b1af08e89dd095bc1a4c9c9cfcb892d15",
"_spec": "js-message@1.0.5",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\Events-Server\\node_modules\\node-ipc",
"author": {
"name": "Brandon Nozaki Miller"
},
"bugs": {
"url": "https://github.com/RIAEvangelist/js-message/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "normalized JS Object and JSON message and event protocol for node.js, vanialla js, react.js, components, actions, stores and dispatchers",
"devDependencies": {},
"engines": {
"node": ">=0.6.0"
},
"homepage": "https://github.com/RIAEvangelist/js-message#readme",
"keywords": [
"message",
"normalize",
"events",
"js",
"json",
"protocol",
"ipc",
"node",
"nodejs",
"node.js",
"react",
"react.js",
"reactjs",
"websocket",
"websockets",
"web",
"socket",
"sockets",
"ws",
"flux",
"reflux",
"component",
"components",
"store",
"stores",
"action",
"actions"
],
"license": "DBAD",
"main": "Message.js",
"name": "js-message",
"repository": {
"type": "git",
"url": "git+https://github.com/RIAEvangelist/js-message.git"
},
"scripts": {
"start": "node devServer.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "1.0.5"
}
-62
View File
@@ -1,62 +0,0 @@
{
"_from": "js-queue@2.0.0",
"_id": "js-queue@2.0.0",
"_inBundle": false,
"_integrity": "sha1-NiITz4YPRo8BJfxslqvBdCUx+Ug=",
"_location": "/js-queue",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "js-queue@2.0.0",
"name": "js-queue",
"escapedName": "js-queue",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/node-ipc"
],
"_resolved": "https://registry.npmjs.org/js-queue/-/js-queue-2.0.0.tgz",
"_shasum": "362213cf860f468f0125fc6c96abc1742531f948",
"_spec": "js-queue@2.0.0",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\Events-Server\\node_modules\\node-ipc",
"author": {
"name": "Brandon Nozaki Miller"
},
"bugs": {
"url": "https://github.com/RIAEvangelist/js-queue/issues"
},
"bundleDependencies": false,
"dependencies": {
"easy-stack": "^1.0.0"
},
"deprecated": false,
"description": "Simple JS queue with auto run for node and browsers",
"engines": {
"node": ">=1.0.0"
},
"homepage": "https://github.com/RIAEvangelist/js-queue#readme",
"keywords": [
"queue",
"node",
"js",
"auto",
"run",
"execute",
"browser",
"react"
],
"license": "DBAD",
"main": "queue.js",
"name": "js-queue",
"repository": {
"type": "git",
"url": "git+https://github.com/RIAEvangelist/js-queue.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "2.0.0"
}
-74
View File
@@ -1,74 +0,0 @@
function Queue(){
Object.defineProperties(
this,
{
add:{
enumerable:true,
writable:false,
value:addToQueue
},
next:{
enumerable:true,
writable:false,
value:run
},
clear:{
enumerable:true,
writable:false,
value:clearQueue
},
contents:{
enumerable:false,
get:getQueue,
set:setQueue
},
autoRun:{
enumerable:true,
writable:true,
value:true
},
stop:{
enumerable:true,
writable:true,
value:false
}
}
);
var queue=[];
var running=false;
var stop=false;
function clearQueue(){
queue=[];
return queue;
}
function getQueue(){
return queue;
}
function setQueue(val){
queue=val;
return queue;
}
function addToQueue(){
for(var i in arguments){
queue.push(arguments[i]);
}
if(!running && !this.stop && this.autoRun){
this.next();
}
}
function run(){
running=true;
if(queue.length<1 || this.stop){
running=false;
return;
}
queue.shift().bind(this)();
}
}
-76
View File
@@ -1,76 +0,0 @@
function Queue(asStack){
Object.defineProperties(
this,
{
add:{
enumerable:true,
writable:false,
value:addToQueue
},
next:{
enumerable:true,
writable:false,
value:run
},
clear:{
enumerable:true,
writable:false,
value:clearQueue
},
contents:{
enumerable:false,
get:getQueue,
set:setQueue
},
autoRun:{
enumerable:true,
writable:true,
value:true
},
stop:{
enumerable:true,
writable:true,
value:false
}
}
);
var queue=[];
var running=false;
var stop=false;
function clearQueue(){
queue=[];
return queue;
}
function getQueue(){
return queue;
}
function setQueue(val){
queue=val;
return queue;
}
function addToQueue(){
for(var i in arguments){
queue.push(arguments[i]);
}
if(!running && !this.stop && this.autoRun){
this.next();
}
}
function run(){
running=true;
if(queue.length<1 || this.stop){
running=false;
return;
}
queue.shift().bind(this)();
}
}
module.exports=Queue;
-3
View File
@@ -1,3 +0,0 @@
const Stack=require('easy-stack');
module.exports = Stack;
-257
View File
@@ -1,257 +0,0 @@
'use strict';
const net = require('net'),
tls = require('tls'),
EventParser = require('../entities/EventParser.js'),
Message = require('js-message'),
fs = require('fs'),
Queue = require('js-queue');
let Events = require('event-pubsub/es5');
if(process.version[1]>4){
Events = require('event-pubsub');
}
let eventParser = new EventParser();
class Client extends Events{
constructor(config,log){
super();
Object.assign(
this,
{
Client : Client,
config : config,
queue : new Queue,
socket : false,
connect : connect,
emit : emit,
log : log,
retriesRemaining:config.maxRetries||0,
explicitlyDisconnected: false
}
);
eventParser=new EventParser(this.config);
}
}
function emit(type,data){
this.log('dispatching event to ', this.id, this.path, ' : ', type, ',', data);
let message=new Message;
message.type=type;
message.data=data;
if(this.config.rawBuffer){
message=new Buffer(type,this.config.encoding);
}else{
message=eventParser.format(message);
}
if(!this.config.sync){
this.socket.write(message);
return;
}
this.queue.add(
syncEmit.bind(this,message)
);
}
function syncEmit(message){
this.log('dispatching event to ', this.id, this.path, ' : ', message);
this.socket.write(message);
}
function connect(){
//init client object for scope persistance especially inside of socket events.
let client=this;
client.log('requested connection to ', client.id, client.path);
if(!this.path){
client.log('\n\n######\nerror: ', client.id ,' client has not specified socket path it wishes to connect to.');
return;
}
const options={};
if(!client.port){
client.log('Connecting client on Unix Socket :', client.path);
options.path=client.path;
if (process.platform ==='win32' && !client.path.startsWith('\\\\.\\pipe\\')){
options.path = options.path.replace(/^\//, '');
options.path = options.path.replace(/\//g, '-');
options.path= `\\\\.\\pipe\\${options.path}`;
}
client.socket = net.connect(options);
}else{
options.host=client.path;
options.port=client.port;
if(client.config.interface.localAddress){
options.localAddress=client.config.interface.localAddress;
}
if(client.config.interface.localPort){
options.localPort=client.config.interface.localPort;
}
if(client.config.interface.family){
options.family=client.config.interface.family;
}
if(client.config.interface.hints){
options.hints=client.config.interface.hints;
}
if(client.config.interface.lookup){
options.lookup=client.config.interface.lookup;
}
if(!client.config.tls){
client.log('Connecting client via TCP to', options);
client.socket = net.connect(options);
}else{
client.log('Connecting client via TLS to', client.path ,client.port,client.config.tls);
if(client.config.tls.private){
client.config.tls.key=fs.readFileSync(client.config.tls.private);
}
if(client.config.tls.public){
client.config.tls.cert=fs.readFileSync(client.config.tls.public);
}
if(client.config.tls.trustedConnections){
if(typeof client.config.tls.trustedConnections === 'string'){
client.config.tls.trustedConnections=[client.config.tls.trustedConnections];
}
client.config.tls.ca=[];
for(let i=0; i<client.config.tls.trustedConnections.length; i++){
client.config.tls.ca.push(
fs.readFileSync(client.config.tls.trustedConnections[i])
);
}
}
Object.assign(client.config.tls,options);
client.socket = tls.connect(
client.config.tls
);
}
}
client.socket.setEncoding(this.config.encoding);
client.socket.on(
'error',
function(err){
client.log('\n\n######\nerror: ', err);
client.publish('error', err);
}
);
client.socket.on(
'connect',
function connectionMade(){
client.publish('connect');
client.retriesRemaining=client.config.maxRetries;
client.log('retrying reset');
}
);
client.socket.on(
'close',
function connectionClosed(){
client.log('connection closed' ,client.id , client.path,
client.retriesRemaining, 'tries remaining of', client.config.maxRetries
);
if(
client.config.stopRetrying ||
client.retriesRemaining<1 ||
client.explicitlyDisconnected
){
client.publish('disconnect');
client.log(
(client.config.id),
'exceeded connection rety amount of',
' or stopRetrying flag set.'
);
client.socket.destroy();
client.publish('destroy');
client=undefined;
return;
}
setTimeout(
function retryTimeout(){
client.retriesRemaining--;
client.connect();
}.bind(null,client),
client.config.retry
);
client.publish('disconnect');
}
);
client.socket.on(
'data',
function(data) {
client.log('## received events ##');
if(client.config.rawBuffer){
client.publish(
'data',
new Buffer(data,client.config.encoding)
);
if(!client.config.sync){
return;
}
client.queue.next();
return;
}
if(!this.ipcBuffer){
this.ipcBuffer='';
}
data=(this.ipcBuffer+=data);
if(data.slice(-1)!=eventParser.delimiter || data.indexOf(eventParser.delimiter) == -1){
client.log('Messages are large, You may want to consider smaller messages.');
return;
}
this.ipcBuffer='';
const events = eventParser.parse(data);
const eCount = events.length;
for(let i=0; i<eCount; i++){
let message=new Message;
message.load(events[i]);
client.log('detected event', message.type, message.data);
client.publish(
message.type,
message.data
);
}
if(!client.config.sync){
return;
}
client.queue.next();
}
);
}
module.exports=Client;
-402
View File
@@ -1,402 +0,0 @@
'use strict';
const net = require('net'),
tls = require('tls'),
fs = require('fs'),
dgram = require('dgram'),
EventParser = require('../entities/EventParser.js'),
Message = require('js-message');
let Events = require('event-pubsub/es5');
if(process.version[1]>4){
Events = require('event-pubsub');
}
let eventParser = new EventParser();
class Server extends Events{
constructor(path,config,log,port){
super();
Object.assign(
this,
{
config : config,
path : path,
port : port,
udp4 : false,
udp6 : false,
log : log,
server : false,
sockets : [],
emit : emit,
broadcast : broadcast
}
);
eventParser=new EventParser(this.config);
this.on(
'close',
serverClosed.bind(this)
);
}
onStart(socket){
this.trigger(
'start',
socket
);
}
stop(){
this.server.close();
}
start(){
if(!this.path){
this.log('Socket Server Path not specified, refusing to start');
return;
}
if(this.config.unlink){
fs.unlink(
this.path,
startServer.bind(this)
);
}else{
startServer.bind(this)();
}
}
}
function emit(socket, type, data){
this.log('dispatching event to socket', ' : ', type, data);
let message=new Message;
message.type=type;
message.data=data;
if(this.config.rawBuffer){
this.log(this.config.encoding)
message=new Buffer(type,this.config.encoding);
}else{
message=eventParser.format(message);
}
if(this.udp4 || this.udp6){
if(!socket.address || !socket.port){
this.log('Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets');
this.broadcast(type,data);
return;
}
this.server.write(
message,
socket
);
return;
}
socket.write(message);
}
function broadcast(type,data){
this.log('broadcasting event to all known sockets listening to ', this.path,' : ', ((this.port)?this.port:''), type, data);
let message=new Message;
message.type=type;
message.data=data;
if(this.config.rawBuffer){
message=new Buffer(type,this.config.encoding);
}else{
message=eventParser.format(message);
}
if(this.udp4 || this.udp6){
for(let i=1, count=this.sockets.length; i<count; i++){
this.server.write(message,this.sockets[i]);
}
}else{
for(let i=0, count=this.sockets.length; i<count; i++){
this.sockets[i].write(message);
}
}
}
function serverClosed(){
for(let i=0, count=this.sockets.length; i<count; i++){
let socket=this.sockets[i];
let destroyedSocketId=false;
if(socket){
if(socket.readable){
continue;
}
}
if(socket.id){
destroyedSocketId=socket.id;
}
this.log('socket disconnected',destroyedSocketId.toString());
if(socket && socket.destroy){
socket.destroy();
}
this.sockets.splice(i,1);
this.publish('socket.disconnected', socket, destroyedSocketId);
return;
}
}
function gotData(socket,data,UDPSocket){
let sock=((this.udp4 || this.udp6)? UDPSocket : socket);
if(this.config.rawBuffer){
data=new Buffer(data,this.config.encoding);
this.publish(
'data',
data,
sock
);
return;
}
if(!this.ipcBuffer){
this.ipcBuffer='';
}
data=(this.ipcBuffer+=data);
if(data.slice(-1)!=eventParser.delimiter || data.indexOf(eventParser.delimiter) == -1){
this.log('Messages are large, You may want to consider smaller messages.');
return;
}
this.ipcBuffer='';
data=eventParser.parse(data);
while(data.length>0){
let message=new Message;
message.load(data.shift());
// Only set the sock id if it is specified.
if (message.data && message.data.id){
sock.id=message.data.id;
}
this.log('received event of : ',message.type,message.data);
this.publish(
message.type,
message.data,
sock
);
}
}
function socketClosed(socket){
this.publish(
'close',
socket
);
}
function serverCreated(socket) {
this.sockets.push(socket);
if(socket.setEncoding){
socket.setEncoding(this.config.encoding);
}
this.log('## socket connection to server detected ##');
socket.on(
'close',
socketClosed.bind(this)
);
socket.on(
'error',
function(err){
this.log('server socket error',err);
this.publish('error',err);
}.bind(this)
);
socket.on(
'data',
gotData.bind(this,socket)
);
socket.on(
'message',
function(msg,rinfo) {
if (!rinfo){
return;
}
this.log('Received UDP message from ', rinfo.address, rinfo.port);
let data;
if(this.config.rawSocket){
data=new Buffer(msg,this.config.encoding);
}else{
data=msg.toString();
}
socket.emit('data',data,rinfo);
}.bind(this)
);
this.publish(
'connect',
socket
);
if(this.config.rawBuffer){
return;
}
}
function startServer() {
this.log(
'starting server on ',this.path,
((this.port)?`:${this.port}`:'')
);
if(!this.udp4 && !this.udp6){
this.log('starting TLS server',this.config.tls);
if(!this.config.tls){
this.server=net.createServer(
serverCreated.bind(this)
);
}else{
startTLSServer.bind(this)();
}
}else{
this.server=dgram.createSocket(
((this.udp4)? 'udp4':'udp6')
);
this.server.write=UDPWrite.bind(this);
this.server.on(
'listening',
function UDPServerStarted() {
serverCreated.bind(this)(this.server);
}.bind(this)
);
}
this.server.on(
'error',
function(err){
this.log('server error',err);
this.publish(
'error',
err
);
}.bind(this)
);
this.server.maxConnections=this.config.maxConnections;
if(!this.port){
this.log('starting server as', 'Unix || Windows Socket');
if (process.platform ==='win32'){
this.path = this.path.replace(/^\//, '');
this.path = this.path.replace(/\//g, '-');
this.path= `\\\\.\\pipe\\${this.path}`;
}
this.server.listen(
this.path,
this.onStart.bind(this)
);
return;
}
if(!this.udp4 && !this.udp6){
this.log('starting server as', (this.config.tls?'TLS':'TCP'));
this.server.listen(
this.port,
this.path,
this.onStart.bind(this)
);
return;
}
this.log('starting server as',((this.udp4)? 'udp4':'udp6'));
this.server.bind(
this.port,
this.path
);
this.onStart(
{
address : this.path,
port : this.port
}
);
}
function startTLSServer(){
this.log('starting TLS server',this.config.tls);
if(this.config.tls.private){
this.config.tls.key=fs.readFileSync(this.config.tls.private);
}else{
this.config.tls.key=fs.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`);
}
if(this.config.tls.public){
this.config.tls.cert=fs.readFileSync(this.config.tls.public);
}else{
this.config.tls.cert=fs.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`);
}
if(this.config.tls.dhparam){
this.config.tls.dhparam=fs.readFileSync(this.config.tls.dhparam);
}
if(this.config.tls.trustedConnections){
if(typeof this.config.tls.trustedConnections === 'string'){
this.config.tls.trustedConnections=[this.config.tls.trustedConnections];
}
this.config.tls.ca=[];
for(let i=0; i<this.config.tls.trustedConnections.length; i++){
this.config.tls.ca.push(
fs.readFileSync(this.config.tls.trustedConnections[i])
);
}
}
this.server=tls.createServer(
this.config.tls,
serverCreated.bind(this)
);
}
function UDPWrite(message,socket){
let data=new Buffer(message, this.config.encoding);
this.server.send(
data,
0,
data.length,
socket.port,
socket.address,
function(err, bytes) {
if(err){
this.log('error writing data to socket',err);
this.publish(
'error',
function(err){
this.publish('error',err);
}
);
}
}
);
}
module.exports=Server;
-80
View File
@@ -1,80 +0,0 @@
'use strict';
/*eslint no-magic-numbers: ["error", { "ignore": [ 0] }]*/
/**
* @module entities
*/
const os = require('os');
/**
* @class Defaults
* @description Defaults Entity
*/
class Defaults{
/**
* @constructor
* @method constructor
* @return {void}
*/
constructor(){
this.appspace='app.';
this.socketRoot='/tmp/';
this.id=os.hostname();
this.encoding='utf8';
this.rawBuffer=false;
this.sync=false;
this.unlink=true;
this.delimiter='\f';
this.silent=false;
this.logDepth=5;
this.logInColor=true;
this.logger=console.log.bind(console);
this.maxConnections=100;
this.retry=500;
this.maxRetries=Infinity;
this.stopRetrying=false;
this.IPType=getIPType();
this.tls=false;
this.networkHost = (this.IPType == 'IPv6') ? '::1' : '127.0.0.1';
this.networkPort = 8000;
this.interface={
localAddress:false,
localPort:false,
family:false,
hints:false,
lookup:false
}
}
}
/**
* method to get ip type
*
* @method getIPType
* @return {string} ip type
*/
function getIPType() {
const networkInterfaces = os.networkInterfaces();
let IPType = '';
if (networkInterfaces
&& Array.isArray(networkInterfaces)
&& networkInterfaces.length > 0) {
// getting the family of first network interface available
IPType = networkInterfaces [
Object.keys( networkInterfaces )[0]
][0].family;
}
return IPType;
}
module.exports=Defaults;
-32
View File
@@ -1,32 +0,0 @@
'use strict';
const Defaults = require('./Defaults.js');
class Parser{
constructor(config){
if(!config){
config=new Defaults;
}
this.delimiter=config.delimiter;
}
format(message){
if(!message.data && message.data!==false && message.data!==0){
message.data={};
}
if(message.data['_maxListeners']){
message.data={};
}
message=message.JSON+this.delimiter;
return message;
}
parse(data){
let events=data.split(this.delimiter);
events.pop();
return events;
}
}
module.exports=Parser;
@@ -1,44 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'goodbye';
ipc.config.retry= 1500;
ipc.config.maxRetries= 10;
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'goodbye'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,50 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.maxRetries=10;
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'hello'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'app.message',
function(data){
ipc.log('got a message from world : ', data.message);
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,51 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
var messages={
goodbye:false,
hello:false
};
ipc.serveNet(
function(){
ipc.server.on(
'app.message',
function(data,socket){
ipc.log('got a message from', (data.id), (data.message));
messages[data.id]=true;
ipc.server.emit(
socket,
'app.message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
if(messages.hello && messages.goodbye){
ipc.log('got all required events, telling clients to kill connection');
ipc.server.broadcast(
'kill.connection',
{
id:ipc.config.id
}
);
}
}
);
}
);
ipc.server.start();
@@ -1,39 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'message',
'hello'
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,44 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.maxConnections=1;
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
ipc.server.emit(
socket,
'message',
data+' world!'
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log('DISCONNECTED\n\n',arguments);
}
);
}
);
ipc.server.on(
'error',
function(err){
ipc.log('Got an ERROR!',err);
}
);
ipc.server.start();
@@ -1,46 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.sync= true;
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
//queue up a bunch of requests to be sent synchronously
for(var i=0; i<10; i++){
ipc.of.world.emit(
'message',
'hello'+i
);
}
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data,'\n\n');
}
);
}
);
console.log(ipc);
@@ -1,45 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.sync = true;
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
//fake some synch procedural code
setTimeout(
function(){
ipc.server.emit(
socket,
'message',
data+' world!'
);
},
3000
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,35 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'hello'
);
}
);
ipc.of.world.on(
'data',
function(data){
ipc.log('got a message from world : ', data,data.toString());
}
);
}
);
@@ -1,40 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.serveNet(
function(){
ipc.server.on(
'connect',
function(socket){
ipc.server.emit(
socket,
'hello'
);
}
);
ipc.server.on(
'data',
function(data,socket){
ipc.log('got a message', data,data.toString());
ipc.server.emit(
socket,
'goodbye'
);
}
);
}
);
ipc.server.start();
@@ -1,47 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'goodbye';
ipc.config.retry= 1500;
ipc.config.maxRetries= 10;
ipc.config.tls={
rejectUnauthorized:false
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'goodbye'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,53 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.maxRetries=10;
ipc.config.tls={
rejectUnauthorized:false
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'hello'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'app.message',
function(data){
ipc.log('got a message from world : ', data.message);
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,55 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key'
};
var messages={
goodbye:false,
hello:false
};
ipc.serveNet(
function(){
ipc.server.on(
'app.message',
function(data,socket){
ipc.log('got a message from', (data.id), (data.message));
messages[data.id]=true;
ipc.server.emit(
socket,
'app.message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
if(messages.hello && messages.goodbye){
ipc.log('got all required events, telling clients to kill connection');
ipc.server.broadcast(
'kill.connection',
{
id:ipc.config.id
}
);
}
}
);
}
);
ipc.server.start();
@@ -1,42 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.tls={
rejectUnauthorized:false
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'message',
'hello'
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,42 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
//node-ipc will default to its local certs
ipc.config.tls={
rejectUnauthorized:false
};
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
ipc.server.emit(
socket,
'message',
data+' world!'
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,47 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.tls={
private: __dirname+'/../../../local-node-ipc-certs/private/client.key',
public: __dirname+'/../../../local-node-ipc-certs/client.pub',
rejectUnauthorized:false,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/server.pub'
]
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'message',
'hello'
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,48 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key',
dhparam: __dirname+'/../../../local-node-ipc-certs/private/dhparam.pem',
requestCert: true,
rejectUnauthorized:false,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/client.pub'
]
};
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
ipc.server.emit(
socket,
'message',
data+' world!'
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,48 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.networkHost='localhost';
ipc.config.tls={
private: __dirname+'/../../../local-node-ipc-certs/private/client.key',
public: __dirname+'/../../../local-node-ipc-certs/client.pub',
rejectUnauthorized:true,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/server.pub'
]
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'message',
'hello'
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,49 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.networkHost='localhost';
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key',
dhparam: __dirname+'/../../../local-node-ipc-certs/private/dhparam.pem',
requestCert: true,
rejectUnauthorized:true,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/client.pub'
]
};
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
ipc.server.emit(
socket,
'message',
data+' world!'
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,42 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.tls={
rejectUnauthorized:false
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'message',
'hello'
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,42 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key'
};
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
ipc.server.emit(
socket,
'message',
data+' world!'
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,47 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.sync= true;
ipc.config.tls={
rejectUnauthorized:false
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
//queue up a bunch of requests to be sent synchronously
for(var i=0; i<10; i++){
ipc.of.world.emit(
'message',
'hello'+i
);
}
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'message',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
@@ -1,48 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.sync= true;
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key'
};
ipc.serveNet(
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message : ', data);
setTimeout(
function(){
ipc.server.emit(
socket,
'message',
data+' world!'
);
},
3000
);
}
);
ipc.server.on(
'socket.disconnected',
function(data,socket){
console.log(arguments);
}
);
}
);
ipc.server.start();
@@ -1,45 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.config.networkHost='localhost';
ipc.config.tls={
private: __dirname+'/../../../local-node-ipc-certs/private/client.key',
public: __dirname+'/../../../local-node-ipc-certs/client.pub',
rejectUnauthorized:true,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/server.pub'
]
};
ipc.connectToNet(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'hello'
);
}
);
ipc.of.world.on(
'data',
function(data){
ipc.log('got a message from world : ', data,data.toString());
}
);
}
);
@@ -1,53 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.config.networkHost='localhost';
ipc.config.tls={
public: __dirname+'/../../../local-node-ipc-certs/server.pub',
private: __dirname+'/../../../local-node-ipc-certs/private/server.key',
dhparam: __dirname+'/../../../local-node-ipc-certs/private/dhparam.pem',
requestCert: true,
rejectUnauthorized:true,
trustedConnections: [
__dirname+'/../../../local-node-ipc-certs/client.pub'
]
};
ipc.serveNet(
function(){
ipc.server.on(
'connect',
function(socket){
console.log('connection detected');
ipc.server.emit(
socket,
'hello'
);
}
);
ipc.server.on(
'data',
function(data,socket){
ipc.log('got a message', data,data.toString());
ipc.server.emit(
socket,
'goodbye'
);
}
);
}
);
ipc.server.start();
@@ -1,48 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* Since there is no client relationship
* with UDP sockets sockets are not kept
* open.
*
* This means the order sockets are opened
* is important.
*
* Start World first. Then you can start
* hello or goodbye in any order you
* choose.
*
* *************************************/
ipc.config.id = 'goodbye';
ipc.config.retry= 1500;
ipc.serveNet(
8002, //we set the port here because the hello client and world server are already using the default of 8000 and the port 8001. So we can not bind to those while hello and world are connected to them.
'udp4',
function(){
ipc.server.on(
'message',
function(data){
ipc.log('got Data');
ipc.log('got a message from ', data.id ,' : ', data.message);
}
);
ipc.server.emit(
{
address : 'localhost',
port : ipc.config.networkPort
},
'message',
{
id : ipc.config.id,
message : 'Goodbye'
}
);
}
);
ipc.server.start();
@@ -1,48 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* Since there is no client relationship
* with UDP sockets sockets are not kept
* open.
*
* This means the order sockets are opened
* is important.
*
* Start World first. Then you can start
* hello or goodbye in any order you
* choose.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.serveNet(
8001, //we set the port here because the world server is already using the default of 8000. So we can not bind to 8000 while world is using it.
'udp4',
function(){
ipc.server.on(
'message',
function(data){
ipc.log('got Data');
ipc.log('got a message from ', data.id ,' : ', data.message);
}
);
ipc.server.emit(
{
address : 'localhost',
port : ipc.config.networkPort
},
'message',
{
id : ipc.config.id,
message : 'Hello'
}
);
}
);
ipc.server.start();
@@ -1,63 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* Since there is no client relationship
* with UDP sockets sockets are not kept
* open.
*
* This means the order sockets are opened
* is important.
*
* Start World first. Then you can start
* hello or goodbye in any order you
* choose.
*
***************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
var messages={
goodbye:false,
hello:false
};
ipc.serveNet(
'udp4',
function(){
console.log(123);
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message from ', data.id ,' : ', data.message);
messages[data.id]=true;
ipc.server.emit(
socket,
'message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
if(messages.hello && messages.goodbye){
ipc.log('got all required events, telling evryone how muchg I am loved!');
ipc.server.broadcast(
'message',
{
id : ipc.config.id,
message : 'Everybody Loves The World! Got messages from hello and goodbye!'
}
);
}
}
);
console.log(ipc.server);
}
);
ipc.server.start();
@@ -1,52 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* UDP Client is really a UDP server
*
* Dedicated UDP sockets on the same
* machine can not be bound to in the
* traditional client/server method
*
* Every UDP socket is it's own UDP server
* And so must have a unique port on its
* machine, unlike TCP or Unix Sockts
* which can share on the same machine.
*
* Since there is no open client server
* relationship, you should start world
* first and then hello.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.serveNet(
8001, //we set the port here because the world server is already using the default of 8000. So we can not bind to 8000 while world is using it.
'udp4',
function(){
ipc.server.on(
'message',
function(data){
ipc.log('got Data');
ipc.log('got a message from ', data.id ,' : ', data.message);
}
);
ipc.server.emit(
{
address : 'localhost',
port : ipc.config.networkPort
},
'message',
{
id : ipc.config.id,
message : 'Hello'
}
);
}
);
ipc.server.start();
@@ -1,47 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* UDP Client is really a UDP server
*
* Dedicated UDP sockets on the same
* machine can not be bound to in the
* traditional client/server method
*
* Every UDP socket is it's own UDP server
* And so must have a unique port on its
* machine, unlike TCP or Unix Sockts
* which can share on the same machine.
*
* Since there is no open client server
* relationship, you should start world
* first and then hello.
*
***************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.serveNet(
'udp4',
function(){
ipc.server.on(
'message',
function(data,socket){
ipc.log('got a message from ', data.id ,' : ', data.message);
ipc.server.emit(
socket,
'message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
}
);
}
);
ipc.server.start();
@@ -1,35 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.serveNet(
8001, //we set the port here because the world server is already using the default of 8000. So we can not bind to 8000 while world is using it.
'udp4',
function(){
ipc.server.on(
'data',
function(data){
ipc.log('got a message from world ', data, data.toString());
}
);
ipc.server.emit(
{
address : 'localhost',
port : ipc.config.networkPort
},
'hello'
);
}
);
ipc.server.start();
@@ -1,43 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* UDP Client is really a UDP server
*
* Dedicated UDP sockets on the same
* machine can not be bound to in the
* traditional client/server method
*
* Every UDP socket is it's own UDP server
* And so must have a unique port on its
* machine, unlike TCP or Unix Sockts
* which can share on the same machine.
*
* Since there is no open client server
* relationship, you should start world
* first and then hello.
*
***************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='ascii';
ipc.serveNet(
'udp4',
function(){
ipc.server.on(
'data',
function(data,socket){
ipc.log('got a message', data,data.toString());
ipc.server.emit(
socket,
'goodbye'
);
}
);
}
);
ipc.server.start();
@@ -1,31 +0,0 @@
const fs = require('fs');
const ipc = require('../../node-ipc');
const socketPath = '/tmp/ipc.sock';
//loop forever so you can see the pid of the cluster sever change in the logs
setInterval(
function() {
ipc.connectTo(
'world',
socketPath,
connecting
);
},
2000
);
function connecting(socket) {
ipc.of.world.on(
'connect',
function() {
ipc.of.world.emit(
'currentDate',
{
message: new Date().toISOString()
}
);
ipc.disconnect('world');
}
);
}
@@ -1,32 +0,0 @@
const fs = require('fs');
const ipc=require('../../../node-ipc');
const cpuCount = require('os').cpus().length;
const cluster = require('cluster');
const socketPath = '/tmp/ipc.sock';
ipc.config.unlink = false;
if (cluster.isMaster) {
if (fs.existsSync(socketPath)) {
fs.unlinkSync(socketPath);
}
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
}else{
ipc.serve(
socketPath,
function() {
ipc.server.on(
'currentDate',
function(data,socket) {
console.log(`pid ${process.pid} got: `, data);
}
);
}
);
ipc.server.start();
console.log(`pid ${process.pid} listening on ${socketPath}`);
}
-43
View File
@@ -1,43 +0,0 @@
'use strict';
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='hex';
ipc.connectTo(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
//make a 6 byte buffer for example
const myBuffer=new Buffer(6).fill(0);
myBuffer.writeUInt16BE(0x02,0);
myBuffer.writeUInt32BE(0xffeecc,2);
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
myBuffer
);
}
);
ipc.of.world.on(
'data',
function(data){
ipc.log('got a message from world : ', data);
}
);
}
);
-40
View File
@@ -1,40 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.config.rawBuffer=true;
ipc.config.encoding='hex';
ipc.serve(
function(){
ipc.server.on(
'connect',
function(socket){
ipc.server.emit(
socket,
[0xaa]
);
}
);
ipc.server.on(
'data',
function(data,socket){
ipc.log('got a message', data);
ipc.server.emit(
socket,
[0x0d,0xee]
);
}
);
}
);
ipc.server.start();
@@ -1,43 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'goodbye';
ipc.config.retry= 1500;
ipc.connectTo(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'goodbye'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,49 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry= 1500;
ipc.connectTo(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'hello'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'app.message',
function(data){
ipc.log('got a message from world : ', data);
}
);
ipc.of.world.on(
'kill.connection',
function(data){
ipc.log('world requested kill.connection');
ipc.disconnect('world');
}
);
}
);
@@ -1,51 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
var messages={
goodbye:false,
hello:false
};
ipc.serve(
function(){
ipc.server.on(
'app.message',
function(data,socket){
ipc.log('got a message from', (data.id), (data.message));
messages[data.id]=true;
ipc.server.emit(
socket,
'app.message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
if(messages.hello && messages.goodbye){
ipc.log('got all required events, telling clients to kill connection');
ipc.server.broadcast(
'kill.connection',
{
id:ipc.config.id
}
);
}
}
);
}
);
ipc.server.start();
@@ -1,44 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'hello';
ipc.config.retry = 1000;
ipc.connectTo(
'world',
function(){
ipc.of.world.on(
'connect',
function(){
ipc.log('## connected to world ##', ipc.config.delay);
ipc.of.world.emit(
'app.message',
{
id : ipc.config.id,
message : 'hello'
}
);
}
);
ipc.of.world.on(
'disconnect',
function(){
ipc.log('disconnected from world');
}
);
ipc.of.world.on(
'app.message',
function(data){
ipc.log('got a message from world : ', data);
}
);
console.log(ipc.of.world.destroy);
}
);
@@ -1,33 +0,0 @@
const ipc=require('../../../node-ipc');
/***************************************\
*
* You should start both hello and world
* then you will see them communicating.
*
* *************************************/
ipc.config.id = 'world';
ipc.config.retry= 1500;
ipc.serve(
function(){
ipc.server.on(
'app.message',
function(data,socket){
ipc.server.emit(
socket,
'app.message',
{
id : ipc.config.id,
message : data.message+' world!'
}
);
}
);
}
);
ipc.server.start();
Loaded 100 of 503 files, more files were not shown because too many files have changed in this diff. Show more