-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction_tracker.py
More file actions
58 lines (47 loc) · 2.08 KB
/
action_tracker.py
File metadata and controls
58 lines (47 loc) · 2.08 KB
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
"""Track actions to prevent duplicate requests."""
import hashlib
import json
from datetime import datetime, timedelta
from typing import Dict, Set
import asyncio
import logging
logger = logging.getLogger(__name__)
class ActionTracker:
"""Tracks recent actions to prevent duplicate processing."""
def __init__(self, ttl_seconds: int = 60):
self._actions: Dict[str, datetime] = {}
self._ttl = timedelta(seconds=ttl_seconds)
self._lock = asyncio.Lock()
def _generate_action_id(self, game_id: int, player_id: int, action_type: str, action_data: dict) -> str:
"""Generate unique ID for an action."""
action_str = json.dumps({
"game_id": game_id,
"player_id": player_id,
"type": action_type,
"data": action_data
}, sort_keys=True)
return hashlib.md5(action_str.encode()).hexdigest()
async def is_duplicate(self, game_id: int, player_id: int, action_type: str, action_data: dict) -> bool:
"""Check if this action was recently processed."""
action_id = self._generate_action_id(game_id, player_id, action_type, action_data)
async with self._lock:
# Clean up old actions
now = datetime.utcnow()
expired = [aid for aid, timestamp in self._actions.items() if now - timestamp > self._ttl]
for aid in expired:
del self._actions[aid]
# Check if action exists
if action_id in self._actions:
logger.warning(f"Duplicate action detected: {action_id}")
return True
# Record action
self._actions[action_id] = now
return False
async def clear_game_actions(self, game_id: int):
"""Clear all actions for a game (e.g., when game ends)."""
async with self._lock:
# Actions are keyed by hash, so we can't easily filter by game_id
# Instead, we'll rely on TTL cleanup
pass
# Global action tracker
action_tracker = ActionTracker(ttl_seconds=60)