Files
lincodex/backend/integration_test/kafka_helpers_test.go
T

194 lines
6.4 KiB
Go

//go:build integration
package integration_test
import (
"context"
"crypto/rand"
"errors"
"strings"
"testing"
"time"
"github.com/moby/moby/client"
"github.com/testcontainers/testcontainers-go"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
)
const (
kafkaTopicPrefix = "integration-"
kafkaReplicationFactor = 1
kafkaOperationTimeout = 15 * time.Second
)
// newKafkaClient returns a client for the test broker that closes when t
// finishes. Options add producer or consumer settings to the seed brokers.
func (env *testEnvironment) newKafkaClient(t *testing.T, options ...kgo.Opt) *kgo.Client {
t.Helper()
if env.kafkaContainer == nil {
t.Fatal("Kafka was not selected in bootstrap")
}
options = append([]kgo.Opt{kgo.SeedBrokers(env.Config.KafkaBrokers...)}, options...)
client, err := kgo.NewClient(options...)
if err != nil {
t.Fatalf("create Kafka client: %v", err)
}
t.Cleanup(client.Close)
return client
}
// newKafkaTopicName returns a name that no other test or shard uses.
func newKafkaTopicName() string {
return kafkaTopicPrefix + strings.ToLower(rand.Text())
}
// createKafkaTopic creates a uniquely named topic and deletes it when t
// finishes, including after a failure. The broker never creates topics on
// demand, so tests create every topic they use.
func (env *testEnvironment) createKafkaTopic(ctx context.Context, t *testing.T, partitions int32) string {
t.Helper()
topic := newKafkaTopicName()
// Register deletion first: a request that times out may still create it.
// The test context is already canceled when cleanup runs.
cleanupCtx := context.WithoutCancel(ctx)
t.Cleanup(func() { env.deleteKafkaTopic(cleanupCtx, t, topic) })
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
responses, err := env.KafkaAdmin.CreateTopics(ctx, partitions, kafkaReplicationFactor, nil, topic)
if err == nil {
var response kadm.CreateTopicResponse
response, err = responses.On(topic, nil)
if err == nil {
err = response.Err
}
}
if err != nil {
t.Fatalf("create Kafka topic %s: %v", topic, err)
}
return topic
}
func (env *testEnvironment) deleteKafkaTopic(ctx context.Context, t *testing.T, topic string) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, cleanupTimeout)
defer cancel()
responses, err := env.KafkaAdmin.DeleteTopics(ctx, topic)
if err == nil {
var response kadm.DeleteTopicResponse
response, err = responses.On(topic, nil)
if err == nil {
err = response.Err
}
}
// A failed creation leaves nothing to delete.
if err != nil && !errors.Is(err, kerr.UnknownTopicOrPartition) {
t.Errorf("delete Kafka topic %s: %v", topic, err)
}
}
func produceKafkaRecords(ctx context.Context, t *testing.T, client *kgo.Client, records ...*kgo.Record) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
if err := client.ProduceSync(ctx, records...).FirstErr(); err != nil {
t.Fatalf("produce %d Kafka records: %v", len(records), err)
}
}
// consumeKafkaRecords reads count records from the start of every partition of
// topic without a consumer group, so no group offsets outlive the test.
func (env *testEnvironment) consumeKafkaRecords(ctx context.Context, t *testing.T, topic string, count int) []*kgo.Record {
t.Helper()
consumer := env.newKafkaClient(t,
kgo.ConsumeTopics(topic),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
records := make([]*kgo.Record, 0, count)
for len(records) < count {
fetches := consumer.PollFetches(ctx)
if err := ctx.Err(); err != nil {
t.Fatalf("consume Kafka topic %s: received %d of %d records: %v", topic, len(records), count, err)
}
if err := fetches.Err(); err != nil {
t.Fatalf("consume Kafka topic %s: %v", topic, err)
}
records = append(records, fetches.Records()...)
}
return records
}
// kafkaTopicExists reports whether the broker metadata contains topic.
func kafkaTopicExists(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) bool {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
topics, err := admin.ListTopics(ctx, topic)
if err != nil {
t.Fatalf("list Kafka topic %s: %v", topic, err)
}
if detail, ok := topics[topic]; ok && detail.Err != nil && !errors.Is(detail.Err, kerr.UnknownTopicOrPartition) {
t.Fatalf("load Kafka topic %s: %v", topic, detail.Err)
}
return topics.Has(topic)
}
// waitForKafkaTopicDeletion allows for the short delay before a deletion
// accepted by the controller reaches broker metadata.
func waitForKafkaTopicDeletion(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
ticker := time.NewTicker(readinessInterval)
defer ticker.Stop()
for kafkaTopicExists(ctx, t, admin, topic) {
select {
case <-ctx.Done():
t.Fatalf("Kafka topic %s still exists after cleanup", topic)
case <-ticker.C:
}
}
}
// pauseKafka freezes the broker without closing its port, so clients see a
// broker that accepts connections and never answers. A stopped container
// would come back on a different host port, which the advertised listener
// and the clients' seed brokers do not follow. The returned function resumes
// the broker; cleanup also resumes it so the container can be terminated.
func (env *testEnvironment) pauseKafka(ctx context.Context, t *testing.T) (resume func()) {
t.Helper()
if env.kafkaContainer == nil {
t.Fatal("Kafka was not selected in bootstrap")
}
docker, err := testcontainers.NewDockerClientWithOpts(ctx)
if err != nil {
t.Fatalf("create Docker client: %v", err)
}
t.Cleanup(func() { _ = docker.Close() })
containerID := env.kafkaContainer.GetContainerID()
pauseCtx, cancel := context.WithTimeout(ctx, stopTimeout)
defer cancel()
if _, err := docker.ContainerPause(pauseCtx, containerID, client.ContainerPauseOptions{}); err != nil {
t.Fatalf("pause Kafka: %v", err)
}
paused := true
resume = func() {
t.Helper()
if !paused {
return
}
resumeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stopTimeout)
defer cancel()
if _, err := docker.ContainerUnpause(resumeCtx, containerID, client.ContainerUnpauseOptions{}); err != nil {
t.Errorf("resume Kafka: %v", err)
return
}
paused = false
}
t.Cleanup(resume)
return resume
}