fix(gdelt): stop retrying 429 over http, add quota backoff
GDELT's DOC 2.0 API answers 429 with a plain-text body, no Retry-After, and a per-IP block window that widens with request volume. The https->http retry only doubled the request count against that quota and could never succeed, and every cycle logged a full traceback. - ingest_gdelt: a 429 (or a 200 with a prose body) now sets a backoff window (GDELT_BACKOFF_BASE=300s, doubling to GDELT_BACKOFF_MAX=1800s, Retry-After honoured when present) and returns 0 instead of raising. - cycles inside the window skip the call entirely, logging one line. - the https->http fallback now only covers TransportError (TLS/connect), not HTTP error statuses. - producer_loop logs a GDELT failure as one WARNING line, no traceback. - tests/test_gdelt_backoff.py covers no-retry-on-429, cooldown skip, doubling and cap, Retry-After, 200-prose, success reset, transport fallback.
This commit is contained in:
parent
54897b49bc
commit
56908aed03
3 changed files with 300 additions and 10 deletions
|
|
@ -56,8 +56,11 @@ async def producer_loop() -> None:
|
|||
try:
|
||||
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
||||
logger.info("GDELT -> %d articles", g)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("GDELT fetch failed")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
||||
# line); anything reaching here is a real failure and a stack
|
||||
# trace every 5 minutes is not actionable, so keep it to one line.
|
||||
logger.warning("GDELT fetch failed: %s", exc)
|
||||
if ENABLE_QUAKES:
|
||||
try:
|
||||
q = await ingest_earthquakes()
|
||||
|
|
|
|||
105
app/sources.py
105
app/sources.py
|
|
@ -4,7 +4,9 @@ from __future__ import annotations
|
|||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
import httpx
|
||||
|
|
@ -143,6 +145,61 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
|||
}
|
||||
|
||||
|
||||
# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window
|
||||
# grows with request volume, so the only useful reaction to a 429 is to stop
|
||||
# asking: skip whole producer cycles, doubling the wait from BASE to MAX.
|
||||
GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300"))
|
||||
GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800"))
|
||||
_gdelt_backoff_secs = 0
|
||||
_gdelt_backoff_until = 0.0 # time.monotonic()
|
||||
|
||||
|
||||
def gdelt_backoff_remaining() -> float:
|
||||
"""Seconds left in the GDELT cooldown window (0 = ready to call)."""
|
||||
return max(0.0, _gdelt_backoff_until - time.monotonic())
|
||||
|
||||
|
||||
def _gdelt_backoff_until_iso() -> str:
|
||||
return (
|
||||
datetime.now(timezone.utc).replace(microsecond=0)
|
||||
+ timedelta(seconds=gdelt_backoff_remaining())
|
||||
).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def _gdelt_start_backoff(retry_after: float | None = None) -> None:
|
||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
||||
wait = retry_after or min(
|
||||
GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2)
|
||||
)
|
||||
_gdelt_backoff_secs = int(wait)
|
||||
_gdelt_backoff_until = time.monotonic() + wait
|
||||
|
||||
|
||||
def _gdelt_clear_backoff() -> None:
|
||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
||||
_gdelt_backoff_secs = 0
|
||||
_gdelt_backoff_until = 0.0
|
||||
|
||||
|
||||
def _gdelt_retry_after(resp: httpx.Response) -> float | None:
|
||||
"""Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither."""
|
||||
raw = resp.headers.get("retry-after")
|
||||
if not raw:
|
||||
return None
|
||||
raw = raw.strip()
|
||||
try:
|
||||
return max(1.0, float(raw))
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return max(
|
||||
1.0,
|
||||
(parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_gdelt_seendate(value: object) -> str:
|
||||
if isinstance(value, str) and len(value) >= 15:
|
||||
try:
|
||||
|
|
@ -176,24 +233,58 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
|
|||
|
||||
|
||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||
"""Fetch articles from the GDELT DOC 2.0 API."""
|
||||
"""Fetch articles from the GDELT DOC 2.0 API.
|
||||
|
||||
GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
|
||||
("Please limit requests to one every 5 seconds"), sends **no** Retry-After,
|
||||
and widens the block window as request volume accumulates. So a 429 is not
|
||||
retried: the ingester stops calling until a backoff window expires, and the
|
||||
cycle is skipped with a single log line. See ``gdelt_backoff_remaining``.
|
||||
"""
|
||||
remaining = gdelt_backoff_remaining()
|
||||
if remaining > 0:
|
||||
logger.info(
|
||||
"GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining)
|
||||
)
|
||||
return 0
|
||||
|
||||
params = gdelt_params(query=query, max_articles=max_articles)
|
||||
data: dict = {"articles": []}
|
||||
async with httpx.AsyncClient(
|
||||
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
||||
) as client:
|
||||
try:
|
||||
resp = await client.get(GDELT_API, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
||||
except httpx.TransportError as exc:
|
||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
||||
# Only transport failures (TLS/connect) get the fallback — an HTTP
|
||||
# error status is a quota answer and retrying it just burns the
|
||||
# same per-IP budget a second time.
|
||||
logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc)
|
||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||
resp = await client.get(http_url, params=params)
|
||||
|
||||
if resp.status_code == 429:
|
||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
||||
logger.warning(
|
||||
"GDELT 429 (rate limited) -> backing off until %s",
|
||||
_gdelt_backoff_until_iso(),
|
||||
)
|
||||
return 0
|
||||
|
||||
try:
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except (httpx.HTTPStatusError, ValueError) as exc:
|
||||
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
|
||||
# JSON decode failure is "busy", not "no results".
|
||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
||||
logger.warning(
|
||||
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
|
||||
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
|
||||
)
|
||||
return 0
|
||||
|
||||
_gdelt_clear_backoff()
|
||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.gdelt", event)
|
||||
|
|
|
|||
Loading…
Reference in a new issue