218 lines
11 KiB
Python
218 lines
11 KiB
Python
from datetime import datetime, timezone
|
||
import hashlib
|
||
import json
|
||
from fastapi import APIRouter, Depends, Header, Request
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import func, select
|
||
from sqlalchemy.exc import IntegrityError
|
||
from .assets import owned_asset
|
||
from .auth import Actor, csrf_actor, current_actor
|
||
from .dto import job_dto
|
||
from .errors import fail
|
||
from .events import emit_job
|
||
from .models import Event, Job, JobAsset, new_id, utcnow
|
||
|
||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||
GPU_TYPES = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"}
|
||
CPU_TYPES = {"math.solve", "media.structure", "video.compose", "audio.speech"}
|
||
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
|
||
|
||
|
||
class Submit(BaseModel):
|
||
task_type: str
|
||
input: dict = Field(default_factory=dict)
|
||
parameters: dict = Field(default_factory=dict)
|
||
count: int = Field(default=1, ge=1, le=4)
|
||
scheduled_at: datetime | None = None
|
||
|
||
|
||
async def owned_job(session, job_id, owner_id):
|
||
job = await session.scalar(select(Job).where(Job.id == job_id, Job.owner_id == owner_id))
|
||
if job is None:
|
||
fail(404, "job_not_found", "任务不存在")
|
||
return job
|
||
|
||
|
||
def input_ids(inputs, parameters):
|
||
result = []
|
||
for field in ("image_asset_id", "audio_asset_id", "asset_id"):
|
||
if inputs.get(field):
|
||
result.append(inputs[field])
|
||
if inputs.get("asset_ids"):
|
||
if not isinstance(inputs["asset_ids"], list):
|
||
fail(422, "invalid_assets", "asset_ids 必须为素材编号列表")
|
||
result.extend(inputs["asset_ids"])
|
||
for clip in parameters.get("clips", []):
|
||
if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str):
|
||
fail(422, "invalid_clip", "每个片段需要素材编号")
|
||
result.append(clip["asset_id"])
|
||
if parameters.get("audio_asset_id"):
|
||
result.append(parameters["audio_asset_id"])
|
||
if any(not isinstance(value, str) or len(value) > 64 for value in result):
|
||
fail(422, "invalid_assets", "素材编号格式不正确")
|
||
return list(dict.fromkeys(result))
|
||
|
||
|
||
async def validate_submission(session, body, owner_id, settings):
|
||
if body.task_type not in GPU_TYPES | CPU_TYPES:
|
||
fail(422, "unsupported_task", "不支持此任务类型")
|
||
allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"}
|
||
if set(body.input) - allowed:
|
||
fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL")
|
||
if body.count > 1 and body.task_type not in {"image.generate", "defect.generate"}:
|
||
fail(422, "batch_not_supported", "此任务类型不支持批量生成")
|
||
if body.task_type == "audio.speech" and not settings.tts_base_url:
|
||
fail(422, "speech_unavailable", "尚未配置真实配音服务")
|
||
from .providers import ProviderError, validate_arguments
|
||
try:
|
||
validate_arguments(body.task_type, body.input, body.parameters, settings)
|
||
except ProviderError as exc:
|
||
fail(400, exc.code, exc.message)
|
||
prompt = body.input.get("prompt", "")
|
||
if not isinstance(prompt, str) or len(prompt) > 8000:
|
||
fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本")
|
||
if body.task_type in {"image.generate", "video.generate", "defect.generate", "math.solve", "audio.speech"} and not prompt.strip():
|
||
fail(422, "prompt_required", "请输入提示词或文本")
|
||
ids = input_ids(body.input, body.parameters)
|
||
assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids}
|
||
required = {"defect.generate": "image_asset_id", "audio.transcribe": "audio_asset_id", "media.structure": "asset_id"}
|
||
if body.task_type in required:
|
||
key = required[body.task_type]
|
||
value = body.input.get(key) or (body.input.get("asset_id") if key == "audio_asset_id" else None)
|
||
if not value:
|
||
fail(422, "asset_required", "此任务需要输入素材")
|
||
for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})):
|
||
if body.input.get(key) and assets[body.input[key]].kind not in kinds:
|
||
fail(422, "wrong_asset_kind", "输入素材类型不正确")
|
||
if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {"image", "video"}:
|
||
fail(422, "wrong_asset_kind", "素材理解需要图片或视频")
|
||
if body.task_type == "audio.transcribe":
|
||
source_id = body.input.get("audio_asset_id") or body.input.get("asset_id")
|
||
if assets[source_id].kind not in {"audio", "video"}:
|
||
fail(422, "wrong_asset_kind", "转写需要音频或视频素材")
|
||
if body.task_type == "video.compose" and not ids:
|
||
fail(422, "clips_required", "请添加待合成片段")
|
||
if body.task_type == "video.compose":
|
||
if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])):
|
||
fail(422, "wrong_asset_kind", "编排片段必须为视频素材")
|
||
audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id")
|
||
if audio_id and assets[audio_id].kind != "audio":
|
||
fail(422, "wrong_asset_kind", "成片音轨必须为音频素材")
|
||
if body.scheduled_at is not None and body.scheduled_at.tzinfo is None:
|
||
fail(422, "timezone_required", "定时任务时间须包含时区")
|
||
return ids
|
||
|
||
|
||
async def create_jobs(session, body, actor, settings, key=None):
|
||
if key is not None and not 1 <= len(key) <= 128:
|
||
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
|
||
payload = body.model_dump(mode="json")
|
||
try:
|
||
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
|
||
allow_nan=False).encode()).hexdigest()
|
||
except (ValueError, TypeError):
|
||
fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON")
|
||
if key:
|
||
existing = (await session.scalars(select(Job).where(Job.owner_id == actor.id, Job.request_key == key)
|
||
.order_by(Job.batch_index))).all()
|
||
if existing:
|
||
if existing[0].request_hash != fingerprint:
|
||
fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数")
|
||
return existing
|
||
ids = await validate_submission(session, body, actor.id, settings)
|
||
scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None
|
||
jobs = []
|
||
for index in range(body.count):
|
||
job_id = new_id()
|
||
future = scheduled and scheduled > utcnow()
|
||
parameters = dict(body.parameters)
|
||
if body.count > 1:
|
||
parameters["seed"] = (parameters.get("seed", 42) + index) % (2 ** 32)
|
||
job = Job(id=job_id, owner_id=actor.id, task_type=body.task_type,
|
||
state="scheduled" if future else "submitting", phase="scheduled" if future else "waiting_dispatch",
|
||
version=1, input_json=body.input, parameters=parameters, request_key=key,
|
||
request_hash=fingerprint, batch_index=index, upstream_key="cmvr-visual:" + job_id,
|
||
scheduled_at=scheduled, next_action_at=scheduled if future else utcnow(),
|
||
attempt_count=0, work_attempt=0, preemptions=0, cancel_requested=False)
|
||
session.add(job)
|
||
await session.flush()
|
||
session.add_all(JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids)
|
||
await emit_job(session, job, increment=False)
|
||
jobs.append(job)
|
||
return jobs
|
||
|
||
|
||
def wake(request):
|
||
request.app.state.coordinator.wake()
|
||
|
||
|
||
@router.post("", status_code=202)
|
||
async def submit(body: Submit, request: Request, idempotency_key: str | None = Header(default=None),
|
||
actor: Actor = Depends(csrf_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
try:
|
||
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
|
||
await session.commit()
|
||
except IntegrityError:
|
||
await session.rollback()
|
||
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
|
||
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
||
wake(request)
|
||
return result
|
||
|
||
|
||
@router.get("")
|
||
async def list_jobs(request: Request, page: int = 1, page_size: int = 24, task_type: str = "", state: str = "",
|
||
actor: Actor = Depends(current_actor)):
|
||
if page < 1 or not 1 <= page_size <= 100:
|
||
fail(422, "invalid_page", "分页参数无效")
|
||
async with request.app.state.db.session() as session:
|
||
query = select(Job).where(Job.owner_id == actor.id)
|
||
if task_type:
|
||
query = query.where(Job.task_type == task_type)
|
||
if state:
|
||
query = query.where(Job.state == state)
|
||
total = await session.scalar(select(func.count()).select_from(query.subquery()))
|
||
jobs = (await session.scalars(query.order_by(Job.created_at.desc(), Job.id.desc())
|
||
.offset((page - 1) * page_size).limit(page_size))).all()
|
||
cursor = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0
|
||
return {"items": [await job_dto(session, job) for job in jobs], "total": total,
|
||
"page": page, "page_size": page_size, "cursor": cursor}
|
||
|
||
|
||
@router.get("/{job_id}")
|
||
async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
return await job_dto(session, await owned_job(session, job_id, actor.id))
|
||
|
||
|
||
@router.post("/{job_id}/cancel")
|
||
async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
job = await owned_job(session, job_id, actor.id)
|
||
if job.state not in TERMINAL and job.state != "collecting":
|
||
job.cancel_requested = True
|
||
if job.upstream_id is None and job.upstream_payload is None and job.phase not in {"cpu_running", "preparing"}:
|
||
job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow()
|
||
else:
|
||
job.state, job.phase = "cancelling", "cancellation_pending"
|
||
await emit_job(session, job)
|
||
await session.commit()
|
||
result = await job_dto(session, job)
|
||
wake(request)
|
||
return result
|
||
|
||
|
||
@router.post("/{job_id}/retry", status_code=202)
|
||
async def retry(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||
async with request.app.state.db.session() as session:
|
||
old = await owned_job(session, job_id, actor.id)
|
||
if old.state not in TERMINAL:
|
||
fail(409, "job_not_finished", "请先等待或取消当前任务")
|
||
body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters)
|
||
jobs = await create_jobs(session, body, actor, request.app.state.settings)
|
||
await session.commit()
|
||
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
||
wake(request)
|
||
return result
|