summaryrefslogtreecommitdiff
path: root/server/handlers.py
blob: 902cdbbd78734e7c225845e19a78d3b4cd945ad5 (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
# coding=utf-8

from concurrent.futures import ThreadPoolExecutor
import traceback
from errors.session import *
import server
import logging


class CodeqService(object):
    """Base class for all CodeQ services.
    """
    session_is_optional = False

    def process(self, request):
        pass


class CreateSession(CodeqService):
    """Creates a new anonymous session.
    To promote the session to the authenticated status, a subsequent
    login or signup must follow.
    """
    session_is_optional = True

    def process(self, request):
        request.reply({'code': 0, 'message': 'OK', 'sid': server.user_session.UserSession().get_sid()})


class Login(CodeqService):
    """Logs in a client, authenticating the session.
    """
    def process(self, request):
        js = request.data
        username = js.get('username')
        password = js.get('password')
        if username is None:
            request.reply({'code': 1, 'message': 'Username was not provided'})
        elif password is None:
            request.reply({'code': 2, 'message': 'Password was not provided'})
        else:
            session = request.session
            try:
                session.login(username, password)
            except AuthenticationFailed:
                request.reply({'code': 3, 'message': 'Username or password do not match'})
            else:
                settings = session.get_settings()
                request.reply({'code': 0, 'message': 'OK', 'settings': settings})


class Logout(CodeqService):
    def process(self, request):
        request.session.destroy()
        request.reply({'code': 0, 'message': 'OK'})


class Signup(CodeqService):
    def process(self, request):
        js = request.data
        username = js.get('username')
        name = js.get('name')
        email = js.get('email')
        password = js.get('password')
        lang = js.get('lang') or 'en'
        if username is None:
            request.reply({'code': 1, 'message': 'Username was not provided'})
        if email is None:
            request.reply({'code': 2, 'message': 'Email was not provided'})
        elif password is None:
            request.reply({'code': 3, 'message': 'Password was not provided'})
        else:
            try:
                request.session.signup(username, name, email, password, lang)
            except UserExists:
                request.reply({'code': 10, 'message': 'Username already exists'})
            except SignupFailed:
                request.reply({'code': 11, 'message': 'Sign-up failed'})
            else:
                request.reply({'code': 0, 'message': 'OK'})


class ChangePassword(CodeqService):
    def process(self, request):
        js = request.data
        password = js.get('password')
        if password is None:
            request.reply({'code': 1, 'message': 'Password was not provided'})
        else:
            try:
                request.session.change_password(password)
            except PasswordChangeFailed:
                request.reply({'code': 2, 'message': 'Password change failed'})
            else:
                request.reply({'code': 0, 'message': 'OK'})


class UpdateSettings(CodeqService):
    def process(self, request):
        js = request.data
        settings = js.get('settings')
        if settings is None:
            request.reply({'code': 1, 'message': 'New settings not provided'})
        else:
            try:
                request.session.update_settings(settings)
            except NoSuchSession:
                request.reply({'code': 2, 'message': 'No such session'})
            else:
                request.reply({'code': 0, 'message': 'OK'})


class Activity(CodeqService):
    def process(self, request):
        js = request.data
        trace = js.get('trace')
        solution = js.get('solution')
        problem_id = js.get('problem_id')
        if (trace is not None) or (solution is not None):
            # we have something to do
            if problem_id is None:
                request.reply({'code': 1, 'message': 'Problem ID is missing'})
            else:
                request.session.update_solution(problem_id, trace, solution)
                request.end()  # no feedback, just acknowledge the reception


class Query(CodeqService):
    def process(self, request):
        js = request.data
        step = js.get('step')
        if step is None:
            request.reply({'code': 1, 'message': '"step" is not set'})
        else:
            problem_id = js.get('problem_id')
            if problem_id is None:
                request.reply({'code': 4, 'message': 'Problem ID not given'})
            else:
                session = request.session
                trace = js.get('trace')
                program = None
                prolog = session.current_language_session()
                if prolog is None:
                    result = {'code': 6, 'message': 'No language session is active'}
                elif not isinstance(prolog, server.prolog_session.PrologSession):
                    result = {'code': 7, 'message': 'The currently active session is not Prolog'}
                elif step == 'run':
                    program = js.get('program')
                    query = js.get('query')
                    if program is None:
                        result = {'code': 2, 'message': 'No program specified'}
                    elif query is None:
                        result = {'code': 3, 'message': 'No query specified'}
                    else:
                        messages, status, have_more = prolog.run_for_user(session.get_uid(), problem_id, program, query)
                        result = {'code': 0, 'message': 'ok', 'terminal': {'messages': messages, 'status': status, 'have_more': have_more}}
                elif step == 'next':
                    messages, status, have_more = prolog.step()
                    result = {'code': 0, 'message': 'ok', 'terminal': {'messages': messages, 'status': status, 'have_more': have_more}}
                elif step == 'end':
                    messages, status, have_more = prolog.destroy()
                    result = {'code': 0, 'message': 'ok', 'terminal': {'messages': messages, 'status': status, 'have_more': have_more}}
                else:
                    result = {'code': 5, 'message': 'Unknown prolog step: {0}'.format(step)}
                if program or trace:
                    session.update_solution(problem_id, trace, program)
                request.reply(result)


# Push user program to the Python interpreter to be exec'd.
class PythonExec(CodeqService):
    def process(self, request):
        program = request.data.get('program')
        python = request.session.current_language_session()
        if program is None:
            request.reply({'code': 1, 'message': 'No program specified'})
        elif not isinstance(python, server.python_session.PythonSession):
            request.reply({'code': 2, 'message': 'The currently active session is not Python'})
        else:
            python.exec(program)
            request.reply({'code': 0, 'message': 'ok'})


# Send an interrupt to the Python interpreter.
class PythonStop(CodeqService):
    def process(self, request):
        python = request.session.current_language_session()
        if not isinstance(python, server.python_session.PythonSession):
            request.reply({'code': 2, 'message': 'The currently active session is not Python'})
        else:
            python.stop()
            request.reply({'code': 0, 'message': 'ok'})


# Push stdin to the Python interpreter.
class PythonPush(CodeqService):
    def process(self, request):
        text = request.data.get('text')
        python = request.session.current_language_session()
        if text is None:
            request.reply({'code': 1, 'message': 'No input specified'})
        elif not isinstance(python, server.python_session.PythonSession):
            request.reply({'code': 2, 'message': 'The currently active session is not Python'})
        else:
            python.push(text)
            request.reply({'code': 0, 'message': 'ok'})


class Hint(CodeqService):
    def process(self, request):
        js = request.data
        language = js.get('language')  # TODO: remove
        problem_id = js.get('problem_id')
        program = js.get('program')

        if problem_id is None:
            request.reply({'code': 1, 'message': 'No problem ID specified'})
        elif program is None:
            request.reply({'code': 2, 'message': 'No program specified'})
        else:
            session = request.session
            lang_session = session.current_language_session()
            if lang_session is None:
                request.reply({'code': 3, 'message': 'No active session exists'})
            else:
                hints = lang_session.hint(session.get_sid(), problem_id, program)
                request.reply({'code': 0, 'message': 'ok', 'hints': hints})


class Test(CodeqService):
    def process(self, request):
        js = request.data
        language = js.get('language')  # TODO: remove
        problem_id = js.get('problem_id')
        program = js.get('program')

        if problem_id is None:
            request.reply({'code': 1, 'message': 'No problem ID specified'})
        elif program is None:
            request.reply({'code': 2, 'message': 'No program specified'})
        else:
            session = request.session
            lang_session = session.current_language_session()
            if lang_session is None:
                request.reply({'code': 3, 'message': 'No active session exists'})
            else:
                hints = lang_session.test(session.get_sid(), problem_id, program)
                request.reply({'code': 0, 'message': 'ok', 'hints': hints})


class GetCurrentSolution(CodeqService):
    def process(self, request):
        js = request.data
        problem_id = js.get('problem_id')
        if problem_id is None:
            request.reply({'code': 1, 'message': 'Problem ID not specified'})
        else:
            request.reply({'code': 0, 'message': 'ok', 'data': request.session.current_solution(problem_id)})


class LoadProblem(CodeqService):
    def process(self, request):
        problem_id = request.data.get('problem_id')
        if problem_id is None:
            request.reply({'code': 1, 'message': 'There is no active session'})
        else:
            session = request.session.load_language_session(problem_id)
            if session is None:
                request.reply({'code': 2, 'message': 'The session failed to load'})
            else:
                request.reply({'code': 0, 'message': 'OK'})


class EndProblem(CodeqService):
    def process(self, request):
        request.session.end_language_session()
        request.end()


# maps actions to their handlers
incoming_handlers = {
    'create_session': CreateSession(),
    'login': Login(),
    'signup': Signup(),
    'change_password': ChangePassword(),
    'get_current_solution': GetCurrentSolution(),
    'logout': Logout(),
    'activity': Activity(),
    'query': Query(),
    'python_exec': PythonExec(),
    'python_push': PythonPush(),
    'python_stop': PythonStop(),
    'hint': Hint(),
    'update_settings': UpdateSettings(),
    'test': Test(),
    'load_problem': LoadProblem(),
    'end_problem': EndProblem()
}


class Request(object):
    def __init__(self, tid, original_sid, session, data):
        """Creates a new request

        :param tid: communicator-level transaction ID (global relative to the specific communicator where it originated)
        :param original_sid: session ID, optional
        :param session: the actual session with the original_sid, if it exists; the processor may swap it for a new session
        :param data: the request data from the client
        :return: new instance
        """
        self._tid = tid
        self._original_sid = original_sid
        self.session = session
        self.data = data
        self.is_finished = False

    def reply(self, data):
        """Reply to this request.

        :param data: the dictionary representing the reply, that will be converted to JSON
        :return: None
        """
        if data is None:
            self.end()
            return
        if self._original_sid is not None:
            sid = data.get('sid')
            if sid is None:
                data['sid'] = self._original_sid
            elif sid != self._original_sid:
                data['sid'] = self._original_sid
                data['new_sid'] = sid
        # it is important to reply with the same tid and sid parameters as were in the request, so message accounting doesn't get confused
        send(self._tid, self._original_sid, data)
        self.is_finished = True

    def end(self):
        """Conclude the request, without sending a response.

        This is to acknowledge that the response has been received.
        :return: None
        """
        send(self._tid, self._original_sid, None)
        self.is_finished = True


########## low-level machinery, subject to change to support more than the single socket communicator ##########

_executor = ThreadPoolExecutor(max_workers=100)

def _invoke_handler(handler, request):
    try:
        logging.debug('Worker thread processing data={}'.format(str(request.data)))
        handler.process(request)
        if not request.is_finished:
            logging.error('ERROR: the request was not concluded!')
            request.reply({'code': -1, 'message': 'Request processing did not provide a reply'})
        logging.debug('Processing finished')
    except NotLoggedIn:
        if request.is_finished:
            logging.error('Caught the NotLoggedIn exception, but the request has already been replied to!')
        else:
            request.reply({'code': -1, 'message': 'Cannot execute the request: not logged in'})
    except Exception as e:
        logging.critical('ERROR: data processing failed: ' + str(e))
        logging.critical(traceback.format_exc())
        if request.is_finished:
            logging.critical('The request has already been replied to, the client will not be aware of the error!')
        else:
            request.reply({'code': -1, 'message': 'Internal error: ' + str(e)})

def serve_request(json_obj):
    if not isinstance(json_obj, dict):
        raise RequestProcessingError('Require a request represented as a dict, instead got: ' + str(type(json_obj)))
    tid = json_obj.get('tid')  # session ID and transaction ID uniquely identify a transaction
    sid = json_obj.get('sid')
    action = json_obj.get('action')
    if action is None:
        raise RequestProcessingError('Request does not contain an action')
    if not isinstance(action, str):
        raise RequestProcessingError('Requested action must be a string, got: ' + str(type(action)))
    handler = incoming_handlers.get(action)
    if handler is None:
        raise RequestProcessingError('No handler for ' + action)
    logging.debug("Attempting to serve action={}".format(action))
    session = None
    if sid is None:
        if not handler.session_is_optional:
            raise RequestProcessingError('Request is missing a session-ID')
    else:
        del json_obj['sid']
        try:
            session = server.user_session.get_session_by_id(sid)
        except NoSuchSession:
            if not handler.session_is_optional:
                raise RequestProcessingError('This user session has expired. Please log-in again.')
    _executor.submit(_invoke_handler, handler, Request(tid, sid, session, json_obj))

def send(tid, sid, json_obj):
    # just a proxy function for now
    logging.debug('Sending reply: {}'.format(str(json_obj)))
    server.socket.sendPacket(tid, sid, json_obj)

def stop():
    global _executor
    _executor.shutdown()
    _executor = None