From 0da6ba149adf57fa8ede13a097db5dcc1f3decec Mon Sep 17 00:00:00 2001 From: Ayush Raj Date: Tue, 1 Dec 2026 19:05:03 +0530 Subject: [PATCH] infra: prepare staged Render Free migration and readiness checks (#17) --- .github/workflows/price-provenance.yml | 1 + README.md | 19 +-- backend/.python-version | 2 +- backend/main.py | 42 +++--- backend/routers/prices.py | 13 +- backend/services/commodity_service.py | 77 +++++++++-- backend/tests/test_deployment_readiness.py | 142 +++++++++++++++++++++ docs/render-migration.md | 66 ++++++++++ render.yaml | 20 +++ 9 files changed, 346 insertions(+), 36 deletions(-) create mode 100644 backend/tests/test_deployment_readiness.py create mode 100644 docs/render-migration.md create mode 100644 render.yaml diff --git a/.github/workflows/price-provenance.yml b/.github/workflows/price-provenance.yml index 46d1b7f..cc42840 100644 --- a/.github/workflows/price-provenance.yml +++ b/.github/workflows/price-provenance.yml @@ -4,6 +4,7 @@ on: pull_request: paths: - 'backend/**' + - 'render.yaml' - 'frontend/**' - '.github/workflows/price-provenance.yml' workflow_dispatch: diff --git a/README.md b/README.md index c6d4864..7d315ae 100644 --- a/README.md +++ b/README.md @@ -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 | --- @@ -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 ``` @@ -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 @@ -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 | @@ -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 @@ -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* ## License diff --git a/backend/.python-version b/backend/.python-version index 5506cb9..2419ad5 100644 --- a/backend/.python-version +++ b/backend/.python-version @@ -1 +1 @@ -3.11.9 +3.11.9 diff --git a/backend/main.py b/backend/main.py index 3c6ed80..3935753 100644 --- a/backend/main.py +++ b/backend/main.py @@ -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 @@ -17,7 +20,6 @@ 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", @@ -25,35 +27,41 @@ ) 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=["*"], diff --git a/backend/routers/prices.py b/backend/routers/prices.py index 074bf3f..6cbc6b2 100644 --- a/backend/routers/prices.py +++ b/backend/routers/prices.py @@ -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() @@ -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) diff --git a/backend/services/commodity_service.py b/backend/services/commodity_service.py index a59232c..f7d17b7 100644 --- a/backend/services/commodity_service.py +++ b/backend/services/commodity_service.py @@ -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: @@ -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: diff --git a/backend/tests/test_deployment_readiness.py b/backend/tests/test_deployment_readiness.py new file mode 100644 index 0000000..9ea0542 --- /dev/null +++ b/backend/tests/test_deployment_readiness.py @@ -0,0 +1,142 @@ +"""Deployment readiness checks; no external provider or hosting credentials needed.""" +import asyncio +import importlib +import os +import unittest +from datetime import datetime, timezone +from unittest.mock import AsyncMock, patch + +import httpx + +import main +from services import commodity_service as svc + + +def provider_quote(): + return { + "price": 101.25, "previousClose": 100.0, "high24h": 103.0, "low24h": 99.0, + "history": [], "sourceTimestamp": datetime.now(timezone.utc).isoformat(), + } + + +class DeploymentReadinessTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + await svc.stop_price_refresh() + svc._cache.clear() + svc._last_real.clear() + svc._cache_ts = None + + async def asyncTearDown(self): + await svc.stop_price_refresh() + svc._cache.clear() + svc._last_real.clear() + svc._cache_ts = None + + async def test_startup_and_health_do_not_wait_for_provider(self): + started = asyncio.Event() + async def blocked(): + started.set() + await asyncio.Event().wait() + + async def exercise(): + async with main.lifespan(main.app): + await started.wait() + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=main.app), base_url="http://test" + ) as client: + response = await client.get("/api/health") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json(), {"status": "ok"}) + with patch.object(svc, "get_all_prices", side_effect=blocked): + await asyncio.wait_for(exercise(), timeout=2) + + async def test_readiness_is_cache_only_and_reports_provider_failure(self): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=main.app), base_url="http://test" + ) as client: + with patch.object(svc, "_fetch_yfinance", return_value=None) as fetch: + cold = await client.get("/api/ready") + self.assertEqual(cold.status_code, 503) + self.assertEqual(cold.json()["status"], "warming") + self.assertEqual(cold.json()["marketData"]["usableQuotes"], 0) + fetch.assert_not_called() + await svc.get_all_prices() + failed = await client.get("/api/ready") + self.assertEqual(failed.status_code, 503) + self.assertEqual(failed.json()["status"], "unavailable") + self.assertEqual(fetch.call_count, len(svc.COMMODITIES_CONFIG)) + self.assertEqual(failed.json()["marketData"]["unavailable"], len(svc.COMMODITIES_CONFIG)) + svc._cache_ts = None + with patch.object(svc, "_fetch_yfinance", return_value=provider_quote()): + await svc.get_all_prices() + ready = await client.get("/api/ready") + self.assertEqual(ready.status_code, 200) + self.assertEqual(ready.json()["status"], "ready") + self.assertEqual(ready.json()["marketData"]["usableQuotes"], len(svc.COMMODITIES_CONFIG)) + + async def test_cold_requests_share_refresh_and_return_bounded_unavailable_snapshot(self): + release = asyncio.Event() + async def slow_refresh(): + await release.wait() + return [svc._observed(cfg, provider_quote()) for cfg in svc.COMMODITIES_CONFIG] + + with patch.object(svc, "_fetch_all", new=AsyncMock(side_effect=slow_refresh)) as fetch, patch.object(svc, "REQUEST_WAIT_SECONDS", .02): + snapshots = await asyncio.gather(*(svc.get_all_prices() for _ in range(6))) + self.assertEqual(fetch.await_count, 1) + for snapshot in snapshots: + self.assertEqual(len(snapshot), len(svc.COMMODITIES_CONFIG)) + self.assertTrue(all(c.dataStatus == "unavailable" and c.price is None for c in snapshot)) + self.assertTrue(svc.cache_readiness()["marketData"]["refreshInProgress"]) + release.set() + await asyncio.wait_for(svc._refresh_task, timeout=1) + recovered = await svc.get_all_prices() + self.assertTrue(all(c.dataStatus == "provider" for c in recovered)) + self.assertEqual(fetch.await_count, 1) + + async def test_expired_cache_remains_stale_while_shared_refresh_runs(self): + with patch.object(svc, "_fetch_yfinance", return_value=provider_quote()): + original = await svc.get_all_prices() + svc._cache_ts = None + release = asyncio.Event() + async def slow_refresh(): + await release.wait() + return original + with patch.object(svc, "_fetch_all", side_effect=slow_refresh), patch.object(svc, "REQUEST_WAIT_SECONDS", .02): + fallback = await svc.get_all_prices() + self.assertEqual(fallback[0].dataStatus, "stale") + self.assertEqual(fallback[0].sourceTimestamp, original[0].sourceTimestamp) + self.assertEqual(fallback[0].fetchedAt, original[0].fetchedAt) + self.assertEqual(svc.cache_readiness()["status"], "degraded") + release.set() + await asyncio.wait_for(svc._refresh_task, timeout=1) + + async def test_cancelled_caller_does_not_cancel_shared_refresh(self): + started, release = asyncio.Event(), asyncio.Event() + async def slow_refresh(): + started.set() + await release.wait() + return [svc._observed(cfg, provider_quote()) for cfg in svc.COMMODITIES_CONFIG] + with patch.object(svc, "_fetch_all", side_effect=slow_refresh): + caller = asyncio.create_task(svc.get_all_prices()) + await started.wait() + caller.cancel() + with self.assertRaises(asyncio.CancelledError): + await caller + self.assertFalse(svc._refresh_task.done()) + release.set() + await asyncio.wait_for(svc._refresh_task, timeout=1) + self.assertEqual(svc.cache_readiness()["status"], "ready") + + async def test_explicit_cors_allowlist(self): + try: + with patch.dict(os.environ, {"ALLOWED_ORIGINS": " https://preview.example.com , https://commoditychain.vercel.app "}): + importlib.reload(main) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=main.app), base_url="http://test" + ) as client: + allowed = await client.get("/api/health", headers={"Origin": "https://preview.example.com"}) + denied = await client.get("/api/health", headers={"Origin": "https://other.example.com"}) + self.assertEqual(allowed.headers.get("access-control-allow-origin"), "https://preview.example.com") + self.assertNotIn("access-control-allow-origin", denied.headers) + finally: + importlib.reload(main) diff --git a/docs/render-migration.md b/docs/render-migration.md new file mode 100644 index 0000000..548ae01 --- /dev/null +++ b/docs/render-migration.md @@ -0,0 +1,66 @@ +# Render Free migration — staged verification (#17) + +The Azure deployment is currently blocked by an OIDC identity mismatch at the Azure login step. This candidate does not modify or disable the Azure workflow, change Vercel production variables, or create paid infrastructure. Keep the migration issue open until runtime verification and cutover are complete. + +## 1. Create the candidate service (before merging) + +1. Sign in at https://dashboard.render.com and connect your GitHub account. +2. Create a Blueprint from ayushcmd/commoditychain. Select the branch `infra/issue-17-render-migration` and the root `render.yaml` file. Review the resource list; it should contain exactly one Free web service, no database or paid resources. Confirm the branch is the PR branch, not main. Automatic service deploys are off during verification. +3. If the Blueprint setup cannot select the branch, create a Web Service manually using that branch and these identical settings: + +| Setting | Value | +| --- | --- | +| Runtime | Python | +| Region | Singapore (or an available free region if configuring manually) | +| Plan | Free | +| Root Directory | backend | +| Build | pip install -r requirements.txt | +| Start | uvicorn main:app --host 0.0.0.0 --port $PORT --workers 1 --timeout-graceful-shutdown 10 | +| Health check | /api/health | +| Auto-Deploy | Off | +| PYTHON_VERSION | 3.11.9 | +| ALLOWED_ORIGINS | https://commoditychain.vercel.app | + +4. In Render Environment, add GROQ_API_KEY and NEWS_API_KEY privately if available and appropriate for your provider plans. Both are optional for price service startup. Yahoo Finance and the existing FX endpoint do not require these keys. Do not paste keys in source, logs, or issue comments. The AI and news functionality require valid provider configuration; API quota/plan restrictions still apply. +5. Deploy the PR branch. Copy the actual assigned HTTPS URL from the Render Dashboard. Do not assume a particular hostname. + +## 2. Verify process and data readiness + +Set BASE to the actual service origin (no trailing slash), e.g. on a Unix shell: + +```sh +BASE=https://YOUR-ACTUAL-SERVICE.onrender.com +curl -i --max-time 120 "$BASE/api/health" +curl -i --max-time 30 "$BASE/api/ready" +curl -fsS --max-time 30 "$BASE/api/prices" +curl -i --max-time 30 -H "Origin: https://commoditychain.vercel.app" "$BASE/api/health" +``` + +- Liveness: HTTP 200 with status ok. This only establishes that the process can serve requests; Render uses this check so upstream failures don't cause restart loops. +- Readiness: HTTP 503 while warming or with zero complete genuine price records. HTTP 200 with ready/degraded once at least one usable provider or explicitly stale quote exists. Inspect counts and timestamps; HTTP 200 alone is not sufficient to approve migration. Readiness never calls the provider. +- Prices: expect configured commodity identities, explicit source/dataStatus/isSimulated fields and real source timestamps. Unavailable records are null, never fake prices. Check that genuine quotes render and that symbols/units match the intended instruments. A stale quote may be expected outside trading hours. +- HTTP CORS: the allowed origin receives its matching access-control-allow-origin header. Add the exact Vercel preview URL origin to ALLOWED_ORIGINS for preview testing (comma-separated). Do not broadly allow all Vercel subdomains. CORS is not authentication and does not restrict direct API clients or WebSockets. +- Check /docs, /api/news?commodity=gold (requires key for articles), /api/rates and a small analyst request if configured. See /docs for request schemas. Inspect provider status rather than assuming a successful HTTP response means data is correct. +- Connect to wss://YOUR-ACTUAL-SERVICE.onrender.com/ws/prices using a WebSocket client; verify a JSON quote array arrives and subsequent snapshots arrive, and reply {"pong":true} to application pings. Test disconnect/reconnect. Run a browser preview test as described below. + +Startup schedules warmup without blocking ASGI startup. Each quote request waits at most eight seconds for the process-local shared refresh, then returns explicitly stale cached quotes or unavailable records. The upstream task continues; the next request can obtain completed data. Cancelling one caller does not cancel the shared refresh. Shutdown cancels asyncio tasks, but cannot forcibly stop an already running synchronous yfinance thread. Upstream requests remain sequential with existing provider timeouts; bounded worker pools, history cache and backoff remain issue #5. + +## 3. Vercel preview only + +- Use a Preview environment override scoped to the migration branch, or a separate temporary preview project if branch-specific environment variables are unavailable. +- Set NEXT_PUBLIC_API_URL to the actual Render HTTPS origin, with no trailing slash. Set NEXT_PUBLIC_WS_URL to the same origin using wss:// (or remove the override to derive it automatically). Do not include /api or /ws/prices in these base URLs. +- Add the exact preview origin to Render ALLOWED_ORIGINS. Redeploy that preview; Next.js public environment variables are embedded at build time. +- Verify dashboard, Explorer, charts, alerts, watchlist, exports, news, analyst, and HTTP fallback in browser developer tools. Check both REST and WS payloads and cold-start behavior after normal inactivity. Do not configure artificial keepalive jobs. +- Leave production Vercel variables and the Azure workflow as-is until all verification succeeds. + +## 4. Cutover and rollback (separate approval) + +After CI and the candidate runtime checks pass, review/merge the PR with owner approval. Point the Render service/Blueprint to main; remove obsolete branch-specific staging overrides as appropriate and verify the main commit before enabling automatic deploys. Do not delete the staging branch until this transition succeeds. Update production Vercel URL variables, redeploy, and verify again. Only after stable production verification, separately approve disabling Azure deployment and any Azure resource cleanup. Save old production variables for rollback; note that the current Azure deployment is blocked, so reverting its URL alone may not restore service. + +## Free-tier limitations + +Render Free is a hobby/testing tier (512 MB, shared CPU). It can sleep after 15 minutes without inbound traffic, with wake-up taking about a minute, and has an ephemeral filesystem, 750 instance hours per workspace/month, bandwidth/build allowances and outbound-traffic restrictions. A persistent WebSocket may keep the instance active if it receives inbound messages; this is normal client traffic, not an uptime guarantee. Cold starts may exceed the frontend's existing 45-second HTTP deadline; the fallback transport retries. Cache is process-local and lost on restart. One Uvicorn worker avoids duplicated caches and unnecessary memory. Verify actual provider access and memory usage; do not assume Yahoo Finance accepts Render IPs or that NewsAPI permits production use. Render docs: https://render.com/docs/free ; https://render.com/docs/blueprint-spec ; https://render.com/docs/health-checks ; https://render.com/docs/websocket . + +## Automated checks + +Run `cd backend && python -m unittest discover -s tests -v` after installing requirements. The existing PR workflow also runs frontend transport tests, TypeScript and build. Mocked tests do not prove cloud deployment success. The migration remains unverified until the candidate is deployed and tested. diff --git a/render.yaml b/render.yaml new file mode 100644 index 0000000..0eb72f7 --- /dev/null +++ b/render.yaml @@ -0,0 +1,20 @@ +# Candidate backend only. Azure remains untouched until verified. +# Select the migration branch when creating the Blueprint; no hardcoded branch. +services: + - type: web + name: commoditychain-api + runtime: python + plan: free + region: singapore + rootDir: backend + buildCommand: pip install -r requirements.txt + startCommand: uvicorn main:app --host 0.0.0.0 --port $PORT --workers 1 --timeout-graceful-shutdown 10 + healthCheckPath: /api/health + autoDeployTrigger: 'off' + envVars: + - key: PYTHON_VERSION + value: "3.11.9" + - key: ALLOWED_ORIGINS + value: https://commoditychain.vercel.app + # Add optional GROQ_API_KEY and NEWS_API_KEY manually in Render's + # Environment page. Never put their values in the repository.