229 lines
8.7 KiB
Go
229 lines
8.7 KiB
Go
// 用户确认应用冲突生成输出:不重新生成,只在当前目标代数、位置和版本均确认后写入已存结果。
|
|
package platform
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// applyCanvasAIOutput 要求 conflict、尚未应用且 run 未取消;v2 显式绑定目标画布/incarnation 和逻辑操作身份。
|
|
func (s *service) applyCanvasAIOutput(w http.ResponseWriter, r *http.Request, project, account string) error {
|
|
if r.Method != http.MethodPost {
|
|
reject(w, 405, "method_not_allowed")
|
|
return nil
|
|
}
|
|
key, id := canvasIdempotencyKey(r), r.PathValue("run")
|
|
if !uuidSlugPattern.MatchString(key) || !uuidSlugPattern.MatchString(id) {
|
|
reject(w, 400, "invalid_ai_request")
|
|
return nil
|
|
}
|
|
expected, ok := expectedVersion(w, r)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
var input struct {
|
|
ProtocolVersion int `json:"protocol_version,omitempty"`
|
|
RequestID string `json:"request_id,omitempty"`
|
|
OperationID string `json:"operation_id,omitempty"`
|
|
TargetIncarnation int64 `json:"target_incarnation,omitempty"`
|
|
TargetCanvasID string `json:"target_canvas_id,omitempty"`
|
|
NodeID string `json:"node_id"`
|
|
OutputID string `json:"output_id"`
|
|
}
|
|
if !decode(w, r, &input) {
|
|
return nil
|
|
}
|
|
if !canvasID.MatchString(input.NodeID) || !uuidSlugPattern.MatchString(input.OutputID) {
|
|
reject(w, 400, "invalid_ai_request")
|
|
return nil
|
|
}
|
|
canonical := input.ProtocolVersion != 0 || input.RequestID != "" || input.OperationID != "" || input.TargetIncarnation != 0 || input.TargetCanvasID != ""
|
|
if canonical && (input.ProtocolVersion != 2 || input.RequestID != key || !uuidSlugPattern.MatchString(input.OperationID) || input.TargetIncarnation < 1 || !uuidSlugPattern.MatchString(input.TargetCanvasID) || !acceptsCanvasV2(r)) {
|
|
reject(w, 400, "invalid_ai_protocol")
|
|
return nil
|
|
}
|
|
hash := payloadDigest(input)
|
|
if canonical {
|
|
hash = payloadDigest(response{"input": input, "if_match": expected})
|
|
}
|
|
workspace, board := r.PathValue("workspace"), r.PathValue("material")
|
|
tx, err := s.db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
_, role, err := lockCanvasAIRunRoute(r.Context(), tx, project, workspace, board, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var receipt *canvasAIRequest
|
|
if canonical {
|
|
receipt = &canvasAIRequest{Key: key, Hash: hash, Action: "run.apply", Board: board, Run: id, Operation: input.OperationID}
|
|
if done, e := beginCanvasAIRequest(w, r, tx, project, workspace, account, receipt); done || e != nil {
|
|
return e
|
|
}
|
|
}
|
|
rejectRequest := func(status int, code string) error {
|
|
return rejectCanvasAIRequest(w, r, tx, project, workspace, account, receipt, status, code)
|
|
}
|
|
if role == "viewer" {
|
|
return rejectRequest(403, "forbidden")
|
|
}
|
|
var runStatus string
|
|
err = tx.QueryRowContext(r.Context(), `SELECT status FROM canvas_ai_runs WHERE project=$1 AND workspace_id=$2 AND board_id=$3 AND id=$4 FOR UPDATE`, project, workspace, board, id).Scan(&runStatus)
|
|
if err == sql.ErrNoRows {
|
|
return rejectRequest(404, "not_found")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var previousHash string
|
|
var previous json.RawMessage
|
|
err = tx.QueryRowContext(r.Context(), `SELECT payload_hash,response_body FROM canvas_ai_mutations WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND account_id=$4 AND action='apply' AND idempotency_key=$5`, project, workspace, id, account, key).Scan(&previousHash, &previous)
|
|
if err == nil {
|
|
if hash != previousHash {
|
|
reject(w, 409, "idempotency_conflict")
|
|
return nil
|
|
}
|
|
var saved struct {
|
|
Version int64 `json:"canvas_version"`
|
|
}
|
|
_ = json.Unmarshal(previous, &saved)
|
|
setVersion(w, saved.Version)
|
|
reply(w, 200, previous)
|
|
return nil
|
|
}
|
|
if err != sql.ErrNoRows {
|
|
return err
|
|
}
|
|
// 输出必须属于该 run 并与请求 node 匹配,不能拿另一输出 ID 或已应用结果重复写入。
|
|
var stepID, targetBoard, node, status string
|
|
var outputRaw, frozenRaw json.RawMessage
|
|
var applied sql.NullInt64
|
|
err = tx.QueryRowContext(r.Context(), `SELECT id,board_id::text,node_id,status,output,frozen_input,applied_version FROM canvas_ai_steps WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND output->>'output_id'=$4 FOR UPDATE`, project, workspace, id, input.OutputID).Scan(&stepID, &targetBoard, &node, &status, &outputRaw, &frozenRaw, &applied)
|
|
if err == sql.ErrNoRows {
|
|
return rejectRequest(404, "not_found")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if node != input.NodeID || status != "conflict" || applied.Valid || runStatus == "cancelled" {
|
|
return rejectRequest(409, "output_not_applicable")
|
|
}
|
|
var output struct {
|
|
Kind string `json:"kind"`
|
|
Text string `json:"text"`
|
|
AssetID string `json:"assetId"`
|
|
Src string `json:"src"`
|
|
}
|
|
if err = json.Unmarshal(outputRaw, &output); err != nil {
|
|
return err
|
|
}
|
|
var frozen canvasAIStepPlan
|
|
if err = json.Unmarshal(frozenRaw, &frozen); err != nil {
|
|
return err
|
|
}
|
|
if canonical && (frozen.TargetIncarnation != input.TargetIncarnation || frozen.CanonicalRoot == "") {
|
|
return rejectRequest(409, "target_changed")
|
|
}
|
|
// 生成后 owner 可能改变,使用权威身份重新解析;请求确认的 TargetCanvasID 必须仍是当前位置。
|
|
targetBoard, identityOK, err := resolveCanvasAITarget(r.Context(), tx, project, workspace, frozen)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !identityOK {
|
|
return rejectRequest(409, "target_changed")
|
|
}
|
|
if canonical && targetBoard != input.TargetCanvasID {
|
|
return rejectRequest(409, "target_changed")
|
|
}
|
|
_, role, err = lockMaterial(r.Context(), tx, project, workspace, targetBoard, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if role == "viewer" {
|
|
return rejectRequest(403, "forbidden")
|
|
}
|
|
snapshot, err := loadCanvas(r, tx, project, workspace, targetBoard)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if snapshot.Version != expected {
|
|
return rejectRequest(412, "version_conflict")
|
|
}
|
|
// 显式应用允许覆盖已编辑的内容,但仍检查输出模态、字节/字符预算及图片当前可读性。
|
|
patch := response{}
|
|
switch output.Kind {
|
|
case "text":
|
|
if !canvasChoice(frozen.Kind, "text", "script", "plain-text") || !utf8.ValidString(output.Text) || utf8.RuneCountInString(output.Text) > 100000 {
|
|
return rejectRequest(422, "model_incompatible")
|
|
}
|
|
patch["text"] = output.Text
|
|
case "image":
|
|
if !canvasChoice(frozen.Kind, "image", "plain-image") || !uuidSlugPattern.MatchString(output.AssetID) || output.Src != s.assetURL(project, workspace, output.AssetID) {
|
|
return rejectRequest(422, "model_incompatible")
|
|
}
|
|
readable, err := assetReadable(r, tx, project, workspace, output.AssetID, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !readable {
|
|
return rejectRequest(404, "not_found")
|
|
}
|
|
patch["src"] = output.Src
|
|
patch["assetId"] = output.AssetID
|
|
default:
|
|
return rejectRequest(422, "model_incompatible")
|
|
}
|
|
|
|
var doc map[string]any
|
|
if err = json.Unmarshal(snapshot.Document, &doc); err != nil {
|
|
return err
|
|
}
|
|
var target map[string]any
|
|
for _, v := range doc["nodes"].([]any) {
|
|
n := v.(map[string]any)
|
|
if n["id"] == node {
|
|
target = n["data"].(map[string]any)
|
|
}
|
|
}
|
|
if target == nil {
|
|
return rejectRequest(404, "not_found")
|
|
}
|
|
if target["kind"] != frozen.Kind {
|
|
return rejectRequest(409, "ownership_conflict")
|
|
}
|
|
// 通过共享窄字段 patch 保存,原几何和未知元数据不被旧输出快照回滚;应用版本与事件/回执同事务提交。
|
|
change, err := prepareCanvasAIPatch(r, tx, project, workspace, snapshot, node, patch)
|
|
if err != nil {
|
|
return rejectRequest(413, "canvas_too_large")
|
|
}
|
|
snapshot = change.Snapshot
|
|
if err = s.saveCanvasAIChange(r, tx, project, workspace, account, change); err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = tx.ExecContext(r.Context(), `UPDATE canvas_ai_steps SET applied_version=$5,applied_board_id=$6 WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND id=$4`, project, workspace, id, stepID, snapshot.Version, targetBoard)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result := response{"run_id": id, "step_id": stepID, "board_id": targetBoard, "node_id": node, "output_id": input.OutputID, "canvas_version": snapshot.Version, "patch": patch}
|
|
change.addTargetContext(result, frozen)
|
|
if receipt != nil {
|
|
result["status"] = "applied"
|
|
bindCanvasAIReceipt(result, receipt)
|
|
}
|
|
if err = appendAIEvent(r.Context(), tx, project, workspace, id, "step.applied", result); err != nil {
|
|
return err
|
|
}
|
|
encoded, _ := json.Marshal(result)
|
|
_, err = tx.ExecContext(r.Context(), `INSERT INTO canvas_ai_mutations(project,workspace_id,run_id,account_id,action,idempotency_key,payload_hash,response_body) VALUES($1,$2,$3,$4,'apply',$5,$6,$7)`, project, workspace, id, account, key, hash, encoded)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
setVersion(w, snapshot.Version)
|
|
return commitCanvasAIReceipt(w, r, tx, project, workspace, account, receipt, 200, "applied", result)
|
|
}
|