// 🤖 Tests for the global id allocator. Two harnesses: // // - memCounter: an in-memory, CAS-correct fake of the counterStore interface // for the block/refill/retry LOGIC — deterministic, no HTTP. // - fakeCASS3: an httptest S3 fake that speaks conditional writes (If-Match / // If-None-Match → 412), driven by the REAL aws-sdk-go-v2 client via New's // Endpoint override — the same fake-endpoint pattern s3blobstore_test.go // uses, so the production S3 code path (conditional PutObject, ETag reads, // 412 → retry) is exercised for real. The repo has no shared S3 fake with // conditional-write support, so this one is scoped to exactly the CAS // operations the allocator uses. package idalloc import ( "context" "fmt" "io" "net/http" "net/http/httptest" "sync" "testing" ) // --- in-memory CAS fake ------------------------------------------------------ // memCounter is a faithful compare-and-swap over one value: a swap succeeds only // if its token matches the current version, exactly like S3's ETag conditional. type memCounter struct { mu sync.Mutex value uint64 exists bool ver int // bumps on every successful swap; token is "v" loads int swapOK int // successful swaps = blocks reserved } func (m *memCounter) tokenLocked() string { if !m.exists { return "" } return fmt.Sprintf("v%d", m.ver) } func (m *memCounter) load(ctx context.Context) (uint64, string, error) { m.mu.Lock() defer m.mu.Unlock() m.loads++ return m.value, m.tokenLocked(), nil } func (m *memCounter) swap(ctx context.Context, token string, newValue uint64) (bool, error) { m.mu.Lock() defer m.mu.Unlock() if token != m.tokenLocked() { return false, nil // stale token: a competitor moved the counter first } m.value = newValue m.exists = true m.ver++ m.swapOK++ return true, nil } // flakyStore wraps a memCounter and, for the first `conflicts` swaps, simulates a // competitor slipping a block in between the caller's load and its swap: it // advances the underlying counter and then reports the caller's write as lost. // This drives the CAS-conflict retry branch deterministically. type flakyStore struct { inner *memCounter competitorBlock uint64 mu sync.Mutex conflicts int injected int } func (f *flakyStore) load(ctx context.Context) (uint64, string, error) { return f.inner.load(ctx) } func (f *flakyStore) swap(ctx context.Context, token string, newValue uint64) (bool, error) { f.mu.Lock() inject := f.conflicts > 0 if inject { f.conflicts-- f.injected++ } f.mu.Unlock() if inject { cur, tok, _ := f.inner.load(ctx) if _, err := f.inner.swap(ctx, tok, cur+f.competitorBlock); err != nil { return false, err } return false, nil // caller's token is now stale } return f.inner.swap(ctx, token, newValue) } func TestAllocateBlockRefill(t *testing.T) { m := &memCounter{} a := newWithStore(m, 4) // small block so 10 ids span multiple reservations ctx := context.Background() var got []uint64 for i := 0; i < 10; i++ { id, err := a.Allocate(ctx) if err != nil { t.Fatalf("allocate %d: %v", i, err) } got = append(got, id) } for i, id := range got { if want := uint64(i + 1); id != want { t.Fatalf("id[%d] = %d, want %d (ids must be 1-based and contiguous)", i, id, want) } } // ceil(10/4) = 3 blocks; each block is one S3 CAS. This is the whole point: // 10 ids cost 3 S3 writes, not 10. if m.swapOK != 3 { t.Fatalf("reservations = %d, want 3 (blocks of 4 covering 10 ids)", m.swapOK) } if m.value != 12 { t.Fatalf("high-water = %d, want 12 (3 blocks of 4)", m.value) } } func TestAllocatePersistsAcrossRestart(t *testing.T) { m := &memCounter{} ctx := context.Background() // A reserves a block of 100 but hands out only 3 ids, then "crashes". a := newWithStore(m, 100) for i := 0; i < 3; i++ { if _, err := a.Allocate(ctx); err != nil { t.Fatalf("A allocate: %v", err) } } if m.value != 100 { t.Fatalf("high-water after A = %d, want 100", m.value) } // A fresh allocator over the same backing store must continue PAST the stored // high-water — skipping the unused tail of A's block (ids 4..100 are burned). b := newWithStore(m, 100) id, err := b.Allocate(ctx) if err != nil { t.Fatalf("B allocate: %v", err) } if id != 101 { t.Fatalf("restarted allocator handed out %d, want 101 (must not reuse A's block)", id) } } func TestAllocateRetriesOnCASConflict(t *testing.T) { inner := &memCounter{} f := &flakyStore{inner: inner, competitorBlock: 7, conflicts: 1} a := newWithStore(f, 100) id, err := a.Allocate(context.Background()) if err != nil { t.Fatalf("allocate: %v", err) } if f.injected != 1 { t.Fatalf("injected conflicts = %d, want 1 (the retry path must have fired)", f.injected) } // The competitor took ids [1,7]; our retry must start strictly after it. if id != 8 { t.Fatalf("id after conflict = %d, want 8 (must skip the competitor's block)", id) } if inner.value != 107 { t.Fatalf("high-water = %d, want 107 (competitor's 7 + our block of 100)", inner.value) } } func TestAllocateConcurrentUniqueAcrossAllocators(t *testing.T) { // Two independent allocators over ONE shared counter — the production shape: // two region clouds minting at once must never collide. shared := &memCounter{} a1 := newWithStore(shared, 10) a2 := newWithStore(shared, 10) ctx := context.Background() const goroutines = 8 const perGoroutine = 200 // > blockSize, so every goroutine forces refills var mu sync.Mutex seen := map[uint64]bool{} var wg sync.WaitGroup run := func(a *Allocator) { defer wg.Done() for i := 0; i < perGoroutine; i++ { id, err := a.Allocate(ctx) if err != nil { t.Errorf("allocate: %v", err) return } mu.Lock() if seen[id] { t.Errorf("duplicate id handed out: %d", id) } seen[id] = true mu.Unlock() } } for i := 0; i < goroutines; i++ { wg.Add(2) go run(a1) go run(a2) } wg.Wait() want := goroutines * 2 * perGoroutine if len(seen) != want { t.Fatalf("unique ids = %d, want %d (concurrent allocators overlapped)", len(seen), want) } for id := range seen { if id == 0 { t.Fatalf("handed out id 0 (ids must be 1-based)") } } } // --- httptest S3 fake (real SDK path) --------------------------------------- type fakeObj struct { body []byte etag string // includes the surrounding quotes, as S3 returns them } // fakeCASS3 is just enough S3 for the counter: path-style GET / conditional PUT // over an in-memory map, honouring If-Match / If-None-Match with a real 412. type fakeCASS3 struct { mu sync.Mutex objects map[string]fakeObj etagSeq int gets int putOK int put412 int // forceConflicts makes the next N PUTs answer 412 regardless of the // precondition — S3's ConditionalRequestConflict, letting a single-threaded // test drive the retry loop over the real wire deterministically. forceConflicts int } func (f *fakeCASS3) precondition412(w http.ResponseWriter) { f.put412++ w.Header().Set("Content-Type", "application/xml") w.WriteHeader(http.StatusPreconditionFailed) io.WriteString(w, `PreconditionFailedAt least one of the preconditions you specified did not hold.`) } func (f *fakeCASS3) handler(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() key := r.URL.Path switch r.Method { case http.MethodGet: f.gets++ obj, ok := f.objects[key] if !ok { w.Header().Set("Content-Type", "application/xml") w.WriteHeader(http.StatusNotFound) io.WriteString(w, `NoSuchKeyThe specified key does not exist.`) return } w.Header().Set("ETag", obj.etag) w.WriteHeader(http.StatusOK) w.Write(obj.body) case http.MethodPut: if f.forceConflicts > 0 { f.forceConflicts-- f.precondition412(w) return } body, _ := io.ReadAll(r.Body) obj, exists := f.objects[key] if r.Header.Get("If-None-Match") == "*" && exists { f.precondition412(w) // create-only, but it already exists return } if m := r.Header.Get("If-Match"); m != "" && (!exists || m != obj.etag) { f.precondition412(w) // replace-only, but the object moved on return } f.etagSeq++ etag := fmt.Sprintf("\"e%d\"", f.etagSeq) f.objects[key] = fakeObj{body: body, etag: etag} f.putOK++ w.Header().Set("ETag", etag) w.WriteHeader(http.StatusOK) default: w.WriteHeader(http.StatusNotImplemented) } } func newFakeS3Allocator(t *testing.T, blockSize uint64) (*Allocator, *fakeCASS3) { t.Helper() fake := &fakeCASS3{objects: map[string]fakeObj{}} srv := httptest.NewServer(http.HandlerFunc(fake.handler)) t.Cleanup(srv.Close) // Static creds + region so the SDK's signer is satisfied offline (same as // s3blobstore_test.go). t.Setenv("AWS_ACCESS_KEY_ID", "test") t.Setenv("AWS_SECRET_ACCESS_KEY", "test") t.Setenv("AWS_REGION", "auto") a, err := New(context.Background(), Config{ Bucket: "idbucket", Prefix: "pfx", Endpoint: srv.URL, BlockSize: blockSize, }) if err != nil { t.Fatalf("New: %v", err) } return a, fake } func TestS3AllocatorRoundTrip(t *testing.T) { a, fake := newFakeS3Allocator(t, 100) ctx := context.Background() for i := 0; i < 5; i++ { id, err := a.Allocate(ctx) if err != nil { t.Fatalf("allocate %d: %v", i, err) } if want := uint64(i + 1); id != want { t.Fatalf("id[%d] = %d, want %d", i, id, want) } } // 5 ids, one block: exactly one successful PUT. if fake.putOK != 1 { t.Fatalf("successful PUTs = %d, want 1 (one block for 5 ids)", fake.putOK) } obj := fake.objects["/idbucket/pfx/mesh/id-sequence"] if string(obj.body) != "100" { t.Fatalf("counter object = %q, want \"100\"", obj.body) } } func TestS3AllocatorRetriesReal412(t *testing.T) { a, fake := newFakeS3Allocator(t, 100) fake.forceConflicts = 2 // the first two PUTs come back 412 over the real SDK id, err := a.Allocate(context.Background()) if err != nil { t.Fatalf("allocate: %v", err) } if id != 1 { t.Fatalf("id = %d, want 1", id) } if fake.put412 != 2 { t.Fatalf("412 responses = %d, want 2 (the SDK must have retried each)", fake.put412) } if fake.putOK != 1 { t.Fatalf("successful PUTs = %d, want 1", fake.putOK) } } func TestS3AllocatorConcurrentUnique(t *testing.T) { // Two allocators, one fake bucket, blockSize 1 → maximum CAS contention over // the real conditional-PUT path. Uniqueness can only hold if 412s are being // retried correctly. fake := &fakeCASS3{objects: map[string]fakeObj{}} srv := httptest.NewServer(http.HandlerFunc(fake.handler)) t.Cleanup(srv.Close) t.Setenv("AWS_ACCESS_KEY_ID", "test") t.Setenv("AWS_SECRET_ACCESS_KEY", "test") t.Setenv("AWS_REGION", "auto") newA := func() *Allocator { a, err := New(context.Background(), Config{Bucket: "idbucket", Endpoint: srv.URL, BlockSize: 1}) if err != nil { t.Fatalf("New: %v", err) } return a } a1, a2 := newA(), newA() ctx := context.Background() const goroutines = 6 const perGoroutine = 40 var mu sync.Mutex seen := map[uint64]bool{} var wg sync.WaitGroup run := func(a *Allocator) { defer wg.Done() for i := 0; i < perGoroutine; i++ { id, err := a.Allocate(ctx) if err != nil { t.Errorf("allocate: %v", err) return } mu.Lock() if seen[id] { t.Errorf("duplicate id: %d", id) } seen[id] = true mu.Unlock() } } for i := 0; i < goroutines; i++ { wg.Add(2) go run(a1) go run(a2) } wg.Wait() if want := goroutines * 2 * perGoroutine; len(seen) != want { t.Fatalf("unique ids = %d, want %d", len(seen), want) } }