fix(17-06): singleton route retries a lost first-or-create race

Two first requests to GET .../singleton both missed the record; the
loser's insert hit the unique index and the route answered 500. A
unique violation from SingletonRecord now reruns the transaction once,
which finds the winner's record. TestSingleton fires six concurrent
first requests and requires 200 with the same id from each.
This commit is contained in:
2026-10-12 19:31:01 +02:00
parent 91593da1f7
commit 6312929148
4 changed files with 60 additions and 7 deletions

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"strings"
"sync"
"testing"
"git.golem15.com/golem15/summercms/modules/pact"
@@ -47,11 +48,36 @@ func (plainProfiles) RequiredPermissions() []string { return []string{"acme.comp
func (plainProfiles) NewRecord() any { return &companionsProfile{} }
// TestSingleton pins the D-11 routes on Postgres: the singleton route
// creates the record once and answers its id; the record shows and updates; list, create, delete, bulk delete
// creates the record once, also when first requests race (each answers 200
// with the same id), and answers its id; the record shows and updates; list, create, delete, bulk delete
// and reorder answer 404; the form schema says singleton; a controller that
// is not a singleton answers 404 on the route; anonymous requests 401.
func TestSingleton(t *testing.T) {
e := newCompanionsEnv(t)
// Concurrent first requests: the losers of the first-or-create race
// retry and find the winner's record.
var wg sync.WaitGroup
answers := make([]*struct {
code int
body string
}, 6)
for i := range answers {
wg.Add(1)
go func(i int) {
defer wg.Done()
rec := e.send(t, http.MethodGet, "/acme/companions/profiles/singleton", nil, true)
answers[i] = &struct {
code int
body string
}{rec.Code, rec.Body.String()}
}(i)
}
wg.Wait()
for i, answer := range answers {
if answer.code != http.StatusOK || answer.body != answers[0].body {
t.Fatalf("concurrent first request %d: status=%d body=%s (first: %s)", i, answer.code, answer.body, answers[0].body)
}
}
first := e.send(t, http.MethodGet, "/acme/companions/profiles/singleton", nil, true)
id := dataID(t, first.Body.Bytes())
for range 2 {