Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -43,7 +43,7 @@ _request_log_cache = {
|
|
| 43 |
"ts": 0.0,
|
| 44 |
"data": None, # Cached parsed log data
|
| 45 |
}
|
| 46 |
-
REQUEST_LOG_CACHE_TTL_SEC =
|
| 47 |
|
| 48 |
# -------------------------
|
| 49 |
# Helpers
|
|
@@ -147,8 +147,9 @@ def _log_request(
|
|
| 147 |
|
| 148 |
_request_log_buffer.append(log_entry)
|
| 149 |
|
| 150 |
-
# Flush buffer to Hub every
|
| 151 |
-
|
|
|
|
| 152 |
_flush_request_log()
|
| 153 |
|
| 154 |
def _flush_request_log():
|
|
@@ -231,10 +232,22 @@ def _get_recent_requests_from_log(ip_address: str) -> list:
|
|
| 231 |
def _check_suspicious_activity(ip_address: str, order_number: str) -> list:
|
| 232 |
"""Check for suspicious patterns and return list of flags"""
|
| 233 |
flags = []
|
|
|
|
| 234 |
|
| 235 |
# Get recent requests from the persistent log
|
| 236 |
recent_request_ages = _get_recent_requests_from_log(ip_address)
|
| 237 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
# Count current request
|
| 239 |
total_requests = len(recent_request_ages) + 1
|
| 240 |
|
|
|
|
| 43 |
"ts": 0.0,
|
| 44 |
"data": None, # Cached parsed log data
|
| 45 |
}
|
| 46 |
+
REQUEST_LOG_CACHE_TTL_SEC = 15.0 # Cache log for 15 seconds
|
| 47 |
|
| 48 |
# -------------------------
|
| 49 |
# Helpers
|
|
|
|
| 147 |
|
| 148 |
_request_log_buffer.append(log_entry)
|
| 149 |
|
| 150 |
+
# Flush buffer to Hub every 5 requests or if suspicious activity detected
|
| 151 |
+
# Lower threshold to ensure better tracking in load-balanced environments
|
| 152 |
+
if len(_request_log_buffer) >= 5 or suspicious_flags:
|
| 153 |
_flush_request_log()
|
| 154 |
|
| 155 |
def _flush_request_log():
|
|
|
|
| 232 |
def _check_suspicious_activity(ip_address: str, order_number: str) -> list:
|
| 233 |
"""Check for suspicious patterns and return list of flags"""
|
| 234 |
flags = []
|
| 235 |
+
now_dt = datetime.now(timezone.utc)
|
| 236 |
|
| 237 |
# Get recent requests from the persistent log
|
| 238 |
recent_request_ages = _get_recent_requests_from_log(ip_address)
|
| 239 |
|
| 240 |
+
# Also check the buffer for requests not yet written to the log
|
| 241 |
+
for entry in _request_log_buffer:
|
| 242 |
+
if entry['ip_address'] == ip_address:
|
| 243 |
+
try:
|
| 244 |
+
timestamp = datetime.fromisoformat(entry['timestamp'])
|
| 245 |
+
age_seconds = (now_dt - timestamp).total_seconds()
|
| 246 |
+
if age_seconds < 3600:
|
| 247 |
+
recent_request_ages.append(age_seconds)
|
| 248 |
+
except (ValueError, KeyError):
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
# Count current request
|
| 252 |
total_requests = len(recent_request_ages) + 1
|
| 253 |
|