Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/price-provenance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
pull_request:
paths:
- 'backend/**'
- 'render.yaml'
- 'frontend/**'
- '.github/workflows/price-provenance.yml'
workflow_dispatch:
Expand Down
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,11 @@
| Styling | Custom CSS variable design system (dark + light) |
| Backend | FastAPI + WebSockets |
| AI | Groq Llama 3.3 70B (free tier) |
| Price data | Twelve Data API (real-time) |
| Metals fallback | metals.live |
| Price data | Yahoo Finance (provider observations, potentially delayed) |
| FX rates | open.er-api.com |
| News | NewsAPI + clearly marked cached feed (no mock fallback) |
| Frontend host | Vercel |
| Backend host | Azure App Service (B1 · Central India) |
| Backend host | Azure App Service (existing); Render Free migration pending verification |
| CI/CD | GitHub Actions |

---
Expand Down Expand Up @@ -72,7 +71,6 @@ Open `http://localhost:3000` · API docs at `http://localhost:8000/docs`
```
ALLOWED_ORIGINS=http://localhost:3000
GROQ_API_KEY= # console.groq.com — free
TWELVE_DATA_KEY= # twelvedata.com — free tier
NEWS_API_KEY= # newsapi.org — optional
WEBSITES_PORT=8000
```
Expand All @@ -90,9 +88,12 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000
| Layer | Platform | Notes |
|---|---|---|
| Frontend | Vercel | Auto-deploy on push to `main` |
| Backend | Azure App Service B1 | GitHub Actions CI/CD via `.github/workflows/main_commoditychain-api.yml` |
| Backend (existing) | Azure App Service | Existing GitHub Actions workflow remains enabled; deployment authentication currently blocked |
| Backend (candidate) | Render Free | Staged migration; see [deployment and verification guide](docs/render-migration.md) |

**Azure App Service settings:**
**Render migration:** root `render.yaml` defines a single free Python service, with manual deployment until verification. Do not change production Vercel variables or disable Azure until the candidate is verified.

**Azure App Service settings (existing):**
- Runtime: Python 3.11 · Linux
- Startup command: `uvicorn main:app --host 0.0.0.0 --port 8000`
- Always On: enabled
Expand All @@ -104,6 +105,8 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000

| Method | Route | Description |
|---|---|---|
| GET | `/api/health` | Process liveness (no provider calls) |
| GET | `/api/ready` | Cached market-data readiness (503 until usable quotes exist) |
| GET | `/api/prices` | All commodity prices |
| GET | `/api/prices/:id` | Single commodity |
| GET | `/api/news` | News feed with source, availability and fetch timestamp |
Expand All @@ -125,7 +128,7 @@ commoditychain/
main.py # FastAPI app, 9 routers
requirements.txt
services/
commodity_service.py # Twelve Data + GBM fallback
commodity_service.py # Yahoo Finance, explicit stale/unavailable states
routers/
prices.py / websocket.py / news.py / fx.py
analyst.py / simulator.py / export.py
Expand Down Expand Up @@ -158,7 +161,7 @@ commoditychain/
---

*Built by Ayush Raj
*Stack: Next.js 14 · FastAPI · Groq · Twelve Data · Vercel · Azure*
*Stack: Next.js 14 · FastAPI · Groq · Yahoo Finance · Vercel · Azure / planned Render*

<!-- open-workers:bottom:start -->
## License
Expand Down
2 changes: 1 addition & 1 deletion backend/.python-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.11.9
3.11.9
42 changes: 25 additions & 17 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# Load local configuration before routers read credentials. Hosted env takes precedence.
load_dotenv()

from routers.prices import router as prices_router
from routers.websocket import router as ws_router, _broadcast_loop
from routers.news import router as news_router
Expand All @@ -17,43 +20,48 @@
from routers.india import router as india_router
from routers.correlation import router as correlation_router

load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("main")

ALLOWED_ORIGINS = os.getenv(
"ALLOWED_ORIGINS",
"*",
).split(",")
ALLOWED_ORIGINS = [origin.strip() for origin in os.getenv("ALLOWED_ORIGINS", "*").split(",") if origin.strip()]


@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting CommodityChain backend v4")
async def _warm_cache():
from services.commodity_service import get_all_prices
try:
data = await get_all_prices()
logger.info("Warm cache: %d commodities loaded", len(data))
logger.info("Initial price snapshot: %d records", len(data))
except Exception as exc:
logger.warning("Cache warm failed: %s", exc)
task = asyncio.create_task(_broadcast_loop())
yield
task.cancel()
logger.warning("Cache warm failed: %s", type(exc).__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
from services.commodity_service import stop_price_refresh
logger.info("Starting CommodityChain backend v4")
# Accept HTTP requests immediately; a provider outage must not block startup.
tasks = [
asyncio.create_task(_warm_cache(), name="price-cache-warmup"),
asyncio.create_task(_broadcast_loop(), name="price-broadcast"),
]
try:
await task
except asyncio.CancelledError:
pass
yield
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await stop_price_refresh()


app = FastAPI(title="CommodityChain API", version="4.0.0", lifespan=lifespan)

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origins=ALLOWED_ORIGINS,
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
Expand Down
13 changes: 11 additions & 2 deletions backend/routers/prices.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from models.commodity import Commodity
from services.commodity_service import get_all_prices, get_price_by_id
from services.commodity_service import get_all_prices, get_price_by_id, cache_readiness

router = APIRouter(prefix="/api", tags=["prices"])


@router.get("/prices", response_model=list[Commodity])
async def list_prices():
"""Return all commodity prices (served from cache, TTL 55s)."""
"""Return all commodity prices (served from cache, TTL 60s)."""
return await get_all_prices()


Expand Down Expand Up @@ -39,4 +40,12 @@ async def ticker():

@router.get("/health")
async def health():
"""Process liveness only: safe for platform health checks."""
return {"status": "ok"}


@router.get("/ready")
async def readiness():
"""Market-data readiness without external network calls."""
report = cache_readiness()
return JSONResponse(report, status_code=200 if report["marketData"]["usableQuotes"] else 503)
77 changes: 69 additions & 8 deletions backend/services/commodity_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
_cache: dict[str, Commodity] = {}
_last_real: dict[str, Commodity] = {}
_cache_ts: datetime | None = None
_refresh_lock = asyncio.Lock()
_refresh_task: asyncio.Task | None = None
REQUEST_WAIT_SECONDS = 8


def _now() -> datetime:
Expand Down Expand Up @@ -132,15 +133,75 @@ def _stale() -> bool:
return _cache_ts is None or (_now() - _cache_ts).total_seconds() >= CACHE_TTL


async def get_all_prices() -> list[Commodity]:
def _cached_snapshot(*, refreshing: bool = False) -> list[Commodity]:
"""Always return configured identities, with no invented numeric data."""
result = []
for cfg in COMMODITIES_CONFIG:
quote = _cache.get(cfg["id"])
if quote is None:
quote = Commodity(**_identity(cfg), dataStatus="unavailable")
elif refreshing and quote.dataStatus == "provider":
quote = quote.model_copy(update={"dataStatus": "stale", "isStale": True})
result.append(_mark_age(quote))
return result


def cache_readiness() -> dict:
"""Read only process-local state; never contact an upstream provider."""
records = _cached_snapshot(refreshing=_stale())
counts = {status: sum(c.dataStatus == status for c in records)
for status in ("provider", "stale", "unavailable")}
complete = [c for c in records if c.source == "yahoo_finance" and not c.isSimulated
and all(v is not None and math.isfinite(v)
for v in (c.price, c.previousClose, c.change, c.changePercent))]
refreshing = _refresh_task is not None and not _refresh_task.done()
if not complete:
status = "warming" if refreshing or _cache_ts is None else "unavailable"
else:
status = "ready" if len(complete) == len(records) and counts["provider"] == len(records) else "degraded"
return {
"status": status,
"marketData": {
"configured": len(records), **counts, "usableQuotes": len(complete),
"refreshInProgress": refreshing,
"cacheUpdatedAt": _cache_ts.isoformat() if _cache_ts else None,
},
}


async def _refresh_cache():
global _cache, _cache_ts
try:
fresh = await _fetch_all()
_cache = {c.id: c for c in fresh}
_cache_ts = _now()
except Exception as exc:
logger.warning("Price refresh failed: %s", type(exc).__name__)
# Preserve prior genuine observations and avoid a tight retry loop.
_cache = {c.id: c for c in _cached_snapshot(refreshing=True)}
_cache_ts = _now()


async def get_all_prices() -> list[Commodity]:
global _refresh_task
if _stale():
async with _refresh_lock:
if _stale():
fresh = await _fetch_all()
_cache = {c.id: c for c in fresh}
_cache_ts = _now()
return [_mark_age(c) for c in _cache.values()]
# No await between checking and publishing the task; one refresh per event loop.
if _refresh_task is None or _refresh_task.done():
_refresh_task = asyncio.create_task(_refresh_cache(), name="commodity-refresh")
try:
# A timed-out/disconnected caller must not cancel other callers' refresh.
await asyncio.wait_for(asyncio.shield(_refresh_task), timeout=REQUEST_WAIT_SECONDS)
except asyncio.TimeoutError:
return _cached_snapshot(refreshing=True)
return _cached_snapshot()


async def stop_price_refresh():
global _refresh_task
task, _refresh_task = _refresh_task, None
if task is not None and not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)


async def get_price_by_id(cid: str) -> Commodity | None:
Expand Down
Loading
Loading