200 lines
6.1 KiB
Go
200 lines
6.1 KiB
Go
package platform
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
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 {
|
|
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
|
|
}
|
|
hash := payloadDigest(input)
|
|
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 := lockMaterial(r.Context(), tx, project, workspace, board, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if role == "viewer" {
|
|
reject(w, 403, "forbidden")
|
|
return nil
|
|
}
|
|
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 != 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
|
|
}
|
|
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 != nil {
|
|
return err
|
|
}
|
|
if node != input.NodeID || status != "conflict" || applied.Valid || runStatus == "cancelled" {
|
|
reject(w, 409, "output_not_applicable")
|
|
return nil
|
|
}
|
|
_, role, err = lockMaterial(r.Context(), tx, project, workspace, targetBoard, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if role == "viewer" {
|
|
reject(w, 403, "forbidden")
|
|
return nil
|
|
}
|
|
snapshot, err := loadCanvas(r, tx, project, workspace, targetBoard)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if snapshot.Version != expected {
|
|
reject(w, 412, "version_conflict")
|
|
return nil
|
|
}
|
|
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
|
|
}
|
|
identityOK, err := canvasAIIdentityMatches(r.Context(), tx, project, workspace, frozen)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !identityOK {
|
|
reject(w, 409, "target_changed")
|
|
return nil
|
|
}
|
|
patch := response{}
|
|
switch output.Kind {
|
|
case "text":
|
|
if !canvasChoice(frozen.Kind, "text", "script", "plain-text") || !utf8.ValidString(output.Text) || utf8.RuneCountInString(output.Text) > 100000 {
|
|
reject(w, 422, "model_incompatible")
|
|
return nil
|
|
}
|
|
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) {
|
|
reject(w, 422, "model_incompatible")
|
|
return nil
|
|
}
|
|
readable, err := assetReadable(r, tx, project, workspace, output.AssetID, account)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !readable {
|
|
reject(w, 404, "not_found")
|
|
return nil
|
|
}
|
|
patch["src"] = output.Src
|
|
patch["assetId"] = output.AssetID
|
|
default:
|
|
reject(w, 422, "model_incompatible")
|
|
return nil
|
|
}
|
|
|
|
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 {
|
|
reject(w, 404, "not_found")
|
|
return nil
|
|
}
|
|
if target["kind"] != frozen.Kind {
|
|
reject(w, 409, "ownership_conflict")
|
|
return nil
|
|
}
|
|
change, err := prepareCanvasAIPatch(r, tx, project, workspace, snapshot, node, patch)
|
|
if err != nil {
|
|
reject(w, 413, "canvas_too_large")
|
|
return nil
|
|
}
|
|
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 WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND id=$4`, project, workspace, id, stepID, snapshot.Version)
|
|
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.addCanonical(result)
|
|
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
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
setVersion(w, snapshot.Version)
|
|
reply(w, 200, result)
|
|
return nil
|
|
}
|