algospaced-dsa / routers /challenges.py
iamfebin's picture
feat: player economy, item catalog, vault inventory, and companion gifting
aa1fcca
Raw History Blame Contribute Delete
12.6 kB
import asyncio
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel
import ai_cache
import db
import llm_reviewer
import sandbox
import sql_playground
from core.auth import Client, get_auth_session
from core.limiter import check_burst_rate_limit
router = APIRouter(tags=["challenges"])
DAILY_PYTHON_CHALLENGE_CACHE = {} # maps YYYY-MM-DD to challenge dict
ACTIVE_SQL_CHALLENGES = {} # maps user_id to active challenge dict
class SubmitPythonRequest(BaseModel):
code: str
@router.get("/api/challenges/python/daily")
async def get_daily_python_challenge(
request: Request,
client: Client = Depends(get_auth_session),
x_ai_provider: str = Header(None),
x_custom_api_key: str = Header(None),
x_gemini_api_key: str = Header(None),
):
api_key = x_custom_api_key or x_gemini_api_key
check_burst_rate_limit(request, api_key)
challenge = await llm_reviewer.generate_daily_python_challenge_async(
custom_api_key=api_key, custom_provider=x_ai_provider
)
if "error" in challenge:
raise HTTPException(
status_code=500, detail=f"Failed to generate challenge: {challenge['error']}"
)
today_str = datetime.now(UTC).strftime("%Y-%m-%d")
DAILY_PYTHON_CHALLENGE_CACHE[today_str] = challenge
user_id = await asyncio.to_thread(db.get_current_user_id, client)
completed = False
if user_id:
try:
completed = await asyncio.to_thread(
db.has_completed_challenge, "python", challenge.get("title", ""), client
)
except Exception:
pass
score_record = await asyncio.to_thread(db.get_user_score, client)
total_score = score_record["total_score"] if score_record else 0
return {
"title": challenge.get("title"),
"description": challenge.get("description"),
"difficulty": challenge.get("difficulty"),
"points": challenge.get("points"),
"starter_code": challenge.get("starter_code"),
"completed": completed,
"total_score": total_score,
}
@router.post("/api/challenges/python/submit")
async def submit_python_challenge(
req: SubmitPythonRequest, client: Client = Depends(get_auth_session)
):
today_str = datetime.now(UTC).strftime("%Y-%m-%d")
if today_str not in DAILY_PYTHON_CHALLENGE_CACHE:
challenge = await llm_reviewer.generate_daily_python_challenge_async()
if "error" in challenge:
raise HTTPException(
status_code=500, detail=f"No challenge available: {challenge['error']}"
)
DAILY_PYTHON_CHALLENGE_CACHE[today_str] = challenge
challenge = DAILY_PYTHON_CHALLENGE_CACHE[today_str]
test_cases = challenge.get("test_cases", [])
run_res = await sandbox.run_python_sandbox_async(req.code, test_cases)
if not run_res.get("success", False):
return {
"success": False,
"error": run_res.get("error", "Unknown execution error"),
"sandbox_type": run_res.get("sandbox_type"),
}
results = run_res.get("results", [])
all_passed = len(results) > 0 and all(r.get("status") == "passed" for r in results)
points_awarded = 0
completed_before = False
total_score = 0
user_id = await asyncio.to_thread(db.get_current_user_id, client)
if all_passed and user_id:
title = challenge.get("title", "Daily Python Challenge")
points = challenge.get("points", 100)
try:
completed_before = await asyncio.to_thread(
db.has_completed_challenge, "python", title, client
)
except Exception:
pass
if not completed_before:
await asyncio.to_thread(db.increment_user_score, points, "python", client)
await asyncio.to_thread(db.add_challenge_history, "python", title, points, client)
points_awarded = points
score_record = await asyncio.to_thread(db.get_user_score, client)
if score_record:
total_score = score_record["total_score"]
if all_passed:
gold_awarded = 100
curr = await asyncio.to_thread(db.increment_user_gold, 100, client)
new_balance = curr.get("gold", 100) if curr else 100
else:
gold_awarded = 0
curr = await asyncio.to_thread(db.get_user_currency, client)
new_balance = curr.get("gold", 0) if curr else 0
return {
"success": True,
"all_passed": all_passed,
"results": results,
"points_awarded": points_awarded,
"completed_before": completed_before,
"total_score": total_score,
"gold_awarded": gold_awarded,
"new_balance": new_balance,
"sandbox_type": run_res.get("sandbox_type"),
"sandbox_warning": run_res.get("sandbox_warning"),
}
class SQLQueryRequest(BaseModel):
query: str
@router.post("/api/challenges/mysql/init")
async def init_mysql_challenge(
request: Request,
refresh: bool = False,
client: Client = Depends(get_auth_session),
x_ai_provider: str = Header(None),
x_custom_api_key: str = Header(None),
x_gemini_api_key: str = Header(None),
):
user_id = await asyncio.to_thread(db.get_current_user_id, client)
if not user_id:
raise HTTPException(status_code=401, detail="Authentication failed")
api_key = x_custom_api_key or x_gemini_api_key
check_burst_rate_limit(request, api_key)
challenge = await llm_reviewer.generate_sql_challenge_async(
custom_api_key=api_key, custom_provider=x_ai_provider, force_refresh=refresh
)
if "error" in challenge:
raise HTTPException(
status_code=500, detail=f"Failed to generate SQL challenge: {challenge['error']}"
)
init_res = await asyncio.to_thread(sql_playground.init_user_db, user_id, challenge)
if not init_res.get("success", False):
raise HTTPException(
status_code=500, detail=f"Failed to initialize database: {init_res.get('error')}"
)
ACTIVE_SQL_CHALLENGES[user_id] = challenge
score_record = await asyncio.to_thread(db.get_user_score, client)
total_score = score_record["total_score"] if score_record else 0
return {
"success": True,
"title": challenge.get("title"),
"objective": challenge.get("objective"),
"points": challenge.get("points"),
"schema": init_res.get("schema"),
"challenge_type": challenge.get("challenge_type"),
"total_score": total_score,
}
@router.get("/api/challenges/mysql/status")
async def get_mysql_status(
request: Request,
client: Client = Depends(get_auth_session),
x_ai_provider: str = Header(None),
x_custom_api_key: str = Header(None),
x_gemini_api_key: str = Header(None),
):
user_id = await asyncio.to_thread(db.get_current_user_id, client)
if not user_id:
raise HTTPException(status_code=401, detail="Authentication failed")
if user_id not in ACTIVE_SQL_CHALLENGES:
today_str = datetime.now(UTC).strftime("%Y-%m-%d")
challenge = await ai_cache.get_daily_sql_challenge_async(today_str)
if not challenge or not isinstance(challenge, dict) or "title" not in challenge:
api_key = x_custom_api_key or x_gemini_api_key
challenge = await llm_reviewer.generate_sql_challenge_async(
custom_api_key=api_key, custom_provider=x_ai_provider, force_refresh=False
)
if challenge and "title" in challenge:
init_res = await asyncio.to_thread(sql_playground.init_user_db, user_id, challenge)
if init_res.get("success", False):
ACTIVE_SQL_CHALLENGES[user_id] = challenge
else:
return {
"active": False,
"message": "No active SQL session. Please initialize with 'db init'.",
}
else:
return {
"active": False,
"message": "No active SQL session. Please initialize with 'db init'.",
}
challenge = ACTIVE_SQL_CHALLENGES[user_id]
schema = {}
try:
def _get_schema():
conn = sql_playground.get_connection(user_id)
try:
return sql_playground.get_db_schema(conn)
finally:
conn.close()
schema = await asyncio.to_thread(_get_schema)
except Exception:
pass
completed = False
try:
completed = await asyncio.to_thread(
db.has_completed_challenge, "mysql", challenge.get("title", ""), client
)
except Exception:
pass
score_record = await asyncio.to_thread(db.get_user_score, client)
total_score = score_record["total_score"] if score_record else 0
return {
"active": True,
"title": challenge.get("title"),
"objective": challenge.get("objective"),
"points": challenge.get("points"),
"challenge_type": challenge.get("challenge_type"),
"schema": schema,
"completed": completed,
"total_score": total_score,
}
@router.post("/api/challenges/mysql/query")
async def run_mysql_query(req: SQLQueryRequest, client: Client = Depends(get_auth_session)):
user_id = await asyncio.to_thread(db.get_current_user_id, client)
if not user_id:
raise HTTPException(status_code=401, detail="Authentication failed")
if user_id not in ACTIVE_SQL_CHALLENGES:
today_str = datetime.now(UTC).strftime("%Y-%m-%d")
cached_challenge = await ai_cache.get_daily_sql_challenge_async(today_str)
if cached_challenge and isinstance(cached_challenge, dict) and "title" in cached_challenge:
ACTIVE_SQL_CHALLENGES[user_id] = cached_challenge
else:
raise HTTPException(
status_code=400, detail="No active SQL session. Type 'db init' first."
)
challenge = ACTIVE_SQL_CHALLENGES[user_id]
run_res = await asyncio.to_thread(sql_playground.run_user_query, user_id, req.query, challenge)
if not run_res.get("success", False):
return {"success": False, "error": run_res.get("error", "Unknown database error")}
is_correct = run_res.get("is_correct", False)
points_awarded = 0
completed_before = False
total_score = 0
if is_correct:
title = challenge.get("title", "SQL Challenge")
points = challenge.get("points", 150)
try:
completed_before = await asyncio.to_thread(
db.has_completed_challenge, "mysql", title, client
)
except Exception:
pass
if not completed_before:
await asyncio.to_thread(db.increment_user_score, points, "mysql", client)
await asyncio.to_thread(db.add_challenge_history, "mysql", title, points, client)
points_awarded = points
score_record = await asyncio.to_thread(db.get_user_score, client)
if score_record:
total_score = score_record["total_score"]
if is_correct:
gold_awarded = 100
curr = await asyncio.to_thread(db.increment_user_gold, 100, client)
new_balance = curr.get("gold", 100) if curr else 100
else:
gold_awarded = 0
curr = await asyncio.to_thread(db.get_user_currency, client)
new_balance = curr.get("gold", 0) if curr else 0
return {
"success": True,
"is_correct": is_correct,
"columns": run_res.get("columns", []),
"rows": run_res.get("rows", []),
"rows_affected": run_res.get("rows_affected", 0),
"schema": run_res.get("schema", {}),
"points_awarded": points_awarded,
"completed_before": completed_before,
"total_score": total_score,
"gold_awarded": gold_awarded,
"new_balance": new_balance,
}
@router.get("/api/scores")
async def get_user_scores(client: Client = Depends(get_auth_session)):
def _fetch_scores():
user_id = db.get_current_user_id(client)
score_data = db.get_user_score(client)
return score_data or {
"user_id": user_id,
"total_score": 0,
"python_challenges_completed": 0,
"sql_challenges_completed": 0,
}
return await asyncio.to_thread(_fetch_scores)
@router.get("/api/scores/history")
async def get_user_challenge_history(client: Client = Depends(get_auth_session)):
return await asyncio.to_thread(db.get_challenge_history, client)