Files
seaweedfs/weed/s3api/s3notification/publisher_test.go
T
Chris LuandClaude Opus 5.5 515b905011 s3notification: lose the test lock on the fetch of the records' partition (#13324)
TestALeadThatLostItsLockDoesNotSend dropped the forwarder lock on the
first fetch of any partition, then waited for a fetch of partition 0.
When another partition's goroutine fetched first, the lead stopped before
partition 0 was fetched and the wait timed out (seen on the 32-bit job).
The hook now gets the request and drops the lock on partition 0's fetch.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:50 -08:00

738 lines
24 KiB
Go

package s3notification
import (
"context"
"errors"
"fmt"
"io"
"net"
"slices"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
type fakeTopicPublisher struct {
mu sync.Mutex
stall bool
keys []string
stalled []chan struct{}
shutdowns int
}
func (f *fakeTopicPublisher) PublishRecord(key []byte, value *schema_pb.RecordValue) (<-chan struct{}, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.keys = append(f.keys, string(key))
acked := make(chan struct{})
if f.stall {
f.stalled = append(f.stalled, acked)
} else {
close(acked)
}
return acked, nil
}
func (f *fakeTopicPublisher) Shutdown() error {
f.mu.Lock()
f.shutdowns++
f.mu.Unlock()
return nil
}
func (f *fakeTopicPublisher) ackStalled() {
f.mu.Lock()
defer f.mu.Unlock()
f.stall = false
for _, acked := range f.stalled {
close(acked)
}
f.stalled = nil
}
func (f *fakeTopicPublisher) published() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.keys...)
}
// testPublisher has one fake MQ publisher per topic; setUp fails while failSetup is set.
type testPublisher struct {
*Publisher
mu sync.Mutex
topics map[string]*fakeTopicPublisher
stall bool
failSetup atomic.Bool
setupCalls atomic.Int32
}
func newTestPublisher(t *testing.T, targets ...string) *testPublisher {
t.Helper()
tp := &testPublisher{topics: map[string]*fakeTopicPublisher{}}
tp.Publisher = NewPublisher(func() []string { return nil }, nil)
tp.ackWait = 100 * time.Millisecond
tp.configureTopic = func(ctx context.Context, tt topic.Topic) error {
tp.setupCalls.Add(1)
if tp.failSetup.Load() {
return errors.New("balancer not ready")
}
return nil
}
tp.newTopicPublisher = func(ctx context.Context, tt topic.Topic) (topicPublisher, error) {
tp.mu.Lock()
defer tp.mu.Unlock()
f := &fakeTopicPublisher{stall: tp.stall}
tp.topics[tt.Name] = f
return f, nil
}
t.Cleanup(tp.Close)
if len(targets) > 0 {
tp.Sync(registryOf(t, targets...))
}
return tp
}
func (tp *testPublisher) topic(name string) *fakeTopicPublisher {
tp.mu.Lock()
defer tp.mu.Unlock()
return tp.topics["notify-"+name]
}
func registryOf(t *testing.T, names ...string) *Registry {
t.Helper()
content := `{"targets":[`
for i, name := range names {
if i > 0 {
content += ","
}
content += fmt.Sprintf(`{"name":%q,"type":"topic","enabled":true,"allowed_buckets":["*"]}`, name)
}
reg, err := ParseTargets([]byte(content + `]}`))
if err != nil {
t.Fatal(err)
}
return reg
}
func waitUntil(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(5 * time.Millisecond)
}
}
func testRecord() *schema_pb.RecordValue {
return (&Event{Name: EventObjectCreatedPut, Bucket: "photos", Key: "k", LogTsNs: 1}).RecordValue("id")
}
func dropped(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsCounter.WithLabelValues(target, "dropped"))
}
func TestPublishFansOutToEachTargetAndWaitsForAcks(t *testing.T) {
tp := newTestPublisher(t, "orders", "audit")
acked := tp.Publish(context.Background(), []Message{
{Target: "orders", Key: []byte("b/k1"), Value: testRecord()},
{Target: "audit", Key: []byte("b/k1"), Value: testRecord()},
{Target: "orders", Key: []byte("b/k2"), Value: testRecord()},
})
if !acked {
t.Fatal("records not acked")
}
if got := tp.topic("orders").published(); len(got) != 2 || got[0] != "b/k1" || got[1] != "b/k2" {
t.Fatalf("orders topic got %v", got)
}
if got := tp.topic("audit").published(); len(got) != 1 {
t.Fatalf("audit topic got %v", got)
}
}
func TestPublishGivesUpWaitingButKeepsTheRecord(t *testing.T) {
tp := newTestPublisher(t)
tp.stall = true
tp.Sync(registryOf(t, "slow"))
start := time.Now()
if tp.Publish(context.Background(), []Message{{Target: "slow", Key: []byte("b/k"), Value: testRecord()}}) {
t.Fatal("a stalled record reported acked")
}
if waited := time.Since(start); waited < tp.ackWait || waited > tp.ackWait+time.Second {
t.Fatalf("waited %v, want about %v", waited, tp.ackWait)
}
waitUntil(t, "the record to reach the publisher", func() bool {
f := tp.topic("slow")
return f != nil && len(f.published()) == 1
})
if d := dropped("slow"); d != 0 {
t.Fatalf("a late record was counted dropped %v times", d)
}
}
func TestPublishStopsWaitingWhenTheRequestEnds(t *testing.T) {
tp := newTestPublisher(t)
tp.stall = true
tp.ackWait = time.Minute
tp.Sync(registryOf(t, "slow"))
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
done := make(chan bool)
go func() { done <- tp.Publish(ctx, []Message{{Target: "slow", Key: []byte("b/k")}}) }()
select {
case acked := <-done:
if acked {
t.Fatal("reported acked")
}
case <-time.After(10 * time.Second):
t.Fatal("Publish kept waiting after the request ended")
}
}
func TestPublishQueuesThroughABrokerColdStart(t *testing.T) {
tp := newTestPublisher(t)
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "orders"))
if tp.Publish(context.Background(), []Message{{Target: "orders", Key: []byte("b/early")}}) {
t.Fatal("acked before the topic exists")
}
waitUntil(t, "setup retries", func() bool { return tp.setupCalls.Load() >= 2 })
tp.failSetup.Store(false)
waitUntil(t, "the queued record to be published", func() bool {
f := tp.topic("orders")
return f != nil && len(f.published()) == 1
})
if !tp.Publish(context.Background(), []Message{{Target: "orders", Key: []byte("b/late")}}) {
t.Fatal("record after setup not acked")
}
}
func TestPublishDropsWhenTheQueueIsFull(t *testing.T) {
tp := newTestPublisher(t)
tp.queueSize = 2
tp.ackWait = 10 * time.Millisecond
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "full"))
before := dropped("full")
messages := []Message{{Target: "full", Key: []byte("b/1")}, {Target: "full", Key: []byte("b/2")}, {Target: "full", Key: []byte("b/3")}}
if tp.Publish(context.Background(), messages) {
t.Fatal("acked with the broker down")
}
if got := dropped("full") - before; got != 1 {
t.Fatalf("dropped %v records, want 1", got)
}
tp.failSetup.Store(false)
waitUntil(t, "the queued records", func() bool {
f := tp.topic("full")
return f != nil && len(f.published()) == 2
})
}
func TestPublishDropsForATargetWithoutAWorker(t *testing.T) {
tp := newTestPublisher(t, "orders")
before := dropped("gone")
if tp.Publish(context.Background(), []Message{{Target: "gone", Key: []byte("b/k")}}) {
t.Fatal("acked a record for an unknown target")
}
if got := dropped("gone") - before; got != 1 {
t.Fatalf("dropped %v, want 1", got)
}
}
func TestSyncStopsRemovedAndDisabledTargets(t *testing.T) {
tp := newTestPublisher(t, "keep", "remove", "disable")
for _, name := range []string{"keep", "remove", "disable"} {
name := name
waitUntil(t, name+" set up", func() bool { return tp.topic(name) != nil })
}
reg, err := ParseTargets([]byte(`{"targets":[
{"name":"keep","type":"topic","enabled":true,"allowed_buckets":["*"]},
{"name":"disable","type":"topic","enabled":false,"allowed_buckets":["*"]}]}`))
if err != nil {
t.Fatal(err)
}
tp.Sync(reg)
for _, name := range []string{"remove", "disable"} {
f := tp.topic(name)
waitUntil(t, name+" shut down", func() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.shutdowns == 1 })
}
if f := tp.topic("keep"); f.shutdowns != 0 {
t.Fatal("a kept target was shut down")
}
if tp.Publish(context.Background(), []Message{{Target: "remove", Key: []byte("b/k")}}) {
t.Fatal("a removed target still takes records")
}
}
type failingTopicPublisher struct{}
func (failingTopicPublisher) PublishRecord([]byte, *schema_pb.RecordValue) (<-chan struct{}, error) {
return nil, errors.New("publisher is closed")
}
func (failingTopicPublisher) Shutdown() error { return nil }
func late(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsLateCounter.WithLabelValues(target))
}
func TestADroppedRecordEndsTheWaitAndIsCountedOnce(t *testing.T) {
t.Run("publish error", func(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = time.Minute
tp.newTopicPublisher = func(context.Context, topic.Topic) (topicPublisher, error) { return failingTopicPublisher{}, nil }
tp.Sync(registryOf(t, "failing"))
droppedBefore, lateBefore := dropped("failing"), late("failing")
start := time.Now()
if tp.Publish(context.Background(), []Message{{Target: "failing", Key: []byte("b/k")}}) {
t.Fatal("a record the publisher refused reported acked")
}
if waited := time.Since(start); waited > 5*time.Second {
t.Fatalf("waited %v for a record already dropped", waited)
}
if d, l := dropped("failing")-droppedBefore, late("failing")-lateBefore; d != 1 || l != 0 {
t.Fatalf("counted dropped %v, late %v; want 1 and 0", d, l)
}
})
t.Run("target removed", func(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = time.Minute
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "removed"))
droppedBefore, lateBefore := dropped("removed"), late("removed")
result := make(chan bool)
go func() { result <- tp.Publish(context.Background(), []Message{{Target: "removed", Key: []byte("b/k")}}) }()
waitUntil(t, "the record to be queued", func() bool {
tp.mu.Lock()
defer tp.mu.Unlock()
return len(tp.targets["removed"].queue) == 1
})
tp.Sync(registryOf(t))
select {
case acked := <-result:
if acked {
t.Fatal("a dropped record reported acked")
}
case <-time.After(5 * time.Second):
t.Fatal("Publish kept waiting for a record its removed target dropped")
}
if d, l := dropped("removed")-droppedBefore, late("removed")-lateBefore; d != 1 || l != 0 {
t.Fatalf("counted dropped %v, late %v; want 1 and 0", d, l)
}
})
}
func TestStoppedTargetDropsItsQueue(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = 10 * time.Millisecond
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "stuck"))
tp.mu.Lock()
worker := tp.targets["stuck"]
tp.mu.Unlock()
droppedBefore, lateBefore := dropped("stuck"), late("stuck")
tp.Publish(context.Background(), []Message{{Target: "stuck", Key: []byte("b/k")}})
tp.Sync(registryOf(t))
<-worker.done
if n := len(worker.queue); n != 0 {
t.Fatalf("%d records left queued", n)
}
// late when its request answered, then dropped when its target stopped
if d, l := dropped("stuck")-droppedBefore, late("stuck")-lateBefore; d != 1 || l != 1 {
t.Fatalf("counted dropped %v, late %v; want 1 and 1", d, l)
}
}
func acked(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsCounter.WithLabelValues(target, "acked"))
}
func TestARecordIsCountedOnceAsAckedOrDroppedAndLateSeparately(t *testing.T) {
for _, tc := range []struct {
name string
run func(w *targetWorker, r *pendingRecord)
acked, dropped, late float64
}{
{"timeout between a drop's count and its done", func(w *targetWorker, r *pendingRecord) {
w.afterDropSettled = func() { r.answered() }
w.drop(r, "test")
}, 0, 1, 0},
{"late, then dropped", func(w *targetWorker, r *pendingRecord) {
r.answered()
w.drop(r, "test")
}, 0, 1, 1},
{"late, then acked", func(w *targetWorker, r *pendingRecord) {
r.answered()
r.settle(recordAcked)
}, 1, 0, 1},
{"dropped, then a stray ack", func(w *targetWorker, r *pendingRecord) {
w.drop(r, "test")
r.settle(recordAcked)
}, 0, 1, 0},
{"answered twice", func(w *targetWorker, r *pendingRecord) {
r.answered()
r.answered()
w.drop(r, "test")
}, 0, 1, 1},
} {
t.Run(tc.name, func(t *testing.T) {
target := "count-" + tc.name
record := &pendingRecord{target: target, done: make(chan struct{})}
a, d, l := acked(target), dropped(target), late(target)
tc.run(&targetWorker{name: target}, record)
if got := [3]float64{acked(target) - a, dropped(target) - d, late(target) - l}; got != [3]float64{tc.acked, tc.dropped, tc.late} {
t.Fatalf("acked, dropped, late = %v, want %v", got, [3]float64{tc.acked, tc.dropped, tc.late})
}
})
}
}
// fullTopicPublisher is an MQ publisher whose partition buffer is full while
// the broker is away: PublishRecord blocks until Shutdown closes its input,
// and Shutdown then waits for acks that never come.
type fullTopicPublisher struct {
closed chan struct{}
closeOnce sync.Once
neverAcked chan struct{}
published atomic.Int32
}
func (f *fullTopicPublisher) PublishRecord(key []byte, value *schema_pb.RecordValue) (<-chan struct{}, error) {
f.published.Add(1)
<-f.closed
return nil, errors.New("publisher is closed")
}
func (f *fullTopicPublisher) Shutdown() error {
f.closeOnce.Do(func() { close(f.closed) })
<-f.neverAcked
return nil
}
func TestStoppingATargetReleasesAPublisherBlockedOnAFullBuffer(t *testing.T) {
for _, stop := range []string{"removed", "closed"} {
t.Run(stop, func(t *testing.T) {
full := &fullTopicPublisher{closed: make(chan struct{}), neverAcked: make(chan struct{})}
t.Cleanup(func() { close(full.neverAcked) })
tp := newTestPublisher(t)
tp.newTopicPublisher = func(context.Context, topic.Topic) (topicPublisher, error) { return full, nil }
tp.ackWait = 10 * time.Millisecond
tp.Sync(registryOf(t, "down"))
tp.mu.Lock()
worker := tp.targets["down"]
tp.mu.Unlock()
tp.Publish(context.Background(), []Message{{Target: "down", Key: []byte("b/k1")}, {Target: "down", Key: []byte("b/k2")}})
waitUntil(t, "the worker to block in PublishRecord", func() bool { return full.published.Load() == 1 })
returned := make(chan struct{})
go func() {
if stop == "removed" {
tp.Sync(registryOf(t))
} else {
tp.Close()
}
close(returned)
}()
select {
case <-returned:
case <-time.After(5 * time.Second):
t.Fatal("stopping the target waited for the publisher to flush")
}
select {
case <-worker.done:
case <-time.After(5 * time.Second):
t.Fatal("the worker is still blocked in PublishRecord")
}
if n := full.published.Load(); n != 1 {
t.Fatalf("the stopped target published %d records, want only the one in flight", n)
}
})
}
}
// fakeBroker is an in-process broker that refuses topic configuration while
// it is "starting", then leads every partition, acks each message, and serves
// what it holds to FetchMessage.
type fakeBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
refuseFirst int32
failLookups bool // the partitions never get a leader
lookups atomic.Int32
hang bool // ConfigureTopic accepts the call and never answers
mu sync.Mutex
configures int32
configured *mq_pb.ConfigureTopicRequest
recordType []*schema_pb.RecordType // every record type a ConfigureTopic carried
stored map[string][]string
values [][]byte
logs map[fakeLogKey]*fakeLog
fetches map[fakeLogKey]int
// version and partitionCount are the generation and number of the
// partitions lookups list; a repartition changes them
version int64
partitionCount int32
// retired holds the partition count of each generation a repartition replaced
retired map[int64]int32
// unsealed retired generations are neither listed nor served, as before a drain seals them
unsealed map[int64]bool
// segment, when set, ends each fetch at the next multiple of it, as a
// flushed segment's boundary does
segment int64
failFetches int
// holding makes a fetch at holdAt return no records, as a broker that
// cannot read a span it reports below its high-water mark does
holding bool
holdAt int64
// onFetch runs as a fetch arrives
onFetch func(req *mq_pb.FetchMessageRequest)
// fetchErrorCode, when set, answers every fetch with that broker error, as a broker that cannot read the files does
fetchErrorCode int32
}
func (b *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
if b.hang {
<-ctx.Done()
return nil, ctx.Err()
}
b.mu.Lock()
defer b.mu.Unlock()
b.configures++
if b.configures <= b.refuseFirst {
return nil, status.Error(codes.Unavailable, "no balancer")
}
if req.Retention != nil {
b.configured = req
}
b.recordType = append(b.recordType, req.MessageRecordType)
return &mq_pb.ConfigureTopicResponse{}, nil
}
func (b *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
b.lookups.Add(1)
if b.failLookups {
return nil, status.Error(codes.Unavailable, "no broker available")
}
b.mu.Lock()
defer b.mu.Unlock()
resp := &mq_pb.LookupTopicBrokersResponse{Topic: req.Topic}
for _, partition := range b.assignedLocked() {
resp.BrokerPartitionAssignments = append(resp.BrokerPartitionAssignments, &mq_pb.BrokerPartitionAssignment{
Partition: partition,
LeaderBroker: b.addr,
})
}
if req.IncludeRetired {
for version, count := range b.retired {
if b.unsealed[version] {
continue
}
// listed as the broker finds them, from their directory names
for _, partition := range generationPartitions(atSecond(version), count) {
if log := b.logs[fakeLogKey{version, partition.RangeStart}]; log != nil && int64(len(log.values)) > log.start {
resp.RetiredPartitions = append(resp.RetiredPartitions, &mq_pb.RetiredPartition{
Partition: partition, LogStartOffset: log.start, HighWaterMark: int64(len(log.values)),
})
}
}
}
}
return resp, nil
}
// assignedLocked is the current generation's partitions, TopicPartitionCount
// of them unless a repartition set partitionCount.
func (b *fakeBroker) assignedLocked() []*schema_pb.Partition {
count := int32(TopicPartitionCount)
if b.partitionCount > 0 {
count = b.partitionCount
}
return generationPartitions(b.version, count)
}
func generationPartitions(version int64, count int32) []*schema_pb.Partition {
width := pub_balancer.MaxPartitionCount / count
var partitions []*schema_pb.Partition
for i := int32(0); i < count; i++ {
stop := (i + 1) * width
if i == count-1 {
stop = pub_balancer.MaxPartitionCount
}
partitions = append(partitions, &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop, UnixTimeNs: version})
}
return partitions
}
func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
init, err := stream.Recv()
if err != nil {
return err
}
partition := fmt.Sprint(init.GetInit().GetPartition().GetRangeStart())
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
for {
req, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
data := req.GetData()
if data == nil || data.Ctrl != nil {
continue
}
b.mu.Lock()
b.stored[partition] = append(b.stored[partition], string(data.Key))
b.values = append(b.values, data.Value)
p := init.GetInit().GetPartition()
b.appendLocked(fakeLogKey{p.GetUnixTimeNs(), p.GetRangeStart()}, data.Value)
b.mu.Unlock()
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
return err
}
}
}
func startFakeBroker(t *testing.T, broker *fakeBroker) *fakeBroker {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
broker.addr = listener.Addr().String()
broker.stored = map[string][]string{}
server := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(server, broker)
go server.Serve(listener)
t.Cleanup(server.Stop)
return broker
}
func TestConfigureTopicMovesPastAHangingBroker(t *testing.T) {
hanging := startFakeBroker(t, &fakeBroker{hang: true})
healthy := startFakeBroker(t, &fakeBroker{})
p := NewPublisher(func() []string { return []string{hanging.addr, healthy.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
p.configureTimeout = 200 * time.Millisecond
result := make(chan error, 1)
go func() {
result <- p.configureTopicOnBroker(context.Background(), topic.NewTopic(TopicNamespace, "notify-t"))
}()
select {
case err := <-result:
if err != nil {
t.Fatalf("configure topic: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("setup is stuck on a broker that never answers")
}
healthy.mu.Lock()
defer healthy.mu.Unlock()
if healthy.configured == nil {
t.Fatal("the next broker was not asked")
}
}
func TestRemovingATargetStopsItsPublisherStillStarting(t *testing.T) {
broker := startFakeBroker(t, &fakeBroker{failLookups: true})
p := NewPublisher(func() []string { return []string{broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
t.Cleanup(p.Close)
p.Sync(registryOf(t, "orphan"))
p.mu.Lock()
worker := p.targets["orphan"]
p.mu.Unlock()
waitUntil(t, "partition lookups to be retried", func() bool { return broker.lookups.Load() >= 2 })
p.Sync(registryOf(t))
select {
case <-worker.done:
case <-time.After(10 * time.Second):
t.Fatal("the removed target's publisher is still starting")
}
lookups := broker.lookups.Load()
time.Sleep(6 * time.Second) // past the MQ publisher's longest lookup backoff
if after := broker.lookups.Load(); after != lookups {
t.Fatalf("lookups went on after the target was removed: %d then %d", lookups, after)
}
}
func TestPublisherCreatesTheTopicAndPublishesThroughABroker(t *testing.T) {
broker := startFakeBroker(t, &fakeBroker{refuseFirst: 2})
p := NewPublisher(func() []string { return []string{broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
t.Cleanup(p.Close)
p.Sync(registryOf(t, "orders"))
var messages []Message
for i := 0; i < 20; i++ {
messages = append(messages, Message{Target: "orders", Key: MessageKey("photos", fmt.Sprintf("k%d", i)), Value: testRecord()})
}
// The first attempts meet a broker still taking the balancer lock.
waitUntil(t, "records acked", func() bool { return p.Publish(context.Background(), messages[:1]) })
if !p.Publish(context.Background(), messages) {
t.Fatal("records not acked")
}
broker.mu.Lock()
defer broker.mu.Unlock()
if broker.configures <= broker.refuseFirst {
t.Fatalf("topic configured %d times, want retries past %d refusals", broker.configures, broker.refuseFirst)
}
req := broker.configured
if req == nil || req.Topic.Namespace != "s3" || req.Topic.Name != "notify-orders" || req.PartitionCount != 4 ||
!req.Retention.Enabled || req.Retention.RetentionSeconds != 7*24*3600 ||
!slices.Equal(req.KeyColumns, []string{"bucket_name", "object_key"}) || req.SchemaFormat != "" {
t.Fatalf("topic configured as %v", req)
}
// the MQ publisher configures the topic too; neither may change its schema
for _, recordType := range broker.recordType {
if !proto.Equal(recordType, EventRecordType()) {
t.Fatalf("topic configured with record type %v", recordType)
}
}
for _, value := range broker.values {
stored := &schema_pb.RecordValue{}
if err := proto.Unmarshal(value, stored); err != nil || !proto.Equal(stored, testRecord()) {
t.Fatalf("stored value %v (%v), want the published record", stored, err)
}
}
// every copy of one key landed in one partition
partitionOf := map[string]string{}
for partition, keys := range broker.stored {
for _, key := range keys {
if other, ok := partitionOf[key]; ok && other != partition {
t.Fatalf("key %s in partitions %s and %s", key, other, partition)
}
partitionOf[key] = partition
}
}
if len(partitionOf) != 20 {
t.Fatalf("stored %d distinct keys, want 20", len(partitionOf))
}
}