package main import ( "context" "sync" "testing" "time" "github.com/alicebob/miniredis/v2" "github.com/redis/go-redis/v9" ) // newReplicas starts two brokers on one Redis, as two wicket replicas // share one. func newReplicas(t *testing.T) (*Broker, *Broker, *miniredis.Miniredis) { t.Helper() mr := miniredis.RunT(t) start := func() *Broker { backend := newRedisBackendFromClient(redis.NewClient(&redis.Options{Addr: mr.Addr()}), 1000) t.Cleanup(func() { backend.Close() }) broker := NewBroker(backend, NewMetrics("test")) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) if err := broker.Start(ctx); err != nil { t.Fatal(err) } return broker } return start(), start(), mr } func subscribe(t *testing.T, b *Broker, path, lastEventID string) <-chan *Event { t.Helper() ch, unsub, err := b.Subscribe(path, lastEventID) if err != nil { t.Fatal(err) } t.Cleanup(unsub) return ch } func receiveN(t *testing.T, ch <-chan *Event, n int) []*Event { t.Helper() events := make([]*Event, n) for i := range events { events[i] = mustReceive(t, ch, 5*time.Second) } return events } // A burst of concurrent publishes on both replicas reaches a live // subscriber in the order of its IDs and its times, and a subscriber // that resumes from the middle of the burst on the other replica gets // exactly the rest, in the same order. func TestReplicas_aBurstArrivesInOneOrderLiveAndOnReplay(t *testing.T) { a, b, _ := newReplicas(t) live := subscribe(t, b, "test", "") var wg sync.WaitGroup for i := range 20 { wg.Add(1) go func() { defer wg.Done() replica := []*Broker{a, b}[i%2] if err := replica.Publish(&Event{Path: "test", Payload: map[string]any{"n": i}}); err != nil { t.Error(err) } }() } wg.Wait() received := receiveN(t, live, 20) for i := 1; i < len(received); i++ { previous, _ := parseEventID(received[i-1].ID) id, _ := parseEventID(received[i].ID) if !id.after(previous) || received[i].Timestamp.Before(received[i-1].Timestamp) { t.Fatalf("event %d (%s at %s) came after %s at %s", i, received[i].ID, received[i].Timestamp, received[i-1].ID, received[i-1].Timestamp) } } replay := receiveN(t, subscribe(t, a, "test", received[9].ID), 10) for i, e := range replay { if e.ID != received[10+i].ID { t.Errorf("replayed event %d is %s, want %s", i, e.ID, received[10+i].ID) } } }