-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
93 lines (76 loc) · 2.05 KB
/
server.js
File metadata and controls
93 lines (76 loc) · 2.05 KB
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
// Configs
var config = require('./config.js');
// UDP REQ
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
// Database
var db = require('./database/' + config.db.name);
var dbConn = null;
// Flush
var flushCache = {};
var flushLoop = null;
// Get db connection
console.log('Connecting to the ' + config.db.name + ' database on: ' + config.db.url);
db.connect(config.db.url, function(err, db) {
if (err) throw err;
dbConn = db;
// Bind the server
server.bind(config.server.port, config.server.host);
});
// When do we start listening
server.on('listening', function() {
var serverInfo = server.address();
console.log('listening on: ' + serverInfo.address + ':' + serverInfo.port);
// MAIN LOOP
// Flush cache to db
flushLoop = setInterval(function() {
// Preserve flushCache, this way we can get new msg's
var tempCache = flushCache;
flushCache = {};
// Flush the tempCache
db.flush(dbConn, tempCache, function(err) {
// Delete the tempcache
delete tempCache;
});
}, config.server.flushInterval);
});
// What do to with received messages
server.on('message', function(message, remote) {
var messageComponents = message.toString().split('|');
if (messageComponents.length != 3) {
throw 'Wrong message structure';
}
// Handle the message
switch (messageComponents[0]) {
case 'c':
handleCounter(messageComponents[1], messageComponents[2], remote);
break;
case 't':
handleTick(messageComponents[1], messageComponents[2], remote);
break;
default:
console.log('Unhandled message: ' + message);
}
});
var handleCounter = function(table, value, remote) {
if (!flushCache[table]) {
flushCache[table] = { rows:[] };
}
var countDefinition = {
type: 'counter',
timestamp: new Date(),
value: value
};
flushCache[table]['rows'].push(countDefinition);
};
var handleTick = function(table, value, remote) {
if (!flushCache[table]) {
flushCache[table] = { rows:[] };
}
var countDefinition = {
type: 'tick',
timestamp: new Date(),
value: value
};
flushCache[table]['rows'].push(countDefinition);
};