@@ -1521,7 +1497,6 @@ 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);
@@ -1781,7 +1756,6 @@ function showView(name) {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
- if (articlesOn) loadArticleBlips();
}
}
if (name === 'news') loadNews(false);
@@ -1874,7 +1848,6 @@ 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) {
@@ -2017,13 +1990,6 @@ function renderNewsTicker(articles, summaries, tickerItems) {
items = `
`;
- // 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;
}
@@ -2357,8 +2323,7 @@ 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, newsRenderer = null;
-let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
+let newsGroup = null, newsOn = false, newsReq = 0;
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)
@@ -2522,17 +2487,6 @@ 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() {
@@ -2547,12 +2501,10 @@ async function initMap() {
const sel = document.getElementById('map-layer');
sel.innerHTML = mapLayers.map(l =>
`
`).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 === 'BlueMarble_ShadedRelief_Bathymetry')
- || mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
+ 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;
@@ -2659,7 +2611,6 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
- if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
sendLiveViewport();
}, 500);
@@ -2672,7 +2623,6 @@ 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;
@@ -2695,7 +2645,6 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
- if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
}, 250);
});
@@ -2718,9 +2667,8 @@ function syncHud() {
set('cams', camsOn);
set('blips', blipsOn);
set('news', newsOn);
- set('articles', articlesOn);
}
-let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null, hudArticlesCount = null;
+let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null;
function setMapAttribution(text) {
if (!map) return;
@@ -3302,7 +3250,6 @@ 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();
@@ -3318,16 +3265,11 @@ 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,
+ renderer: pointCanvas(),
})
.bindPopup(`
` +
`
◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}
` +
@@ -3347,106 +3289,6 @@ 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 `
` +
- `
◈ ${esc(b.domain || 'article')}${b.category ? ' · ' + esc(b.category) : ''}
` +
- `
${esc(b.headline || 'Untitled article')}` +
- `
${meta.join(' · ')}
` +
- (b.url ? `
source ↗` : '') +
- `
`;
-}
-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: '
' + n + '
',
- 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;
diff --git a/tests/test_adsb_watch.py b/tests/test_adsb_watch.py
deleted file mode 100644
index 77b080f..0000000
--- a/tests/test_adsb_watch.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""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()
- }
diff --git a/tests/test_gdelt_backoff.py b/tests/test_gdelt_backoff.py
deleted file mode 100644
index 3abeb50..0000000
--- a/tests/test_gdelt_backoff.py
+++ /dev/null
@@ -1,199 +0,0 @@
-"""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
diff --git a/tests/test_gdelt_bulk.py b/tests/test_gdelt_bulk.py
deleted file mode 100644
index e25df69..0000000
--- a/tests/test_gdelt_bulk.py
+++ /dev/null
@@ -1,274 +0,0 @@
-"""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",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- (
- "
Gary Stevens"
- "
20261121211600"
- "
Protest in Iowa & Nebraska"
- ),
-])
-
-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", "", "", "", "", "", "", "",
- "", "", "", "
Power outage hits grid",
-])
-
-
-@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