-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.js
More file actions
224 lines (183 loc) · 6.97 KB
/
tracker.js
File metadata and controls
224 lines (183 loc) · 6.97 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
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
/*global Map*/
import L2LConnection from "./interface.js";
import { defaultActions, defaultTrackerActions } from "./default-actions.js";
// Array.from(L2LTracker._trackers.keys());
// Array.from(L2LTracker._trackers.values())[1].remove()
export default class L2LTracker extends L2LConnection {
static trackerKey(hostname, port, ioPath, namespace) {
return `${hostname}:${port}${ioPath}-${namespace}`
}
static ensure(options) {
// options should include
// namespace - socket.io namespace to use
// io - io server instance
// port, hostname,
// autoOpen - defaults to true
var {io, port, hostname, namespace, autoOpen} = options;
if (!this._trackers) this._trackers = new Map();
var key = this.trackerKey(hostname, port, io.path(), namespace),
tracker = this._trackers.get(key);
if (!tracker) {
tracker = new this(namespace, io);
this._trackers.set(key, tracker);
if (autoOpen || autoOpen === undefined) tracker.open();
} else {
tracker.changeIo(io);
}
return tracker;
}
constructor(ns, io) {
super();
this.namespace = ns;
this.io = io;
this._open = false;
this._connectionHandler = null;
this.clients = new Map();
this.addService("register",
(tracker, msg, ackfn, socket) =>
tracker.registerClient(msg, ackfn, socket));
this.addService("unregister",
(tracker, msg, ackfn, socket) =>
tracker.unregisterClient(msg, ackfn, socket));
Object.keys(defaultActions).forEach(name =>
this.addService(name, defaultActions[name]));
Object.keys(defaultTrackerActions).forEach(name =>
this.addService(name, defaultTrackerActions[name]));
}
get ioNamespace() { return this.io.of(this.namespace); }
changeIo(io) {
if (this.io === io) return;
let isOnline = this.isOnline;
return this.close().then(() => {
this.io = io; // ensure io instance is up-to-date
if (isOnline) return this.open();
});
}
getTrackerList() {
// .... this won't work.... !
return Array.from(this.constructor._trackers).map(ea => ea[1])
}
isOnline() { return this._open; }
getClientIdForSocketId(wantedSocketId) {
for (let [key, {socketId}] of this.clients)
if (wantedSocketId === socketId) return key;
}
getSocketForClientId(clientId) {
let clientData = this.clients.get(clientId);
return clientData ? this.ioNamespace.sockets[clientData.socketId] : null;
}
removeDisconnectedClients() {
let ids = Array.from(this.clients.keys());
let toRemove = ids.filter(id => !this.getSocketForClientId(id));
toRemove = toRemove.map(id => {
let client = this.clients.get(id);
this.clients.delete(id);
return `${id} (${client ? client.socketId : ''})`;
});
if (toRemove.length) {
console.log(`[l2l] ${this} removing disconnected clients ${toRemove.join(',')}`);
}
}
open() {
if (this.isOnline()) return Promise.resolve(this);
if (this.debug) console.log(`[l2l] ${this} starts listening to connection events`);
this._open = true;
this.ioNamespace.on("connection", this._connectionHandler = this.onConnection.bind(this));
return Promise.resolve(this);
}
close() {
if (!this.isOnline()) return Promise.resolve();
if (this.debug) console.log(`[l2l] ${this} stops listening to connection events`)
this.ioNamespace.removeListener("connection", this._connectionHandler)
var ns = this.namespace.replace(/^\/?/, "/");
for (var id in this.io.nsps[ns].sockets) {
try {
var s = this.io.nsps[ns].sockets[id];
s.disconnect(true);
this.io.nsps[ns].remove(s);
} catch (e) {
console.error(`error in ${this}.disconnect`, e.stack || e)
}
}
delete this.io.nsps[ns]
this._connectionHandler = null;
this._open = false;
return Promise.resolve();
}
remove() {
for (let [key, tracker] of this.constructor._trackers)
if (tracker === this)
this.constructor._trackers.delete(key)
return this.close();
}
onConnection(socket) {
if (this.debug) console.log(`[l2l] ${this} got connection request ${socket.id}`);
socket.join('defaultRoom');
if (this.debug) console.log(`[l2l] ${socket.id} joined defaultRoom`);
// FIXME, remove this
let ip = socket.request.headers["x-real-ip"] || socket.request.socket.remoteAddress;
console.log(`[l2l] ${this} client connected ${socket.id} ${ip}`);
socket.on("error", (err) => this.onError(err));
socket.on("connect", () => this.onConnect(socket));
socket.on("disconnect", () => this.onDisconnect(socket));
this.installEventToMessageTranslator(socket);
}
onConnect(socket) {
if (this.debug) console.log(`[l2l] ${this} connected to ${socket.id}`);
}
onDisconnect(socket) {
if (this.debug) console.log(`[l2l] ${this} disconnected from ${socket.id}`);
}
registerClient({sender, data}, answerFn, socket) {
this.debug && console.log(`[l2l] ${this} got register request ${JSON.stringify({sender, data})}`);
this.clients.set(sender, {socketId: socket.id, registeredAt: new Date(), info: data});
var msgNo = this._outgoingOrderNumberingByTargets.get(sender);
typeof answerFn === "function" && answerFn({nextMessageNumber: msgNo, trackerId: this.id});
}
unregisterClient(_, answerFn, socket) {
let clientId = this.getClientIdForSocketId(socket.id);
let client = this.clients.get(clientId);
console.log(`[l2l] ${this} got unregister request ${clientId} (${client ? client.socketId : ''})`);
this.clients.delete(clientId);
typeof answerFn === "function" && answerFn();
}
receive(msg, socket, ackFn) {
// this.debug && console.log(`[l2l] ${this} received`, msg);
// 1. is the message for the tracker itself?
if (!msg.target || msg.target === this.id || msg.target === "tracker") {
this.dispatchL2LMessageToSelf(msg, socket, ackFn);
return;
}
// 2. do we know the target? if not return error
var targetSocket = this.getSocketForClientId(msg.target);
if (!targetSocket) {
var error = `target ${msg.target} not found`;
console.warn(error)
if (typeof ackFn === "function")
ackFn(this.prepareAnswerMessage(msg, {error}));
return;
}
// 3. otherwise dispatch message and relay answer
typeof ackFn === "function" ?
targetSocket.emit(msg.action, msg, ackFn) :
targetSocket.emit(msg.action, msg)
}
send(msg, ackFn) {
[msg, ackFn] = this.prepareSend(msg, ackFn);
return this.whenOnline().then(() => {
var {action, target} = msg,
socket = this.getSocketForClientId(target);
if (!socket) {
var errMsg = `Trying to send message ${action} to ${target} but cannot find a connection to it!`;
console.error(errMsg);
throw new Error(errMsg);
}
typeof ackFn === "function" ?
socket.emit(action, msg, ackFn) :
socket.emit(action, msg);
});
}
toString() {
return `L2LTracker(${this.namespace}, open: ${this.isOnline()})`
}
}