310 lines
15 KiB
Go
310 lines
15 KiB
Go
package platform
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strconv"
|
|
"testing"
|
|
)
|
|
|
|
func TestCanvasConnectionTransactions(t *testing.T) {
|
|
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
|
|
if dsn == "" {
|
|
t.Skip("requires an isolated integration database")
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
ctx := context.Background()
|
|
var random [12]byte
|
|
_, _ = rand.Read(random[:])
|
|
project := "connections-" + hex.EncodeToString(random[:])
|
|
defer func() {
|
|
for _, table := range []string{"canvas_transactions", "canvas_subgraphs", "workspaces", "project_accounts"} {
|
|
_, _ = db.ExecContext(ctx, "DELETE FROM "+table+" WHERE project=$1", project)
|
|
}
|
|
}()
|
|
tokens := []string{}
|
|
accounts := []string{}
|
|
for range 3 {
|
|
var account string
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO project_accounts(project,id) VALUES($1,gen_random_uuid()) RETURNING id::text`, project).Scan(&account); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var value [32]byte
|
|
_, _ = rand.Read(value[:])
|
|
token := base64.RawURLEncoding.EncodeToString(value[:])
|
|
hash := sha256.Sum256([]byte(token))
|
|
if _, err = db.ExecContext(ctx, `INSERT INTO project_sessions(token_hash,project,account_id,expires_at) VALUES($1,$2,$3,now()+interval '1 hour')`, base64.RawURLEncoding.EncodeToString(hash[:]), project, account); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
tokens = append(tokens, token)
|
|
accounts = append(accounts, account)
|
|
}
|
|
var workspace, root string
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO workspaces(project,name,owner_id) VALUES($1,'Connections',$2) RETURNING id::text`, project, accounts[0]).Scan(&workspace); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for i, role := range []string{"admin", "viewer"} {
|
|
if _, err = db.ExecContext(ctx, `INSERT INTO workspace_members VALUES($1,$2,$3,$4,now())`, project, workspace, accounts[i], role); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO materials(project,workspace_id,kind,title,created_by,canvas_document) VALUES($1,$2,'board','Root',$3,$4) RETURNING id::text`, project, workspace, accounts[0], json.RawMessage(canvasFixture)).Scan(&root); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mux := http.NewServeMux()
|
|
Register(mux, db, map[string]string{project: "https://app.example.com/auth/callback"}, "https://api.example.com", nil)
|
|
base := "/projects/" + project + "/workspaces/" + workspace + "/materials/"
|
|
path := func(board string) string { return base + board + "/canvas" }
|
|
do := func(method, url, token string, body any, version int64, key string) *httptest.ResponseRecorder {
|
|
raw, _ := json.Marshal(body)
|
|
r := httptest.NewRequest(method, url, bytes.NewReader(raw))
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
r.Header.Set("Accept", "application/vnd.foundry.canvas+json;version=2")
|
|
if version > 0 {
|
|
r.Header.Set("If-Match", strconv.Quote(strconv.FormatInt(version, 10)))
|
|
}
|
|
if key != "" {
|
|
r.Header.Set("Idempotency-Key", key)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
mux.ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
call := func(method, url, token string, body any, status int, version int64, key string) response {
|
|
t.Helper()
|
|
w := do(method, url, token, body, version, key)
|
|
if w.Code != status {
|
|
t.Fatalf("%s %s got %d %s want %d", method, url, w.Code, w.Body.String(), status)
|
|
}
|
|
out := response{}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out
|
|
}
|
|
key := func(n int) string { return fmt.Sprintf("a0000000-0000-4000-8000-%012d", n) }
|
|
versions := func(ids ...string) map[string]int64 {
|
|
t.Helper()
|
|
out := map[string]int64{}
|
|
for _, id := range ids {
|
|
out[id] = int64(call("GET", path(id), tokens[0], nil, 200, 0, "")["version"].(float64))
|
|
}
|
|
return out
|
|
}
|
|
create := func(board, frame string, n int) string {
|
|
t.Helper()
|
|
v := versions(board)[board]
|
|
result := call("POST", path(board)+"/subgraphs", tokens[0], response{"frame": response{"id": frame, "title": frame, "position": response{"x": 10, "y": 20}, "width": 600, "height": 400, "labelMode": "fixed"}}, 201, v, key(n))
|
|
return result["child_board"].(map[string]any)["id"].(string)
|
|
}
|
|
seed := func(board string, nodes ...string) {
|
|
t.Helper()
|
|
values := []any{}
|
|
for _, id := range nodes {
|
|
values = append(values, response{"id": id, "type": "material", "position": response{"x": 10, "y": 20}, "data": response{"kind": "text", "title": id, "text": "preserved"}})
|
|
}
|
|
call("PATCH", path(board), tokens[0], response{"document": response{"schema_version": 2, "nodes": values, "edges": []any{}, "viewport": response{"x": 0, "y": 0, "zoom": 1}}}, 200, 1, "")
|
|
}
|
|
left := create(root, "left", 1)
|
|
right := create(root, "right", 2)
|
|
seed(left, "l1", "l2")
|
|
seed(right, "r1")
|
|
leaf := create(left, "nested", 3)
|
|
seed(leaf, "deep")
|
|
command := func(source, node, target, targetNode, id string, ids ...string) response {
|
|
return response{"source": response{"board_id": source, "node_id": node, "handle": "right"}, "target": response{"board_id": target, "node_id": targetNode, "handle": "left"}, "edge": response{"id": id, "data": response{"appearance": response{"color": "#123456", "width": 2}, "path": response{"type": "bezier-chain", "knots": []any{response{"id": "k", "position": response{"x": 200, "y": 300}, "in": response{"x": -20, "y": 0}, "out": response{"x": 20, "y": 0}, "mode": "symmetric"}}}}}, "expected_versions": versions(ids...)}
|
|
}
|
|
firstBody := command(leaf, "deep", root, "a", "external", root, left, leaf)
|
|
beforeLeaf := call("GET", path(leaf), tokens[0], nil, 200, 0, "")["document"]
|
|
first := call("POST", path(root)+"/connections", tokens[0], firstBody, 201, 0, key(4))
|
|
if len(first["created_ports"].([]any)) != 2 {
|
|
t.Fatal("nested connection missing ports")
|
|
}
|
|
retry := call("POST", path(root)+"/connections", tokens[0], firstBody, 201, 0, key(4))
|
|
if retry["transaction_id"] != first["transaction_id"] {
|
|
t.Fatal("retry duplicated operation")
|
|
}
|
|
changedBody := command(leaf, "deep", root, "a", "different", root, left, leaf)
|
|
call("POST", path(root)+"/connections", tokens[0], changedBody, 409, 0, key(4))
|
|
afterLeaf := call("GET", path(leaf), tokens[0], nil, 200, 0, "")["document"]
|
|
if payloadDigest(beforeLeaf) != payloadDigest(afterLeaf) {
|
|
t.Fatal("connection changed leaf content")
|
|
}
|
|
parent := first["parent"].(map[string]any)
|
|
edge := first["connection"].(map[string]any)["edge"].(map[string]any)
|
|
if edge["source"] != "left" || edge["target"] != "a" || edge["data"].(map[string]any)["appearance"].(map[string]any)["color"] != "#123456" {
|
|
t.Fatal("connection edge lost mapping/style")
|
|
}
|
|
if len(parent["document"].(map[string]any)["edges"].([]any)) != 2 {
|
|
t.Fatal("existing edge lost")
|
|
}
|
|
undo := call("POST", path(root)+"/transactions/"+first["transaction_id"].(string)+"/undo", tokens[0], response{"expected_versions": versions(root, left, leaf)}, 200, 0, key(5))
|
|
if len(undo["snapshots"].([]any)) != 3 {
|
|
t.Fatal("undo did not restore complete chain")
|
|
}
|
|
for board, frame := range map[string]string{root: "left", left: "nested"} {
|
|
document := call("GET", path(board), tokens[0], nil, 200, 0, "")["document"]
|
|
raw, _ := json.Marshal(document)
|
|
if len(canvasNodeData(raw)[frame]["ports"].([]any)) != 0 {
|
|
t.Fatal("undo left ports behind")
|
|
}
|
|
}
|
|
redoBody := command(leaf, "deep", root, "a", "external", root, left, leaf)
|
|
redone := call("POST", path(root)+"/connections", tokens[0], redoBody, 201, 0, key(6))
|
|
if payloadDigest(redone["connection"]) != payloadDigest(first["connection"]) {
|
|
t.Fatal("redo changed stable ports")
|
|
}
|
|
reused := call("POST", path(root)+"/connections", tokens[0], command(leaf, "deep", root, "b", "second", root, left, leaf), 201, 0, key(7))
|
|
if len(reused["created_ports"].([]any)) != 0 {
|
|
t.Fatal("same source endpoint duplicated ports")
|
|
}
|
|
sibling := call("POST", path(root)+"/connections", tokens[0], command(left, "l1", right, "r1", "sibling", root, left, right), 201, 0, key(8))
|
|
if len(sibling["created_ports"].([]any)) != 2 {
|
|
t.Fatal("sibling connection missing boundary ports")
|
|
}
|
|
reverse := call("POST", path(root)+"/connections", tokens[0], command(root, "b", leaf, "deep", "reverse", root, left, leaf), 201, 0, key(9))
|
|
if len(reverse["created_ports"].([]any)) != 2 {
|
|
t.Fatal("input chain reused output ports")
|
|
}
|
|
// Missing/stale participant versions, bad endpoints and permission failures are atomic.
|
|
stable := versions(root, left, leaf)
|
|
missing := command(leaf, "deep", root, "a", "missing", root, left)
|
|
required := call("POST", path(root)+"/connections", tokens[0], missing, 428, 0, key(10))
|
|
if len(required["details"].(map[string]any)["required_board_ids"].([]any)) != 3 {
|
|
t.Fatal("version response omitted participants")
|
|
}
|
|
stale := command(leaf, "deep", root, "a", "stale", root, left, leaf)
|
|
stale["expected_versions"].(map[string]int64)[leaf]--
|
|
call("POST", path(root)+"/connections", tokens[0], stale, 412, 0, key(11))
|
|
call("POST", path(root)+"/connections", tokens[0], command(leaf, "absent", root, "a", "bad-node", root, left, leaf), 409, 0, key(12))
|
|
call("POST", path(root)+"/connections", tokens[0], command(root, "icon", leaf, "deep", "icon-edge", root, left, leaf), 409, 0, key(13))
|
|
call("POST", path(root)+"/connections", tokens[0], command(leaf, "deep", left, "l1", "wrong-owner", root, left, leaf), 409, 0, key(14))
|
|
call("POST", path(root)+"/connections", tokens[0], command(leaf, "deep", root, "a", "external", root, left, leaf), 409, 0, key(15))
|
|
call("POST", path(root)+"/connections", tokens[1], command(leaf, "deep", root, "a", "viewer", root, left, leaf), 403, 0, key(16))
|
|
call("POST", path(root)+"/connections", tokens[2], command(leaf, "deep", root, "a", "outsider", root, left, leaf), 404, 0, key(17))
|
|
invalid := command(leaf, "deep", root, "a", "handle", root, left, leaf)
|
|
invalid["source"].(response)["handle"] = "port:fake"
|
|
call("POST", path(root)+"/connections", tokens[0], invalid, 400, 0, key(18))
|
|
if payloadDigest(stable) != payloadDigest(versions(root, left, leaf)) {
|
|
t.Fatal("rejected transaction partially changed versions")
|
|
}
|
|
// The actual nested mapping is resolvable by the same reader used by AI propagation.
|
|
graph := map[string]canvasSnapshot{}
|
|
for _, board := range []string{root, left, leaf} {
|
|
read := call("GET", path(board), tokens[0], nil, 200, 0, "")
|
|
raw, _ := json.Marshal(read["document"])
|
|
graph[board] = canvasSnapshot{BoardID: board, Version: int64(read["version"].(float64)), Document: raw}
|
|
}
|
|
reader := readerFromSnapshots(graph, map[string]int{})
|
|
reader.snapshots = map[string]canvasSnapshot{}
|
|
reader.documents = map[string]map[string]any{}
|
|
reader.parents = map[string]subgraphRelation{}
|
|
reader.parentKnown = map[string]bool{}
|
|
resolved, err := reader.resolve(root, edge["source"].(string), edge["sourceHandle"].(string), "output", 0)
|
|
if err != nil || resolved != canvasNodeKey(leaf, "deep") {
|
|
t.Fatal("AI reader cannot resolve newly created port chain")
|
|
}
|
|
// Ordinary saves must still reject port retargeting.
|
|
readParent := call("GET", path(root), tokens[0], nil, 200, 0, "")
|
|
parentDoc := readParent["document"].(map[string]any)
|
|
for _, value := range parentDoc["nodes"].([]any) {
|
|
node := value.(map[string]any)
|
|
if node["id"] == "left" {
|
|
node["data"].(map[string]any)["ports"].([]any)[0].(map[string]any)["nodeId"] = "l2"
|
|
}
|
|
}
|
|
call("PATCH", path(root), tokens[0], response{"document": parentDoc}, 409, int64(readParent["version"].(float64)), "")
|
|
var otherWorkspace, otherBoard, unrelatedBoard string
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO workspaces(project,name,owner_id) VALUES($1,'Other',$2) RETURNING id::text`, project, accounts[0]).Scan(&otherWorkspace); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.ExecContext(ctx, `INSERT INTO workspace_members VALUES($1,$2,$3,'admin',now())`, project, otherWorkspace, accounts[0]); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, target := range []struct {
|
|
workspace string
|
|
id *string
|
|
}{{otherWorkspace, &otherBoard}, {workspace, &unrelatedBoard}} {
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO materials(project,workspace_id,kind,title,created_by,canvas_document) VALUES($1,$2,'board','Other',$3,$4) RETURNING id::text`, project, target.workspace, accounts[0], json.RawMessage(canvasFixture)).Scan(target.id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
call("POST", path(root)+"/connections", tokens[0], command(left, "l1", otherBoard, "a", "cross-workspace", root, left), 404, 0, key(21))
|
|
call("POST", path(root)+"/connections", tokens[0], command(left, "l1", unrelatedBoard, "a", "unrelated", root, left), 409, 0, key(22))
|
|
legacyRequest := httptest.NewRequest("POST", path(root)+"/connections", bytes.NewReader([]byte("{}")))
|
|
legacyRequest.Header.Set("Authorization", "Bearer "+tokens[0])
|
|
legacyResponse := httptest.NewRecorder()
|
|
mux.ServeHTTP(legacyResponse, legacyRequest)
|
|
if legacyResponse.Code != 409 {
|
|
t.Fatal("connection mutation accepted a legacy client")
|
|
}
|
|
caps := call("GET", path(root)+"/capabilities", tokens[0], nil, 200, 0, "")
|
|
if caps["subgraphs"].(map[string]any)["connections"] != true {
|
|
t.Fatal("capabilities omitted connection transaction")
|
|
}
|
|
// Four simultaneous retries create exactly one edge/receipt and advance versions once.
|
|
concurrent := command(left, "l2", root, "a", "concurrent", root, left)
|
|
prior := versions(root, left)
|
|
start := make(chan struct{})
|
|
results := make(chan *httptest.ResponseRecorder, 4)
|
|
for range 4 {
|
|
go func() { <-start; results <- do("POST", path(root)+"/connections", tokens[0], concurrent, 0, key(19)) }()
|
|
}
|
|
close(start)
|
|
transaction := ""
|
|
for range 4 {
|
|
w := <-results
|
|
if w.Code != 201 {
|
|
t.Fatalf("concurrent request: %d %s", w.Code, w.Body.String())
|
|
}
|
|
var result response
|
|
_ = json.Unmarshal(w.Body.Bytes(), &result)
|
|
id := result["transaction_id"].(string)
|
|
if transaction != "" && transaction != id {
|
|
t.Fatal("concurrent retry duplicated receipt")
|
|
}
|
|
transaction = id
|
|
}
|
|
for id, v := range versions(root, left) {
|
|
if v != prior[id]+1 {
|
|
t.Fatal("concurrent retry advanced version twice")
|
|
}
|
|
}
|
|
// A full coordinator rejects the entire operation, including new leaf ports.
|
|
snapshot := call("GET", path(root), tokens[0], nil, 200, 0, "")
|
|
doc := snapshot["document"].(map[string]any)
|
|
edges := []any{}
|
|
for i := 0; i < 2000; i++ {
|
|
edges = append(edges, response{"id": fmt.Sprint("full-", i), "source": "a", "target": "b", "sourceHandle": "right", "targetHandle": "left"})
|
|
}
|
|
doc["edges"] = edges
|
|
call("PATCH", path(root), tokens[0], response{"document": doc}, 200, int64(snapshot["version"].(float64)), "")
|
|
capacity := command(left, "l2", root, "a", "capacity", root, left)
|
|
capacity["source"].(response)["handle"] = "top"
|
|
beforeFailure := versions(root, left)
|
|
beforeLeft := call("GET", path(left), tokens[0], nil, 200, 0, "")["document"]
|
|
call("POST", path(root)+"/connections", tokens[0], capacity, 413, 0, key(20))
|
|
afterLeft := call("GET", path(left), tokens[0], nil, 200, 0, "")["document"]
|
|
if payloadDigest(beforeLeft) != payloadDigest(afterLeft) || payloadDigest(beforeFailure) != payloadDigest(versions(root, left)) {
|
|
t.Fatal("capacity failure left ports or versions behind")
|
|
}
|
|
var receipts int
|
|
if err = db.QueryRowContext(ctx, `SELECT count(*) FROM canvas_transactions WHERE project=$1 AND action='create_connection' AND idempotency_key=$2`, project, key(20)).Scan(&receipts); err != nil || receipts != 0 {
|
|
t.Fatal("rejected connection left a receipt")
|
|
}
|
|
}
|