Merge pull request 'fix(gdelt): stop retrying 429 over http, back off instead of tracebacking' (#69) from fix/gdelt-429-backoff into master
All checks were successful
build-and-deploy / build-push (push) Successful in 17s
All checks were successful
build-and-deploy / build-push (push) Successful in 17s
This commit is contained in:
commit
fc0cd41b7a
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)
|
||||
|
|
|
|||
196
tests/test_gdelt_backoff.py
Normal file
196
tests/test_gdelt_backoff.py
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies.
|
||||
|
||||
GDELT answers ``429`` with a plain-text "Please limit requests to one every 5
|
||||
seconds" body and no Retry-After header. The ingester must not spend a second
|
||||
request from the same IP on a status error, and must stop calling until the
|
||||
backoff window expires instead of raising a traceback every cycle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_clear_backoff()
|
||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
|
||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800)
|
||||
yield
|
||||
sources._gdelt_clear_backoff()
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
"""Stands in for httpx.AsyncClient; records every GET it is asked for."""
|
||||
|
||||
def __init__(self, responses, calls):
|
||||
self._responses = list(responses)
|
||||
self._calls = calls
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url, params=None):
|
||||
self._calls.append(url)
|
||||
resp = self._responses.pop(0)
|
||||
resp.request = httpx.Request("GET", url)
|
||||
return resp
|
||||
|
||||
|
||||
def _install(monkeypatch, responses):
|
||||
import sources
|
||||
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls)
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _no_publish(monkeypatch):
|
||||
import sources
|
||||
|
||||
published: list[str] = []
|
||||
|
||||
async def _fake(subject, event):
|
||||
published.append(subject)
|
||||
|
||||
monkeypatch.setattr(sources, "publish_event", _fake)
|
||||
return published
|
||||
|
||||
|
||||
def test_429_does_not_retry_http_and_starts_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch,
|
||||
[httpx.Response(429, text="Please limit requests to one every 5 seconds")],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert calls == [sources.GDELT_API] # exactly one request, no http fallback
|
||||
assert sources.gdelt_backoff_remaining() > 250
|
||||
|
||||
|
||||
def test_cycle_skipped_while_backing_off(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")]
|
||||
)
|
||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
assert len(calls) == 1
|
||||
|
||||
# A second cycle inside the window must not touch the network at all.
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
assert n == 0
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_backoff_doubles_then_caps(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_start_backoff()
|
||||
first = sources._gdelt_backoff_secs
|
||||
sources._gdelt_start_backoff()
|
||||
second = sources._gdelt_backoff_secs
|
||||
for _ in range(6):
|
||||
sources._gdelt_start_backoff()
|
||||
|
||||
assert first == 300
|
||||
assert second == 600
|
||||
assert sources._gdelt_backoff_secs == 1800
|
||||
|
||||
|
||||
def test_retry_after_header_is_honoured(monkeypatch):
|
||||
import sources
|
||||
|
||||
_install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")])
|
||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert 40 <= sources.gdelt_backoff_remaining() <= 45
|
||||
|
||||
|
||||
def test_200_prose_body_treated_as_throttle(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch,
|
||||
[httpx.Response(200, text="Please limit requests to one every 5 seconds")],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert len(calls) == 1
|
||||
assert sources.gdelt_backoff_remaining() > 250
|
||||
|
||||
|
||||
def test_success_publishes_and_clears_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_start_backoff()
|
||||
sources._gdelt_clear_backoff()
|
||||
published = _no_publish(monkeypatch)
|
||||
_install(
|
||||
monkeypatch,
|
||||
[
|
||||
httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"articles": [
|
||||
{
|
||||
"url": "https://example.com/a",
|
||||
"title": "Protest",
|
||||
"domain": "example.com",
|
||||
"seendate": "20261121T120000Z",
|
||||
"language": "English",
|
||||
"sourcecountry": "United States",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 1
|
||||
assert published == ["events.gdelt"]
|
||||
assert sources.gdelt_backoff_remaining() == 0
|
||||
|
||||
|
||||
def test_transport_error_still_falls_back_to_http(monkeypatch):
|
||||
import sources
|
||||
|
||||
class _BoomClient(_FakeClient):
|
||||
async def get(self, url, params=None):
|
||||
self._calls.append(url)
|
||||
if url.startswith("https://"):
|
||||
raise httpx.ConnectError("tls handshake failed")
|
||||
resp = self._responses.pop(0)
|
||||
resp.request = httpx.Request("GET", url)
|
||||
return resp
|
||||
|
||||
calls: list[str] = []
|
||||
responses = [httpx.Response(200, json={"articles": []})]
|
||||
monkeypatch.setattr(
|
||||
sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls)
|
||||
)
|
||||
_no_publish(monkeypatch)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)]
|
||||
assert sources.gdelt_backoff_remaining() == 0
|
||||
Loading…
Reference in a new issue