"""Visitor limits for the public site, so one visitor can't take the GPU from everyone else or use up the free monthly GPU credit. Running locally (not public) nothing is limited. The numbers come from `public:` in the config file (PublicLimits in settings.py). """ from __future__ import annotations import threading from collections.abc import Iterator from contextlib import contextmanager from datetime import timedelta from fastapi import HTTPException from sqlmodel import Session, col, func, or_, select from stemdeck.models import ACTIVE_JOB_STATUSES, Job, Song, Usage, utcnow from stemdeck.settings import get_config, get_settings WINDOW = timedelta(hours=24) # Checking the limits and inserting the job happen under this lock, so parallel requests can't all pass the # check before any of them is counted (the public site runs one server process). _admission = threading.Lock() def _count(session: Session, statement: object) -> int: return int(session.exec(statement).one()) # type: ignore[call-overload] def check_can_start(session: Session, owner: str, client: str, *, new_song: bool) -> None: """Raise an HTTPException with a friendly message when this visitor may not start another job now.""" if not get_settings().public: return limits = get_config().public active = _count(session, select(func.count()).select_from(Job).join(Song, col(Job.song_id) == col(Song.id)) .where(or_(Song.owner == owner, Song.client == client), col(Job.status).in_(ACTIVE_JOB_STATUSES))) if active >= limits.max_active_jobs_per_visitor: raise HTTPException(429, "You already have a song processing. Wait for it to finish, then start the next.") if new_song: songs = _count(session, select(func.count()).select_from(Song).where(Song.owner == owner)) if songs >= limits.max_songs_per_visitor: raise HTTPException(409, f"Your library is full ({limits.max_songs_per_visitor} songs on this free " "site). Delete a song first.") since = utcnow() - WINDOW mine = _count(session, select(func.count()).select_from(Usage).where( col(Usage.created_at) >= since, or_(Usage.owner == owner, Usage.client == client))) if mine >= limits.jobs_per_visitor_per_day: raise HTTPException(429, f"You've used today's {limits.jobs_per_visitor_per_day} free jobs on this site. " "Try again tomorrow.") everyone = _count(session, select(func.count()).select_from(Usage).where(col(Usage.created_at) >= since)) if everyone >= limits.jobs_per_day: raise HTTPException(503, "This free site has used up today's processing time. Try again tomorrow.") queued = _count(session, select(func.count()).select_from(Job).where(Job.status == "queued")) if queued >= limits.max_queued_jobs: raise HTTPException(503, "The site is busy right now. Try again in a few minutes.") @contextmanager def admit(session: Session, owner: str, client: str, kind: str, *, new_song: bool) -> Iterator[None]: """Check the limits, let the caller insert its job, then count it, all under one lock (public site only). Raises HTTPException like check_can_start; when the caller's block raises, nothing is counted.""" if not get_settings().public: yield return with _admission: check_can_start(session, owner, client, new_song=new_song) yield session.add(Usage(owner=owner, client=client, kind=kind)) session.commit() def purge_old_usage(session: Session) -> int: """Forget usage older than the limits look at. Returns how many rows were removed.""" old = session.exec(select(Usage).where(col(Usage.created_at) < utcnow() - 2 * WINDOW)).all() for row in old: session.delete(row) session.commit() return len(old)