Compare commits

..
Author SHA1 Message Date
76035535bc Merge pull request 'fix(gdelt): ingest the 15-minute GKG bulk file' (#70) from fix/gdelt-bulk-gkg into master
All checks were successful
build-and-deploy / build-push (push) Successful in 21s
2026-11-21 23:37:46 +00:00
Lance Walters
8f38ff6ff8 fix(gdelt): ingest the 15-minute GKG bulk file, keep the DOC API as fallback
The DOC 2.0 API is per-IP quota'd (429 with no Retry-After) and only lands a
fetch every 5-6 cycles, so gdel-t2 coverage was near zero. GDELT publishes the
same articles every 15 minutes as static files with no key and no quota.

ingest_gdelt now parses lastupdate.txt, downloads the newest *.gkg.csv.zip,
filters rows to the CONFIG GDELT query terms (matched against GKG theme
tokens), and maps each surviving row into the existing events.gdelt shape:
title from PAGE_TITLE, url from DocumentIdentifier (so event_dedup on URL is
unchanged), body = source domain, location_name/lat/lon from V2Locations, and
PAGE_PRECISEPUBTIMESTAMP as source_timestamp. Publishing goes through
_publish_unknown, so known URLs are skipped before they hit NATS.

The DOC path (with its 429 backoff) still runs, but only when the bulk fetch
itself fails.
2026-11-21 18:37:31 -05:00
fc0cd41b7a 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
2026-11-21 23:13:19 +00:00
Sirius DevOps
56908aed03 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.
2026-11-21 18:12:56 -05:00
54897b49bc Merge pull request 'fix(adsb): keep aircraft ingest alive with no browser viewport' (#68) from fix/adsb-idle-watch-poll into master
All checks were successful
build-and-deploy / build-push (push) Successful in 3m38s
2026-11-21 22:30:58 +00:00
Sirius DevOps
366ee12b46 fix(adsb): keep aircraft ingest alive with no browser viewport
The ADSB refresh loop only persisted positions for registered WS viewports,
so aircraft_positions went silent for a day whenever nobody had the map open
(max(ts) frozen at 2026-11-20 04:58 while USGS/news ingest kept running).

When no client viewport is registered the loop now sweeps the chokepoint
presets (ADSB_WATCH_ENABLED=1, ADSB_WATCH_INTERVAL=30s, 5 boxes ~65-81 nm)
through the same fetch_aircraft(persist=True) path, so the hypertable and
aircraft_tracks_1min keep advancing unattended. Viewport polling keeps its
8 s cadence when a tab is connected.
2026-11-21 17:30:47 -05:00
915f6cbe25 Merge pull request 'feat(hud): Blue Marble default basemap + constant-speed readable news ticker' (#67) from wt/t_88bfa75f into master
All checks were successful
build-and-deploy / build-push (push) Successful in 17s
2026-11-20 04:45:54 +00:00
Sirius DevOps
a72ddc30f8 feat(hud): Blue Marble default basemap + constant-speed readable news ticker
- initMap preferred chain: BlueMarble_ShadedRelief_Bathymetry first (static,
  gap-free); VIIRS/MODIS satellite remain selectable. No basemap persistence
  exists (osint.mapDefaults stores overlay prefs only), so first-load default
  is the whole change. has_time=false hides time controls via mapLayerChanged.
- News ticker: animation-duration computed from rendered group width for a
  constant 28 px/s regardless of headline count, recomputed on every 3-min
  rebuild; CSS fallback raised 90s -> 240s. Seamless two-copy -50% loop kept;
  market ticker untouched (60s CSS, no inline override).

Verified in real browser vs mock API + live GIBS tiles: fresh load selects
Blue Marble (8/8 tiles), Terra satellite round-trip renders with time controls,
measured ticker speed 28.01 px/s (was ~88), critical-news/blips toggles clean
(1 shared canvas -> 0, no reload), zero console errors.
2026-11-19 23:45:22 -05:00
a268eefb84 Merge pull request 'fix(map): one persistent canvas renderer for critical-news pins (per-pin leak + only-last-pin-clickable)' (#66) from wt/t_40da439a into master
All checks were successful
build-and-deploy / build-push (push) Successful in 19s
2026-11-20 04:31:31 +00:00
Sirius DevOps
577a96658d fix(map): one persistent canvas renderer for critical-news pins
loadNewsPins() called renderer: pointCanvas() INSIDE the per-pin .map(),
giving every critical pin its own full-viewport L.canvas (~19 MB each at
retina 2x). Renderers were never removed on refresh (Leaflet keeps empty
renderers mounted), so canvases grew without bound (35 after 6 refreshes
measured) and stacked pointer-events:auto siblings at z100 meant only the
LAST pin's canvas received clicks — Kyiv (first) was dead, Kherson (last)
worked. This is the user-reported 'selecting Critical News reloads the
site': unbounded full-viewport canvases stall the GPU/main thread.

Fix (mirrors T2's articlesRenderer pattern):
- hoist one persistent L.canvas({padding:0.5}) into module-level
  newsRenderer, shared by all pins and reused across refreshes; L.Canvas
  hit-tests every drawn path so ALL pins are clickable
- remove the renderer on toggle-off (0 canvases when layer off)
- guard L.Canvas.prototype._redraw against detached renderers: Leaflet
  1.9.4's moveend-driven _updatePaths() calls _redraw() directly, nulling
  _redrawRequest without cancelling a pending animation frame; removing
  the renderer before that orphaned frame fires crashes on the deleted
  2d context ('clearRect of undefined'). No-op when detached, unchanged
  when live.

Verified in real browser against local mock of /api/news/map (5 pins) +
/api/news/blips (1398-row T2 fixture):
- all 5 pins open their popups on click, Article Blips ON and OFF
- canvas count flat at 1 across 12 pan/zoom refreshes (was +5/refresh);
  0 when toggled off, 1 when back on
- 6 toggle off/on cycles: every CDP eval 1-2 ms, no navigation/reload
  (boot sentinel + navigation entries unchanged), counts/HUD 0<->5
- 4 toggles mid-map-motion (race stress): zero errors
- article blips still clickable above the canvas (svg z200 pe:none)
- popup content, cyan styling, counts/HUD byte-identical; zero console
  errors across the full session

app/static/index.html only, +19/-2.
2026-11-19 23:29:48 -05:00
fe2b5df369 Merge pull request 'feat(map): dense per-article blip layer from /api/news/blips (T2 frontend)' (#65) from wt/t_305683a2 into master
All checks were successful
build-and-deploy / build-push (push) Successful in 10s
2026-11-20 03:53:27 +00:00
44897a86d4 Merge pull request 'news: per-article proximate geolocation + GET /api/news/blips' (#64) from wt/t_bc15eb53 into master
All checks were successful
build-and-deploy / build-push (push) Successful in 23s
2026-11-20 03:52:57 +00:00
Sirius DevOps
e6ef6b79f9 feat(map): dense per-article blip layer from /api/news/blips
Additive 'Article Blips' layer on the HUD map (default OFF), separate
from the critical-news pins:
- GET /api/news/blips?bbox=&limit=1000 (frozen T1 contract), own
  superseded-request counter + overlayAbort handling, bbox refresh on
  pan/zoom and a NEWS_REFRESH_MS timer while enabled
- small radius-3 violet circleMarkers in a chunked markerClusterGroup
  (maxClusterRadius 40) with quiet violet cluster icons; one persistent
  SVG renderer (clickable paths, click-through root, no container leak)
- click -> .blip-pop popup: headline, domain, category, location_name +
  confidence, score, source link (esc() on every field)
- legend toggle + count, ARTICLES HUD chip, syncHud wiring
- graceful 404/failure: warn + idle at 0, map and critical pins unaffected
- .leaflet-heatmap-layer pointer-events:none — the visual-only FIRMS
  canvas sat on top of the overlay pane and ate clicks meant for vector
  blips/pins (pre-existing; fixes click-through for canvas pins too)

Critical-news layer and /api/news/map consumption unchanged.
2026-11-19 22:52:32 -05:00
8 changed files with 1088 additions and 19 deletions

View file

@ -107,3 +107,12 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser
# viewports; with no tab open it persisted nothing and aircraft_positions went
# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint
# presets while idle, so the hypertable keeps advancing unattended.
ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8"))
ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes")
# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol.
ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30"))

View file

@ -126,14 +126,49 @@ app.include_router(auth_router)
STATIC_DIR = Path(__file__).parent / "static"
def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]:
"""Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat).
Used only while no browser viewport is registered: without it the refresh
loop persists nothing and ``aircraft_positions`` silently stalls whenever
nobody has the map open.
"""
from chokepoints import chokepoints
out: list[tuple[float, float, float, float]] = []
for preset in chokepoints():
try:
# Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order).
minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(","))
except (KeyError, TypeError, ValueError):
continue
out.append((minlon, minlat, maxlon, maxlat))
return out
async def _adsb_refresh_loop() -> None:
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft.
When no client viewport is registered the loop sweeps the watch boxes
(chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps
advancing with no map open.
"""
from ws_manager import manager
from live_layers import fetch_aircraft
from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL
watch_boxes: list[tuple[float, float, float, float]] | None = None
while True:
interval = ADSB_REFRESH_INTERVAL
try:
boxes = manager.viewports()
if not boxes and ADSB_WATCH_ENABLED:
if watch_boxes is None:
watch_boxes = _adsb_watch_boxes()
boxes = watch_boxes
interval = ADSB_WATCH_INTERVAL
logger.debug("adsb_idle_watch", boxes=len(boxes))
for box in boxes:
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
try:
@ -142,7 +177,7 @@ async def _adsb_refresh_loop() -> None:
logger.warning("adsb_refresh_failed", error=str(exc))
except Exception as exc: # noqa: BLE001
logger.warning("adsb_refresh_loop", error=str(exc))
await asyncio.sleep(8)
await asyncio.sleep(interval)
class CachedStaticFiles(StaticFiles):

View file

@ -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()

View file

@ -2,9 +2,15 @@
from __future__ import annotations
import html
import io
import json
import logging
from datetime import datetime, timezone
import os
import re
import time
import zipfile
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
import httpx
@ -143,6 +149,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:
@ -175,25 +236,59 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
return events
async def ingest_gdelt(query: str = "", max_articles: int = 50):
"""Fetch articles from the GDELT DOC 2.0 API."""
async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
"""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)
@ -201,6 +296,240 @@ async def ingest_gdelt(query: str = "", max_articles: int = 50):
return len(events)
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
#
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
# published every 15 minutes as static files under /gdeltv2/ with no key and no
# quota, indexed by ``lastupdate.txt``:
# *.export.CSV.zip events (CAMEO codes)
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
# domain, themes, locations with lat/lon, tone, and the
# page title in the V2ExtrasXML column
# GKG is the one that carries title + geo, so map a filtered row into the same
# event shape ``parse_gdelt_articles`` produces and let the existing
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
GDELT_BULK_LASTUPDATE = os.getenv(
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
)
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
# 15-minute file behind it only changes 4x/hour.
_gdelt_bulk_last_file: str | None = None
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
def gdelt_query_terms(query: str = "") -> list[str]:
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
Used to filter bulk rows against their GKG theme tokens instead of
publishing every article in the 15-minute window.
"""
q = (query or "").strip() or GDELT_DEFAULT_QUERY
terms: list[str] = []
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
term = part.strip().strip('"').strip("'").strip().lower()
if term and term not in terms:
terms.append(term)
return terms
def _term_hits_themes(term: str, themes: str) -> bool:
"""Term matches when every word of it appears in the theme token list."""
words = [w for w in re.split(r"[\s_\-]+", term) if w]
return bool(words) and all(w in themes for w in words)
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
so the fetch never follows a redirect into a stale mirror.
"""
for line in (lastupdate_text or "").splitlines():
parts = line.split()
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
continue
url = parts[2]
if url.startswith("http://"):
url = "https://" + url[len("http://"):]
return url.rsplit("/", 1)[-1], url
return None
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
"""First location in a V2Locations field -> (lat, lon, name).
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
adm2 slot is sometimes dropped, so read the triple from the end.
"""
segment = (field or "").split(";", 1)[0]
parts = segment.split("#")
if len(parts) < 5:
return None, None, None
name = parts[1].strip() or None
try:
lat = float(parts[-3])
lon = float(parts[-2])
except (TypeError, ValueError):
return None, None, name
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
return None, None, name
return lat, lon, name
def _gkg_tone(field: str) -> float | None:
try:
return _parse_gdelt_tone(field.split(",", 1)[0])
except (AttributeError, IndexError):
return None
def _gkg_timestamp(row: list[str], extras: str) -> str:
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
stamps = []
pub = _PAGE_PUB_TS_RE.search(extras)
if pub is not None:
stamps.append(pub.group(1))
if len(row) > 1 and isinstance(row[1], str):
stamps.append(row[1][:14])
for stamp in stamps:
try:
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
tzinfo=timezone.utc
).isoformat()
except ValueError:
continue
return datetime.now(timezone.utc).isoformat()
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
Returns None when the row has no usable URL or matches none of ``terms``.
"""
if len(row) < 8:
return None
url = (row[4] or "").strip()
if not url.startswith(("http://", "https://")):
return None
raw_themes = row[7] or ""
themes = raw_themes.lower()
matched = [t for t in terms if _term_hits_themes(t, themes)]
if not matched:
return None
extras = row[-1] if isinstance(row[-1], str) else ""
title_match = _PAGE_TITLE_RE.search(extras)
title = html.unescape(title_match.group(1)).strip() if title_match else None
lat = lon = loc_name = None
for idx in (9, 10):
if idx < len(row):
lat, lon, loc_name = _gkg_location(row[idx])
if lat is not None:
break
theme_tokens = [t for t in raw_themes.split(";") if t]
tags = matched + [
t for t in theme_tokens
if any(w in t.lower() for w in matched)
]
tags = list(dict.fromkeys(tags))[:10]
return {
"source_type": "gdel-t2",
"title": title,
"body": (row[3] or "").strip() or None,
"url": url,
"location_lat": lat,
"location_lon": lon,
"location_name": loc_name,
"source_timestamp": _gkg_timestamp(row, extras),
"tags": tags,
"raw": {
"gkg_record_id": row[0],
"source_common_name": row[3],
"source_collection": row[2],
"themes": theme_tokens[:12],
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
"bulk_file": bulk_file,
},
}
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
"""Publish new articles from the newest 15-minute GKG bulk file.
No API key, no per-IP quota, and the existing URL dedupe means re-reading
the same file after a restart publishes nothing new.
"""
global _gdelt_bulk_last_file
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
async with httpx.AsyncClient(
timeout=120, headers=_ua_headers(), follow_redirects=True,
) as client:
index = await client.get(GDELT_BULK_LASTUPDATE)
index.raise_for_status()
picked = select_gdelt_bulk_url(index.text)
if picked is None:
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
return 0
filename, url = picked
if filename == _gdelt_bulk_last_file:
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
return 0
archive = await client.get(url)
archive.raise_for_status()
terms = gdelt_query_terms(query)
events: list[dict] = []
scanned = 0
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
member = zf.namelist()[0]
with zf.open(member) as fh:
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
if not line.strip():
continue
scanned += 1
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
if event is not None and len(events) < cap:
events.append(event)
published = await _publish_unknown("events.gdelt", events)
_gdelt_bulk_last_file = filename
logger.info(
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
filename, len(events), scanned, "/".join(terms), published,
)
return published
async def ingest_gdelt(query: str = "", max_articles: int = 50):
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
on the hot path.
"""
if GDELT_BULK_ENABLED:
try:
return await ingest_gdelt_bulk(query=query)
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
logger.warning(
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
type(exc).__name__, str(exc)[:160],
)
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
def _parse_gdelt_tone(tone: str) -> float | None:
"""Parse GDELT tone string to a -1..1 sentiment score."""
try:

View file

@ -274,6 +274,21 @@
.marker-cluster-medium div { font-size: 11px; }
.marker-cluster-large div { font-size: 12px; }
/* ── Article blip clusters (quiet violet, matches the small blips) ── */
.marker-cluster-articles { background-color: rgba(160, 108, 213, 0.16); }
.marker-cluster-articles div {
background-color: rgba(122, 74, 160, 0.88);
color: #efe6f9;
font-weight: 600;
box-shadow: 0 0 10px rgba(160, 108, 213, 0.35), 0 0 2px rgba(3, 6, 9, 0.9);
}
.articles-sm div { font-size: 10px; }
.articles-md div { font-size: 11px; }
.articles-lg div { font-size: 12px; }
/* FIRMS heat is visual-only (no listeners) but its canvas sits on top
of the overlay pane and eats clicks meant for vector blips/pins. */
.leaflet-heatmap-layer { pointer-events: none; }
/* ── Map hint + HUD chips ── */
.map-hint {
position: absolute; left: 12px; bottom: 12px; z-index: 500;
@ -299,6 +314,7 @@
.hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; }
.hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); }
.hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); }
.hud-chip .c.articles { background: #a06cd5; box-shadow: 0 0 6px rgba(160,108,213,0.6); }
.hud-chip.off { opacity: 0.4; }
#dvr-bar {
position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%);
@ -357,6 +373,7 @@
.lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; }
.lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); }
.lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); }
.lp-dot.articles { background: #a06cd5; box-shadow: 0 0 7px rgba(160,108,213,0.6); }
.lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); }
.lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; }
.lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; }
@ -703,7 +720,7 @@
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
}
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
.ticker.news .tick-track { animation-duration: 90s; }
.ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
.tick-group { display: flex; align-items: center; }
@ -1017,6 +1034,12 @@
<span class="lp-count" id="lp-news-count">0</span>
</div>
</div>
<div class="lp-layer">
<div class="lp-row">
<label class="lp-name" title="Per-article proximate locations from the news feed (last 24h)"><input type="checkbox" id="lp-articles-on" onchange="toggleArticleBlips()"> <span class="lp-dot articles"></span> Article Blips</label>
<span class="lp-count" id="lp-articles-count">0</span>
</div>
</div>
<div class="lp-layer">
<div class="lp-row">
@ -1121,6 +1144,7 @@
<div class="hud-chip" id="hud-cams"><span class="c cams"></span>CAMS <b id="hud-cams-n">—</b></div>
<div class="hud-chip" id="hud-blips"><span class="c blips"></span>BLIPS <b id="hud-blips-n">—</b></div>
<div class="hud-chip" id="hud-news"><span class="c news"></span>NEWS <b id="hud-news-n">—</b></div>
<div class="hud-chip" id="hud-articles"><span class="c articles"></span>ARTICLES <b id="hud-articles-n">—</b></div>
</div>
<div id="cheat-sheet" class="cheat-sheet" hidden role="dialog" aria-label="Keyboard shortcuts">
<h3>Shortcuts</h3>
@ -1497,6 +1521,7 @@ const COUNT_HUD = {
'lp-cams-count': 'hud-cams-n',
'lp-blips-count': 'hud-blips-n',
'lp-news-count': 'hud-news-n',
'lp-articles-count': 'hud-articles-n',
};
function setLayerCount(id, value) {
const el = document.getElementById(id);
@ -1756,6 +1781,7 @@ function showView(name) {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
}
}
if (name === 'news') loadNews(false);
@ -1848,6 +1874,7 @@ function initMarketTicker() {
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
let newsInterval = null;
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
const NEWS_TICKER_PX_PER_S = 28; // constant readable scroll speed for the news ticker
let newsTickerBuilt = false;
function newsEsc(s) {
@ -1990,6 +2017,13 @@ function renderNewsTicker(articles, summaries, tickerItems) {
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
}
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
// Constant pixel speed regardless of headline count: the marquee travels
// one group width (track = two identical copies, keyframe goes to -50%).
// Recomputed on every rebuild; market ticker keeps its own CSS duration.
const groupWidth = track.scrollWidth / 2;
track.style.animationDuration = groupWidth > 0
? `${(groupWidth / NEWS_TICKER_PX_PER_S).toFixed(2)}s`
: '';
newsTickerBuilt = true;
}
@ -2323,7 +2357,8 @@ async function saveSummaryModel() {
let map = null, mapLayer = null, mapInitStarted = false;
let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false;
let blipsGroup = null, blipsOn = false, blipsSince = '24h';
let newsGroup = null, newsOn = false, newsReq = 0;
let newsGroup = null, newsOn = false, newsReq = 0, newsRenderer = null;
let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h';
let camsOpacity = 1.0, baseOpacity = 1.0;
let camReq = 0, fireReq = 0, blipReq = 0; // stale-response guards (rapid zoom races)
@ -2487,6 +2522,17 @@ function overlayFetch(url) {
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
}
function isAbort(e) { return e && e.name === 'AbortError'; }
/* Leaflet 1.9.4 race guard: a moveend-driven _updatePaths() calls _redraw()
directly, which nulls _redrawRequest WITHOUT cancelling an already-pending
animation frame. If the renderer is removed before that orphaned frame
fires (e.g. layer toggle-off), _redraw crashes on the deleted 2d context
("Cannot read properties of undefined (reading 'clearRect')"). No-op
redraws on detached renderers instead; live renderers are unaffected. */
const _canvasRedraw = L.Canvas.prototype._redraw;
L.Canvas.prototype._redraw = function () {
if (!this._ctx) return;
return _canvasRedraw.apply(this, arguments);
};
const pointCanvas = () => L.canvas({ padding: 0.5 });
async function initMap() {
@ -2501,10 +2547,12 @@ async function initMap() {
const sel = document.getElementById('map-layer');
sel.innerHTML = mapLayers.map(l =>
`<option value="${l.id}">${l.title}</option>`).join('');
// Blue Marble first: static, gap-free basemap. Satellite true-color
// (VIIRS/MODIS) has cloud/coverage gaps — still selectable below.
const preferred =
mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|| mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|| mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|| mapLayers.find(l => !l.has_time)
|| mapLayers[0];
if (preferred) sel.value = preferred.id;
@ -2611,6 +2659,7 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
sendLiveViewport();
}, 500);
@ -2623,6 +2672,7 @@ async function initMap() {
camsOn = document.getElementById('lp-cams-on').checked;
blipsOn = document.getElementById('lp-blips-on').checked;
newsOn = document.getElementById('lp-news-on').checked;
articlesOn = document.getElementById('lp-articles-on').checked;
firesSince = document.getElementById('lp-fires-since').value;
blipsSince = document.getElementById('lp-blips-since').value;
radarOn = document.getElementById('lp-radar-on').checked;
@ -2645,6 +2695,7 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
}, 250);
});
@ -2667,8 +2718,9 @@ function syncHud() {
set('cams', camsOn);
set('blips', blipsOn);
set('news', newsOn);
set('articles', articlesOn);
}
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null;
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null, hudArticlesCount = null;
function setMapAttribution(text) {
if (!map) return;
@ -3250,6 +3302,7 @@ async function toggleNewsPins() {
}
newsReq++;
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
if (newsRenderer && map) { map.removeLayer(newsRenderer); newsRenderer = null; }
hudNewsCount = null;
setLayerCount('lp-news-count', '0');
syncHud();
@ -3265,11 +3318,16 @@ async function loadNewsPins() {
const items = Array.isArray(data) ? data : [];
if (newsGroup) map.removeLayer(newsGroup);
const col = '#35e0ff';
// One persistent canvas renderer shared by ALL pins: L.Canvas
// hit-tests every drawn path, so each pin stays clickable (a fresh
// canvas per pin stacked empty siblings over all but the last), and
// reusing it across refreshes leaks no full-viewport containers.
const renderer = newsRenderer || (newsRenderer = L.canvas({ padding: 0.5 }));
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
newsGroup = L.layerGroup(pins.map(it => {
return L.circleMarker([it.lat, it.lon], {
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
renderer: pointCanvas(),
renderer,
})
.bindPopup(`<div class="blip-pop">` +
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
@ -3289,6 +3347,106 @@ async function loadNewsPins() {
}
}
/* ── ARTICLE BLIPS (per-article proximate geo, all severities) ──
GET /api/news/blips — dense field of small clustered circleMarkers.
Separate from the critical-pin layer above; default OFF. Until the
backend endpoint lands, a 404 idles the layer at 0 without breaking
the map or the critical pins. */
const ARTICLE_BLIP_COL = '#a06cd5'; // quiet violet — critical pins are cyan
function articleBlipPopup(b) {
const loc = esc(b.location_name || 'no location label') +
(b.location_confidence ? ' (' + esc(b.location_confidence) + ')' : '');
const meta = [newsTimeAgo(b.created_at), loc];
if (b.score != null) meta.push('score ' + esc(b.score));
return `<div class="blip-pop">` +
`<div class="blip-src">◈ ${esc(b.domain || 'article')}${b.category ? ' · ' + esc(b.category) : ''}</div>` +
`<b>${esc(b.headline || 'Untitled article')}</b>` +
`<div class="blip-time">${meta.join(' · ')}</div>` +
(b.url ? `<a href="${esc(b.url)}" target="_blank" rel="noopener">source ↗</a>` : '') +
`</div>`;
}
async function toggleArticleBlips() {
articlesOn = document.getElementById('lp-articles-on').checked;
if (articlesOn) {
await loadArticleBlips();
// Same cadence as the news poll; own timer so the layer refreshes
// even when the News view (which starts newsInterval) was never opened.
if (!articlesTimer) articlesTimer = setInterval(() => { if (articlesOn) loadArticleBlips(); }, NEWS_REFRESH_MS);
return;
}
articlesReq++;
if (articlesTimer) { clearInterval(articlesTimer); articlesTimer = null; }
articlesGroup = dropLayer(articlesGroup);
if (articlesRenderer && map) { map.removeLayer(articlesRenderer); articlesRenderer = null; }
hudArticlesCount = null;
setLayerCount('lp-articles-count', '0');
syncHud();
}
async function loadArticleBlips() {
if (!map) return;
const req = ++articlesReq;
const zero = () => {
articlesGroup = dropLayer(articlesGroup);
hudArticlesCount = 0;
setLayerCount('lp-articles-count', '0');
syncHud();
};
try {
const r = await overlayFetch(`${API}/api/news/blips?bbox=${currentBBox()}&limit=1000`);
if (req !== articlesReq) return; // superseded by a newer pan/zoom
if (!r.ok) {
console.warn(`Article blips: /api/news/blips ${r.status} — layer idle`);
zero();
return;
}
const data = await r.json();
if (req !== articlesReq) return;
const seen = new Set();
const rows = (Array.isArray(data) ? data : []).filter(b => {
if (!Number.isFinite(Number(b.lat)) || !Number.isFinite(Number(b.lon))) return false;
if (b.id != null) { if (seen.has(b.id)) return false; seen.add(b.id); }
return true;
});
articlesGroup = dropLayer(articlesGroup);
// One persistent SVG renderer: paths are individually clickable and
// the pe:none root lets clicks fall through to the canvas pins below
// (Leaflet stacks svg z200 over canvas z100). A fresh renderer per
// refresh would leak a full-viewport container on every pan/zoom.
const renderer = articlesRenderer || (articlesRenderer = L.svg({ padding: 0.5 }));
const markers = rows.map(b => L.circleMarker([Number(b.lat), Number(b.lon)], {
radius: 3, weight: 1, color: ARTICLE_BLIP_COL, fillColor: ARTICLE_BLIP_COL,
fillOpacity: 0.5, opacity: 0.75, renderer,
}).bindPopup(articleBlipPopup(b)));
articlesGroup = L.markerClusterGroup({
maxClusterRadius: 40,
showCoverageOnHover: false,
spiderfyOnMaxZoom: true,
chunkedLoading: true,
chunkInterval: 100,
chunkDelay: 10,
iconCreateFunction: (cluster) => {
const n = cluster.getChildCount();
const size = n < 10 ? 'sm' : n < 100 ? 'md' : 'lg';
return L.divIcon({
html: '<div><span>' + n + '</span></div>',
className: 'marker-cluster marker-cluster-articles articles-' + size,
iconSize: L.point(40, 40),
});
},
});
articlesGroup.addLayers(markers);
articlesGroup.addTo(map);
setLayerCount('lp-articles-count', rows.length.toLocaleString());
hudArticlesCount = rows.length;
syncHud();
} catch (e) {
if (isAbort(e)) return;
if (req !== articlesReq) return;
console.warn('Article blips load failed', e);
zero();
}
}
/* ── Live overlays (radar / alerts / WFIGS / aircraft / trains / AIS / NHC) ── */
function refreshLiveOverlays() {
if (!map) return;

62
tests/test_adsb_watch.py Normal file
View file

@ -0,0 +1,62 @@
"""Tests for the idle ADS-B watch sweep.
Regression: the refresh loop only persisted aircraft for *connected browser
viewports*, so ``aircraft_positions`` went silent for a day whenever nobody had
the map open (observed 2026-11-20 04:58 -> 2026-11-21). When no viewport is
registered the loop must sweep the chokepoint presets instead.
"""
from __future__ import annotations
import asyncio
from chokepoints import chokepoints
from live_layers import bbox_center_radius_nm, parse_bbox
from main import _adsb_watch_boxes, _adsb_refresh_loop
from ws_manager import manager
def test_watch_boxes_cover_every_chokepoint() -> None:
boxes = _adsb_watch_boxes()
assert len(boxes) == len(chokepoints())
for box in boxes:
minlon, minlat, maxlon, maxlat = box
# Preset catalog order is minlat,minlon,maxlat,maxlon: a lon/lat swap
# would put e.g. Hormuz at lat 56 lon 26.
assert -90 <= minlat < maxlat <= 90
assert -180 <= minlon < maxlon <= 180
# ADSB.lol 403s any dist > 250 nm; live_layer clamps to 150 nm.
assert bbox_center_radius_nm(minlon, minlat, maxlon, maxlat)[2] <= 150
def test_watch_box_order_matches_catalog() -> None:
hormuz = next(p for p in chokepoints() if p["id"] == "hormuz")
minlat, minlon, maxlat, maxlon = (float(v) for v in hormuz["bbox"].split(","))
assert (minlon, minlat, maxlon, maxlat) in _adsb_watch_boxes()
# parse_bbox (the app's viewport order) agrees with the converted box.
assert parse_bbox(f"{minlon},{minlat},{maxlon},{maxlat}") == (minlon, minlat, maxlon, maxlat)
def test_idle_loop_polls_watch_boxes(monkeypatch) -> None:
"""With no client viewport the loop must call fetch_aircraft(persist=True)."""
calls: list[tuple[str, bool]] = []
async def fake_fetch(bbox: str, limit: int = 2000, persist: bool = False):
calls.append((bbox, persist))
return []
monkeypatch.setattr("live_layers.fetch_aircraft", fake_fetch)
assert manager.viewports() == []
async def run() -> None:
try:
await asyncio.wait_for(_adsb_refresh_loop(), 0.5)
except asyncio.TimeoutError:
pass
asyncio.run(run())
assert calls, "idle loop persisted nothing"
assert all(persist for _, persist in calls)
assert {bbox for bbox, _ in calls} == {
f"{b[0]},{b[1]},{b[2]},{b[3]}" for b in _adsb_watch_boxes()
}

199
tests/test_gdelt_backoff.py Normal file
View file

@ -0,0 +1,199 @@
"""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)
# These tests cover the DOC 2.0 path, which is now the fallback behind the
# 15-minute bulk GKG file (tests/test_gdelt_bulk.py covers that path).
monkeypatch.setattr(sources, "GDELT_BULK_ENABLED", False)
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

274
tests/test_gdelt_bulk.py Normal file
View file

@ -0,0 +1,274 @@
"""GDELT 15-minute bulk GKG ingest (throttle-free path).
The DOC 2.0 API is per-IP quota'd (429). The same article coverage is served as
static 15-minute files with no key and no quota. These tests pin the mapping
from a GKG row into the existing ``events.gdelt`` event shape, the CONFIG-term
filter that keeps volume bounded, and the DOC fallback contract.
"""
from __future__ import annotations
import io
import zipfile
import httpx
import pytest
LASTUPDATE = """33287 99e984fd826497ae5765484af3b11521 http://data.gdeltproject.org/gdeltv2/20261121234500.export.CSV.zip
46052 c09f32f728f695f2bf753540aa92e6ce http://data.gdeltproject.org/gdeltv2/20261121234500.mentions.CSV.zip
2361330 0804c7df5b359f177aeff85cad63d539 http://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip
"""
# GKG row shape (27 tab-separated fields): id, date, collection, common name,
# document id, V1Counts, V2Counts, V1Themes, V2Themes, V2Locations, ..., tone,
# ..., V2ExtrasXML.
GKG_ROW = "\t".join([
"20261121234500-11",
"20261121234500",
"1",
"dominicanrepublicpost.com",
"https://dominicanrepublicpost.com/protest-in-iowa/",
"PROTEST#29000##0######;",
"PROTEST#29000##0#######287;",
"PROTEST;TAX_FNCACT;VIOLENT_UNREST;",
"PROTEST,12;TAX_FNCACT,4;",
"",
"",
"",
"",
"",
"",
"-4.75,0.5,6.1,7.2,18.3,0,206",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
(
"<PAGE_AUTHORS>Gary Stevens</PAGE_AUTHORS>"
"<PAGE_PRECISEPUBTIMESTAMP>20261121211600</PAGE_PRECISEPUBTIMESTAMP>"
"<PAGE_TITLE>Protest in Iowa &amp; Nebraska</PAGE_TITLE>"
),
])
LOCATIONS_ROW = "\t".join([
"20261121234500-12", "20261121234500", "1", "wkzo.com",
"https://wkzo.com/power-outage/",
"", "", "POWER_OUTAGE;CYBER_ATTACK;", "POWER_OUTAGE,9;", "",
"", "", "", "", "", "-2.0,0.1,1.0,1.0,1.0,0,10", "", "", "", "", "", "", "",
"", "", "", "<PAGE_TITLE>Power outage hits grid</PAGE_TITLE>",
])
@pytest.fixture(autouse=True)
def _reset_bulk_state(monkeypatch):
import sources
monkeypatch.setattr(sources, "_gdelt_bulk_last_file", None)
monkeypatch.setattr(sources, "GDELT_BULK_MAX_EVENTS", 100)
sources._gdelt_clear_backoff()
yield
sources._gdelt_clear_backoff()
def _gkg_zip(rows: list[str]) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("20261121234500.gkg.csv", "\n".join(rows) + "\n")
return buf.getvalue()
class _FakeClient:
def __init__(self, index_text: str, archive: bytes | None, calls: list[str], fail_archive=False):
self._index_text = index_text
self._archive = archive
self._calls = calls
self._fail_archive = fail_archive
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, url, params=None, **kw):
self._calls.append(url)
request = httpx.Request("GET", url)
if url.endswith("lastupdate.txt"):
return httpx.Response(200, text=self._index_text, request=request)
if self._fail_archive:
raise httpx.TransportError("boom")
return httpx.Response(200, content=self._archive or b"", request=request)
def _install(monkeypatch, index_text=LASTUPDATE, archive=None, fail_archive=False):
import sources
calls: list[str] = []
monkeypatch.setattr(
sources.httpx, "AsyncClient",
lambda **kw: _FakeClient(index_text, archive, calls, fail_archive),
)
return calls
def _collect(monkeypatch):
import sources
published: list[dict] = []
async def _fake_publish(subject, events):
assert subject == "events.gdelt"
published.extend(events)
return len(events)
monkeypatch.setattr(sources, "_publish_unknown", _fake_publish)
return published
def _no_network(monkeypatch):
"""Fail the run if anything reaches the DOC 2.0 API."""
import sources
async def _boom(*a, **kw):
raise AssertionError("DOC API must not be called when bulk data lands")
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _boom)
def test_query_terms_from_config_string():
import sources
assert sources.gdelt_query_terms("") == [
"unrest", "protest", "outage", "cyber", "power outage",
]
assert sources.gdelt_query_terms('(flood OR "power outage")') == [
"flood", "power outage",
]
def test_select_gdelt_bulk_url_picks_gkg_and_forces_https():
import sources
picked = sources.select_gdelt_bulk_url(LASTUPDATE)
assert picked == (
"20261121234500.gkg.csv.zip",
"https://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip",
)
assert sources.select_gdelt_bulk_url("") is None
def test_parse_gkg_row_maps_into_event_shape():
import sources
terms = sources.gdelt_query_terms("")
event = sources.parse_gkg_row(GKG_ROW.split("\t"), terms, "20261121234500.gkg.csv.zip")
assert event["source_type"] == "gdel-t2"
assert event["url"] == "https://dominicanrepublicpost.com/protest-in-iowa/"
assert event["title"] == "Protest in Iowa & Nebraska"
assert event["body"] == "dominicanrepublicpost.com"
# Publish time comes from PAGE_PRECISEPUBTIMESTAMP, not the window stamp.
assert event["source_timestamp"] == "2026-11-21T21:16:00+00:00"
assert "protest" in event["tags"] and "VIOLENT_UNREST" in event["tags"]
assert event["raw"]["bulk_file"] == "20261121234500.gkg.csv.zip"
assert event["raw"]["tone"] == pytest.approx(-4.75 / 4249.0)
# No V2Locations in this row -> no fake geo.
assert event["location_lat"] is None and event["location_lon"] is None
def test_parse_gkg_row_reads_geo_from_v2locations():
import sources
row = GKG_ROW.split("\t")
row[9] = (
"4#Middletown, Iowa, United States#US#IA#40.8284#-91.259#-1834425"
";1#United States#US#US#39.8283#-98.5795#US"
)
event = sources.parse_gkg_row(row, sources.gdelt_query_terms(""))
assert event["location_lat"] == pytest.approx(40.8284)
assert event["location_lon"] == pytest.approx(-91.259)
assert event["location_name"] == "Middletown, Iowa, United States"
def test_gkg_location_tolerates_short_and_bad_forms():
import sources
# adm2 slot dropped: lat/lon are still the last two before the feature id.
assert sources._gkg_location("2#California, United States#US#USCA#36.17#-119.746#CA") == (
pytest.approx(36.17), pytest.approx(-119.746), "California, United States",
)
assert sources._gkg_location("")[0] is None
assert sources._gkg_location("1#Nowhere#US#US#999#999#X")[0] is None
def test_parse_gkg_row_drops_rows_without_query_terms():
import sources
row = GKG_ROW.split("\t")
row[7] = "SPORTS;ENTERTAINMENT;"
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
row = GKG_ROW.split("\t")
row[4] = ""
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
@pytest.mark.asyncio
async def test_ingest_gdelt_bulk_publishes_filtered_rows_and_skips_repeat(monkeypatch):
import sources
_install(monkeypatch, archive=_gkg_zip([GKG_ROW, LOCATIONS_ROW]))
published = _collect(monkeypatch)
_no_network(monkeypatch)
count = await sources.ingest_gdelt()
assert count == 2
assert {e["url"] for e in published} == {
"https://dominicanrepublicpost.com/protest-in-iowa/",
"https://wkzo.com/power-outage/",
}
# Second cycle: same file, nothing new fetched or published.
before = len(published)
assert await sources.ingest_gdelt() == 0
assert len(published) == before
@pytest.mark.asyncio
async def test_ingest_gdelt_bulk_caps_events_per_file(monkeypatch):
import sources
rows = []
for i in range(5):
row = GKG_ROW.split("\t")
row[0] = f"20261121234500-{i}"
row[4] = f"https://example.com/story-{i}"
rows.append("\t".join(row))
_install(monkeypatch, archive=_gkg_zip(rows))
published = _collect(monkeypatch)
_no_network(monkeypatch)
assert await sources.ingest_gdelt_bulk(max_events=2) == 2
assert len(published) == 2
@pytest.mark.asyncio
async def test_ingest_gdelt_falls_back_to_doc_when_bulk_fails(monkeypatch):
import sources
_install(monkeypatch, fail_archive=True)
calls = {"doc": 0}
async def _doc(query="", max_articles=50):
calls["doc"] += 1
return 7
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _doc)
assert await sources.ingest_gdelt() == 7
assert calls["doc"] == 1