Skip to content
33 changes: 15 additions & 18 deletions downstreamadapter/sink/kafka/sink.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,27 +126,24 @@ func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.
if err != nil {
return errors.Trace(err)
}
if _, exists := topics[topic]; exists {
return nil
}

topicConfig := options.DeriveTopicConfig()
if !topicConfig.AutoCreate {
return errors.ErrKafkaInvalidConfig.GenWithStack("`auto-create-topic` is false, and %s not found", topic)
}
if _, exists := topics[topic]; !exists {
topicConfig := options.DeriveTopicConfig()
if !topicConfig.AutoCreate {
return errors.ErrKafkaInvalidConfig.GenWithStack("`auto-create-topic` is false, and %s not found", topic)
}

// the topic is not created, only validate.
err = adminClient.CreateTopic(&kafka.TopicDetail{
Name: topic,
NumPartitions: topicConfig.PartitionNum,
ReplicationFactor: topicConfig.ReplicationFactor,
}, true)
if err != nil {
return errors.WrapError(errors.ErrKafkaCreateTopic, err)
// the topic is not created, only validate.
err = adminClient.CreateTopic(&kafka.TopicDetail{
Name: topic,
NumPartitions: topicConfig.PartitionNum,
ReplicationFactor: topicConfig.ReplicationFactor,
}, true)
if err != nil {
return errors.WrapError(errors.ErrKafkaCreateTopic, err)
}
}

_, err = codec.NewEventEncoder(ctx, encoderConfig, claimCheck)
if err != nil {
if _, err = codec.NewEventEncoder(ctx, encoderConfig, claimCheck); err != nil {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return errors.Trace(err)
}
return nil
Expand Down
45 changes: 36 additions & 9 deletions downstreamadapter/sink/kafka/sink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@ package kafka
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/IBM/sarama"
"github.com/golang/mock/gomock"
"github.com/pingcap/ticdc/downstreamadapter/sink/columnselector"
"github.com/pingcap/ticdc/downstreamadapter/sink/eventrouter"
Expand All @@ -37,17 +40,41 @@ import (

const kafkaSinkTestTopic = "mock_topic"

func TestVerifyValidatesEncoderConfigBeforeKafkaConnection(t *testing.T) {
openProtocol := config.ProtocolOpen.String()
sinkConfig := &config.SinkConfig{Protocol: &openProtocol}
sinkURI, err := url.Parse("kafka://127.0.0.1:1/" + kafkaSinkTestTopic + "?max-batch-size=0")
func TestVerifyInvalidConfig(t *testing.T) {
broker := sarama.NewMockBroker(t, 1)
defer broker.Close()
broker.SetHandlerByMap(map[string]sarama.MockResponse{
"ApiVersionsRequest": sarama.NewMockApiVersionsResponse(t).SetApiKeys(
[]sarama.ApiVersionsResponseKey{
{ApiKey: 0},
{ApiKey: 1},
{ApiKey: 2},
{ApiKey: 3, MaxVersion: 9},
}),
"MetadataRequest": sarama.NewMockMetadataResponse(t).
SetController(broker.BrokerID()).
SetBroker(broker.Addr(), broker.BrokerID()).
SetLeader(kafkaSinkTestTopic, 0, broker.BrokerID()),
"DescribeConfigsRequest": sarama.NewMockDescribeConfigsResponse(t),
})

schemaRegistry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "invalid response", http.StatusInternalServerError)
}))
defer schemaRegistry.Close()

avroProtocol := config.ProtocolAvro.String()
sinkConfig := &config.SinkConfig{
Protocol: &avroProtocol,
SchemaRegistry: &schemaRegistry.URL,
}
sinkURI, err := url.Parse("kafka://" + broker.Addr() + "/" + kafkaSinkTestTopic +
"?required-acks=1&kafka-version=2.4.0")
require.NoError(t, err)

changefeedID := common.NewChangefeedID4Test("test", "verify-existing-topic")
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err = Verify(ctx, changefeedID, sinkURI, sinkConfig)
require.ErrorContains(t, err, "invalid max-batch-size 0")
changefeedID := common.NewChangefeedID4Test("test", "verify-invalid-config")
err = Verify(context.Background(), changefeedID, sinkURI, sinkConfig)
require.ErrorContains(t, err, "ErrAvroSchemaAPIError")
}

func newKafkaSinkForTestWithProducers(ctx context.Context,
Expand Down
18 changes: 16 additions & 2 deletions pkg/sink/kafka/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,27 @@ func (a *saramaAdminClient) GetTopicsMeta(topics []string, ignoreTopicError bool
continue
}
result[meta.Name] = TopicDetail{
Name: meta.Name,
NumPartitions: int32(len(meta.Partitions)),
Name: meta.Name,
NumPartitions: int32(len(meta.Partitions)),
ReplicationFactor: minReplicationFactor(meta.Partitions),
}
}
return result, nil
}

func minReplicationFactor(partitions []*sarama.PartitionMetadata) int16 {
minReplicas := 0
for i, partition := range partitions {
if partition == nil {
return 0
}
if i == 0 || len(partition.Replicas) < minReplicas {
minReplicas = len(partition.Replicas)
}
}
return int16(minReplicas)
}

// IsAdminAuthorizationFailed checks whether err is an authorization failure from Kafka admin APIs.
func IsAdminAuthorizationFailed(err error) bool {
return errors.Is(err, sarama.ErrTopicAuthorizationFailed) ||
Expand Down
24 changes: 24 additions & 0 deletions pkg/sink/kafka/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package kafka
import (
"testing"

"github.com/IBM/sarama"
"github.com/golang/mock/gomock"
"github.com/pingcap/ticdc/pkg/common"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -62,3 +63,26 @@ func TestAdminClientClose(t *testing.T) {
})
}
}

func TestTopicReplicationFactor(t *testing.T) {
ctrl := gomock.NewController(t)
admin := NewMocksaramaClusterAdmin(ctrl)
admin.EXPECT().DescribeTopics([]string{"test-topic"}).Return([]*sarama.TopicMetadata{
{
Name: "test-topic",
Err: sarama.ErrNoError,
Partitions: []*sarama.PartitionMetadata{
{Replicas: []int32{1, 2, 3}},
{Replicas: []int32{1, 2}},
},
},
}, nil)

client := &saramaAdminClient{
changefeed: common.NewChangeFeedIDWithName("test", "default"),
admin: admin,
}
topics, err := client.GetTopicsMeta([]string{"test-topic"}, false)
require.NoError(t, err)
require.Equal(t, int16(2), topics["test-topic"].ReplicationFactor)
}
6 changes: 5 additions & 1 deletion pkg/sink/kafka/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,11 @@ func validateRequiredAcks(
if options.RequiredAcks != WaitForAll {
return nil
}
return validateMinInsyncReplicas(ctx, admin, topics, topic, int(options.ReplicationFactor))
replicationFactor := options.ReplicationFactor
if info, exists := topics[topic]; exists {
replicationFactor = info.ReplicationFactor
}
return validateMinInsyncReplicas(ctx, admin, topics, topic, int(replicationFactor))
}

func adjustExistingTopicOption(
Expand Down
20 changes: 16 additions & 4 deletions pkg/sink/kafka/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ func newKafkaAdminFixture(t *testing.T) *kafkaAdminFixture {
}

func (f *kafkaAdminFixture) addTopic(name string, partitionNum int32) {
f.topics[name] = TopicDetail{Name: name, NumPartitions: partitionNum}
f.topics[name] = TopicDetail{
Name: name,
NumPartitions: partitionNum,
ReplicationFactor: mockClusterReplicationFactor,
}
}

func (f *kafkaAdminFixture) getTopicsMeta(
Expand Down Expand Up @@ -450,8 +454,9 @@ func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *t
adminClient := adminFixture.admin

detail := &TopicDetail{
Name: topicName,
NumPartitions: 3,
Name: topicName,
NumPartitions: 3,
ReplicationFactor: mockClusterReplicationFactor,
}
err := adminClient.CreateTopic(detail, false)
require.NoError(t, err)
Expand Down Expand Up @@ -540,9 +545,16 @@ func TestAdjustConfigMinInsyncReplicas(t *testing.T) {
err = adjustOptions(ctx, changefeedID, adminClient, options, topicName)
require.Nil(t, err)

// topic found, and have `min.insync.replicas`, but set to 2, larger than `replication-factor`.
// Existing topics use their actual replication factor rather than the option
// used only when creating a topic.
adminFixture.setMinInsyncReplicas("2")
err = adjustOptions(ctx, changefeedID, adminClient, options, defaultMockTopicName)
require.NoError(t, err)

topicDetail := adminFixture.topics[defaultMockTopicName]
topicDetail.ReplicationFactor = 1
adminFixture.topics[defaultMockTopicName] = topicDetail
err = adjustOptions(ctx, changefeedID, adminClient, options, defaultMockTopicName)
require.Regexp(t,
".*`replication-factor` 1 is smaller than the `min.insync.replicas` 2 of topic.*",
errors.Cause(err),
Expand Down
Loading