|
1 | 1 | import time |
2 | | -from beanie.operators import Ne |
3 | 2 | from app.models.db.state import State |
4 | 3 | from app.models.state_status_enum import StateStatusEnum |
5 | 4 | from app.singletons.logs_manager import LogsManager |
6 | | -from app.config.settings import get_settings |
7 | 5 |
|
8 | 6 | logger = LogsManager().get_logger() |
9 | 7 |
|
10 | 8 |
|
11 | 9 | async def check_node_timeout(): |
12 | 10 | try: |
13 | | - settings = get_settings() |
14 | 11 | current_time_ms = int(time.time() * 1000) |
15 | 12 |
|
16 | 13 | logger.info(f"Checking for timed out nodes at {current_time_ms}") |
17 | 14 |
|
18 | | - # Find all QUEUED states with queued_at set |
19 | | - queued_states = await State.find( |
20 | | - State.status == StateStatusEnum.QUEUED, |
21 | | - Ne(State.queued_at, None) |
22 | | - ).to_list() |
| 15 | + # Use database query to find and update timed out states in one operation |
| 16 | + result = await State.get_pymongo_collection().update_many( |
| 17 | + { |
| 18 | + "status": StateStatusEnum.QUEUED, |
| 19 | + "timeout_at": {"$ne": None, "$lte": current_time_ms} |
| 20 | + }, |
| 21 | + { |
| 22 | + "$set": { |
| 23 | + "status": StateStatusEnum.TIMEDOUT, |
| 24 | + "error": "Node execution timed out" |
| 25 | + } |
| 26 | + } |
| 27 | + ) |
23 | 28 |
|
24 | | - states_to_timeout = [] |
25 | | - |
26 | | - for state in queued_states: |
27 | | - # Use state-specific timeout if available, otherwise fall back to global |
28 | | - timeout_minutes = state.timeout_minutes if state.timeout_minutes else settings.node_timeout_minutes |
29 | | - timeout_ms = timeout_minutes * 60 * 1000 |
30 | | - timeout_threshold = current_time_ms - timeout_ms |
31 | | - |
32 | | - if state.queued_at <= timeout_threshold: |
33 | | - state.status = StateStatusEnum.TIMEDOUT |
34 | | - state.error = f"Node execution timed out after {timeout_minutes} minutes" |
35 | | - states_to_timeout.append(state) |
36 | | - |
37 | | - if states_to_timeout: |
38 | | - # Update all timed out states in bulk |
39 | | - await State.save_all(states_to_timeout) |
40 | | - logger.info(f"Marked {len(states_to_timeout)} states as TIMEDOUT") |
| 29 | + if result.modified_count > 0: |
| 30 | + logger.info(f"Marked {result.modified_count} states as TIMEDOUT") |
41 | 31 |
|
42 | 32 | except Exception: |
43 | 33 | logger.error("Error checking node timeout", exc_info=True) |
0 commit comments