summaryrefslogtreecommitdiff
path: root/js/codeq/comms.js
blob: 2d934bd74b80c7f61c2758dc1c07c9ad57802507 (plain)
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
(function () {
    // ================================================================================
    // Errors generated in this module
    // ================================================================================

    var BinaryMessageError = function (message) {
        var e = new Error(message);
        this.message = message;
        if (e.stack) this.stack = e.stack;
    };
    BinaryMessageError.prototype = new Error();
    BinaryMessageError.prototype.name = 'BinaryMessageError';

    var MessageParseError = function (message) {
        var e;
        if (message instanceof Error) {
            e = message;
            this.message = 'Message parse error: ' + e.toString();
        }
        else {
            e = new Error(message);
            this.message = message;
        }
        if (e.stack) this.stack = e.stack;
    };
    MessageParseError.prototype = new Error();
    MessageParseError.prototype.name = 'MessageParseError';

    // ================================================================================
    // engine.io communication support functions (long polling / websocket communication)
    // ================================================================================

    var currentTID = 0, // transaction ID of the next message
        sid = null, // session ID, changes after each successful initial login
        socket = null,
        reconnectTimer = null,
        login_username = null,
        login_password = null,
        waiters = {}, // keyed by TID: {packet, created, promise}
        connected = false,
        connectPromise = null,
        requestHandlers = {}, // handlers for requests (events) from the server, keyed by event ID, value is an array of handlers
        handleIncomingMessageError = function (error, data) {
            if (error instanceof BinaryMessageError) {
                codeq.log.error('Incoming message is not a string, attempting reconnect');
                connected = false;
                socket.close(); // connection will be reestablished in the close event handler
            }
            else if (error instanceof MessageParseError) {
                codeq.log.error('Incoming message is not a JSON message, ignoring: ' + data);
            }
            else {
                codeq.log.error('Unknown error, attempting reconnect: ' + error);
                connected = false;
                socket.close(); // connection will be reestablished in the close event handler
            }
        },
        parseData = function (data) {
            if (typeof data !== 'string') {
                throw new BinaryMessageError('Message is not a string');
            }

            try {
                return JSON.parse(data);
            }
            catch (e) {
                codeq.log.error('Incoming message is not a JSON message, ignoring: ' + data);
                throw new MessageParseError(e);
            }
        },
        onMessage = function (data) {
            var m, waiter, event, handlers, i, N;

            try {
                m = parseData(data);
            }
            catch (e) {
                handleIncomingMessageError(e, data);
                return;
            }

            if ('tid' in m) {
                waiter = waiters[m.tid];
                if (waiter) {
                    delete waiters[m.tid];
                    waiter.promise.resolve(m);
                    codeq.log.debug('Delivered an incoming message, TID=' + m.tid);
                    return;
                }
                else {
                    codeq.log.debug('There is noone waiting for the incoming message, TID=' + m.tid);
                }
            }

            event = m.event;
            if (typeof event !== 'string') {
                codeq.log.info('Incoming message without a TID and with no event name, dropping it on the floor: ' + data);
                return;
            }

            handlers = requestHandlers[event];
            if (!handlers) {
                codeq.log.info('Incoming event message cannot be handled: no handler registered for ' + event);
                return;
            }

            N = handlers.length;
            for (i = 0; i < N; i++) {
                setTimeout((function (handler) {return function () {
                    handler(m);
                }})(handlers[i]), 0);
            }
        },
        onConnect = function () {
            var tid, sortedWaiters = [], i;
            connected = true;
            if (connectPromise) {
                // manual connect
                connectPromise.resolve();
                connectPromise = null;
            }
            else {
                // auto re-connect
            }
            // resend anything not already sent
            for (tid in waiters) {
                if (waiters.hasOwnProperty(tid)) {
                    sortedWaiters.push(waiters[tid]);
                }
            }
            // sort by ascending transaction ID before sending
            sortedWaiters.sort(function (a, b) {return a.tid - b.tid;});
            for (i = 0; i < sortedWaiters.length; i++) {
                (function (waiter) {
                    if (!waiter.sent) {
                        socket.send(JSON.stringify(waiter.packet), function () {
                            waiter.sent = true;
                        });
                    }
                })(sortedWaiters[i]);
            }
        },
        onClose = function () {
            connected = false;
            if (connectPromise) {
                // resulted from manual connect, don't attempt reconnect
                connectPromise.reject(new Error('Connection failed'));
                connectPromise = null;
                socket.off('open', onConnect);
                socket.off('close', onClose);
                socket.off('message', onMessage);
                socket = null;
            }
            else {
                // spurious disconnect, attempt reconnect
                reconnectTimer = setTimeout(function () {
                    reconnectTimer = null;
                    socket.open();
                }, 250); // reconnect in quarter of a second
            }
        };

    // ================================================================================
    // AJAX communication support functions (loading of static web resources)
    // ================================================================================

    var languageCache = {},// language defs, keyed by language identifier
        problemCache = {},// problem cache, 3-level, keyed by: language, problem group, and problem identifier
        ajaxGet = function (url) {
            return Q.Promise(function (resolve, reject, notify) {
                $.ajax({
                    dataType: 'json',
                    type: 'GET',
                    url: url,
                    error: function (jqXHR, textStatus, errorThrown) {
                        codeq.log.error('AJAX to ' + url + ' failed with status ' + textStatus, errorThrown);
                        reject(errorThrown || new Error(textStatus));
                    },
                    success: function (data, textStatus, jqXHR) {
                        var s;
                        if ((typeof data === 'object') && (data !== null)) {
                            // got a JSON
                            resolve(data);
                        }
                        else {
                            s = 'AJAX to ' + url + ' did not result in a JSON object';
                            if (typeof data === 'string') {
                                s += ', the response was:\n' + data;
                            }
                            else if (typeof textStatus === 'string') {
                                s += ', status was: ' + textStatus;
                            }
                            codeq.log.error(s);
                            reject(new Error(s));
                        }
                    }
                });
            });
        },
        ajaxPrefix;

    ajaxPrefix = location.pathname;
    if (!ajaxPrefix) ajaxPrefix = '/';
    else if (ajaxPrefix[ajaxPrefix.length - 1] !== '/') {
        ajaxPrefix = ajaxPrefix.split('/');
        ajaxPrefix[ajaxPrefix.length - 1] = '';
        ajaxPrefix = ajaxPrefix.join('/');
    }
    ajaxPrefix = ajaxPrefix + 'data/';

    // ================================================================================
    // This module's API methods
    // ================================================================================

    codeq.comms = {
        'connect': function () {
            var deferred = Q.defer();

            if (connectPromise) {
                // connection already taking place
                connectPromise.then(deferred.resolve, deferred.reject, deferred.notify);
            }
            else if (socket) {
                // already connected
                if (connected) {
                    deferred.resolve();
                }
                else {
                    // auto re-connecting
                    connectPromise = deferred;
                }
            }
            else {
                // create a new connection
                connectPromise = deferred;
                socket = eio('ws://' + location.host, {
                    'upgrade': true,
                    'path': '/ws',
                    'transports': ['polling', 'websocket']
                });
                socket.on('open', onConnect);
                socket.on('close', onClose);
                socket.on('message', onMessage);
            }

            return deferred.promise;
        },
        'disconnect': function () {
            if (socket) {
                socket.off('open', onConnect);
                socket.off('close', onClose);
                socket.off('message', onMessage);
                socket.close();
                socket = null;
            }
            if (reconnectTimer !== null) {
                clearTimeout(reconnectTimer);
                reconnectTimer = null;
            }
            connected = false;
            if (connectPromise) {
                connectPromise.reject(new Error('Forced disconnect'));
                connectPromise = null;
            }
            login_password = null; // manual disconnect will prevent auto-login
            sid = null;
        },
        'send': function (packet) {
            return Q.Promise(function (resolve, reject, notify) {
                var waiter = {
                    'packet': packet,
                    'created': Date.now(),
                    'promise': {'resolve': resolve, 'reject': reject, 'notify': notify},
                    'sent': false
                };
                packet.tid = currentTID;
                if (sid !== null) packet.sid = sid;
                waiters[currentTID] = waiter;
                currentTID++;
                if (connected) {
                    socket.send(JSON.stringify(packet), function () { waiter.sent = true; });
                }
            });
        },
        'login': function (username, password) {
            var packet = {'action': 'login', 'username': username, 'password': password},
                myself = this,
                performLogin = function () {
                    return myself.send(packet).then(function (response) {
                        if (response.code === 0) {
                            // login successful, remember the login credentials for auto-reconnects
                            login_username = username;
                            login_password = password;
                            sid = response.new_sid || response.sid;
                        }
                        return response;
                    });
                };
            if (socket) return performLogin();
            // this is the only method where we do connect() first, if we're not already connected
            return this.connect().then(performLogin);
        },

        sendActivity: function commsSendActivity (trace, solution, problem_id) {
            return this.send({'action': 'activity', 'trace': trace, 'solution': solution, 'problem_id': problem_id});
        },

        sendQuery: function commsSendQuery (query, problem_id) {
            query['action'] = 'query';
            return this.send(query);
        },

        sendPythonExec: function commsSendPythonExec (json) {
            json['action'] = 'python_exec';
            return this.send(json);
        },

        sendPythonPush: function commsSendPythonPush (json) {
            json['action'] = 'python_push';
            return this.send(json);
        },

        sendPythonStop: function commsSendPythonStop (json) {
            json['action'] = 'python_stop';
            return this.send(json);
        },

        sendHint: function commsSendHint (json) {
            json['action'] = 'hint';
            return this.send(json);
        },

        sendTest: function commsSendTest (json) {
            json['action'] = 'test';
            return this.send(json);
        },

        getProblem: function commsGetProblem (language, problem_group, problem) {
            return this.send({
                'action': 'get_problem',
                'language': language,
                'problem_group': problem_group,
                'problem': problem
            });
        },

        'on': function (event, handler) {
            var handlers = requestHandlers[event],
                N, i;
            if (!handlers) {
                handlers = [handler];
                requestHandlers[event] = handlers;
                return;
            }
            N = handlers.length;
            for (i = 0; i < N; i++) {
                if (handlers[i] === handler) return; // already registered
            }
            handlers.push(handler);
        },

        'off': function (event, handler) {
            var handlers = requestHandlers[event],
                N, i;
            if (!handlers) return; // none registered
            if (arguments.length == 1) {
                // no handler specified -> remove all handlers for this event
                delete requestHandlers[event];
                handlers.length = 0;
            }
            else {
                N = handlers.length;
                for (i = 0; i < N; i++) {
                    if (handlers[i] === handler) {
                        handlers.splice(i, 1);
                        if (handlers.length === 0) {
                            delete requestHandlers[event];
                        }
                        return;
                    }
                }
            }
        },

        'getLanguageDef': function (identifier) {
            var x = languageCache[identifier];
            if ((typeof x === 'object') && (x !== null)) {
                // already defined
                if (typeof x.then === 'function') {
                    // it's a promise, it means it's not resolved yet
                    return x;
                }
                else {
                    // return a resolved promise with the cached value
                    return Q(x);
                }
            }
            x = ajaxGet(ajaxPrefix + identifier + '/language.json').then(
                function getLanguageDefSuccess(data) {
                    languageCache[identifier] = data;
                    return data; // proxy further
                },
                function getLanguageDefFail(exception) {
                    delete languageCache[identifier];
                    throw exception || new Error('Could not load language ' + identifier); // proxy further
                }
            );
            languageCache[identifier] = x;
            return x;
        }
    };
})();