-
Notifications
You must be signed in to change notification settings - Fork 15
/
session_manager.js
486 lines (409 loc) · 17.4 KB
/
session_manager.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
* Copyright 2011 by the AToMPM team and licensed under the LGPL
* See COPYING.lesser and README.md in the root of this project for full details
*/
const _utils = require("./utils");
const _sio = require("socket.io");
const logger = require("./logger");
const _url = require("url");
const _cp = require("child_process");
const _path = require("path");
const _uuid = require("uuid");
const {jsons} = require("./utils");
/* an array of WebWorkers
... each has its own mmmk instance */
let workers = [];
/* an array of response objects
... for workers to write on when they complete requests */
let responses = [];
/* a map of client IDs to their worker wids */
let clientIDs2csids = {};
let clientIDs2asids = {};
/* a map of socket IDs to the client/worker IDs who are listening
this is to aid debugging
*/
let socketIds2Ids = {};
/* a map of worker ids to socket.io socket session ids
... each socket is registered to exactly one worker
... several sockets may be registered to the same worker */
let workerIds2socketIds = {};
/* a map of worker ids to the type of worker
* used for logging
*/
let workerIds2workerType = {};
/* the socket server which listens to the main http server (in httpwsd.js) */
let socket_server = null;
/** Syntactic sugar to build and send a socket.io message **/
function __send(socket, statusCode, reason, data, headers)
{
let s = "socketio <br/>" + statusCode;
if (reason != undefined) s += " " + reason;
let id = socketIds2Ids[socket.id];
let to = "client";
if (id != undefined && id.includes("worker")) to = id;
s += "<br/>" + " to : "+id;
if (data != undefined && data['changelog'] == undefined) s += "<br/>" + jsons(data);
logger.http( s,{'from':"session_mngr", "to": to});
socket.emit('message',
{'statusCode':statusCode,
'reason':reason,
'headers':(headers || {'Content-Type': 'text/plain'}),
'data':data});
}
function init_session_manager(httpserver){
function allow_request(req, callback){
callback(null, true);
}
socket_server = new _sio.Server(httpserver,
{
"allowRequest": allow_request,
"cors": {
origin: "*",
}
}
);
socket_server.sockets.on('connection',
function(socket)
{
/* unregister this socket from the specified worker ... when a worker
has no more registered sockets, terminate it */
function unregister(wid)
{
logger.http("socketio _ 'unregister'" ,{'at':"session_mngr"});
let i = workerIds2socketIds[wid].indexOf(socket.id);
if( i === -1 ){
__send(socket,403,'already unregistered from worker');
}else
{
workerIds2socketIds[wid].splice(i,1);
if( workerIds2socketIds[wid].length === 0 )
{
workers[wid].kill();
workers[wid] = undefined;
delete workerIds2socketIds[wid];
// TODO: Delete worker from clientIDs2csids
}
__send(socket,200);
}
}
/* onmessage : on reception of data from client or csworker*/
socket.on('message',
function(msg/*{method:_,url:_}*/)
{
let url = _url.parse(msg.url,true);
let loc = {'at':"session_mngr"};
if (url['query'] != undefined && url['query']['id'] != undefined && url['query']['id'].includes("worker")){
loc = {'from':url['query']['id'],'to':"session_mngr"};
}
logger.http("socketio _ 'message' <br/>" + msg.method + " " + JSON.stringify(url['query']) + "<br/>" + url.pathname,loc);
/* the client asks to create a new session or join a session */
/* the session manager then has a map from client ID to the worker ID */
if (msg.method == 'POST' && (url.pathname.match(/createSession/)) || url.pathname.match(/joinSession/)) {
let cid = url['query']['cid'];
if (cid == undefined) {
logger.http("socketio <br/> 400 : invalid client id"+ url['query']['cid'] ,{'from':"session_mngr", 'to':'client'});
__send(socket, 400, 'invalid client id :: ' + url['query']['cid']);
return;
}
// determine whether to create or join a session
// and whether to do screenshare or modelshare
let existingcwid = url['query']['cswid'];
let existingawid = url['query']['aswid'];
let isScreenshare = existingcwid != undefined && existingawid == undefined;
let isModelshare = existingcwid != undefined && existingawid != undefined;
let cwid = undefined;
let awid = undefined;
// normal case, not sharing
if (!isScreenshare && !isModelshare){
// create a new csworker and asworker
cwid = __createNewWorker('/csworker');
awid = __createNewWorker('/asworker');
// set up client-csworker comms
__registerListener(cwid, socket.id, cid);
clientIDs2csids[cid] = [cwid];
clientIDs2asids[cid] = awid;
// set up the csworker listening to the asworker
let params = {'aswid': awid};
workers[cwid].send(
{
'method': 'PUT',
'uri': '/aswSubscription',
'reqData': params
});
}else if (isScreenshare){
// no workers created
// set up client-csworker comms
__registerListener(existingcwid, socket.id, cid);
clientIDs2csids[cid] = [existingcwid];
clientIDs2asids[cid] = existingawid;
cwid = existingcwid;
} else if (isModelshare){
// create a new csworker
cwid = __createNewWorker('/csworker');
// set up client-csworker comms
__registerListener(cwid, socket.id, cid);
clientIDs2csids[cid] = [cwid];
clientIDs2asids[cid] = existingawid;
/* TODO: Has to be done by the client in init.js
to avoid a race condition with the client
asking for csworker state too early
*/
// set up the csworker listening to the asworker
// clones the existing csworker
// let params = {'aswid': existingawid, 'cswid': existingcwid};
// workers[cwid].send(
// {
// 'method': 'PUT',
// 'uri': '/aswSubscription',
// 'reqData': params
// });
awid = existingawid;
}
/* respond worker id (used to identify associated workers) */
__send(socket, 201, undefined, {'wid': cwid, 'awid': awid});
return;
}
/* check for worker id and it's validity */
if( url['query'] === undefined ||
url['query']['wid'] === undefined ){
return __send(socket,400,'missing worker id');
}
let wid = url['query']['wid'];
if( workers[wid] === undefined ) {
__send(socket,400,'unknown worker id :: '+wid);
}
/* register socket for requested worker */
else if( msg.method === 'POST' && url.pathname.match(/changeListener$/) )
{
let id = undefined;
if (url['query'] != undefined && url['query']['id'] != undefined) id = url['query']['id'];
if (__registerListener(wid, socket.id, id)){
__send(socket,201);
}else{
__send(socket,403,'already registered to worker');
}
}
/* unregister socket for requested worker */
else if( msg.method === 'DELETE' &&
url.pathname.match(/changeListener$/) ) {
unregister(wid);
}
/* unsupported request */
else {
__send(socket,501);
}
});
/* ondisconnect : on disconnection of socket */
socket.on('disconnect',
function()
{
logger.http("socketio _ 'disconnect'",{'at':"session_mngr"});
for( let wid in workerIds2socketIds )
for( let i in workerIds2socketIds[wid] )
if( workerIds2socketIds[wid][i] === socket.id )
{
unregister(wid);
return;
}
});
});
}
function __registerListener(wid, socketID, id){
logger.http("Socket for " + id + " now listening to worker " + wid, {'at': 'session_mngr'});
socketIds2Ids[socketID] = id;
if (workerIds2socketIds[wid] == undefined){
workerIds2socketIds[wid] = [];
}
if( workerIds2socketIds[wid].indexOf(socketID) > -1 ) {
return false;
}else{
workerIds2socketIds[wid].push(socketID);
return true;
}
}
function __createNewWorker(workerType){
/* setup and store new worker */
let worker = _cp.fork(_path.join(__dirname, '__worker.js'));
let wid = workers.push(worker)-1;
workerIds2socketIds[wid] = [];
workerIds2workerType[wid] = workerType;
worker.on('message',
function(msg)
{
/* push changes (if any) to registered sockets... even empty
changelogs are pushed to facilitate sequence number-based
ordering */
if( msg['changelog'] !== undefined )
{
send_to_all(wid, msg);
}
/* respond to a request */
if( msg['respIndex'] !== undefined )
_utils.respond(
responses[msg['respIndex']],
msg['statusCode'],
msg['reason'],
JSON.stringify(
{'headers':
(msg['headers'] ||
{'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'}),
'data':msg['data'],
'sequence#':msg['sequence#']}),
{'Content-Type': 'application/json'});
});
let msg = {'workerType':workerType, 'workerId':wid};
logger.http("process _ 'init'+ <br/>" + JSON.stringify(msg),{'from':"session_mngr",'to': workerType + wid, 'type':"-)"});
worker.send(msg);
return wid
}
function handle_http_message(url, req, resp){
logger.http("fcn call _ 'message'",{'from': 'server', 'to':"session_mngr"});
/* create new client ID and return it */
if (req.method == 'POST' && url.pathname == '/newCID'){
let cid = _uuid.v4()
logger.http("http _ 'resp cid'+ <br/>" + ''+cid ,{'from':"session_mngr",'to': 'client', 'type':"-)"});
_utils.respond(
resp,
201,
'',
''+cid);
return;
}
// build and return urls for screenshare and modelshare
else if (url.pathname.includes('/collabReq')) {
if (url['query'] == undefined || url['query']['cid'] == undefined){
_utils.respond(resp, 400, 'missing client ID for collab');
return;
}
if (url['query'] == undefined || url['query']['user'] == undefined){
_utils.respond(resp, 400, 'missing host for collab');
return;
}
if (url['query'] == undefined || url['query']['address'] == undefined){
_utils.respond(resp, 400, 'missing address for collab');
return;
}
let cid = url['query']['cid'];
let host = url['query']['user'];
let address = url['query']['address'];
let cswid = clientIDs2csids[cid][0];
let aswid = clientIDs2asids[cid];
let screenShareURL = address + "?host=" + host + "&cswid=" + cswid;
let modelShareURL = screenShareURL + "&aswid=" + aswid;
let params = {'screenShare': screenShareURL, "modelShare": modelShareURL};
_utils.respond(
resp,
201,
'',
params);
return;
}
/* spawn new worker */
else if( (url.pathname == '/csworker' || url.pathname == '/asworker')
&& req.method == 'POST' )
{
let wid = __createNewWorker(url.pathname);
/* respond worker id (used to identify associated worker) */
_utils.respond(
resp,
201,
'',
''+wid);
return;
}
if (url['query'] == undefined){
_utils.respond(resp, 400, 'invalid query: ' + url);
return;
}
let wids = undefined;
// first, try to get the wid(s) from the client id
// this is developed so that clients can talk to multiple cs workers if needed
if (url['query']['cid'] != undefined && url['query']['swid'] == undefined ){
wids = clientIDs2csids[url['query']['cid']];
}
// if the mapping wasn't possible, check if the message contains the wid
// this is normal in the case for a HTTP message from a CSWorker
if (wids == undefined && url['query']['wid'] != undefined){
wids = [parseInt(url['query']['wid'])];
}
/* check for worker id and it's validity */
if (wids == undefined) {
_utils.respond(resp, 400, 'missing worker id');
return;
}
for (let wid of wids) {
if (workers[wid] == undefined)
_utils.respond(resp, 400, 'wid ' + wid + ' not found in workers: ' + workers);
}
/* save resp object and forward request to worker(s) (if request is PUT or
POST, recover request data first) */
// again, in the future, requests might need to be directed to multiple workers
if (req.method == 'PUT' || req.method == 'POST') {
let reqData = '';
req.addListener("data", function (chunk) {
reqData += chunk;
});
req.addListener("end",
function () {
for (let wid of wids) {
workers[wid].send(
{
'method': req.method,
'uri': url.pathname,
'reqData': (reqData == '' ?
undefined :
eval('(' + reqData + ')')),
'uriData': url['query'],
'respIndex': responses.push(resp) - 1,
'cid': url['query']['cid'],
});
}
});
} else {
for (let wid of wids) {
workers[wid].send(
{
'method': req.method,
'uri': url.pathname,
'uriData': url['query'],
'respIndex': responses.push(resp) - 1,
'cid': url['query']['cid'],
});
}
}
}
function send_to_all(wid, msg){
let _msg = {
'changelog':msg['changelog'],
'sequence#':msg['sequence#'],
'hitchhiker':msg['hitchhiker'],
'cid':msg['cid']
};
// simplify the msg for logging
let log_data = {'cid':msg['cid'], 'hitchhiker':_utils.collapse_hitchhiker(msg['hitchhiker'])};
let s = "socketio sending chglg <br/>" + JSON.stringify(log_data) + "<br/>";
for (let ch of _utils.collapse_changelog(msg["changelog"])){
s += jsons(ch) + "<br/>";
}
logger.http(s,{'at': workerIds2workerType[wid] + wid});
workerIds2socketIds[wid].forEach(
function(sid)
{
__send(
socket_server.sockets.sockets.get(sid),
undefined,
undefined,
_msg);
});
}
module.exports = {
workers,
responses,
workerIds2socketIds,
workerIds2workerType,
socket_server,
init_session_manager,
handle_http_message,
}