diff --git a/README.md b/README.md index 01f330a..c6d4864 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ | Watchlist | Hypothetical portfolio with live unrealised PnL | | Alerts | Browser push notification price alerts (localStorage) | | Export Data | CSV / JSON price history download | -| News | Commodity-filtered news feed with AI sentiment labels | +| News | Commodity-filtered provider headlines with availability and freshness labels | | Learn | Explainer articles — oil, gold, futures, copper, India context | | Analyst | Groq Llama 3.3 70B chat with live price context + 3 persona modes | | Simulator | India macro impact model — drag crude price, see petrol/inflation/INR | @@ -39,7 +39,7 @@ | Price data | Twelve Data API (real-time) | | Metals fallback | metals.live | | FX rates | open.er-api.com | -| News | NewsAPI + curated fallback | +| News | NewsAPI + clearly marked cached feed (no mock fallback) | | Frontend host | Vercel | | Backend host | Azure App Service (B1 · Central India) | | CI/CD | GitHub Actions | @@ -106,7 +106,7 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000 |---|---|---| | GET | `/api/prices` | All commodity prices | | GET | `/api/prices/:id` | Single commodity | -| GET | `/api/news` | News feed | +| GET | `/api/news` | News feed with source, availability and fetch timestamp | | GET | `/api/rates` | Live FX rates | | POST | `/api/analyst` | AI analysis (Groq) | | POST | `/api/simulate` | India macro shock model | diff --git a/backend/routers/news.py b/backend/routers/news.py index 9391e33..9376fb9 100644 --- a/backend/routers/news.py +++ b/backend/routers/news.py @@ -1,98 +1,212 @@ -""" -News router — fetches commodity-related headlines from NewsAPI. -Falls back to curated realistic headlines if API key not set. -Free tier: 100 requests/day at newsapi.org -""" - -import os +"""NewsAPI headlines with explicit availability and bounded, per-filter caching.""" +import asyncio +import hashlib import logging -from datetime import datetime, timezone, timedelta +import os +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from urllib.parse import urlsplit import httpx -from fastapi import APIRouter, Query +from fastapi import APIRouter, HTTPException, Query logger = logging.getLogger(__name__) router = APIRouter(prefix="/api", tags=["news"]) -NEWS_API_KEY = os.getenv("NEWS_API_KEY", "") - -COMMODITY_QUERIES: dict[str, str] = { - "all": "commodity prices OR crude oil OR gold OR silver OR natural gas", - "crude-wti": "crude oil WTI prices", - "crude-brent": "brent crude oil", - "natural-gas": "natural gas prices energy", - "gold": "gold prices commodities", - "silver": "silver prices metals", - "copper": "copper prices metals", - "aluminium": "aluminium prices metals", - "platinum": "platinum prices metals", +COMMODITY_QUERIES = { + "all": '"commodity prices" OR "crude oil" OR "gold prices" OR "silver prices" OR "natural gas" OR "copper prices" OR "aluminium prices" OR "platinum prices"', + "crude-wti": '"crude oil" AND (WTI OR prices)', + "crude-brent": '"brent crude" OR "brent oil"', + "natural-gas": '"natural gas" AND (prices OR energy)', + "gold": '"gold prices" OR "gold futures"', + "silver": '"silver prices" OR "silver futures"', + "copper": '"copper prices" OR "copper futures"', + "aluminium": '"aluminium prices" OR "aluminum prices"', + "platinum": '"platinum prices" OR "platinum futures"', } +# Nine filters x eight refreshes per day = 72 calls/day per continuously running +# process when healthy, below a nominal 100/day quota. Not a distributed quota. +CACHE_TTL = timedelta(hours=3) +MAX_STALE = timedelta(hours=48) +NEWS_WINDOW = timedelta(days=7) +FAILURE_TTL = timedelta(minutes=15) +RATE_LIMIT_TTL = timedelta(hours=1) +REQUEST_TIMEOUT = 10 +PAGE_SIZE = 30 + + +@dataclass +class CacheEntry: + articles: list[dict] + fetched_at: datetime + + +_cache: dict[str, CacheEntry] = {} +_failures: dict[str, tuple[datetime, str]] = {} +_locks = {key: asyncio.Lock() for key in COMMODITY_QUERIES} +_rate_limited_until: datetime | None = None + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +class NewsFailure(Exception): + def __init__(self, reason: str, retry_after: int | None = None): + super().__init__(reason) + self.reason = reason + self.retry_after = retry_after -MOCK_NEWS = [ - {"id": "1", "title": "Gold surges above $3,300 as Fed signals rate pause", "source": "Reuters", "url": "https://reuters.com", "publishedAt": "2025-04-05T08:30:00Z", "commodity": "gold", "sentiment": "positive", "readTime": 3, "description": "Gold prices climbed to multi-week highs after Federal Reserve officials indicated a potential pause in interest rate hikes amid cooling inflation data."}, - {"id": "2", "title": "Crude oil slips on demand concerns from China slowdown", "source": "Bloomberg", "url": "https://bloomberg.com", "publishedAt": "2025-04-05T07:15:00Z", "commodity": "crude-wti", "sentiment": "negative", "readTime": 4, "description": "WTI crude fell 0.8% as manufacturing data from China came in weaker than expected, raising concerns about near-term demand for energy commodities."}, - {"id": "3", "title": "Natural gas prices rise on cold weather forecasts across Europe", "source": "Financial Times", "url": "https://ft.com", "publishedAt": "2025-04-05T06:00:00Z", "commodity": "natural-gas", "sentiment": "positive", "readTime": 3, "description": "European natural gas futures climbed 2.3% after weather models showed below-average temperatures forecast for the next two weeks across key consuming regions."}, - {"id": "4", "title": "Copper hits 3-week high on supply disruption fears in Chile", "source": "CNBC", "url": "https://cnbc.com", "publishedAt": "2025-04-04T14:00:00Z", "commodity": "copper", "sentiment": "positive", "readTime": 3, "description": "Copper prices surged to their highest level in three weeks after reports emerged of potential strike action at Escondida, the world largest copper mine."}, - {"id": "5", "title": "Silver outperforms gold as industrial demand outlook improves", "source": "Kitco", "url": "https://kitco.com", "publishedAt": "2025-04-04T11:30:00Z", "commodity": "silver", "sentiment": "positive", "readTime": 2, "description": "Silver prices outpaced gold gains this week as analysts revised upward their forecasts for solar panel production, a key driver of silver industrial demand."}, - {"id": "6", "title": "OPEC maintains output cuts, Brent crude finds support at $85", "source": "Reuters", "url": "https://reuters.com", "publishedAt": "2025-04-04T09:00:00Z", "commodity": "crude-brent", "sentiment": "neutral", "readTime": 4, "description": "OPEC confirmed it would maintain current production quotas through the second quarter, providing a floor for Brent crude prices near the $85 per barrel level."}, - {"id": "7", "title": "Platinum deficit expected to widen in 2025 on EV demand", "source": "World Platinum Council", "url": "https://platinuminvestment.com", "publishedAt": "2025-04-03T12:00:00Z", "commodity": "platinum", "sentiment": "positive", "readTime": 5, "description": "The World Platinum Investment Council raised its 2025 deficit forecast as hydrogen fuel cell vehicle production accelerates, consuming more platinum catalyst material."}, - {"id": "8", "title": "Aluminium prices under pressure as US tariff exemptions expire", "source": "Metal Bulletin", "url": "https://metalbulletin.com", "publishedAt": "2025-04-03T08:30:00Z", "commodity": "aluminium", "sentiment": "negative", "readTime": 3, "description": "Aluminium futures dropped as temporary tariff exemptions for several major exporters are set to expire, potentially disrupting trade flows to US consumers."}, - {"id": "9", "title": "India gold imports hit record high ahead of wedding season", "source": "Economic Times", "url": "https://economictimes.com", "publishedAt": "2025-04-02T10:00:00Z", "commodity": "gold", "sentiment": "positive", "readTime": 3, "description": "India gold imports surged 34% year-over-year in March as jewellers stocked ahead of the peak wedding and festival season, providing strong physical demand support."}, - {"id": "10", "title": "Natural gas storage deficit narrows, tempering price rally", "source": "EIA", "url": "https://eia.gov", "publishedAt": "2025-04-02T08:00:00Z", "commodity": "natural-gas", "sentiment": "neutral", "readTime": 2, "description": "US natural gas storage levels closed the gap with the 5-year average after a warmer-than-expected end to winter, reducing the urgency of the ongoing price rally."}, - {"id": "11", "title": "Copper demand from data centres to double by 2030, says Goldman", "source": "Goldman Sachs", "url": "https://goldmansachs.com", "publishedAt": "2025-04-01T14:00:00Z", "commodity": "copper", "sentiment": "positive", "readTime": 4, "description": "Goldman Sachs raised its long-term copper price target citing surging demand from AI data centre infrastructure, which requires significantly more copper wiring than traditional buildings."}, - {"id": "12", "title": "Silver industrial demand hits record on photovoltaic expansion", "source": "Silver Institute", "url": "https://silverinstitute.org", "publishedAt": "2025-04-01T09:00:00Z", "commodity": "silver", "sentiment": "positive", "readTime": 3, "description": "The Silver Institute reported industrial fabrication demand reached an all-time high driven by photovoltaic panel manufacturing in China and India."}, -] - - -async def _fetch_newsapi(query: str) -> list[dict]: - url = "https://newsapi.org/v2/everything" + +def _article(raw, commodity: str, now: datetime) -> dict | None: + if not isinstance(raw, dict): + return None + title, url, published = (raw.get(k) for k in ("title", "url", "publishedAt")) + publisher = raw.get("source") + source = publisher.get("name") if isinstance(publisher, dict) else None + if not all(isinstance(v, str) and v.strip() for v in (title, url, published, source)): + return None + if any(v.strip().lower() in ("[removed]", "removed") for v in (title, source)): + return None + try: + link = urlsplit(url) + if (link.scheme not in ("http", "https") or not link.hostname + or link.username or link.password or not link.path.strip("/") + or any(ch.isspace() for ch in url)): + return None + stamp = datetime.fromisoformat(published.replace("Z", "+00:00")) + if stamp.tzinfo is None: + return None + stamp = stamp.astimezone(timezone.utc) + if stamp > now or stamp < now - NEWS_WINDOW: + return None + except (ValueError, OverflowError): + return None + description = raw.get("description") + return { + "id": hashlib.sha256(url.encode()).hexdigest(), + "title": title.strip(), + "source": source.strip(), + "url": url, + "publishedAt": stamp.isoformat(), + "commodity": commodity, + "description": description.strip() if isinstance(description, str) else "", + } + + +def _retry_seconds(value: str | None) -> int | None: + if not value: + return None + try: + return max(0, int(value)) + except ValueError: + try: + from email.utils import parsedate_to_datetime + stamp = parsedate_to_datetime(value) + return max(0, int((stamp - _now()).total_seconds())) + except (TypeError, ValueError, OverflowError): + return None + + +async def _fetch_newsapi(commodity: str, key: str) -> list[dict]: + now = _now() params = { - "q": query, + "q": COMMODITY_QUERIES[commodity], "sortBy": "publishedAt", "language": "en", - "pageSize": 12, - "apiKey": NEWS_API_KEY, + "pageSize": PAGE_SIZE, + "from": (now - NEWS_WINDOW).isoformat(), + } + try: + async with httpx.AsyncClient(timeout=8, follow_redirects=False) as client: + response = await asyncio.wait_for( + client.get("https://newsapi.org/v2/everything", params=params, + headers={"X-Api-Key": key}), timeout=REQUEST_TIMEOUT + ) + if response.status_code == 429: + raise NewsFailure("rate_limited", _retry_seconds(response.headers.get("Retry-After"))) + if response.status_code in (401, 403): + raise NewsFailure("provider_access_denied") + response.raise_for_status() + payload = response.json() + except (asyncio.TimeoutError, httpx.TimeoutException): + raise NewsFailure("timeout") from None + except (httpx.HTTPError, ValueError): + raise NewsFailure("provider_error") from None + if not isinstance(payload, dict): + raise NewsFailure("invalid_response") + if payload.get("status") != "ok": + if payload.get("code") in ("rateLimited", "apiKeyExhausted"): + raise NewsFailure("rate_limited") + if payload.get("code") in ("apiKeyInvalid", "apiKeyDisabled", "apiKeyMissing"): + raise NewsFailure("provider_access_denied") + raise NewsFailure("provider_error") + raw_articles = payload.get("articles") + if not isinstance(raw_articles, list): + raise NewsFailure("invalid_response") + articles = {} + for raw in raw_articles: + article = _article(raw, commodity, now) + if article is not None: + articles.setdefault(article["id"], article) + if raw_articles and not articles: + raise NewsFailure("no_valid_articles") + return sorted(articles.values(), key=lambda a: a["publishedAt"], reverse=True) + + +def _feed(commodity: str, limit: int, now: datetime, reason: str | None = None) -> dict: + entry = _cache.get(commodity) + if entry and now - entry.fetched_at <= MAX_STALE: + # Do not present articles that have aged out of the publication window. + articles = [a for a in entry.articles + if datetime.fromisoformat(a["publishedAt"]) >= now - NEWS_WINDOW] + return { + "commodity": commodity, "source": "newsapi", + "status": "stale" if reason else "provider", + "reason": reason, "fetchedAt": entry.fetched_at.isoformat(), + "articles": articles[:limit], + } + return { + "commodity": commodity, "source": None, "status": "unavailable", + "reason": reason or "provider_error", "fetchedAt": None, "articles": [], } - async with httpx.AsyncClient(timeout=8) as client: - resp = await client.get(url, params=params) - resp.raise_for_status() - data = resp.json() - articles = data.get("articles", []) - result = [] - for i, a in enumerate(articles): - result.append({ - "id": str(i), - "title": a.get("title", ""), - "source": a.get("source", {}).get("name", ""), - "url": a.get("url", ""), - "publishedAt": a.get("publishedAt", ""), - "commodity": "all", - "sentiment": "neutral", - "readTime": max(2, len(a.get("description", "")) // 200), - "description": a.get("description", ""), - }) - return result @router.get("/news") async def get_news( commodity: str = Query(default="all"), - limit: int = Query(default=12, le=30), + limit: int = Query(default=12, ge=1, le=30), ): - if NEWS_API_KEY: + global _rate_limited_until + if commodity not in COMMODITY_QUERIES: + raise HTTPException(status_code=422, detail="Unsupported commodity filter") + # Read after dotenv initialization; never include the key in responses/logs. + key = os.getenv("NEWS_API_KEY", "").strip() + async with _locks[commodity]: + now = _now() + if not key: + return _feed(commodity, limit, now, "not_configured") + entry = _cache.get(commodity) + if entry and now - entry.fetched_at < CACHE_TTL: + return _feed(commodity, limit, now) + if _rate_limited_until and now < _rate_limited_until: + return _feed(commodity, limit, now, "rate_limited") + failure = _failures.get(commodity) + if failure and now < failure[0]: + return _feed(commodity, limit, now, failure[1]) try: - query = COMMODITY_QUERIES.get(commodity, COMMODITY_QUERIES["all"]) - articles = await _fetch_newsapi(query) - return articles[:limit] - except Exception as exc: - logger.warning("NewsAPI failed: %s — returning mock data", exc) - - # Filter mock by commodity - if commodity == "all": - filtered = MOCK_NEWS - else: - filtered = [n for n in MOCK_NEWS if n["commodity"] == commodity or commodity == "all"] - if not filtered: - filtered = MOCK_NEWS - - return filtered[:limit] + articles = await _fetch_newsapi(commodity, key) + except NewsFailure as exc: + now = _now() + cooldown = FAILURE_TTL + if exc.reason == "rate_limited": + # Respect Retry-After, with a one-hour minimum and a safe upper bound. + cooldown = max(RATE_LIMIT_TTL, timedelta(seconds=min(exc.retry_after or 0, 86400))) + _rate_limited_until = now + cooldown + _failures[commodity] = (now + cooldown, exc.reason) + logger.warning("NewsAPI unavailable for %s: %s", commodity, exc.reason) + return _feed(commodity, limit, now, exc.reason) + now = _now() + _cache[commodity] = CacheEntry(articles, now) + _failures.pop(commodity, None) + return _feed(commodity, limit, now) diff --git a/backend/tests/test_news_integrity.py b/backend/tests/test_news_integrity.py new file mode 100644 index 0000000..08996d4 --- /dev/null +++ b/backend/tests/test_news_integrity.py @@ -0,0 +1,187 @@ +"""Offline tests for NewsAPI provenance, caching and failure states.""" +import asyncio +import os +import unittest +from datetime import datetime, timedelta, timezone +from unittest.mock import patch + +import httpx +from fastapi import FastAPI + +from routers import news + + +class NewsIntegrityTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + news._cache.clear() + news._failures.clear() + news._rate_limited_until = None + self.now = datetime(2026, 1, 10, 12, tzinfo=timezone.utc) + self.calls = [] + self.clock = patch.object(news, "_now", side_effect=lambda: self.now) + self.clock.start() + self.addCleanup(self.clock.stop) + self.env = patch.dict(os.environ, {"NEWS_API_KEY": "test-only-key"}) + self.env.start() + self.addCleanup(self.env.stop) + self.client_class = httpx.AsyncClient + self.handler = lambda request: httpx.Response(200, json={"status": "ok", "articles": []}) + + async def handle(request): + self.calls.append(request) + return self.handler(request) + + self.transport = patch.object(news.httpx, "AsyncClient", side_effect=lambda **kwargs: + self.client_class(transport=httpx.MockTransport(handle), **kwargs)) + self.transport.start() + self.addCleanup(self.transport.stop) + + def article(self, slug="gold-market", **updates): + return { + "title": "Test provider article", + "source": {"name": "Test publisher"}, + "url": "https://example.com/news/" + slug, + "publishedAt": (self.now - timedelta(hours=2)).isoformat(), + "description": None, + **updates, + } + + def success(self, *articles): + self.handler = lambda request: httpx.Response( + 200, json={"status": "ok", "articles": list(articles)} + ) + + async def feed(self, commodity="gold", limit=12): + return await news.get_news(commodity=commodity, limit=limit) + + async def test_missing_key_has_no_fake_articles_or_upstream_request(self): + with patch.dict(os.environ, {"NEWS_API_KEY": ""}): + result = await self.feed() + self.assertEqual(result["status"], "unavailable") + self.assertEqual(result["reason"], "not_configured") + self.assertIsNone(result["source"]) + self.assertIsNone(result["fetchedAt"]) + self.assertEqual(result["articles"], []) + self.assertEqual(len(self.calls), 0) + + async def test_success_validates_deduplicates_and_sorts(self): + newer = self.article("newer") + older = self.article("older", publishedAt=(self.now - timedelta(days=1)).isoformat()) + self.success(older, newer, newer, + self.article(url="https://example.com/"), + self.article(url="javascript:alert(1)"), + self.article(url="https://user:pass@example.com/news"), + self.article(source=None), self.article(title="[Removed]"), + self.article(publishedAt="not-a-date"), + self.article(publishedAt=(self.now + timedelta(hours=1)).isoformat()), + self.article(publishedAt=(self.now - timedelta(days=8)).isoformat())) + result = await self.feed(limit=30) + self.assertEqual(result["status"], "provider") + self.assertEqual(result["source"], "newsapi") + self.assertIsNone(result["reason"]) + self.assertEqual(result["fetchedAt"], self.now.isoformat()) + self.assertEqual([a["url"] for a in result["articles"]], [newer["url"], older["url"]]) + self.assertEqual(result["articles"][0]["description"], "") + self.assertEqual(result["articles"][0]["commodity"], "gold") + self.assertNotIn("sentiment", result["articles"][0]) + self.assertEqual(self.calls[0].headers["x-api-key"], "test-only-key") + self.assertNotIn("test-only-key", str(self.calls[0].url)) + self.assertEqual(self.calls[0].url.params["pageSize"], "30") + + async def test_cache_reused_across_limits_and_isolated_by_filter(self): + self.success(self.article("one"), self.article("two")) + one, two = await asyncio.gather(self.feed(limit=1), self.feed(limit=2)) + self.assertEqual(len(self.calls), 1) + self.assertEqual(len(one["articles"]), 1) + self.assertEqual(len(two["articles"]), 2) + self.now += timedelta(hours=1) + cached = await self.feed() + self.assertEqual(cached["fetchedAt"], one["fetchedAt"]) + other = await self.feed("silver") + self.assertEqual(len(self.calls), 2) + self.assertEqual(other["articles"][0]["commodity"], "silver") + + async def test_rate_limit_blocks_other_uncached_filters_and_respects_retry_after(self): + self.handler = lambda request: httpx.Response(429, headers={"Retry-After": "7200"}) + result = await self.feed() + self.assertEqual(result["reason"], "rate_limited") + self.assertEqual(result["status"], "unavailable") + self.now += timedelta(minutes=90) + self.assertEqual((await self.feed("silver"))["reason"], "rate_limited") + self.assertEqual(len(self.calls), 1) + self.now += timedelta(minutes=31) + self.success(self.article()) + self.assertEqual((await self.feed("silver"))["status"], "provider") + self.assertEqual(len(self.calls), 2) + + async def test_timeout_keeps_last_known_feed_and_then_expires(self): + self.success(self.article()) + initial = await self.feed() + self.now += news.CACHE_TTL + timedelta(seconds=1) + + def timeout(request): + raise httpx.ReadTimeout("test timeout", request=request) + + self.handler = timeout + stale = await self.feed() + self.assertEqual(stale["status"], "stale") + self.assertEqual(stale["reason"], "timeout") + self.assertEqual(stale["articles"], initial["articles"]) + self.assertEqual(stale["fetchedAt"], initial["fetchedAt"]) + self.assertEqual((await self.feed())["status"], "stale") + self.assertEqual(len(self.calls), 2) + self.now += news.MAX_STALE + expired = await self.feed() + self.assertEqual(expired["status"], "unavailable") + self.assertEqual(expired["articles"], []) + self.assertIsNone(expired["fetchedAt"]) + + async def test_timeout_with_no_cache_and_recovery(self): + def timeout(request): + raise httpx.ReadTimeout("test timeout", request=request) + self.handler = timeout + failed = await self.feed() + self.assertEqual(failed["reason"], "timeout") + self.assertEqual(failed["status"], "unavailable") + self.now += news.FAILURE_TTL + timedelta(seconds=1) + self.success(self.article()) + recovered = await self.feed() + self.assertEqual(recovered["status"], "provider") + self.assertIsNone(recovered["reason"]) + + async def test_empty_success_is_not_a_provider_failure(self): + result = await self.feed() + self.assertEqual(result["status"], "provider") + self.assertIsNone(result["reason"]) + self.assertEqual(result["articles"], []) + self.assertEqual((await self.feed())["status"], "provider") + self.assertEqual(len(self.calls), 1) + + async def test_malformed_payload_and_access_denied(self): + self.handler = lambda request: httpx.Response(200, json={"status": "ok", "articles": None}) + self.assertEqual((await self.feed())["reason"], "invalid_response") + self.handler = lambda request: httpx.Response(401, json={"message": "test-only-key"}) + denied = await self.feed("silver") + self.assertEqual(denied["reason"], "provider_access_denied") + self.assertNotIn("test-only-key", str(denied)) + + async def test_all_invalid_articles_not_presented_as_success(self): + self.success(self.article(url="https://example.com")) + result = await self.feed() + self.assertEqual(result["reason"], "no_valid_articles") + self.assertEqual(result["articles"], []) + + async def test_http_filter_and_limit_validation(self): + app = FastAPI() + app.include_router(news.router) + async with self.client_class(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + for query in ("commodity=unknown", "limit=0", "limit=31"): + response = await client.get("/api/news?" + query) + self.assertEqual(response.status_code, 422) + response = await client.get("/api/news?commodity=gold&limit=2") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["status"], "provider") + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/news-data-contract.md b/docs/news-data-contract.md new file mode 100644 index 0000000..5d41403 --- /dev/null +++ b/docs/news-data-contract.md @@ -0,0 +1,25 @@ +# News data contract + +GET /api/news?commodity=gold&limit=12 returns an object, not the old unmarked article array. + +- `commodity`: requested filter, one of the nine configured markets or all; invalid filters and limits outside 1–30 return HTTP 422. +- `status`: provider (successful upstream response, including a genuine empty result), stale (last successful response retained after a failure), unavailable (no usable cached response). +- `source`: newsapi when a provider response is available; null otherwise. +- `reason`: null on success; otherwise not_configured, rate_limited, timeout, provider_access_denied, provider_error, invalid_response or no_valid_articles. +- `fetchedAt`: UTC time of last successful provider request, distinct from each article's publication timestamp. +- `articles`: provider-supplied titles, publisher names, descriptions and original URLs, deduplicated and sorted by publication time. Only articles dated within the last seven days are retained. Missing descriptions remain empty. Root URLs, non-HTTP(S) URLs and malformed or removed records are rejected. Link structure is validated; individual publisher pages are not fetched or independently fact-checked. Paywalls and link rot remain possible. +- No mock articles, fabricated sentiment tags, or invented reading-time estimates. + +## Caching and failures + +Per-filter in-memory cache: 3 hours fresh, up to 48 hours since retrieval during provider failures, with a seven-day publication window. Each fetch requests up to 30 results, independent of the caller's limit. Concurrent requests for the same filter share a refresh. Failures cool down for 15 minutes; rate limits pause uncached requests across filters for at least an hour, honoring Retry-After up to 24 hours. This is process-local caching, not a distributed quota or persistence guarantee. Nine filters at a three-hour healthy refresh interval can make about 72 upstream requests per continuously running process per day; restarts, multiple instances, errors and shared accounts may increase usage. The UI retry button respects server caching. + +Set NEWS_API_KEY in the backend environment; no key means an explicit unavailable/stale feed. The upstream request has a 10-second overall request deadline and uses a header instead of putting the key in the query string. + +## Deployment and testing + +Deploy compatible frontend and backend together. If rolling separately, deploy frontend first: it deliberately rejects legacy unmarked arrays rather than displaying old mock articles. The legacy frontend expects an array and cannot consume the new envelope. + +Run `cd backend && python -m unittest discover -s tests -v`. MockTransport tests cover missing credentials, successful and empty responses, validation, caching, filter isolation, HTTP 429, cooldowns, timeout, stale expiry, recovery and access denial. The existing PR workflow runs these tests plus frontend type checks and the production build. + +Actual provider credentials, commercial/production licensing, real provider availability and link accessibility need verification in the deployed environment. A valid provider key and plan that permits the deployment are required. diff --git a/frontend/src/app/news/page.tsx b/frontend/src/app/news/page.tsx index 6418662..ea53587 100644 --- a/frontend/src/app/news/page.tsx +++ b/frontend/src/app/news/page.tsx @@ -1,7 +1,7 @@ "use client"; import { useState, useEffect } from "react"; -import { NewsArticle } from "@/types"; +import { NewsFeed, NewsFailureReason } from "@/types"; import { api } from "@/lib/api"; import { Navbar } from "@/components/Navbar"; import { usePrices } from "@/hooks/usePrices"; @@ -14,32 +14,56 @@ const COMMODITY_FILTERS = [ { id: "gold", label: "Gold" }, { id: "silver", label: "Silver" }, { id: "copper", label: "Copper" }, + { id: "aluminium", label: "Aluminium" }, { id: "platinum", label: "Platinum" }, ]; -const SENTIMENT_COLOR = { positive: "var(--up)", negative: "var(--down)", neutral: "var(--text-tertiary)" }; -const SENTIMENT_BG = { positive: "var(--up-dim)", negative: "var(--down-dim)", neutral: "var(--bg-elevated)" }; - -function timeAgo(iso: string) { - const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 1000); - if (diff < 3600) return `${Math.floor(diff / 60)}m ago`; - if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`; - return `${Math.floor(diff / 86400)}d ago`; +const REASON_MESSAGES: Record = { + not_configured: "The news provider is not configured.", + rate_limited: "The news provider has reached its request limit. Please try again later.", + timeout: "The news provider timed out.", + provider_access_denied: "The news provider rejected access.", + provider_error: "The news provider is temporarily unavailable.", + invalid_response: "The news provider returned an invalid response.", + no_valid_articles: "The provider returned no usable article records.", +}; + +function formatDate(iso: string) { + return new Date(iso).toLocaleString("en-IN", { + year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", + timeZoneName: "short", + }); } export default function NewsPage() { const { isConnected, lastUpdated, priceNotice } = usePrices(); - const [articles, setArticles] = useState([]); + const [feed, setFeed] = useState(null); + const [error, setError] = useState(null); + const [refresh, setRefresh] = useState(0); const [filter, setFilter] = useState("all"); const [loading, setLoading] = useState(true); useEffect(() => { + let active = true; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 15000); setLoading(true); - api.getNews(filter) - .then(setArticles) - .catch(console.error) - .finally(() => setLoading(false)); - }, [filter]); + setFeed(null); + setError(null); + api.getNews(filter, controller.signal) + .then(value => { if (active) setFeed(value); }) + .catch(() => { + if (active) setError(controller.signal.aborted + ? "News request timed out. Please try again." + : "News could not be loaded or verified. No unverified headlines will be shown."); + }) + .finally(() => { clearTimeout(timer); if (active) setLoading(false); }); + return () => { active = false; clearTimeout(timer); controller.abort(); }; + }, [filter, refresh]); + + const currentFeed = feed?.commodity === filter ? feed : null; + const articles = currentFeed?.articles ?? []; + const reason = currentFeed?.reason ? REASON_MESSAGES[currentFeed.reason] : null; return (
@@ -48,19 +72,31 @@ export default function NewsPage() {

Market News

-

Latest commodity headlines — sentiment tagged

+

Provider-supplied commodity headlines from the last seven days; coverage may be delayed

{/* Filter tabs */}
{COMMODITY_FILTERS.map(f => ( - ))}
+
+
+ {loading ? "Loading provider news…" : error ? error : currentFeed?.status === "provider" + ? "NewsAPI · Provider feed (may be delayed)" + : currentFeed?.status === "stale" ? "Stale cached feed — " + reason + : reason ?? "News unavailable."} + {currentFeed?.fetchedAt &&
Last successful fetch: {formatDate(currentFeed.fetchedAt)}
} +
+ +
+ {/* Articles grid */} {loading ? (
@@ -77,15 +113,12 @@ export default function NewsPage() { onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.transform = "translateY(0)"; }}> {/* Top accent */} -
+
{/* Header */}
{a.source} -
- {a.sentiment} - {a.readTime} min -
+ {currentFeed?.status === "stale" ? "Cached article" : "Via NewsAPI"}
{/* Title */} @@ -96,7 +129,7 @@ export default function NewsPage() { {/* Footer */}
- {timeAgo(a.publishedAt)} + Read article
@@ -105,7 +138,7 @@ export default function NewsPage() { )} {!loading && articles.length === 0 && ( -
No articles found for this filter.
+
{error || currentFeed?.status === "unavailable" ? "No verified provider headlines available." : currentFeed?.status === "stale" ? "No cached articles remain in the publication window." : "No matching articles found in the provider feed."}
)}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 04ee815..73f7f8c 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,17 +1,56 @@ -import { CommodityQuote, NewsArticle, FxRates } from "@/types"; +import { CommodityQuote, NewsArticle, NewsFeed, FxRates } from "@/types"; const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"; -async function get(path: string): Promise { - const res = await fetch(`${BASE}${path}`, { next: { revalidate: 0 } }); +async function get(path: string, signal?: AbortSignal): Promise { + const res = await fetch(`${BASE}${path}`, { next: { revalidate: 0 }, signal }); if (!res.ok) throw new Error(`API ${res.status}: ${path}`); return res.json() as Promise; } +const NEWS_REASONS = ["not_configured", "rate_limited", "timeout", "provider_access_denied", + "provider_error", "invalid_response", "no_valid_articles"]; + +function isArticle(value: unknown, commodity: string): value is NewsArticle { + if (!value || typeof value !== "object") return false; + const a = value as Record; + if (typeof a.id !== "string" || !a.id || typeof a.title !== "string" || !a.title.trim() || + typeof a.source !== "string" || !a.source.trim() || typeof a.url !== "string" || + typeof a.publishedAt !== "string" || !Number.isFinite(Date.parse(a.publishedAt)) || + Date.parse(a.publishedAt) > Date.now() + 5 * 60 * 1000 || + a.commodity !== commodity || typeof a.description !== "string") return false; + try { + const url = new URL(a.url); + return ["http:", "https:"].includes(url.protocol) && !!url.hostname && + !url.username && !url.password && url.pathname.replace(/\//g, "").length > 0; + } catch { + return false; + } +} + +function parseNewsFeed(value: unknown, commodity: string): NewsFeed { + // Older backends returned unmarked arrays, including hardcoded headlines. + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Unverified news response"); + const f = value as Record; + if (f.commodity !== commodity || !Array.isArray(f.articles) || + !f.articles.every(a => isArticle(a, commodity))) throw new Error("Invalid news response"); + const knownReason = typeof f.reason === "string" && NEWS_REASONS.includes(f.reason); + if (f.status === "unavailable") { + if (f.source !== null || f.fetchedAt !== null || f.articles.length || !knownReason) + throw new Error("Invalid unavailable news response"); + } else if ((f.status !== "provider" && f.status !== "stale") || f.source !== "newsapi" || + typeof f.fetchedAt !== "string" || !Number.isFinite(Date.parse(f.fetchedAt)) || + (f.status === "provider" ? f.reason !== null : !knownReason)) { + throw new Error("Invalid news provenance"); + } + return value as NewsFeed; +} + export const api = { getPrices: () => get("/api/prices"), getCommodity: (id: string) => get(`/api/prices/${id}`), getTicker: () => get[]>("/api/ticker"), - getNews: (commodity = "all") => get(`/api/news?commodity=${commodity}&limit=12`), + getNews: async (commodity = "all", signal?: AbortSignal) => + parseNewsFeed(await get(`/api/news?commodity=${encodeURIComponent(commodity)}&limit=12`, signal), commodity), getRates: () => get("/api/rates"), }; diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 1130205..4651aeb 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -43,11 +43,21 @@ export interface NewsArticle { url: string; publishedAt: string; commodity: string; - sentiment: "positive" | "negative" | "neutral"; - readTime: number; description: string; } +export type NewsFailureReason = "not_configured" | "rate_limited" | "timeout" | + "provider_access_denied" | "provider_error" | "invalid_response" | "no_valid_articles"; + +export interface NewsFeed { + commodity: string; + source: "newsapi" | null; + status: "provider" | "stale" | "unavailable"; + reason: NewsFailureReason | null; + fetchedAt: string | null; + articles: NewsArticle[]; +} + export interface FxRates { [currency: string]: number; }