300 lines
11 KiB
Go
300 lines
11 KiB
Go
package platform
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"sort"
|
|
)
|
|
|
|
func canonicalRoot(ctx context.Context, tx *sql.Tx, project, workspace, board string) (string, error) {
|
|
var root string
|
|
err := tx.QueryRowContext(ctx, `SELECT root_id::text FROM canvas_model_canvases WHERE project=$1 AND workspace_id=$2 AND canvas_id=$3`, project, workspace, board).Scan(&root)
|
|
if err == sql.ErrNoRows {
|
|
return "", nil
|
|
}
|
|
return root, err
|
|
}
|
|
func loadCanvasModel(ctx context.Context, tx *sql.Tx, project, workspace, root string) (canvasModel, error) {
|
|
model := emptyModel(root)
|
|
rows, err := tx.QueryContext(ctx, `SELECT canvas_id::text,parent_canvas_id::text,entry_element_id,version,archived FROM canvas_model_canvases WHERE project=$1 AND workspace_id=$2 AND root_id=$3 ORDER BY canvas_id`, project, workspace, root)
|
|
if err != nil {
|
|
return model, err
|
|
}
|
|
for rows.Next() {
|
|
var canvas modelCanvas
|
|
var parent, entry sql.NullString
|
|
var version int64
|
|
var archived bool
|
|
if err = rows.Scan(&canvas.ID, &parent, &entry, &version, &archived); err != nil {
|
|
rows.Close()
|
|
return model, err
|
|
}
|
|
if parent.Valid {
|
|
canvas.Parent = &modelParent{CanvasID: parent.String, EntryElementID: entry.String}
|
|
}
|
|
model.Versions[canvas.ID] = version
|
|
if !archived {
|
|
model.Canvases[canvas.ID] = canvas
|
|
}
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return model, err
|
|
}
|
|
rows, err = tx.QueryContext(ctx, `SELECT element_id,record,deleted,deleted_incarnation FROM canvas_model_elements WHERE project=$1 AND workspace_id=$2 AND root_id=$3 ORDER BY element_id`, project, workspace, root)
|
|
if err != nil {
|
|
return model, err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var id string
|
|
var raw json.RawMessage
|
|
var deleted bool
|
|
var dead int64
|
|
if err = rows.Scan(&id, &raw, &deleted, &dead); err != nil {
|
|
return model, err
|
|
}
|
|
if dead > 0 {
|
|
model.Tombstones[id] = dead
|
|
}
|
|
if !deleted {
|
|
var element map[string]any
|
|
if err = json.Unmarshal(raw, &element); err != nil {
|
|
return model, err
|
|
}
|
|
model.Elements[id] = element
|
|
}
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return model, err
|
|
}
|
|
return model, validateCanvasModel(model)
|
|
}
|
|
|
|
// Only changed element rows are written. canvas_document is a compatibility
|
|
// projection for internal AI readers, never the source of a canonical GET/replay.
|
|
func (s *service) saveCanvasModel(r *http.Request, tx *sql.Tx, project, workspace, account string, before, after canvasModel, participants map[string]bool) error {
|
|
ctx := r.Context()
|
|
if _, err := tx.ExecContext(ctx, `SELECT set_config('foundry.canonical_writer','on',true)`); err != nil {
|
|
return err
|
|
}
|
|
projection, err := projectCanvasModel(after)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, id := range sortedKeys(participants) {
|
|
canvas, active := after.Canvases[id]
|
|
if active {
|
|
if _, existed := before.Versions[id]; !existed {
|
|
title := "Canvas"
|
|
if canvas.Parent != nil {
|
|
data := after.Elements[canvas.Parent.EntryElementID]["data"].(map[string]any)
|
|
if value := modelString(data["title"]); value != "" {
|
|
title = value
|
|
}
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO materials(project,workspace_id,id,kind,title,created_by) VALUES($1,$2,$3,'board',$4,$5)`, project, workspace, id, title, account); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
var parent, entry any
|
|
if canvas.Parent != nil {
|
|
parent, entry = canvas.Parent.CanvasID, canvas.Parent.EntryElementID
|
|
}
|
|
_, err = tx.ExecContext(ctx, `INSERT INTO canvas_model_canvases(project,workspace_id,root_id,canvas_id,parent_canvas_id,entry_element_id,version) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(project,workspace_id,canvas_id) DO UPDATE SET parent_canvas_id=EXCLUDED.parent_canvas_id,entry_element_id=EXCLUDED.entry_element_id,version=EXCLUDED.version,archived=false`, project, workspace, after.Root, id, parent, entry, after.Versions[id])
|
|
} else {
|
|
_, err = tx.ExecContext(ctx, `UPDATE canvas_model_canvases SET archived=true,version=$4 WHERE project=$1 AND workspace_id=$2 AND canvas_id=$3`, project, workspace, id, after.Versions[id])
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, id := range sortedKeys(after.Elements) {
|
|
element := after.Elements[id]
|
|
if modelEqual(before.Elements[id], element) && before.Tombstones[id] == after.Tombstones[id] {
|
|
continue
|
|
}
|
|
raw, err := json.Marshal(element)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
written, err := tx.ExecContext(ctx, `INSERT INTO canvas_model_elements(project,workspace_id,root_id,element_id,owner_canvas_id,incarnation,deleted_incarnation,record) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(project,element_id) DO UPDATE SET owner_canvas_id=EXCLUDED.owner_canvas_id,incarnation=EXCLUDED.incarnation,deleted_incarnation=EXCLUDED.deleted_incarnation,record=EXCLUDED.record,deleted=false WHERE canvas_model_elements.workspace_id=EXCLUDED.workspace_id AND canvas_model_elements.root_id=EXCLUDED.root_id`, project, workspace, after.Root, id, element["ownerCanvasId"], modelInt(element["incarnation"]), after.Tombstones[id], raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if count, err := written.RowsAffected(); err != nil {
|
|
return err
|
|
} else if count != 1 {
|
|
return errModelConflict
|
|
}
|
|
}
|
|
for _, id := range sortedKeys(before.Elements) {
|
|
if after.Elements[id] == nil {
|
|
if _, err = tx.ExecContext(ctx, `UPDATE canvas_model_elements SET deleted=true,deleted_incarnation=incarnation WHERE project=$1 AND workspace_id=$2 AND root_id=$3 AND element_id=$4`, project, workspace, after.Root, id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
// Archive relations first; parent/entry changes then install the final owning tree.
|
|
for _, id := range sortedKeys(participants) {
|
|
if id != after.Root {
|
|
if _, err = tx.ExecContext(ctx, `UPDATE canvas_subgraphs SET archived_at=now() WHERE project=$1 AND workspace_id=$2 AND child_board_id=$3`, project, workspace, id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
canvases := sortedKeys(after.Canvases)
|
|
sort.SliceStable(canvases, func(i, j int) bool {
|
|
a, _ := modelAncestors(after, canvases[i])
|
|
b, _ := modelAncestors(after, canvases[j])
|
|
return len(a) < len(b)
|
|
})
|
|
for _, id := range canvases {
|
|
canvas := after.Canvases[id]
|
|
if !participants[id] || canvas.Parent == nil {
|
|
continue
|
|
}
|
|
_, err = tx.ExecContext(ctx, `INSERT INTO canvas_subgraphs(project,workspace_id,parent_board_id,frame_id,child_board_id) VALUES($1,$2,$3,$4,$5) ON CONFLICT(project,workspace_id,child_board_id) DO UPDATE SET parent_board_id=EXCLUDED.parent_board_id,frame_id=EXCLUDED.frame_id,archived_at=NULL`, project, workspace, canvas.Parent.CanvasID, canvas.Parent.EntryElementID, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, id := range sortedKeys(participants) {
|
|
if _, active := after.Canvases[id]; !active {
|
|
_, err = tx.ExecContext(ctx, `UPDATE materials SET archived_at=COALESCE(archived_at,now()),canvas_version=$4 WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id, after.Versions[id])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
// AI invalidation/asset bindings still run through the existing service checks.
|
|
if err = s.saveCanvas(r, tx, project, workspace, canvasSnapshot{BoardID: id, Version: after.Versions[id], Document: projection[id]}); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE materials SET archived_at=NULL WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func projectCanvasModel(model canvasModel) (map[string]json.RawMessage, error) {
|
|
documents := map[string]map[string]any{}
|
|
for id := range model.Canvases {
|
|
documents[id] = map[string]any{"schema_version": float64(2), "nodes": []any{}, "edges": []any{}, "viewport": map[string]any{"x": float64(0), "y": float64(0), "zoom": float64(1)}}
|
|
}
|
|
elements := sortedKeys(model.Elements)
|
|
sort.SliceStable(elements, func(i, j int) bool {
|
|
return modelString(model.Elements[elements[i]]["orderKey"]) < modelString(model.Elements[elements[j]]["orderKey"])
|
|
})
|
|
childByEntry := map[string]string{}
|
|
for id, canvas := range model.Canvases {
|
|
if canvas.Parent != nil {
|
|
childByEntry[canvas.Parent.EntryElementID] = id
|
|
}
|
|
}
|
|
for _, id := range elements {
|
|
element := model.Elements[id]
|
|
if element["structure"] != "node" {
|
|
continue
|
|
}
|
|
kind := modelString(element["componentId"])
|
|
if modelInt(element["dataVersion"]) != 1 || !canvasChoice(kind, "text", "script", "image", "plain-text", "plain-image", "icon", "frame") {
|
|
continue
|
|
}
|
|
data := map[string]any{}
|
|
for key, value := range element["data"].(map[string]any) {
|
|
data[key] = value
|
|
}
|
|
data["kind"] = kind
|
|
geometry := element["geometry"].(map[string]any)
|
|
data["rotation"] = geometry["rotation"]
|
|
typ := "material"
|
|
switch kind {
|
|
case "plain-text":
|
|
typ = "plainText"
|
|
case "plain-image":
|
|
typ = "plainImage"
|
|
case "icon":
|
|
typ = "icon"
|
|
case "frame":
|
|
typ = "frame"
|
|
}
|
|
if child := childByEntry[id]; child != "" {
|
|
data["subgraph"], data["ports"] = map[string]any{"boardId": child}, []any{}
|
|
}
|
|
node := map[string]any{"id": id, "type": typ, "position": map[string]any{"x": geometry["x"], "y": geometry["y"]}, "width": geometry["width"], "height": geometry["height"], "data": data}
|
|
owner := modelString(element["ownerCanvasId"])
|
|
documents[owner]["nodes"] = append(documents[owner]["nodes"].([]any), node)
|
|
}
|
|
for _, id := range elements {
|
|
element := model.Elements[id]
|
|
if element["structure"] != "connection" {
|
|
continue
|
|
}
|
|
owner := modelString(element["ownerCanvasId"])
|
|
endpoints := []canvasConnectionEndpoint{}
|
|
skip := false
|
|
for index, field := range []string{"source", "target"} {
|
|
endpoint := element[field].(map[string]any)
|
|
node := model.Elements[modelString(endpoint["elementId"])]
|
|
board := modelString(node["ownerCanvasId"])
|
|
if connectionNode(documents[board], modelString(node["id"])) == nil {
|
|
skip = true
|
|
break
|
|
}
|
|
handle := modelString(endpoint["portId"])
|
|
if handle == "" {
|
|
handle = "left"
|
|
if index == 0 {
|
|
handle = "right"
|
|
}
|
|
}
|
|
path := []subgraphRelation{}
|
|
for next := board; next != owner; {
|
|
canvas := model.Canvases[next]
|
|
if canvas.Parent == nil {
|
|
return nil, errCanvasModel
|
|
}
|
|
path = append(path, subgraphRelation{Parent: canvas.Parent.CanvasID, Frame: canvas.Parent.EntryElementID, Child: next})
|
|
next = canvas.Parent.CanvasID
|
|
}
|
|
direction := "output"
|
|
if index == 1 {
|
|
direction = "input"
|
|
}
|
|
resolved, _, err := exposeConnectionEndpoint(canvasConnectionEndpoint{Board: board, Node: modelString(node["id"]), Handle: handle}, direction, path, documents)
|
|
// Direct frame/icon endpoints are canonical concepts; old AI readers cannot execute them.
|
|
if err != nil {
|
|
skip = true
|
|
break
|
|
}
|
|
endpoints = append(endpoints, resolved)
|
|
}
|
|
if skip {
|
|
continue
|
|
}
|
|
data := map[string]any{}
|
|
for key, value := range element["data"].(map[string]any) {
|
|
data[key] = value
|
|
}
|
|
if element["path"] != nil {
|
|
data["path"] = element["path"]
|
|
}
|
|
edge := map[string]any{"id": id, "source": endpoints[0].Node, "target": endpoints[1].Node, "sourceHandle": endpoints[0].Handle, "targetHandle": endpoints[1].Handle, "data": data}
|
|
documents[owner]["edges"] = append(documents[owner]["edges"].([]any), edge)
|
|
}
|
|
result := map[string]json.RawMessage{}
|
|
for id, document := range documents {
|
|
raw, err := json.Marshal(document)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result[id] = raw
|
|
}
|
|
return result, nil
|
|
}
|