# app.py — Hugging Face Space entrypoint (FastAPI + background indexer) import os import threading import time from src.api import app as fastapi_app from src.indexer import realtime_loop from src.db import init_db # ---------------------------------------------------------------------- # Default environment variables (override via HF Space Secrets/Settings) # ---------------------------------------------------------------------- os.environ.setdefault("POLYGON_RPC", "https://polygon-rpc.com/") os.environ.setdefault("DB_PATH", "/tmp/pol_indexer.sqlite") os.environ.setdefault("SCHEMA_PATH", "/tmp/schema.sql") os.environ.setdefault("CONFIRMATIONS", "12") # ---------------------------------------------------------------------- # Indexer background loop wrapper # ---------------------------------------------------------------------- def _run_indexer_forever(): """Run the indexer loop forever with auto-retry on crash.""" while True: try: print("[Indexer] Starting realtime loop...") realtime_loop() # <- if your loop takes args, pass them here except Exception as e: print(f"[Indexer] crashed with error: {e}") time.sleep(10) # ---------------------------------------------------------------------- # FastAPI app served by Hugging Face # ---------------------------------------------------------------------- app = fastapi_app @app.on_event("startup") def _startup(): """Initialize DB schema and launch the indexer thread.""" try: init_db() # make sure schema and tables exist except Exception as e: print(f"[Startup] init_db failed: {e}") t = threading.Thread( target=_run_indexer_forever, name="IndexerThread", daemon=True ) t.start() print("[Startup] Indexer background thread launched")