|
| 1 | +"""Speedtest Tracker action adapter — triggers STT runs and links results.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from datetime import datetime, timezone, timedelta |
| 5 | + |
| 6 | +import requests |
| 7 | + |
| 8 | +from ..types import ExecutionStatus |
| 9 | +from .base import ActionAdapter |
| 10 | + |
| 11 | +log = logging.getLogger("docsis.smart_capture.adapters.speedtest") |
| 12 | + |
| 13 | +MATCH_WINDOW_SECONDS = 300 # 5 minutes |
| 14 | + |
| 15 | + |
| 16 | +class SpeedtestAdapter(ActionAdapter): |
| 17 | + """Triggers a Speedtest Tracker run and matches imported results.""" |
| 18 | + |
| 19 | + def __init__(self, storage, config_mgr): |
| 20 | + super().__init__(action_type="capture") |
| 21 | + self._storage = storage |
| 22 | + self._config = config_mgr |
| 23 | + url = config_mgr.get("speedtest_tracker_url", "").rstrip("/") |
| 24 | + token = config_mgr.get("speedtest_tracker_token", "") |
| 25 | + self._run_url = f"{url}/api/v1/speedtests/run" |
| 26 | + self._session = requests.Session() |
| 27 | + self._session.headers.update({ |
| 28 | + "Authorization": f"Bearer {token}", |
| 29 | + "Accept": "application/json", |
| 30 | + }) |
| 31 | + |
| 32 | + def execute(self, execution_id: int, event: dict) -> tuple[bool, str | None]: |
| 33 | + """POST to STT run endpoint. Updates execution to FIRED or EXPIRED.""" |
| 34 | + try: |
| 35 | + resp = self._session.post(self._run_url, timeout=15) |
| 36 | + if resp.status_code == 201: |
| 37 | + from ...tz import utc_now |
| 38 | + self._storage.update_execution( |
| 39 | + execution_id, |
| 40 | + status=ExecutionStatus.FIRED, |
| 41 | + fired_at=utc_now(), |
| 42 | + ) |
| 43 | + log.info("Smart Capture: triggered STT run (execution #%d)", execution_id) |
| 44 | + return True, None |
| 45 | + else: |
| 46 | + error = f"STT returned {resp.status_code}: {resp.text[:200]}" |
| 47 | + self._storage.update_execution( |
| 48 | + execution_id, |
| 49 | + status=ExecutionStatus.EXPIRED, |
| 50 | + last_error=error, |
| 51 | + attempt_count=1, |
| 52 | + ) |
| 53 | + log.warning("Smart Capture: STT trigger failed for #%d: %s", |
| 54 | + execution_id, error) |
| 55 | + return False, error |
| 56 | + except Exception as e: |
| 57 | + error = str(e) |
| 58 | + self._storage.update_execution( |
| 59 | + execution_id, |
| 60 | + status=ExecutionStatus.EXPIRED, |
| 61 | + last_error=error, |
| 62 | + attempt_count=1, |
| 63 | + ) |
| 64 | + log.warning("Smart Capture: STT trigger error for #%d: %s", |
| 65 | + execution_id, error) |
| 66 | + return False, error |
| 67 | + |
| 68 | + def on_results_imported(self, results: list[dict]): |
| 69 | + """Match newly imported speedtest results to FIRED executions. |
| 70 | +
|
| 71 | + For each FIRED execution (FIFO, oldest first), find the closest |
| 72 | + result within the match window. This ensures the nearest result |
| 73 | + is selected when multiple results fall in the same window. |
| 74 | + """ |
| 75 | + fired = self._storage.get_fired_unmatched(self.action_type) |
| 76 | + if not fired: |
| 77 | + return |
| 78 | + |
| 79 | + # Parse all result timestamps upfront |
| 80 | + parsed_results = [] |
| 81 | + for result in results: |
| 82 | + result_ts = self._parse_timestamp(result.get("timestamp", "")) |
| 83 | + if result_ts is not None: |
| 84 | + parsed_results.append((result, result_ts)) |
| 85 | + |
| 86 | + if not parsed_results: |
| 87 | + return |
| 88 | + |
| 89 | + matched_result_ids = set() |
| 90 | + |
| 91 | + for execution in fired: |
| 92 | + fired_ts = self._parse_timestamp(execution.get("fired_at", "")) |
| 93 | + if fired_ts is None: |
| 94 | + continue |
| 95 | + |
| 96 | + # Find the closest result within [fired_at, fired_at + 5min] |
| 97 | + window_end = fired_ts + timedelta(seconds=MATCH_WINDOW_SECONDS) |
| 98 | + best_result = None |
| 99 | + best_distance = None |
| 100 | + |
| 101 | + for result, result_ts in parsed_results: |
| 102 | + if result.get("id") in matched_result_ids: |
| 103 | + continue |
| 104 | + if fired_ts <= result_ts <= window_end: |
| 105 | + distance = abs((result_ts - fired_ts).total_seconds()) |
| 106 | + if best_distance is None or distance < best_distance: |
| 107 | + best_result = result |
| 108 | + best_distance = distance |
| 109 | + |
| 110 | + if best_result is not None: |
| 111 | + from ...tz import utc_now |
| 112 | + ok = self._storage.claim_execution( |
| 113 | + execution["id"], |
| 114 | + expected_status="fired", |
| 115 | + new_status=ExecutionStatus.COMPLETED, |
| 116 | + completed_at=utc_now(), |
| 117 | + linked_result_id=best_result["id"], |
| 118 | + ) |
| 119 | + if ok: |
| 120 | + log.info("Smart Capture: linked execution #%d to speedtest #%d", |
| 121 | + execution["id"], best_result["id"]) |
| 122 | + matched_result_ids.add(best_result["id"]) |
| 123 | + |
| 124 | + @staticmethod |
| 125 | + def _parse_timestamp(ts: str) -> datetime | None: |
| 126 | + """Parse ISO-8601 timestamp to UTC datetime via fromisoformat(). |
| 127 | +
|
| 128 | + Handles Z-suffix, offset-bearing timestamps (+00:00, +02:00), |
| 129 | + and fractional seconds. All results are converted to UTC. |
| 130 | + """ |
| 131 | + if not ts: |
| 132 | + return None |
| 133 | + try: |
| 134 | + # fromisoformat handles offsets and fractional seconds natively |
| 135 | + # but needs Z replaced with +00:00 on Python < 3.11 |
| 136 | + normalized = ts.replace("Z", "+00:00") if ts.endswith("Z") else ts |
| 137 | + dt = datetime.fromisoformat(normalized) |
| 138 | + # Convert to UTC if offset-aware |
| 139 | + if dt.tzinfo is not None: |
| 140 | + dt = dt.astimezone(timezone.utc) |
| 141 | + else: |
| 142 | + dt = dt.replace(tzinfo=timezone.utc) |
| 143 | + return dt |
| 144 | + except (ValueError, TypeError): |
| 145 | + return None |
0 commit comments