Spaces:
Sleeping
Sleeping
Improve lock handling
Browse files- api/resources/root.py +23 -12
api/resources/root.py
CHANGED
|
@@ -1,25 +1,26 @@
|
|
| 1 |
#!/usr/bin/env python
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
| 4 |
-
from threading import Lock
|
| 5 |
-
|
| 6 |
import falcon
|
| 7 |
from engine import evaluate_solution
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
class RootResource:
|
| 11 |
def __init__(self):
|
| 12 |
self.main_lock = Lock()
|
| 13 |
-
self.task_locks = {}
|
|
|
|
| 14 |
|
| 15 |
def on_get(self, request, response):
|
| 16 |
-
response.text = '
|
| 17 |
|
| 18 |
def on_post(self, request, response):
|
| 19 |
payload = request.media
|
| 20 |
|
| 21 |
-
|
| 22 |
-
if bad_request:
|
| 23 |
response.status = falcon.HTTP_400
|
| 24 |
response.media = {
|
| 25 |
'error': 'task_id or solution are missing',
|
|
@@ -29,11 +30,21 @@ class RootResource:
|
|
| 29 |
task_id = payload['task_id']
|
| 30 |
solution = payload['solution']
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
self.task_locks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
|
|
|
|
|
|
| 4 |
import falcon
|
| 5 |
from engine import evaluate_solution
|
| 6 |
+
from threading import Lock
|
| 7 |
+
from typing import Dict
|
| 8 |
+
import logging
|
| 9 |
|
| 10 |
|
| 11 |
class RootResource:
|
| 12 |
def __init__(self):
|
| 13 |
self.main_lock = Lock()
|
| 14 |
+
self.task_locks: Dict[str, Lock] = {}
|
| 15 |
+
self.max_tasks = 5
|
| 16 |
|
| 17 |
def on_get(self, request, response):
|
| 18 |
+
response.text = 'HES Server v1.2410.0'
|
| 19 |
|
| 20 |
def on_post(self, request, response):
|
| 21 |
payload = request.media
|
| 22 |
|
| 23 |
+
if 'task_id' not in payload or 'solution' not in payload:
|
|
|
|
| 24 |
response.status = falcon.HTTP_400
|
| 25 |
response.media = {
|
| 26 |
'error': 'task_id or solution are missing',
|
|
|
|
| 30 |
task_id = payload['task_id']
|
| 31 |
solution = payload['solution']
|
| 32 |
|
| 33 |
+
try:
|
| 34 |
+
with self.main_lock:
|
| 35 |
+
if len(self.task_locks) >= self.max_tasks:
|
| 36 |
+
# Remove the oldest task lock if we've reached the limit
|
| 37 |
+
oldest_task = next(iter(self.task_locks))
|
| 38 |
+
del self.task_locks[oldest_task]
|
| 39 |
+
|
| 40 |
+
if task_id not in self.task_locks:
|
| 41 |
+
self.task_locks[task_id] = Lock()
|
| 42 |
|
| 43 |
+
with self.task_locks[task_id]:
|
| 44 |
+
passed = evaluate_solution(task_id, solution)
|
| 45 |
|
| 46 |
+
response.media = {'passed': passed}
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logging.error('Error processing request: {}'.format(str(e)))
|
| 49 |
+
response.status = falcon.HTTP_500
|
| 50 |
+
response.media = {'error': 'Internal server error'}
|