cmvr-visual/backend/app/submissions.py

86 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Durable intent records; callers commit the record and resource in one transaction."""
import hashlib
import json
from fastapi import APIRouter, Depends, Request
from sqlalchemy import select
from .auth import Actor, current_actor
from .errors import fail
from .v2_models import Submission
router=APIRouter(prefix="/submissions",tags=["submissions"])
def body_hash(body, schema=2):
try:
return hashlib.sha256(json.dumps({"schema":schema,"body":body},sort_keys=True,separators=(",",":"),ensure_ascii=False,allow_nan=False).encode()).hexdigest()
except (ValueError,TypeError):
fail(422,"invalid_json","请求必须为合法JSON")
async def accept_submission(session, owner_id, operation, key, payload_schema, body):
if not key or not 1<=len(key)<=128:
fail(422,"invalid_idempotency_key","需要1–128字符的幂等键")
digest=body_hash(body,payload_schema)
row=await session.scalar(select(Submission).where(Submission.owner_id==owner_id,Submission.operation==operation,Submission.key==key))
if row:
if row.body_hash!=digest:
fail(409,"idempotency_conflict","此幂等键已用于不同参数")
if row.status=="purged":
fail(410,"resource_purged","提交结果已清理")
return row
row=Submission(owner_id=owner_id,operation=operation,key=key,payload_schema=payload_schema,body_hash=digest,request_json=body,resource_json={})
session.add(row)
await session.flush()
return row
@router.get("/{key}")
async def recover(key:str,request:Request,operation:str,actor:Actor=Depends(current_actor)):
async with request.app.state.db.session() as session:
row=await session.scalar(select(Submission).where(Submission.owner_id==actor.id,Submission.operation==operation,Submission.key==key))
if not row and operation=="jobs.create":
from .models import Job
legacy=(await session.scalars(select(Job).where(Job.owner_id==actor.id,Job.request_key==key).order_by(Job.batch_index))).all()
if legacy:
if any(job.deleted_at is not None for job in legacy):
fail(410,"resource_purged","提交结果已删除")
resources={"job_ids":[job.id for job in legacy]}
return {"key":key,"operation":operation,"status":"accepted","resource_json":resources,**resources}
if not row: fail(404,"submission_not_found","尚未找到提交记录;重试仍须使用原幂等键")
if row.status=="purged": fail(410,"resource_purged","提交结果已清理")
return {"key":row.key,"operation":row.operation,"status":row.status,"resource_json":row.resource_json,**row.resource_json}