-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathspam_protection.py
69 lines (53 loc) · 2.07 KB
/
spam_protection.py
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
"""
Module to monitor UI Spam
"""
import functools
import threading
### consts
SPAM_MAX_TASKS = 3
# number of expensive tasks until the system shuts them down
SPAM_EXPENSIVE_IDS = {
'analyticsDegreeRun', 'analyticsClosenessRun', 'analyticsPathRun', 'analyticsEigenvectorRun', 'analyticsModcommunityRun', 'analyticsModcommunityLayout', 'analyticsClusteringCoeffRun',
'annotationRun',
'layoutRandomApply', 'layoutFDApply', 'layoutEigenApply', 'layoutCartoLocalApply', 'layoutCartoGlobalApply', 'layoutCartoImportanceApply', 'layoutSpectralApply'
}
# IDs of socket connection which reponse to expensive task requests
### functional part
class SpamProtector:
def __init__(self):
self.spam_counter = 0
self.lock = threading.Lock()
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
request_id = ""
result = None
request_message = {}
for arg in args:
if isinstance(arg, dict):
request_message = arg
break
if "id" in request_message.keys():
request_id = request_message["id"]
if request_id not in SPAM_EXPENSIVE_IDS:
return func(*args, **kwargs)
with self.lock:
if self.spam_counter >= SPAM_MAX_TASKS:
print(f"SPAM PROTECTION: Maximum of spam protected requests reached. Shutting down call of: {request_id}.")
return
self.spam_counter += 1
try:
result = func(*args, **kwargs)
except Exception as spam_exc:
print(f"SPAM PROTECTION: A spam_protected request {request_id} threw exception: {spam_exc}")
finally:
with self.lock:
self.spam_counter -= 1
return result
return wrapper
def spam_debug(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("...........", *args)
return func(*args, **kwargs)
return wrapper