This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
352 lines (313 loc) · 10.2 KB
/
server.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
const _ = require('lodash')
const http = require('http')
const browserify = require('browserify-middleware')
const debug = require('debug')('server')
const express = require('express')
const app = express()
const server = http.Server(app)
const io = require('socket.io')(server)
const pd = require('pretty-data').pd
const emitter = require('./sseEmitter')
const DEFAULT_PEER_COUNT = 50
const socklist = {}
const socklist_reverse = {}
const cleanUp = peerID => {
for (let sock of _.values(socklist)) {
// also remove all stats from this peer on the other sockets
debug('found stats on other socks?', sock.stats)
debug('going to remove stats for peer', peerID, sock.stats[peerID])
delete sock.stats[peerID]
}
}
let socketCounter = 0
let report = {}
app.use(express.static('public'))
app.get(
'/js/bundle.js',
browserify([
'debug',
'lodash',
'socket.io-client',
'simple-peer',
{ './client.js': { run: true } }
])
)
app.get('/events', emitter.subscribe)
app.get('/stats', (req, res) => {
res.json(report)
})
server.listen(process.env.PORT || '3001')
// start server polling
serverPolling()
//and the magic goes on...
io.on('connection', socket => {
socklist[socket.id] = {
id: ++socketCounter, // _.keys(socklist).length
active: true,
stats: {}
}
socklist_reverse[socklist[socket.id].id] = socket.id
debug('Connection with ID:', socklist[socket.id].id)
const peersToAdvertise = _.chain(io.sockets.connected)
.values()
.filter(s => {
return socket.id !== s.id
}) // console.log("filter", socklist[socket.id].id, socklist[s.id].id);
.sampleSize(DEFAULT_PEER_COUNT)
.value()
peersToAdvertise.forEach(socket2 => {
debug(
'Advertising peer %s to %s',
socklist[socket.id].id,
socklist[socket2.id].id
)
socket2.emit('peer', {
peerId: socklist[socket.id].id, //socket.id,
initiator: true
})
socket.emit('peer', {
peerId: socklist[socket2.id].id, //socket2.id,
initiator: false
})
})
socket.on('signal', data => {
const sockId = socklist_reverse[data.peerId]
const socket2 = io.sockets.connected[sockId]
if (!socket2) {
return
}
debug(
'Proxying signal from peer %s to %s',
socklist[socket.id].id,
socklist[socket2.id].id
)
socket2.emit('signal', {
signal: data.signal,
peerId: socklist[socket.id].id, //socket.id
sourceSocketId: socket2.id,
sourcePeerId: socklist[socket2.id].id
})
})
socket.on('connected', data => {
const sockId = socklist_reverse[data.peerId]
const socket2 = io.sockets.connected[sockId]
if (!socket2) {
return
}
debug(
'new webRTC connection',
's',
socklist[socket.id].id,
'-> s',
socklist[socket2.id].id,
'info peerId: ',
data.peerId,
'connect',
data.peers[data.peerId].channelName,
data.peers[data.peerId].localAddress,
':',
data.peers[data.peerId].localPort,
'->',
data.peers[data.peerId].remoteAddress,
':',
data.peers[data.peerId].remotePort,
'initiator',
data.peers[data.peerId].initiator
)
})
socket.on('report', data => {
socklist[socket.id].stats[data.peerId] = data
})
socket.on('disconnect', data => {
const peerID = socklist[socket.id].id
delete socklist_reverse[peerID]
debug('peer', peerID, 'disconnected', data, 'remove', socket.id)
cleanUp(peerID)
delete socklist[socket.id]
debug('still active', socklist)
})
socket.on('peerDown', cleanUp)
})
//server polling to create and publish report data
function serverPolling() {
try {
report = {}
for (let sock of _.values(socklist)) {
for (let stat of _.values(sock.stats)) {
report[stat.channel] = report[stat.channel] || {
channel: stat.channel
}
const rep = report[stat.channel]
if (stat.initiator) {
rep.from = sock.id
rep.to = stat.peerId
rep.speed = stat.speed
rep.sent = stat.sent
rep.received = stat.received
rep.lost = stat.received - stat.sent
rep.avgRoundtrip = stat.totaltime //... this is correct! I swear!! ;)
} else {
rep.relayed = stat.relayed
}
}
}
let data = [] // [ [peerFrom, peerTo, roundtrip, speed, channel/connectionId, lostPackages, relayed] ]
_.values(report).forEach(filteredReportElement => {
let dataEntry1 = [
'peer' + filteredReportElement.from,
'peer' + filteredReportElement.to,
Math.max(1, Math.round(filteredReportElement.avgRoundtrip) + 5)
] //, reportElement.speed, reportElement.channel, reportElement.lost, reportElement.relayed];
let dataEntry2 = [
'peer' + filteredReportElement.to,
'peer' + filteredReportElement.from,
Math.max(1, Math.round(filteredReportElement.avgRoundtrip) + 5)
] //, reportElement.speed, reportElement.channel, reportElement.lost, reportElement.relayed];
data.push(dataEntry1)
data.push(dataEntry2)
})
//mocked Data for testing
// let data = [
// ['peer1', 'peer2', 232],
// ['peer1', 'peer3', 323],
// ['peer1', 'peer4', 324],
// ['peer1', 'peer5', 123],
// ['peer1', 'peer6', 434],
// ['peer1', 'peer7', 135],
// ['peer1', 'peer8', 335],
// ['peer1', 'peer9', 332],
// ['peer2', 'peer1', 232],
// ['peer2', 'peer3', 34],
// ['peer2', 'peer4', 21],
// ['peer2', 'peer5', 67],
// ['peer2', 'peer6', 11],
// ['peer2', 'peer7', 12],
// ['peer2', 'peer8', 67],
// ['peer2', 'peer9', 69],
// ['peer3', 'peer1', 553],
// ['peer3', 'peer2', 47],
// ['peer3', 'peer4', 89],
// ['peer3', 'peer5', 46],
// ['peer3', 'peer6', 22],
// ['peer3', 'peer7', 31],
// ['peer3', 'peer8', 48],
// ['peer3', 'peer9', 22],
// ['peer4', 'peer1', 332],
// ['peer4', 'peer2', 62],
// ['peer4', 'peer3', 23],
// ['peer4', 'peer5', 57],
// ['peer4', 'peer6', 62],
// ['peer4', 'peer7', 46],
// ['peer4', 'peer8', 98],
// ['peer4', 'peer9', 97],
// ['peer5', 'peer1', 443],
// ['peer5', 'peer2', 32],
// ['peer5', 'peer3', 34],
// ['peer5', 'peer4', 56],
// ['peer5', 'peer6', 34],
// ['peer5', 'peer7', 77],
// ['peer5', 'peer8', 45],
// ['peer5', 'peer9', 43],
// ['peer6', 'peer1', 765],
// ['peer6', 'peer2', 15],
// ['peer6', 'peer3', 66],
// ['peer6', 'peer4', 44],
// ['peer6', 'peer5', 73],
// ['peer6', 'peer7', 43],
// ['peer6', 'peer8', 78],
// ['peer6', 'peer9', 35],
// ['peer7', 'peer1', 453],
// ['peer7', 'peer2', 34],
// ['peer7', 'peer3', 12],
// ['peer7', 'peer4', 67],
// ['peer7', 'peer5', 85],
// ['peer7', 'peer6', 45],
// ['peer7', 'peer8', 63],
// ['peer7', 'peer9', 23],
// ['peer8', 'peer1', 453],
// ['peer8', 'peer2', 13],
// ['peer8', 'peer3', 43],
// ['peer8', 'peer4', 54],
// ['peer8', 'peer5', 67],
// ['peer8', 'peer6', 74],
// ['peer8', 'peer7', 23],
// ['peer8', 'peer9', 25],
// ['peer9', 'peer1', 544],
// ['peer9', 'peer2', 54],
// ['peer9', 'peer3', 87],
// ['peer9', 'peer4', 94],
// ['peer9', 'peer5', 44],
// ['peer9', 'peer6', 36],
// ['peer9', 'peer7', 23],
// ['peer9', 'peer8', 25]
// ];
data = data.filter(element => {
return (
element[0].indexOf('undefined') === -1 &&
element[1].indexOf('undefined') === -1 &&
!isNaN(element[2])
)
})
if (!isDatareportConsistent(data)) {
console.log(
'data report inonsistent, broken peers in the network. no data will be sent to clients. sanitizing necessary....'
)
data = sanitize(data)
}
//as we generate the report in this interval, we spread it to our subscribers with the emitter.publish function
emitter.publish(JSON.stringify(data))
console.log('stats ', new Date(), '\n===========\n', data, '\n')
} catch (e) {
console.log('serverPolling -> ' + e.message)
}
//setInterval vs setTimeout: setTimeout executes every "function execution time + given timeout", setInterval executes "every given interval time"
setTimeout(serverPolling, 5000)
}
function isDatareportConsistent(report) {
if (report) {
const amountOfPeers = getAmountOfPeers(report)
return getExpectedLengthOfReport(amountOfPeers) === report.length
}
return false
}
function getAmountOfPeers(report) {
return getUniqIds(report).length
}
function getExpectedLengthOfReport(amountOfPeers) {
return amountOfPeers * amountOfPeers - amountOfPeers
}
function getExactAmountAPeerHasToOccure(amountOfPeers) {
return (amountOfPeers * amountOfPeers - amountOfPeers) / amountOfPeers
}
function getUniqIds(data) {
let flattenAndWithoutNumbers = getFlatPeers(data)
return [...new Set(flattenAndWithoutNumbers)] //return new array with Set constructor, to avoid dupplicates
}
function getFlatPeers(data) {
return [].concat(...data).filter(item => {
return parseInt(item) != item //get rid of last column which contains only numbers, we just need to proceed with the string-id's
})
}
function sanitize(report) {
const uniqIds = getUniqIds(report)
let sanitizedReport = report
for (let peer of uniqIds) {
if (!isDatareportConsistent(sanitizedReport)) {
const exactAmountAPeerHasToOccure = getExactAmountAPeerHasToOccure(
getAmountOfPeers(sanitizedReport)
)
const flatReport = getFlatPeers(sanitizedReport)
const peerOccurences =
_.sumBy(flatReport, flatPeer => {
if (flatPeer === peer) return 1
else return 0
}) / 2 // we check for 1/2 because, each peer appears twice in the report
if (peerOccurences < exactAmountAPeerHasToOccure) {
sanitizedReport = sanitizedReport.filter(peerPair => {
return !(peer === peerPair[0] || peer === peerPair[1])
})
}
}
}
return sanitizedReport
}