from sqlalchemy import select, func from app.models import Job, User, Asset, utcnow from datetime import timedelta import shutil import asyncio from app.models import QuotaReservation from app.core.errors import fail CREATION_OPERATIONS = { "jobs.create", "workflow.run", "editor.run", "batch.create", "story.candidate.create", "story.candidate.batch", "story.candidate.retry", "story.render", } 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 app.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 model is Batch: from app.models import ShotCandidate # 独立候选命令没有Batch行,以同次接纳的plan ID作为父计划;旧计划保守按候选计数。 group_id = func.coalesce( ShotCandidate.plan_json["parent_plan_id"].as_string(), ShotCandidate.id ) pending = ( ShotCandidate.deleted_at.is_(None), ShotCandidate.batch_id.is_(None), ShotCandidate.state.not_in({"ready", "failed"}), ) own += await session.scalar( select(func.count(func.distinct(group_id))).where( *pending, ShotCandidate.owner_id == owner_id ) ) total += await session.scalar(select(func.count(func.distinct(group_id))).where(*pending)) if own >= owner_limit or total >= global_limit: fail(429, "quota_exceeded", "Queued workflow or batch limit reached") async def check_story_candidate_capacity(session, settings, owner_id, units): from app.models import ShotCandidate # 持久计划与活动Job分别计数;一个大故事可以等待补队,不能按500个活动Job限额拒收。 pending = ( ShotCandidate.deleted_at.is_(None), ShotCandidate.job_id.is_(None), ShotCandidate.state.not_in({"ready", "failed"}), ) own = await session.scalar( select(func.count()) .select_from(ShotCandidate) .where(*pending, ShotCandidate.owner_id == owner_id) ) total = await session.scalar(select(func.count()).select_from(ShotCandidate).where(*pending)) if ( own + units > settings.max_owner_story_candidates or total + units > settings.max_global_story_candidates ): fail(429, "quota_exceeded", "Queued story candidate plan 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 ) 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} 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 * 0.05)) if disk.free - reserved - storage_incoming < minimum: fail(503, "storage_insufficient", "Insufficient reserved storage") class AssetBudgetError(ValueError): code = "quota_exceeded" message = "Owner asset storage quota exceeded; output retained for reconciliation" retriable = False async def enforce_owner_asset_budget(session, settings, owner_id, incoming_bytes): await session.scalar(select(User).where(User.id == owner_id).with_for_update()) 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): raise AssetBudgetError()