| """Circuit Breaker — utility helpers for probe operations.""" |
| from __future__ import annotations |
|
|
| import hashlib |
| import logging |
| from typing import Any, Dict, Iterable, List, Optional |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| def trip_probe(data: Dict[str, Any]) -> Dict[str, Any]: |
| """Probe trip — normalises and validates *data*.""" |
| result = {k: v for k, v in data.items() if v is not None} |
| if "threshold" not in result: |
| raise ValueError(f"Probe must include 'threshold'") |
| result["id"] = result.get("id") or hashlib.md5( |
| str(result["threshold"]).encode()).hexdigest()[:12] |
| return result |
|
|
|
|
| def close_probes( |
| items: Iterable[Dict[str, Any]], |
| *, |
| status: Optional[str] = None, |
| limit: int = 100, |
| ) -> List[Dict[str, Any]]: |
| """Filter and page a sequence of Probe records.""" |
| out = [i for i in items if status is None or i.get("status") == status] |
| logger.debug("close_probes: %d items after filter", len(out)) |
| return out[:limit] |
|
|
|
|
| def record_probe(record: Dict[str, Any], **overrides: Any) -> Dict[str, Any]: |
| """Return a shallow copy of *record* with *overrides* merged in.""" |
| updated = dict(record) |
| updated.update(overrides) |
| if "failure_count" in updated and not isinstance(updated["failure_count"], (int, float)): |
| try: |
| updated["failure_count"] = float(updated["failure_count"]) |
| except (TypeError, ValueError): |
| pass |
| return updated |
|
|
|
|
| def validate_probe(record: Dict[str, Any]) -> bool: |
| """Return True when *record* satisfies all Probe invariants.""" |
| required = ["threshold", "failure_count", "last_failure_at"] |
| for field in required: |
| if field not in record or record[field] is None: |
| logger.warning("validate_probe: missing field %r", field) |
| return False |
| return isinstance(record.get("id"), str) |
|
|
|
|
| def reset_probe_batch( |
| records: List[Dict[str, Any]], |
| batch_size: int = 50, |
| ) -> List[List[Dict[str, Any]]]: |
| """Slice *records* into chunks of *batch_size* for bulk reset.""" |
| return [records[i : i + batch_size] |
| for i in range(0, len(records), batch_size)] |
|
|