Spaces:
Paused
Paused
Download apps/renderer/services/access/usage.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 3.97 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/access/usage.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/access/usage.py
-
curl -L -o usage.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/access/usage.py
3.97 kB
| """Free tries for Prevision accounts, charged when a job is accepted. | |
| The renderer has no database: the Prevision API (apps/prevision-api, same pod) | |
| keeps the count. A job from a Prevision token is only accepted after that API | |
| records the try (or answers 402 when none are left); a job that then fails on | |
| our side gets its try back. Only authenticated Prevision principals can consume the allowance. | |
| Calls are authorized with a short HS256 token signed with the shared | |
| PROCESSING_TOKEN_SECRET for the Prevision internal audience. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| import jwt | |
| from fastapi import HTTPException | |
| from config.auth import PREVISION_API_INTERNAL_URL, PREVISION_INTERNAL_AUDIENCE, PROCESSING_TOKEN_SECRET | |
| from services.access.policy import Principal | |
| logger = logging.getLogger(__name__) | |
| TIMEOUT_SECONDS = 5 | |
| REFUND_ATTEMPTS = 3 | |
| def _internal_token() -> str: | |
| now = int(time.time()) | |
| return jwt.encode( | |
| {"aud": PREVISION_INTERNAL_AUDIENCE, "iat": now, "exp": now + 60}, | |
| PROCESSING_TOKEN_SECRET, | |
| algorithm="HS256", | |
| ) | |
| def _post(path: str, body: dict | None = None) -> tuple[int, dict]: | |
| request = urllib.request.Request( | |
| f"{PREVISION_API_INTERNAL_URL}{path}", | |
| data=json.dumps(body or {}).encode(), | |
| method="POST", | |
| headers={"Authorization": f"Bearer {_internal_token()}", "Content-Type": "application/json"}, | |
| ) | |
| try: | |
| with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: | |
| raw = response.read() | |
| return response.status, json.loads(raw) if raw else {} | |
| except urllib.error.HTTPError as error: | |
| try: | |
| return error.code, json.loads(error.read() or b"{}") | |
| except ValueError: | |
| return error.code, {} | |
| def charge_free_try(principal: Principal | None, job_id: str) -> str | None: | |
| """Use one free try for this job before it is accepted. Returns the generation id to refund on failure. | |
| Blocking: call it from a worker thread. | |
| """ | |
| if principal is None or not principal.has_free_tries: | |
| return None | |
| try: | |
| status, body = _post("/internal/generations", {"userId": principal.user_id, "jobId": job_id}) | |
| except (urllib.error.URLError, TimeoutError, OSError) as exc: | |
| logger.error("Could not reach the Prevision API to charge a try: %s", exc) | |
| raise HTTPException(status_code=503, detail="The visualizer is busy. Please try again in a moment.") from exc | |
| if status == 201: | |
| return body["data"]["generationId"] | |
| if status == 402: | |
| # The API's reason (NO_FREE_TRIES or PLAN_LIMIT_REACHED) travels in a header, so the | |
| # detail stays the plain message existing clients show. | |
| code = str(((body or {}).get("error") or {}).get("code") or "NO_FREE_TRIES") | |
| raise HTTPException( | |
| status_code=402, detail="You've used all your free visualizations.", headers={"X-Error-Code": code}, | |
| ) | |
| logger.error("Prevision API refused to charge a try: HTTP %s %s", status, body) | |
| raise HTTPException(status_code=503, detail="The visualizer is busy. Please try again in a moment.") | |
| def refund_free_try(generation_id: str | None) -> None: | |
| """Give the try back after our own failure. Best effort, never raises.""" | |
| if not generation_id: | |
| return | |
| for attempt in range(1, REFUND_ATTEMPTS + 1): | |
| try: | |
| status, _ = _post(f"/internal/generations/{generation_id}/refund") | |
| if status == 204: | |
| return | |
| logger.warning("Refund of generation %s answered HTTP %s", generation_id, status) | |
| except (urllib.error.URLError, TimeoutError, OSError) as exc: | |
| logger.warning("Refund of generation %s failed (attempt %s): %s", generation_id, attempt, exc) | |
| time.sleep(attempt) | |
| logger.error("Gave up refunding generation %s", generation_id) | |