from sqlalchemy import select,func from .models import Job,User,Asset,utcnow from datetime import timedelta import shutil import asyncio from .v2_models import QuotaReservation from .errors import fail CREATION_OPERATIONS={"jobs.create","workflow.run","batch.create"} async def reserve_budget(session,owner_id,operation,units=1,bytes_reserved=0,settings=None): owner=await session.scalar(select(User).where(User.id==owner_id).with_for_update()) if owner is None or owner.disabled:fail(403,"owner_disabled","Owner is disabled") if operation in CREATION_OPERATIONS: recent=await session.scalar(select(func.count()).select_from(QuotaReservation).where(QuotaReservation.owner_id==owner_id,QuotaReservation.operation.in_(CREATION_OPERATIONS),QuotaReservation.created_at>utcnow()-timedelta(minutes=1))) if recent>=getattr(settings,"max_creation_commands_per_minute",6):fail(429,"quota_exceeded","Creation rate limit reached") active=Job.state.notin_(["succeeded","failed","cancelled","timed_out"]) own=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==owner_id,active)) total=await session.scalar(select(func.count()).select_from(Job).where(active)) if own+units>getattr(settings,"max_owner_jobs",500) or total+units>getattr(settings,"max_global_jobs",2000): fail(429,"quota_exceeded","Unfinished task quota exceeded") row=QuotaReservation(owner_id=owner_id,operation=operation,units=units,bytes_reserved=bytes_reserved) session.add(row) return row async def check_parent_capacity(session,settings,owner_id,kind): from .v2_models import WorkflowRun,Batch model,terminal,owner_limit,global_limit=(WorkflowRun,{'succeeded','cancelled','failed'},settings.max_owner_runs,settings.max_global_runs) if kind=='run' else (Batch,{'succeeded','cancelled','completed_with_errors'},settings.max_owner_batches,settings.max_global_batches) active=model.state.notin_(terminal) own=await session.scalar(select(func.count()).select_from(model).where(model.owner_id==owner_id,active)) total=await session.scalar(select(func.count()).select_from(model).where(active)) if own>=owner_limit or total>=global_limit: fail(429,'quota_exceeded','Queued workflow or batch limit reached') async def check_storage_budget(session,settings,owner_id,incoming_bytes=0,new_jobs=0,global_incoming_bytes=None): size=await session.scalar(select(func.coalesce(func.sum(Asset.size_bytes),0)).where( Asset.owner_id==owner_id,Asset.ready.is_(True)|Asset.deleted_at.is_(None))) if size+incoming_bytes>getattr(settings,"max_owner_asset_bytes",100*1024**3):fail(429,"quota_exceeded","Owner asset quota exceeded") if settings.mode=="production": storage_incoming=incoming_bytes if global_incoming_bytes is None else global_incoming_bytes # Account only this application's mounted assets/work directories. The # independent model service owns its raw output retention policy. def occupied(root): total=0 for path in root.rglob("*"): if path.is_file() and not path.is_symlink(): total+=path.stat().st_size return total tmp=(settings.asset_root.parent/"tmp").resolve() if not tmp.is_relative_to(settings.workspace_root):raise ValueError("Temporary storage is outside workspace") roots={settings.asset_root.resolve(),settings.job_work_root.resolve(),tmp} # Avoid counting a nested custom mount twice. roots=[root for root in roots if not any(root!=other and root.is_relative_to(other) for other in roots)] actual=sum(await asyncio.gather(*(asyncio.to_thread(occupied,root) for root in roots))) active=await session.scalar(select(func.count()).select_from(Job).where(Job.state.notin_(["succeeded","failed","cancelled","timed_out"]))) reserved=(active+new_jobs)*settings.max_output_bytes*2 if actual+reserved+storage_incoming>getattr(settings,"max_data_bytes",2*1024**4):fail(503,"storage_insufficient","Application output and temporary storage budget exceeded") disk=shutil.disk_usage(settings.asset_root) minimum=max(getattr(settings,"min_free_bytes",50*1024**3),int(disk.total*.05)) if disk.free-reserved-storage_incominggetattr(settings,"max_owner_asset_bytes",100*1024**3):raise AssetBudgetError()