167 lines
6.8 KiB
Go
167 lines
6.8 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"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
func TestCanvasOperationsTransactions(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 entropy [12]byte
|
|
_, _ = rand.Read(entropy[:])
|
|
project := "operations-" + hex.EncodeToString(entropy[:])
|
|
defer func() {
|
|
for _, table := range []string{"canvas_transactions", "workspaces", "project_accounts"} {
|
|
_, _ = db.ExecContext(ctx, "DELETE FROM "+table+" WHERE project=$1", project)
|
|
}
|
|
}()
|
|
accounts, tokens := []string{}, []string{}
|
|
for range 2 {
|
|
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)
|
|
}
|
|
accounts, tokens = append(accounts, account), append(tokens, token)
|
|
}
|
|
var workspace string
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO workspaces(project,name,owner_id) VALUES($1,'Operations',$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(project,workspace_id,account_id,role) VALUES($1,$2,$3,$4)`, project, workspace, accounts[i], role); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
boards := []string{}
|
|
for range 2 {
|
|
var board string
|
|
if err = db.QueryRowContext(ctx, `INSERT INTO materials(project,workspace_id,kind,title,created_by,canvas_document) VALUES($1,$2,'board','Board',$3,$4) RETURNING id::text`, project, workspace, accounts[0], json.RawMessage(operationsFixture)).Scan(&board); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
boards = append(boards, board)
|
|
}
|
|
mux := http.NewServeMux()
|
|
Register(mux, db, map[string]string{project: "https://app.example.com/auth/callback"}, "https://api.example.com", nil)
|
|
path := "/projects/" + project + "/workspaces/" + workspace + "/materials/" + boards[0] + "/canvas/operations"
|
|
key := func(n int) string { return fmt.Sprintf("a0000000-0000-4000-8000-%012d", n) }
|
|
do := func(method, path, token string, input canvasOperationBatch) *httptest.ResponseRecorder {
|
|
encoded, _ := json.Marshal(input)
|
|
request := httptest.NewRequest(method, path, bytes.NewReader(encoded))
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
request.Header.Set("Accept", "application/vnd.foundry.canvas+json;version=2")
|
|
request.Header.Set("Idempotency-Key", input.RequestID)
|
|
writer := httptest.NewRecorder()
|
|
mux.ServeHTTP(writer, request)
|
|
return writer
|
|
}
|
|
call := func(method, path, token string, input canvasOperationBatch, status int) response {
|
|
t.Helper()
|
|
writer := do(method, path, token, input)
|
|
if writer.Code != status {
|
|
t.Fatalf("%s %s got %d %s want %d", method, path, writer.Code, writer.Body.String(), status)
|
|
}
|
|
out := response{}
|
|
if err := json.Unmarshal(writer.Body.Bytes(), &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out
|
|
}
|
|
version := func(board string) int64 {
|
|
t.Helper()
|
|
var value int64
|
|
if err := db.QueryRowContext(ctx, `SELECT canvas_version FROM materials WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, board).Scan(&value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return value
|
|
}
|
|
batch := func(n int, expected int64) canvasOperationBatch {
|
|
return canvasOperationBatch{ProtocolVersion: 1, RequestID: key(n), ExpectedVersions: map[string]int64{boards[0]: expected}, Operations: []canvasOperation{{ID: key(n + 100), Type: "node.patch", CanvasID: boards[0], ElementID: "a", Patch: map[string]json.RawMessage{"data": json.RawMessage(`{"title":"renamed"}`)}}}}
|
|
}
|
|
firstBody := batch(1, 1)
|
|
first := call("POST", path, tokens[0], firstBody, 200)
|
|
retried := call("POST", path, tokens[0], firstBody, 200)
|
|
if first["transaction_id"] != retried["transaction_id"] || version(boards[0]) != 2 {
|
|
t.Fatal("retry duplicated writes or changed receipt identity")
|
|
}
|
|
queried := call("GET", path+"/"+key(1), tokens[0], canvasOperationBatch{}, 200)
|
|
if queried["status"] != "applied" || queried["transaction_id"] != first["transaction_id"] {
|
|
t.Fatal("lost acknowledgment cannot be resolved by request identity")
|
|
}
|
|
altered := batch(1, 2)
|
|
call("POST", path, tokens[0], altered, 409)
|
|
call("GET", path+"/"+key(1), tokens[1], canvasOperationBatch{}, 404)
|
|
call("POST", path, tokens[1], batch(2, 2), 403)
|
|
unknown := call("GET", path+"/"+key(999), tokens[0], canvasOperationBatch{}, 404)
|
|
if unknown["status"] != "unknown" || unknown["terminal"] == true {
|
|
t.Fatal("missing receipt must not claim terminal zero writes")
|
|
}
|
|
// Terminal zero-write responses must remain queryable and reserve their frozen body.
|
|
stale := batch(3, 1)
|
|
rejected := call("POST", path, tokens[0], stale, 412)
|
|
proof := call("GET", path+"/"+key(3), tokens[0], canvasOperationBatch{}, 200)
|
|
if proof["status"] != "not-applied" || proof["terminal"] != true || proof["transaction_id"] != rejected["transaction_id"] {
|
|
t.Fatal("terminal rejection was not persisted")
|
|
}
|
|
call("POST", path, tokens[0], batch(3, 2), 409)
|
|
if version(boards[0]) != 2 {
|
|
t.Fatal("rejected request performed a write")
|
|
}
|
|
// Concurrent exact retries serialize to one transaction and one version increment.
|
|
concurrent := batch(4, 2)
|
|
var wait sync.WaitGroup
|
|
results := make(chan *httptest.ResponseRecorder, 4)
|
|
for range 4 {
|
|
wait.Add(1)
|
|
go func() { defer wait.Done(); results <- do("POST", path, tokens[0], concurrent) }()
|
|
}
|
|
wait.Wait()
|
|
close(results)
|
|
for result := range results {
|
|
if result.Code != 200 {
|
|
t.Fatalf("concurrent retry got %d %s", result.Code, result.Body.String())
|
|
}
|
|
}
|
|
if version(boards[0]) != 3 {
|
|
t.Fatal("concurrent request executed more than once")
|
|
}
|
|
// A valid first participant and an invalid second participant produce no partial write.
|
|
atomic := batch(5, 3)
|
|
atomic.ExpectedVersions[boards[1]] = 1
|
|
atomic.Operations = append(atomic.Operations, canvasOperation{ID: key(500), Type: "node.delete", CanvasID: boards[1], ElementID: "missing"})
|
|
call("POST", path, tokens[0], atomic, 400)
|
|
if version(boards[0]) != 3 || version(boards[1]) != 1 {
|
|
t.Fatal("invalid multi-canvas batch partially committed")
|
|
}
|
|
if call("GET", path+"/"+key(5), tokens[0], canvasOperationBatch{}, 200)["status"] != "not-applied" {
|
|
t.Fatal("invalid batch lost its terminal receipt")
|
|
}
|
|
}
|