forked from phacility/phabricator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAphlictPeerList.js
86 lines (68 loc) · 2.13 KB
/
AphlictPeerList.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
'use strict';
var JX = require('./javelin').JX;
JX.install('AphlictPeerList', {
construct: function() {
this._peers = [];
// Generate a new unique identify for this server. We just use this to
// identify messages we have already seen and figure out which peer is
// actually us, so we don't bounce messages around the cluster forever.
this._fingerprint = this._generateFingerprint();
},
properties: {
},
members: {
_peers: null,
_fingerprint: null,
addPeer: function(peer) {
this._peers.push(peer);
return this;
},
addFingerprint: function(message) {
var fingerprint = this.getFingerprint();
// Check if we've already touched this message. If we have, we do not
// broadcast it again. If we haven't, we add our fingerprint and then
// broadcast the modified version.
var touched = message.touched || [];
for (var ii = 0; ii < touched.length; ii++) {
if (touched[ii] == fingerprint) {
return null;
}
}
touched.push(fingerprint);
message.touched = touched;
return message;
},
broadcastMessage: function(instance, message) {
var ii;
var touches = {};
var touched = message.touched;
for (ii = 0; ii < touched.length; ii++) {
touches[touched[ii]] = true;
}
var peers = this._peers;
for (ii = 0; ii < peers.length; ii++) {
var peer = peers[ii];
// If we know the peer's fingerprint and it has already touched
// this message, don't broadcast it.
var fingerprint = peer.getFingerprint();
if (fingerprint && touches[fingerprint]) {
continue;
}
peer.broadcastMessage(instance, message);
}
},
getFingerprint: function() {
return this._fingerprint;
},
_generateFingerprint: function() {
var src = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
var len = 16;
var out = [];
for (var ii = 0; ii < len; ii++) {
var idx = Math.floor(Math.random() * src.length);
out.push(src[idx]);
}
return out.join('');
}
}
});