brokers.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """Load and query the broker database (references/brokers/*.json).
  2. Each broker is one JSON file for clean diffs/PRs. Files beginning with `_` are
  3. ignored (reserved for notes/scratch).
  4. """
  5. from __future__ import annotations
  6. import json
  7. from pathlib import Path
  8. import paths
  9. import storage
  10. PRIORITY_ORDER = {"crucial": 0, "high": 1, "standard": 2, "long_tail": 3}
  11. def _load_curated(directory: Path | None = None) -> list[dict]:
  12. directory = directory or paths.brokers_dir()
  13. out: list[dict] = []
  14. if not directory.exists():
  15. return out
  16. for fp in sorted(directory.glob("*.json")):
  17. if fp.name.startswith("_"):
  18. continue
  19. out.append(json.loads(fp.read_text(encoding="utf-8")))
  20. return out
  21. def load_live_cache() -> list[dict]:
  22. """Records pulled from BADBOOL via `refresh-brokers` (empty until refreshed)."""
  23. return storage.read_json(paths.brokers_cache_path(), []) or []
  24. def load_registry_cache() -> list[dict]:
  25. """CA Data Broker Registry records (separate coverage lane; empty until refreshed).
  26. Kept OUT of load_all() by default: these are not people-search sites to scan, they
  27. are worked via the CA DROP one-shot + CCPA email. Consumers of the scan/plan/fanout
  28. pipeline must not receive them; use this directly for coverage counts and the DROP/
  29. email lanes.
  30. """
  31. return storage.read_json(paths.registry_cache_path(), []) or []
  32. def load_all(directory: Path | None = None, include_live: bool = True) -> list[dict]:
  33. """Curated records, with live BADBOOL records merged underneath (curated wins)."""
  34. merged: dict[str, dict] = {b["id"]: b for b in _load_curated(directory)}
  35. if include_live:
  36. for b in load_live_cache():
  37. bid = b.get("id")
  38. if bid and bid not in merged:
  39. merged[bid] = b
  40. out = list(merged.values())
  41. out.sort(key=lambda b: (PRIORITY_ORDER.get(b.get("priority", "standard"), 9), b.get("id", "")))
  42. return out
  43. def get(broker_id: str, directory: Path | None = None) -> dict | None:
  44. for b in load_all(directory):
  45. if b.get("id") == broker_id:
  46. return b
  47. return None
  48. def by_priority(*levels: str, directory: Path | None = None) -> list[dict]:
  49. wanted = set(levels) if levels else None
  50. return [b for b in load_all(directory) if wanted is None or b.get("priority") in wanted]
  51. def clusters(directory: Path | None = None) -> dict[str, list[str]]:
  52. """Map a parent broker id -> child site ids it can clear (force-multipliers)."""
  53. out: dict[str, list[str]] = {}
  54. for b in load_all(directory):
  55. owns = b.get("owns") or []
  56. if owns:
  57. out[b["id"]] = list(owns)
  58. return out