-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
284 lines (236 loc) · 7.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
var JsonSocket = require('json-socket');
var dgram = require("dgram");
var net = require("net");
var util = require("util");
var os = require("os");
module.exports = SDSDS = function(host, port, data, udpSwarmPort, debugLevel) {
var instance = this;
this.host = host || this.findFirstNetworkInterfaceAddress();
this.port = port || 9000;
this.data = data || {};
this.udpSwarmPort = udpSwarmPort || 18468;
this.debugLevel = debugLevel || "ERR";
var events = {};
this.on = function(eventName, callback) {
events[eventName] = events[eventName] || [];
events[eventName].push(callback);
};
this.fire = function(eventName, _) {
var args = Array.prototype.slice.call(arguments, 1);
instance.debug("DBG", "firing event: " + eventName);
if(!events[eventName])
return;
for(var i = 0, length = events[eventName].length; i < length; i++)
events[eventName][i].apply(instance, args);
}
this.hostInformation = {
name: this.host + ":" + this.port,
host: this.host,
port: this.port
};
this.hosts = {};
this.connectedOutNodes = {};
this.connectedInNodes = {};
this.udp4 = dgram.createSocket("udp4");
this.udp4.on('error', function(err) {
instance.error(err);
});
this.udp4.on('close', function() {
instance.close();
});
this.udp4.on('message', function(incoming_msg, rinfo) {
try {
var msg = JSON.parse(incoming_msg);
if(msg.host == instance.hostInformation.host && msg.port == instance.hostInformation.port)
return; // This is a message to ourselves!
instance.debug("ALL", "udp message: " + incoming_msg);
instance.connectToSwarmNode(msg);
} catch(e) { }
});
this.udp4.on('listening', function() {
var address = instance.udp4.address();
instance.debug("DBG", "udp server listening " + address.address + ":" + address.port);
setInterval(instance.sendHostBeacon.bind(instance), 5000);
});
this.udp4.bind(this.udpSwarmPort, function() {
instance.udp4.setBroadcast(true);
instance.tcp4 = net.createServer(function(socket) {
socket = new JsonSocket(socket);
socket.sendMessage({type: "handshake_start"});
socket.on('error', function(err) { console.log("tcp4server - error", err); });
socket.on('message', function(data) {
instance.processInHandshake(socket, data);
});
}).listen(instance.hostInformation.port, undefined, undefined, function() {
instance.debug("DBG", "tcp server listening " + instance.hostInformation.port);
instance.fire('listening');
});
});
};
SDSDS.prototype.findFirstNetworkInterfaceAddress = function() {
var ifaces = os.networkInterfaces();
for(var iface in ifaces)
for(var d in ifaces[iface])
if(ifaces[iface][d].family == "IPv4")
return ifaces[iface][d].address;
return "127.0.0.1";
};
SDSDS.prototype.debug = function(level, message) {
var instance = this;
var levels = ["ERR", "WRN", "DBG", "ALL"];
if(levels.indexOf(level) > levels.indexOf(this.debugLevel)) return;
console.log(message);
};
SDSDS.prototype.error = function(err) {
var instance = this;
this.debug("ERR", err);
this.close();
this.fire("error", err);
};
SDSDS.prototype.close = function() {
var instance = this;
if(this.udp4) this.udp4.close();
if(this.tcp4) this.tcp4.close();
this.fire("close");
};
SDSDS.prototype.sendHostBeacon = function() {
var instance = this;
if(!this.udp4 || !this.tcp4) return;
var message = new Buffer(JSON.stringify(this.hostInformation));
this.udp4.send(message, 0, message.length, this.udpSwarmPort, "255.255.255.255", function(err, bytes) {
if(err) instance.error(err);
instance.debug("ALL", "udp broadcast beacon sent");
});
};
SDSDS.prototype.connectToSwarmNode = function(nodeInformation) {
var instance = this;
if(this.connectedOutNodes[nodeInformation.name]) return;
this.debug("DBG", "connecting to new node: " + nodeInformation.name);
var socket = new net.Socket();
socket.connect(nodeInformation.port, nodeInformation.host, function() {
socket = new JsonSocket(socket);
socket.name = nodeInformation.name;
nodeInformation.socket = socket;
instance.connectedOutNodes[socket.name] = {
name: nodeInformation.name,
host: nodeInformation.host,
port: nodeInformation.port,
socket: socket
};
});
socket.on('message', function(data) {
console.log("message", data);
instance.processOut(instance.connectedOutNodes[socket.name], socket, data);
});
socket.on('error', function(err) { console.log("tcp4client - error", err); });
socket.on('close', function() {
instance.fire('disconnected', instance.connectedOutNodes[socket.name]);
delete instance.connectedOutNodes[socket.name];
});
};
SDSDS.prototype.processOut = function(node, socket, data) {
var instance = this;
this.debug("ALL", "> recieved handshake data from " + socket.name + ", " + data);
if(!data.type) return;
switch(data.type) {
case "handshake_start":
socket.sendMessage({
type: "host_details",
host: instance.hostInformation
});
return;
case "sync":
this.processIncomingSync(node, data);
socket.sendMessage({type: "handshake_end"});
instance.fire('connected', node);
return
}
};
SDSDS.prototype.processInHandshake = function(socket, data) {
var instance = this;
this.debug("ALL", "< recieved handshake data from " + (socket.name ? socket.name : "unnamed socket") + ", " + data);
if(!data.type) return;
switch(data.type) {
case "host_details":
socket.name = data.host.name;
instance.connectedInNodes[socket.name] = {
name: socket.name,
host: data.host.host,
port: data.host.port,
socket: socket
};
socket.sendMessage({
type: "sync",
data: instance.data
});
socket.on('error', function(err) {
console.log("tcp4client - error", err);
delete instance.connectedInNodes[socket.name];
instance.fire('left', socket.name);
});
instance.fire('joined', socket.name);
return;
case "handshake_end":
socket._socket.removeAllListeners('message');
socket.on('message', function(data) {
instance.processIn(socket, data);
});
instance.debug("DBG", "connected to swarm node: " + socket.name);
return;
}
};
SDSDS.prototype.processIn = function(socket, data) {
var instance = this;
var node = this.connectedInNodes[socket.name];
if(!node) return;
this.debug("ALL", "< recieved data from " + socket.name + ", " + data);
if(!data.type) return;
switch(data.type) {
case "sync":
return this.processIncomingSync(node, data);
case "write":
return this.processIncomingWrite(node, data);
}
};
SDSDS.prototype.processIncomingSync = function(node, data) {
this.debug("ALL", "syncing data with node " + node.name);
for(var key in data.data) {
data.data[key].timestamp = Date.now();
if(this.data[key] === undefined) {
this.data[key] = data.data[key];
} else if(this.data[key].timestamp < data.data[key].timestamp) {
this.data[key] = data.data[key];
}
}
this.fire('data_sync', node, this.data);
};
SDSDS.prototype.processIncomingWrite = function(node, data) {
this.debug("ALL", "writing data from node " + node.name);
if(this.data[data.key] === undefined) {
this.data[data.key] = data.value;
} else if(this.data[data.key].timestamp < data.value.timestamp) {
this.data[data.key] = data.value;
}
this.fire('data_write', node, data.key, data.value);
};
SDSDS.prototype.get = function(key) {
var instance = this;
return this.data[key];
};
SDSDS.prototype.set = function(key, value) {
var instance = this;
this.data[key] = value;
this.data[key].timestamp = Date.now();
for(var node in this.connectedOutNodes) {
this.connectedOutNodes[node].socket.sendMessage({
type: "write",
key: key,
value: this.data[key]
});
}
return true;
};
SDSDS.prototype.getAll = function(data) {
var instance = this;
return this.data;
};