From 24e27fdb7b9d34a21d9235de6a1115e23af93eb7 Mon Sep 17 00:00:00 2001 From: Ling Jin <7138436+3AceShowHand@users.noreply.github.com> Date: Thu, 23 Jul 2026 20:34:08 +0800 Subject: [PATCH 1/5] This is an automated cherry-pick of #5420 Signed-off-by: ti-chi-bot --- .../sink/cloudstorage/encoder_group_test.go | 1 + downstreamadapter/sink/cloudstorage/sink.go | 8 +- downstreamadapter/sink/helper/helper.go | 9 +- downstreamadapter/sink/kafka/helper.go | 5 +- downstreamadapter/sink/kafka/sink.go | 77 ++++ downstreamadapter/sink/kafka/sink_test.go | 93 +++++ downstreamadapter/sink/pulsar/helper.go | 5 +- pkg/config/large_message.go | 20 +- pkg/config/large_message_test.go | 215 ++++++++++++ .../codec/canal/canal_json_txn_encoder.go | 1 - pkg/sink/codec/common/config.go | 30 +- pkg/sink/codec/common/config_test.go | 160 +++++++++ pkg/sink/codec/open/encoder.go | 4 +- pkg/sink/codec/open/encoder_test.go | 70 +++- pkg/sink/kafka/options.go | 248 ++++++++----- pkg/sink/kafka/options_test.go | 330 +++++++++++++++++- pkg/sink/kafka/sarama_config.go | 2 +- pkg/sink/kafka/sarama_config_test.go | 1 + pkg/sink/kafka/sarama_factory.go | 2 +- tests/integration_tests/_utils/kafka_topic | 12 + .../canal_json_claim_check/run.sh | 9 +- .../canal_json_handle_key_only/run.sh | 1 + .../kafka_big_messages/conf/diff_config.toml | 2 +- .../kafka_big_messages/run.sh | 209 +++++++++-- .../kafka_simple_claim_check/data/data.sql | 6 +- .../kafka_simple_claim_check/run.sh | 7 + .../data/data.sql | 6 +- .../kafka_simple_claim_check_avro/run.sh | 7 + .../kafka_simple_handle_key_only/run.sh | 1 + .../kafka_simple_handle_key_only_avro/run.sh | 1 + .../open_protocol_claim_check/data/data.sql | 1 + .../open_protocol_claim_check/run.sh | 9 +- .../data/data.sql | 1 + .../open_protocol_handle_key_only/run.sh | 1 + tests/utils/kafka_topic/main.go | 68 ++++ 35 files changed, 1445 insertions(+), 177 deletions(-) create mode 100644 pkg/config/large_message_test.go create mode 100644 pkg/sink/codec/common/config_test.go create mode 100755 tests/integration_tests/_utils/kafka_topic create mode 100644 tests/utils/kafka_topic/main.go diff --git a/downstreamadapter/sink/cloudstorage/encoder_group_test.go b/downstreamadapter/sink/cloudstorage/encoder_group_test.go index d7aaf5d632..5edae0785e 100644 --- a/downstreamadapter/sink/cloudstorage/encoder_group_test.go +++ b/downstreamadapter/sink/cloudstorage/encoder_group_test.go @@ -230,6 +230,7 @@ func newTestTxnEncoderConfig(t *testing.T) *common.Config { config.ProtocolCsv, replicaConfig.Sink, config.DefaultMaxMessageBytes, + config.DefaultMaxMessageBytes, ) require.NoError(t, err) return encoderConfig diff --git a/downstreamadapter/sink/cloudstorage/sink.go b/downstreamadapter/sink/cloudstorage/sink.go index 5ba73bce0c..e13c9b4cfb 100644 --- a/downstreamadapter/sink/cloudstorage/sink.go +++ b/downstreamadapter/sink/cloudstorage/sink.go @@ -87,7 +87,7 @@ func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url. if err != nil { return err } - _, err = helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, math.MaxInt) + _, err = helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, math.MaxInt, math.MaxInt) if err != nil { return err } @@ -117,9 +117,9 @@ func New( } // get cloud storage file extension according to the specific protocol. ext := helper.GetFileExtension(protocol) - // the last param maxMsgBytes is mainly to limit the size of a single message for - // batch protocols in mq scenario. In cloud storage sink, we just set it to max int. - encoderConfig, err := helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, math.MaxInt) + // Message size limits are mainly for MQ batch protocols. Cloud storage uses + // max int for both the final message limit and the batch threshold. + encoderConfig, err := helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, math.MaxInt, math.MaxInt) if err != nil { return nil, err } diff --git a/downstreamadapter/sink/helper/helper.go b/downstreamadapter/sink/helper/helper.go index 47cd949220..3911ea6ab5 100644 --- a/downstreamadapter/sink/helper/helper.go +++ b/downstreamadapter/sink/helper/helper.go @@ -50,17 +50,16 @@ func GetEncoderConfig( sinkURI *url.URL, protocol config.Protocol, sinkConfig *config.SinkConfig, - maxMsgBytes int, + maxMessageBytes int, + maxBatchedBytes int, ) (*common.Config, error) { encoderConfig := common.NewConfig(protocol) if err := encoderConfig.Apply(sinkURI, sinkConfig); err != nil { return nil, errors.WrapError(errors.ErrSinkInvalidConfig, err) } - // Always set encoder's `MaxMessageBytes` equal to producer's `MaxMessageBytes` - // to prevent that the encoder generate batched message too large - // then cause producer meet `message too large`. encoderConfig = encoderConfig. - WithMaxMessageBytes(maxMsgBytes). + WithMaxMessageBytes(maxMessageBytes). + WithMaxBatchedBytes(maxBatchedBytes). WithChangefeedID(changefeedID) tz, err := util.GetTimezone(config.GetGlobalServerConfig().TZ) diff --git a/downstreamadapter/sink/kafka/helper.go b/downstreamadapter/sink/kafka/helper.go index c45b7eb10f..7e01402fbc 100644 --- a/downstreamadapter/sink/kafka/helper.go +++ b/downstreamadapter/sink/kafka/helper.go @@ -88,7 +88,10 @@ func newKafkaSinkComponentWithFactory(ctx context.Context, return kafkaComponent, protocol, errors.Trace(err) } - encoderConfig, err := helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, options.MaxMessageBytes) + encoderConfig, err := helper.GetEncoderConfig( + changefeedID, sinkURI, protocol, sinkConfig, + options.MaxMessageBytes, options.MaxBatchedBytes, + ) if err != nil { return kafkaComponent, protocol, errors.Trace(err) } diff --git a/downstreamadapter/sink/kafka/sink.go b/downstreamadapter/sink/kafka/sink.go index e6d1038b26..b5143dca2b 100644 --- a/downstreamadapter/sink/kafka/sink.go +++ b/downstreamadapter/sink/kafka/sink.go @@ -68,9 +68,86 @@ func (s *sink) SinkType() commonType.SinkType { } func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.URL, sinkConfig *config.SinkConfig) error { +<<<<<<< HEAD comp, _, err := newKafkaSinkComponent(ctx, changefeedID, uri, sinkConfig) defer comp.close() return err +======= + protocol, err := helper.GetProtocol(util.GetOrZero(sinkConfig.Protocol)) + if err != nil { + return errors.Trace(err) + } + + topic, err := helper.GetTopic(uri) + if err != nil { + return errors.Trace(err) + } + + options := kafka.NewOptions() + if err = options.Apply(changefeedID, uri, sinkConfig); err != nil { + return errors.WrapError(errors.ErrKafkaInvalidConfig, err) + } + options.Topic = topic + + encoderConfig, err := helper.GetEncoderConfig( + changefeedID, uri, protocol, sinkConfig, + options.MaxMessageBytes, options.MaxBatchedBytes, + ) + if err != nil { + return errors.Trace(err) + } + + isAvroLike := protocol == config.ProtocolAvro || protocol == config.ProtocolDebeziumAvro + if _, err = eventrouter.NewEventRouter(sinkConfig, topic, false, isAvroLike); err != nil { + return errors.Trace(err) + } + + if _, err = columnselector.New(sinkConfig); err != nil { + return errors.Trace(err) + } + + factory, err := kafka.NewSaramaFactory(ctx, options, changefeedID) + if err != nil { + return errors.WrapError(errors.ErrKafkaNewProducer, err) + } + + adminClient, err := factory.AdminClient(ctx) + if err != nil { + return errors.WrapError(errors.ErrKafkaNewProducer, err) + } + defer adminClient.Close() + + topics, err := adminClient.GetTopicsMeta([]string{topic}, false) + 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) + } + + // 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) + } + + encoder, err := codec.NewEventEncoder(ctx, encoderConfig) + if err != nil { + return errors.Trace(err) + } + encoder.Clean() + + return nil +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) } func New( diff --git a/downstreamadapter/sink/kafka/sink_test.go b/downstreamadapter/sink/kafka/sink_test.go index 0bb4708f58..3d51caccfa 100644 --- a/downstreamadapter/sink/kafka/sink_test.go +++ b/downstreamadapter/sink/kafka/sink_test.go @@ -32,6 +32,24 @@ import ( "go.uber.org/atomic" ) +<<<<<<< HEAD +======= +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") + 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") +} + +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) func newKafkaSinkForTestWithProducers(ctx context.Context, asyncProducer kafka.AsyncProducer, syncProducer kafka.SyncProducer, @@ -51,7 +69,82 @@ func newKafkaSinkForTestWithProducers(ctx context.Context, statistics := metrics.NewStatistics(changefeedID, "sink") comp, protocol, err := newKafkaSinkComponentForTest(ctx, changefeedID, sinkURI, sinkConfig) if err != nil { +<<<<<<< HEAD return nil, errors.Trace(err) +======= + return nil, err + } + topic, err := helper.GetTopic(sinkURI) + if err != nil { + return nil, err + } + options := kafka.NewOptions() + if err = options.Apply(changefeedID, sinkURI, sinkConfig); err != nil { + return nil, err + } + options.Topic = topic + + adminClient := kafka.NewMockClusterAdminClient(ctrl) + adminClient.EXPECT().GetTopicsMeta([]string{kafkaSinkTestTopic}, true).Return( + map[string]kafka.TopicDetail{ + kafkaSinkTestTopic: { + Name: kafkaSinkTestTopic, + NumPartitions: 1, + }, + }, nil) + adminClient.EXPECT().Close().AnyTimes() + + metricsCollector := kafka.NewMockMetricsCollector(ctrl) + metricsCollector.EXPECT().Run(gomock.Any()).AnyTimes() + + factory := kafka.NewMockFactory(ctrl) + factory.EXPECT().AsyncProducer(gomock.Any()).Return(asyncProducer, nil) + factory.EXPECT().SyncProducer(gomock.Any()).Return(syncProducer, nil) + factory.EXPECT().MetricsCollector(adminClient).Return(metricsCollector) + + eventRouter, err := eventrouter.NewEventRouter(sinkConfig, topic, false, false) + if err != nil { + return nil, err + } + columnSelector, err := columnselector.New(sinkConfig) + if err != nil { + return nil, err + } + encoderConfig, err := helper.GetEncoderConfig( + changefeedID, sinkURI, protocol, sinkConfig, + options.MaxMessageBytes, options.MaxBatchedBytes, + ) + if err != nil { + return nil, err + } + encoderGroup, err := codec.NewEncoderGroup(ctx, sinkConfig, encoderConfig, changefeedID) + if err != nil { + return nil, err + } + encoder, err := codec.NewEventEncoder(ctx, encoderConfig) + if err != nil { + return nil, err + } + topicManager, err := topicmanager.GetTopicManagerAndTryCreateTopic( + ctx, + changefeedID, + topic, + options.DeriveTopicConfig(), + adminClient, + ) + if err != nil { + return nil, err + } + + comp := components{ + encoderGroup: encoderGroup, + encoder: encoder, + columnSelector: columnSelector, + eventRouter: eventRouter, + topicManager: topicManager, + adminClient: adminClient, + factory: factory, +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) } // We must close adminClient when this func return cause by an error diff --git a/downstreamadapter/sink/pulsar/helper.go b/downstreamadapter/sink/pulsar/helper.go index acc1cddd38..9cfee8c8ad 100644 --- a/downstreamadapter/sink/pulsar/helper.go +++ b/downstreamadapter/sink/pulsar/helper.go @@ -122,7 +122,10 @@ func newPulsarSinkComponentWithFactory(ctx context.Context, return pulsarComponent, protocol, errors.Trace(err) } - encoderConfig, err := helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, config.DefaultMaxMessageBytes) + encoderConfig, err := helper.GetEncoderConfig( + changefeedID, sinkURI, protocol, sinkConfig, + config.DefaultMaxMessageBytes, config.DefaultMaxMessageBytes, + ) if err != nil { return pulsarComponent, protocol, errors.Trace(err) } diff --git a/pkg/config/large_message.go b/pkg/config/large_message.go index d04584b451..6b19afe260 100644 --- a/pkg/config/large_message.go +++ b/pkg/config/large_message.go @@ -15,7 +15,7 @@ package config import ( "github.com/pingcap/ticdc/pkg/compression" - cerror "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/errors" ) const ( @@ -55,34 +55,39 @@ func (c *LargeMessageHandleConfig) AdjustAndValidate(protocol Protocol, enableTi // compression can be enabled independently if !compression.Supported(c.LargeMessageHandleCompression) { - return cerror.ErrInvalidReplicaConfig.GenWithStack( + return errors.ErrInvalidReplicaConfig.GenWithStack( "large message handle compression is not supported, got %s", c.LargeMessageHandleCompression) } if c.LargeMessageHandleOption == LargeMessageHandleOptionNone { return nil } + if c.LargeMessageHandleOption != LargeMessageHandleOptionClaimCheck && + c.LargeMessageHandleOption != LargeMessageHandleOptionHandleKeyOnly { + return errors.ErrInvalidReplicaConfig.GenWithStack( + "unknown large-message-handle-option %s", c.LargeMessageHandleOption) + } switch protocol { case ProtocolOpen, ProtocolSimple: case ProtocolCanalJSON: if !enableTiDBExtension { - return cerror.ErrInvalidReplicaConfig.GenWithStack( + return errors.ErrInvalidReplicaConfig.GenWithStack( "large message handle is set to %s, protocol is %s, but enable-tidb-extension is false", c.LargeMessageHandleOption, protocol.String()) } default: - return cerror.ErrInvalidReplicaConfig.GenWithStack( + return errors.ErrInvalidReplicaConfig.GenWithStack( "large message handle is set to %s, protocol is %s, it's not supported", c.LargeMessageHandleOption, protocol.String()) } if c.LargeMessageHandleOption == LargeMessageHandleOptionClaimCheck { if c.ClaimCheckStorageURI == "" { - return cerror.ErrInvalidReplicaConfig.GenWithStack( + return errors.ErrInvalidReplicaConfig.GenWithStack( "large message handle is set to claim-check, but the claim-check-storage-uri is empty") } if c.ClaimCheckRawValue && protocol == ProtocolOpen { - return cerror.ErrInvalidReplicaConfig.GenWithStack( + return errors.ErrInvalidReplicaConfig.GenWithStack( "large message handle is set to claim-check, raw value is not supported for the open protocol") } } @@ -106,7 +111,8 @@ func (c *LargeMessageHandleConfig) EnableClaimCheck() bool { return c.LargeMessageHandleOption == LargeMessageHandleOptionClaimCheck } -// Disabled returns true if disable large message handle. +// Disabled returns true only when large message handling is explicitly disabled. +// It returns false for nil and unknown configurations. func (c *LargeMessageHandleConfig) Disabled() bool { if c == nil { return false diff --git a/pkg/config/large_message_test.go b/pkg/config/large_message_test.go new file mode 100644 index 0000000000..f0721f4b53 --- /dev/null +++ b/pkg/config/large_message_test.go @@ -0,0 +1,215 @@ +// Copyright 2023 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/compression" + cerror "github.com/pingcap/ticdc/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestLargeMessageHandle4Compression(t *testing.T) { + t.Parallel() + + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + // unsupported compression, return error + largeMessageHandle.LargeMessageHandleCompression = "zstd" + + err := largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) + + largeMessageHandle.LargeMessageHandleCompression = compression.LZ4 + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.NoError(t, err) + + largeMessageHandle.LargeMessageHandleCompression = compression.Snappy + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.NoError(t, err) + + largeMessageHandle.LargeMessageHandleCompression = compression.None + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.NoError(t, err) +} + +func TestLargeMessageHandle4NotSupportedProtocol(t *testing.T) { + t.Parallel() + + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolCanal, true) + require.NoError(t, err) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionHandleKeyOnly + err = largeMessageHandle.AdjustAndValidate(ProtocolCanal, true) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) +} + +func TestLargeMessageHandleRejectsUnknownOption(t *testing.T) { + t.Parallel() + + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + largeMessageHandle.LargeMessageHandleOption = "unknown" + + require.False(t, largeMessageHandle.Disabled()) + err := largeMessageHandle.AdjustAndValidate(ProtocolOpen, false) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) + require.ErrorContains(t, err, "unknown large-message-handle-option unknown") +} + +func TestHandleKeyOnly4CanalJSON(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionHandleKeyOnly + + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionHandleKeyOnly, largeMessageHandle.LargeMessageHandleOption) +} + +func TestClaimCheck4CanalJSON(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionClaimCheck + largeMessageHandle.ClaimCheckStorageURI = "file:///tmp/claim-check" + + for _, rawValue := range []bool{false, true} { + largeMessageHandle.ClaimCheckRawValue = rawValue + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, false) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolCanalJSON, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionClaimCheck, largeMessageHandle.LargeMessageHandleOption) + } +} + +func TestHandleKeyOnly4OpenProtocol(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolOpen, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionHandleKeyOnly + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolOpen, false) + require.NoError(t, err) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolOpen, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionHandleKeyOnly, largeMessageHandle.LargeMessageHandleOption) +} + +func TestClaimCheck4OpenProtocol(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolOpen, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionClaimCheck + largeMessageHandle.ClaimCheckStorageURI = "file:///tmp/claim-check" + + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolOpen, false) + require.NoError(t, err) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolOpen, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionClaimCheck, largeMessageHandle.LargeMessageHandleOption) + + largeMessageHandle.ClaimCheckRawValue = true + err = largeMessageHandle.AdjustAndValidate(ProtocolOpen, true) + require.ErrorIs(t, err, cerror.ErrInvalidReplicaConfig) +} + +func TestHandleKeyOnly4SimpleProtocol(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolSimple, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionHandleKeyOnly + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolSimple, false) + require.NoError(t, err) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolSimple, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionHandleKeyOnly, largeMessageHandle.LargeMessageHandleOption) +} + +func TestClaimCheck4SimpleProtocol(t *testing.T) { + t.Parallel() + + // large-message-handle not set, always no error + largeMessageHandle := NewDefaultLargeMessageHandleConfig() + + err := largeMessageHandle.AdjustAndValidate(ProtocolSimple, false) + require.NoError(t, err) + require.True(t, largeMessageHandle.Disabled()) + + largeMessageHandle.LargeMessageHandleOption = LargeMessageHandleOptionClaimCheck + largeMessageHandle.ClaimCheckStorageURI = "file:///tmp/claim-check" + + // `enable-tidb-extension` is false, return error + err = largeMessageHandle.AdjustAndValidate(ProtocolSimple, false) + require.NoError(t, err) + + // `enable-tidb-extension` is true, no error + err = largeMessageHandle.AdjustAndValidate(ProtocolSimple, true) + require.NoError(t, err) + require.Equal(t, LargeMessageHandleOptionClaimCheck, largeMessageHandle.LargeMessageHandleOption) + + largeMessageHandle.ClaimCheckRawValue = true + err = largeMessageHandle.AdjustAndValidate(ProtocolSimple, true) + require.NoError(t, err) +} diff --git a/pkg/sink/codec/canal/canal_json_txn_encoder.go b/pkg/sink/codec/canal/canal_json_txn_encoder.go index 0af6f4f3f2..3e10d98229 100644 --- a/pkg/sink/codec/canal/canal_json_txn_encoder.go +++ b/pkg/sink/codec/canal/canal_json_txn_encoder.go @@ -65,7 +65,6 @@ func (j *JSONTxnEventEncoder) AppendTxnEvent(event *commonEvent.DMLEvent) error return err } length := len(value) + common.MaxRecordOverhead - // For single message that is longer than max-message-bytes, do not send it. if length > j.config.MaxMessageBytes { log.Warn("Single message is too large for canal-json", zap.Int("maxMessageBytes", j.config.MaxMessageBytes), diff --git a/pkg/sink/codec/common/config.go b/pkg/sink/codec/common/config.go index 0033f4acc3..ecba3412b1 100644 --- a/pkg/sink/codec/common/config.go +++ b/pkg/sink/codec/common/config.go @@ -41,9 +41,12 @@ type Config struct { Protocol config.Protocol - // control batch behavior, only for `open-protocol` and `craft` at the moment. MaxMessageBytes int - MaxBatchSize int + + // MaxBatchedBytes controls open-protocol encoder's maximum number of bytes for a batched message. + MaxBatchedBytes int + // MaxBatchedBytes controls open-protocol encoder's maximum number of events for a batched message. + MaxBatchSize int // DeleteOnlyHandleKeyColumns is true, for the delete event only output the handle key columns. DeleteOnlyHandleKeyColumns bool @@ -114,6 +117,7 @@ func NewConfig(protocol config.Protocol) *Config { Protocol: protocol, MaxMessageBytes: config.DefaultMaxMessageBytes, + MaxBatchedBytes: config.DefaultMaxMessageBytes, MaxBatchSize: defaultMaxBatchSize, EnableTiDBExtension: false, @@ -193,7 +197,7 @@ func (c *Config) Apply(sinkURI *url.URL, sinkConfig *config.SinkConfig) error { var err error urlParameter := &urlConfig{} if err = binding.Query.Bind(req, urlParameter); err != nil { - return errors.WrapError(errors.ErrMySQLInvalidConfig, err) + return errors.WrapError(errors.ErrSinkInvalidConfig, err) } if urlParameter, err = mergeConfig(sinkConfig, urlParameter); err != nil { return err @@ -344,6 +348,12 @@ func (c *Config) WithMaxMessageBytes(bytes int) *Config { return c } +// WithMaxBatchedBytes sets the maximum batched message bytes. +func (c *Config) WithMaxBatchedBytes(bytes int) *Config { + c.MaxBatchedBytes = bytes + return c +} + // WithChangefeedID set the `changefeedID` func (c *Config) WithChangefeedID(id common.ChangeFeedID) *Config { c.ChangefeedID = id @@ -411,15 +421,17 @@ func (c *Config) Validate() error { } if c.MaxMessageBytes <= 0 { - return errors.ErrCodecInvalidConfig.Wrap( - errors.Errorf("invalid max-message-bytes %d", c.MaxMessageBytes), - ) + return errors.ErrCodecInvalidConfig.GenWithStack("invalid max-message-bytes %d", c.MaxMessageBytes) + } + if c.MaxBatchedBytes < 0 { + return errors.ErrCodecInvalidConfig.GenWithStack("invalid max-batch-message-bytes %d", c.MaxBatchedBytes) + } + if c.MaxBatchedBytes > c.MaxMessageBytes { + return errors.ErrCodecInvalidConfig.GenWithStack("max-batch-message-bytes %d cannot be greater than max-message-bytes %d", c.MaxBatchedBytes, c.MaxMessageBytes) } if c.MaxBatchSize <= 0 { - return errors.ErrCodecInvalidConfig.Wrap( - errors.Errorf("invalid max-batch-size %d", c.MaxBatchSize), - ) + return errors.ErrCodecInvalidConfig.GenWithStack("invalid max-batch-size %d", c.MaxBatchSize) } if c.LargeMessageHandle != nil { diff --git a/pkg/sink/codec/common/config_test.go b/pkg/sink/codec/common/config_test.go new file mode 100644 index 0000000000..4369de7216 --- /dev/null +++ b/pkg/sink/codec/common/config_test.go @@ -0,0 +1,160 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// See the License for the specific language governing permissions and +// limitations under the License. + +package common + +import ( + "net/url" + "testing" + + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/util" + "github.com/stretchr/testify/require" +) + +func TestApplyReturnsSinkInvalidConfigForQueryBindingError(t *testing.T) { + cfg := NewConfig(config.ProtocolOpen) + sinkURI, err := url.Parse("kafka://127.0.0.1:9092/topic?max-batch-size=invalid") + require.NoError(t, err) + + err = cfg.Apply(sinkURI, config.GetDefaultReplicaConfig().Sink) + errCode, ok := errors.RFCCode(err) + require.True(t, ok, err) + require.Equal(t, errors.ErrSinkInvalidConfig.RFCCode(), errCode) +} + +func TestValidateMaxBatchMessageBytes(t *testing.T) { + tests := []struct { + name string + adjust func(*Config) + expected string + }{ + { + name: "non-positive max message bytes", + adjust: func(cfg *Config) { + cfg.MaxMessageBytes = 0 + }, + expected: "invalid max-message-bytes 0", + }, + { + name: "negative max batched bytes", + adjust: func(cfg *Config) { + cfg.MaxBatchedBytes = -1 + }, + expected: "invalid max-batch-message-bytes -1", + }, + { + name: "max batched bytes exceeds max message bytes", + adjust: func(cfg *Config) { + cfg.MaxMessageBytes = 100 + cfg.MaxBatchedBytes = 101 + }, + expected: "max-batch-message-bytes 101 cannot be greater than max-message-bytes 100", + }, + { + name: "non-positive max batch size", + adjust: func(cfg *Config) { + cfg.MaxBatchSize = 0 + }, + expected: "invalid max-batch-size 0", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + cfg := NewConfig(config.ProtocolOpen) + test.adjust(cfg) + + err := cfg.Validate() + require.ErrorContains(t, err, test.expected) + errCode, ok := errors.RFCCode(err) + require.True(t, ok, err) + require.Equal(t, errors.ErrCodecInvalidConfig.RFCCode(), errCode) + }) + } +} + +func TestDebeziumAvroSchemaRegistryConfig(t *testing.T) { + t.Parallel() + + cfg := NewConfig(config.ProtocolDebeziumAvro) + cfg.AvroConfluentSchemaRegistry = "http://127.0.0.1:8081" + require.NoError(t, cfg.Validate()) + + cfg = NewConfig(config.ProtocolDebeziumAvro) + cfg.AvroGlueSchemaRegistry = &config.GlueSchemaRegistryConfig{ + RegistryName: "test-registry", + Region: "us-east-1", + } + require.NoError(t, cfg.Validate()) + + cfg = NewConfig(config.ProtocolDebeziumAvro) + require.ErrorContains( + t, + cfg.Validate(), + `Debezium Avro protocol requires parameter "schema-registry" or "glue-schema-registry"`, + ) + + cfg = NewConfig(config.ProtocolDebeziumAvro) + cfg.AvroGlueSchemaRegistry = &config.GlueSchemaRegistryConfig{} + cfg.AvroConfluentSchemaRegistry = "http://127.0.0.1:8081" + require.ErrorContains( + t, + cfg.Validate(), + `Debezium Avro protocol requires only one of "schema-registry" or "glue-schema-registry"`, + ) + + cfg = NewConfig(config.ProtocolDebezium) + cfg.AvroConfluentSchemaRegistry = "http://127.0.0.1:8081" + require.ErrorContains(t, cfg.Validate(), `Debezium protocol does not support schema registry`) +} + +func TestDebeziumAvroGlueSchemaRegistryConfig(t *testing.T) { + t.Parallel() + + cfg := NewConfig(config.ProtocolDebeziumAvro) + sinkURI, err := url.Parse("kafka://127.0.0.1:9092/topic?protocol=debezium-avro") + require.NoError(t, err) + + glueSchemaRegistryConfig := &config.GlueSchemaRegistryConfig{ + RegistryName: "test-registry", + Region: "us-east-1", + } + sinkConfig := config.GetDefaultReplicaConfig().Sink + sinkConfig.KafkaConfig = &config.KafkaConfig{ + GlueSchemaRegistryConfig: glueSchemaRegistryConfig, + } + + err = cfg.Apply(sinkURI, sinkConfig) + require.NoError(t, err) + require.Same(t, glueSchemaRegistryConfig, cfg.AvroGlueSchemaRegistry) + require.Empty(t, cfg.AvroConfluentSchemaRegistry) + require.NoError(t, cfg.Validate()) +} + +func TestDebeziumAvroWatermarkConfig(t *testing.T) { + t.Parallel() + + cfg := NewConfig(config.ProtocolDebeziumAvro) + sinkURI, err := url.Parse("kafka://127.0.0.1:9092/topic?protocol=debezium-avro&enable-tidb-extension=true&avro-enable-watermark=true") + require.NoError(t, err) + + sinkConfig := config.GetDefaultReplicaConfig().Sink + sinkConfig.SchemaRegistry = util.AddressOf("http://127.0.0.1:8081") + err = cfg.Apply(sinkURI, sinkConfig) + require.NoError(t, err) + require.True(t, cfg.EnableTiDBExtension) + require.True(t, cfg.AvroEnableWatermark) + require.Equal(t, "http://127.0.0.1:8081", cfg.AvroConfluentSchemaRegistry) +} diff --git a/pkg/sink/codec/open/encoder.go b/pkg/sink/codec/open/encoder.go index 75f82e9d03..17a323cb7d 100644 --- a/pkg/sink/codec/open/encoder.go +++ b/pkg/sink/codec/open/encoder.go @@ -38,7 +38,7 @@ var ( ) // batchEncoder for open protocol will batch multiple row changed events into a single message. -// One message can contain at most MaxBatchSize events, and the total size of the message cannot exceed MaxMessageBytes. +// One message can contain at most MaxBatchSize events, and the total size of the message cannot exceed MaxBatchedBytes. type batchEncoder struct { messages []*common.Message // buff the callback of the latest message @@ -174,7 +174,7 @@ func (d *batchEncoder) pushMessage(key, value []byte, callback func()) { binary.BigEndian.PutUint64(keyLenByte[:], uint64(len(key))) binary.BigEndian.PutUint64(valueLenByte[:], uint64(len(value))) - if len(d.messages) == 0 || d.messages[len(d.messages)-1].Length()+length > d.config.MaxMessageBytes || d.messages[len(d.messages)-1].GetRowsCount() >= d.config.MaxBatchSize { + if len(d.messages) == 0 || d.messages[len(d.messages)-1].Length()+length > d.config.MaxBatchedBytes || d.messages[len(d.messages)-1].GetRowsCount() >= d.config.MaxBatchSize { d.finalizeCallback() // create a new message versionHead := make([]byte, 8) diff --git a/pkg/sink/codec/open/encoder_test.go b/pkg/sink/codec/open/encoder_test.go index 9b02366709..55f3f37c86 100644 --- a/pkg/sink/codec/open/encoder_test.go +++ b/pkg/sink/codec/open/encoder_test.go @@ -189,7 +189,7 @@ func TestFloatTypes(t *testing.T) { helper.Tk().MustExec("use test") job := helper.DDL2Job(`create table test.t( id int primary key auto_increment, - a float, b float(10, 3), c float(10), + a float, b float(10, 3), c float(10), d double, e double(20, 3))`) dmlEvent := helper.DML2Event("test", "t", `insert into test.t(a,b,c,d,e) values (1.23, 4.56, 7.89, 10.11, 12.13)`) @@ -533,17 +533,17 @@ func TestOtherTypes(t *testing.T) { helper.Tk().MustExec("use test") job := helper.DDL2Job(`create table test.t( - id int primary key auto_increment, + id int primary key auto_increment, a bool, b bool, c year, - d bit(10), e json, - f decimal(10,2), + d bit(10), e json, + f decimal(10,2), g enum('a','b','c'), h set('a','b','c'))`) tableInfo := helper.GetTableInfo(job) dmlEvent := helper.DML2Event("test", "t", `insert into test.t(a, b, c, d, e, f, g, h) values ( - true, false, 2000, - 0b0101010101, '{"key1": "value1"}', - 153.123, + true, false, 2000, + 0b0101010101, '{"key1": "value1"}', + 153.123, 'a', 'a,b')`) require.NotNil(t, dmlEvent) @@ -778,7 +778,9 @@ func TestEncoderMultipleMessage(t *testing.T) { `insert into test.t values (3, 333)`) ctx := context.Background() - codecConfig := common.NewConfig(config.ProtocolOpen).WithMaxMessageBytes(400) + codecConfig := common.NewConfig(config.ProtocolOpen). + WithMaxMessageBytes(1000). + WithMaxBatchedBytes(400) encoder, err := NewBatchEncoder(ctx, codecConfig) require.NoError(t, err) @@ -808,11 +810,13 @@ func TestEncoderMultipleMessage(t *testing.T) { require.Equal(t, 2, len(messages)) require.Equal(t, 2, messages[0].GetRowsCount()) require.Equal(t, 1, messages[1].GetRowsCount()) + require.LessOrEqual(t, messages[0].Length(), codecConfig.MaxBatchedBytes) + require.LessOrEqual(t, messages[1].Length(), codecConfig.MaxBatchedBytes) + require.Equal(t, 0, count) - for _, message := range messages { - message.Callback() - } - + messages[0].Callback() + require.Equal(t, 2, count) + messages[1].Callback() require.Equal(t, 3, count) decoder, err := NewDecoder(ctx, 0, codecConfig, nil) @@ -885,6 +889,48 @@ func TestMessageTooLarge(t *testing.T) { require.Equal(t, count, 0) } +func TestMessageLargerThanBatchLimit(t *testing.T) { + ctx := context.Background() + codecConfig := common.NewConfig(config.ProtocolOpen). + WithMaxMessageBytes(400). + WithMaxBatchedBytes(100) + encoder, err := NewBatchEncoder(ctx, codecConfig) + require.NoError(t, err) + + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.Tk().MustExec("use test") + + job := helper.DDL2Job(`create table test.t(a tinyint primary key, b int)`) + tableInfo := helper.GetTableInfo(job) + dmlEvent := helper.DML2Event("test", "t", `insert into test.t values (1, 123)`) + require.NotNil(t, dmlEvent) + insertRow, ok := dmlEvent.GetNextRow() + require.True(t, ok) + + count := 0 + insertRowEvent := &commonEvent.RowEvent{ + TableInfo: tableInfo, + CommitTs: dmlEvent.GetCommitTs(), + Event: insertRow, + ColumnSelector: columnselector.NewDefaultColumnSelector(), + Callback: func() { count += 1 }, + } + + err = encoder.AppendRowChangedEvent(ctx, "", insertRowEvent) + require.NoError(t, err) + + messages := encoder.Build() + require.Len(t, messages, 1) + require.Equal(t, 1, messages[0].GetRowsCount()) + require.Greater(t, messages[0].Length(), codecConfig.MaxBatchedBytes) + require.LessOrEqual(t, messages[0].Length(), codecConfig.MaxMessageBytes) + require.Equal(t, 0, count) + + messages[0].Callback() + require.Equal(t, 1, count) +} + func TestLargeMessageWithHandleEnableHandleKeyOnly(t *testing.T) { helper := commonEvent.NewEventTestHelper(t) defer helper.Close() diff --git a/pkg/sink/kafka/options.go b/pkg/sink/kafka/options.go index c9b992814e..ed98cd4870 100644 --- a/pkg/sink/kafka/options.go +++ b/pkg/sink/kafka/options.go @@ -26,11 +26,10 @@ import ( "github.com/gin-gonic/gin/binding" "github.com/imdario/mergo" - "github.com/pingcap/errors" "github.com/pingcap/log" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" - cerror "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/security" "go.uber.org/zap" ) @@ -40,13 +39,6 @@ const ( defaultPartitionNum = 3 // defaultMaxRetry is the default retry budget for Kafka producers. defaultMaxRetry = 5 - - // the `max-message-bytes` is set equal to topic's `max.message.bytes`, and is used to check - // whether the message is larger than the max size limit. It's found some message pass the message - // size limit check at the client side and failed at the broker side since message enlarged during - // the network transmission. so we set the `max-message-bytes` to a smaller value to avoid this problem. - // maxMessageBytesOverhead is used to reduce the `max-message-bytes`. - maxMessageBytesOverhead = 128 ) const ( @@ -108,7 +100,7 @@ func requireAcksFromString(acks int) (RequiredAcks, error) { case int(NoResponse): return NoResponse, nil default: - return Unknown, cerror.ErrKafkaInvalidRequiredAcks.GenWithStackByArgs(acks) + return Unknown, errors.ErrKafkaInvalidRequiredAcks.GenWithStackByArgs(acks) } } @@ -143,7 +135,7 @@ type urlConfig struct { InsecureSkipVerify *bool `form:"insecure-skip-verify"` } -// options stores user specified configurations +// options stores Kafka sink configurations type options struct { Topic string BrokerEndpoints []string @@ -156,14 +148,16 @@ type options struct { Version string IsAssignedVersion bool RequestVersion int16 - MaxMessageBytes int - MaxRetry int - Compression string - ClientID string - RequiredAcks RequiredAcks - // Only for test. User can not set this value. - // The current prod default value is 0. - MaxMessages int + + // MaxMessageBytes controls the byte size limit of the producer. + MaxMessageBytes int + // MaxBatchedBytes controls the byte size limit when batching messages. + MaxBatchedBytes int + + MaxRetry int + Compression string + ClientID string + RequiredAcks RequiredAcks // Credential is used to connect to kafka cluster. EnableTLS bool @@ -180,9 +174,9 @@ type options struct { // NewOptions returns a default Kafka configuration func NewOptions() *options { return &options{ - Version: "2.4.0", - // MaxMessageBytes will be used to initialize producer + Version: "2.4.0", MaxMessageBytes: config.DefaultMaxMessageBytes, + MaxBatchedBytes: config.DefaultMaxMessageBytes, MaxRetry: defaultMaxRetry, ReplicationFactor: 1, Compression: "none", @@ -198,11 +192,12 @@ func NewOptions() *options { } // setPartitionNum set the partition-num by the topic's partition count. -func (o *options) setPartitionNum(realPartitionCount int32) error { +func (o *options) setPartitionNum(changefeedID common.ChangeFeedID, realPartitionCount int32) error { // user does not specify the `partition-num` in the sink-uri if o.PartitionNum == 0 { o.PartitionNum = realPartitionCount log.Info("partitionNum is not set, set by topic's partition-num", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), zap.Int32("partitionNum", realPartitionCount)) return nil } @@ -210,8 +205,8 @@ func (o *options) setPartitionNum(realPartitionCount int32) error { if o.PartitionNum < realPartitionCount { log.Warn("number of partition specified in sink-uri is less than that of the actual topic. "+ "Some partitions will not have messages dispatched to", - zap.Int32("sinkUriPartitions", o.PartitionNum), - zap.Int32("topicPartitions", realPartitionCount)) + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), + zap.Int32("sinkUriPartitions", o.PartitionNum), zap.Int32("topicPartitions", realPartitionCount)) return nil } @@ -219,7 +214,7 @@ func (o *options) setPartitionNum(realPartitionCount int32) error { // the real partition count, since messages would be dispatched to different // partitions, this could prevent potential correctness problems. if o.PartitionNum > realPartitionCount { - return cerror.ErrKafkaInvalidPartitionNum.GenWithStack( + return errors.ErrKafkaInvalidPartitionNum.GenWithStack( "the number of partition (%d) specified in sink-uri is more than that of actual topic (%d)", o.PartitionNum, realPartitionCount) } @@ -236,7 +231,7 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, req := &http.Request{URL: sinkURI} urlParameter := &urlConfig{} if err = binding.Query.Bind(req, urlParameter); err != nil { - return cerror.WrapError(cerror.ErrMySQLInvalidConfig, err) + return errors.WrapError(errors.ErrMySQLInvalidConfig, err) } if urlParameter, err = mergeConfig(sinkConfig, urlParameter); err != nil { return err @@ -244,7 +239,7 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, if urlParameter.PartitionNum != nil { o.PartitionNum = *urlParameter.PartitionNum if o.PartitionNum <= 0 { - return cerror.ErrKafkaInvalidPartitionNum.GenWithStackByArgs(o.PartitionNum) + return errors.ErrKafkaInvalidPartitionNum.GenWithStackByArgs(o.PartitionNum) } } @@ -258,8 +253,12 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, } if urlParameter.MaxMessageBytes != nil { + if *urlParameter.MaxMessageBytes <= 0 { + return errors.ErrKafkaInvalidConfig.GenWithStack("invalid max-message-bytes %d", *urlParameter.MaxMessageBytes) + } o.MaxMessageBytes = *urlParameter.MaxMessageBytes } + o.MaxBatchedBytes = o.MaxMessageBytes if urlParameter.MaxRetry != nil && *urlParameter.MaxRetry >= 0 { o.MaxRetry = *urlParameter.MaxRetry @@ -387,7 +386,7 @@ func (o *options) applyTLS(params *urlConfig) error { if o.Credential != nil && !o.Credential.IsEmpty() && !o.Credential.IsTLSEnabled() { - return cerror.WrapError(cerror.ErrKafkaInvalidConfig, + return errors.WrapError(errors.ErrKafkaInvalidConfig, errors.New("ca, cert and key files should all be supplied")) } @@ -401,7 +400,7 @@ func (o *options) applyTLS(params *urlConfig) error { enableTLS := *params.EnableTLS if o.Credential != nil && o.Credential.IsTLSEnabled() && !enableTLS { - return cerror.WrapError(cerror.ErrKafkaInvalidConfig, + return errors.WrapError(errors.ErrKafkaInvalidConfig, errors.New("credential files are supplied, but 'enable-tls' is set to false")) } o.EnableTLS = enableTLS @@ -431,7 +430,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if urlParameter.SASLMechanism != nil && *urlParameter.SASLMechanism != "" { mechanism, err := security.SASLMechanismFromString(*urlParameter.SASLMechanism) if err != nil { - return cerror.WrapError(cerror.ErrKafkaInvalidConfig, err) + return errors.WrapError(errors.ErrKafkaInvalidConfig, err) } o.SASL.SASLMechanism = mechanism } @@ -439,7 +438,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if urlParameter.SASLGssAPIAuthType != nil && *urlParameter.SASLGssAPIAuthType != "" { authType, err := security.AuthTypeFromString(*urlParameter.SASLGssAPIAuthType) if err != nil { - return cerror.WrapError(cerror.ErrKafkaInvalidConfig, err) + return errors.WrapError(errors.ErrKafkaInvalidConfig, err) } o.SASL.GSSAPI.AuthType = authType } @@ -477,7 +476,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if sinkConfig.KafkaConfig.SASLOAuthClientID != nil { clientID := *sinkConfig.KafkaConfig.SASLOAuthClientID if clientID == "" { - return cerror.ErrKafkaInvalidConfig.GenWithStack("OAuth2 client ID cannot be empty") + return errors.ErrKafkaInvalidConfig.GenWithStack("OAuth2 client ID cannot be empty") } o.SASL.OAuth2.ClientID = clientID } @@ -485,7 +484,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if sinkConfig.KafkaConfig.SASLOAuthClientSecret != nil { clientSecret := *sinkConfig.KafkaConfig.SASLOAuthClientSecret if clientSecret == "" { - return cerror.ErrKafkaInvalidConfig.GenWithStack( + return errors.ErrKafkaInvalidConfig.GenWithStack( "OAuth2 client secret cannot be empty") } @@ -493,7 +492,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf decodedClientSecret, err := base64.StdEncoding.DecodeString(clientSecret) if err != nil { log.Error("OAuth2 client secret is not base64 encoded", zap.Error(err)) - return cerror.ErrKafkaInvalidConfig.GenWithStack( + return errors.ErrKafkaInvalidConfig.GenWithStack( "OAuth2 client secret is not base64 encoded") } o.SASL.OAuth2.ClientSecret = string(decodedClientSecret) @@ -502,7 +501,7 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if sinkConfig.KafkaConfig.SASLOAuthTokenURL != nil { tokenURL := *sinkConfig.KafkaConfig.SASLOAuthTokenURL if tokenURL == "" { - return cerror.ErrKafkaInvalidConfig.GenWithStack( + return errors.ErrKafkaInvalidConfig.GenWithStack( "OAuth2 token URL cannot be empty") } o.SASL.OAuth2.TokenURL = tokenURL @@ -510,13 +509,13 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf if o.SASL.OAuth2.IsEnable() { if o.SASL.SASLMechanism != security.OAuthMechanism { - return cerror.ErrKafkaInvalidConfig.GenWithStack( + return errors.ErrKafkaInvalidConfig.GenWithStack( "OAuth2 is only supported with SASL mechanism type OAUTHBEARER, but got %s", o.SASL.SASLMechanism) } if err := o.SASL.OAuth2.Validate(); err != nil { - return cerror.ErrKafkaInvalidConfig.Wrap(err) + return errors.ErrKafkaInvalidConfig.Wrap(err) } o.SASL.OAuth2.SetDefault() } @@ -570,14 +569,17 @@ func NewKafkaClientID(captureAddr string, clientID = commonInvalidChar.ReplaceAllString(clientID, "_") } if !validClientID.MatchString(clientID) { - return "", cerror.ErrKafkaInvalidClientID.GenWithStackByArgs(clientID) + return "", errors.ErrKafkaInvalidClientID.GenWithStackByArgs(clientID) } return } -// adjustOptions adjust the `options` and `sarama.Config` by condition. +// adjustOptions adjusts options with Kafka runtime metadata. +// It overwrites MaxMessageBytes with the final producer message limit derived +// from the topic or broker configuration. func adjustOptions( ctx context.Context, + changefeedID common.ChangeFeedID, admin ClusterAdminClient, options *options, topic string, @@ -587,20 +589,26 @@ func adjustOptions( return errors.Trace(err) } - // Only check replicationFactor >= minInsyncReplicas when producer's required acks is -1. - // If we don't check it, the producer probably can not send message to the topic. - // Because it will wait for the ack from all replicas. But we do not have enough replicas. - if options.RequiredAcks == WaitForAll { - err = validateMinInsyncReplicas(ctx, admin, topics, topic, int(options.ReplicationFactor)) - if err != nil { - return errors.Trace(err) - } + if err = validateRequiredAcks(ctx, admin, topics, topic, options); err != nil { + return errors.Trace(err) } + return adjustTopicOptions(ctx, changefeedID, admin, options, topic, topics) +} +func adjustTopicOptions( + ctx context.Context, + changefeedID common.ChangeFeedID, + admin ClusterAdminClient, + options *options, + topic string, + topics map[string]TopicDetail, +) error { info, exists := topics[topic] // once we have found the topic, no matter `auto-create-topic`, // make sure user input parameters are valid. + var err error if exists { +<<<<<<< HEAD // make sure that producer's `MaxMessageBytes` smaller than topic's `max.message.bytes` topicMaxMessageBytesStr, err := getTopicConfig( ctx, admin, info.Name, @@ -614,35 +622,37 @@ func adjustOptions( if err != nil { return errors.Trace(err) } +======= + err = adjustExistingTopicOption(ctx, changefeedID, admin, options, topic, info) + } else { + adjustNewTopicOptions(admin, changefeedID, options, topic) + } + if err != nil { + return err + } +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) - maxMessageBytes := topicMaxMessageBytes - maxMessageBytesOverhead - if topicMaxMessageBytes <= options.MaxMessageBytes { - log.Warn("topic's `max.message.bytes` less than the `max-message-bytes`,"+ - "use topic's `max.message.bytes` to initialize the Kafka producer", - zap.Int("max.message.bytes", topicMaxMessageBytes), - zap.Int("max-message-bytes", options.MaxMessageBytes), - zap.Int("real-max-message-bytes", maxMessageBytes)) - options.MaxMessageBytes = maxMessageBytes - } else { - if maxMessageBytes < options.MaxMessageBytes { - options.MaxMessageBytes = maxMessageBytes - } - } - - // no need to create the topic, - // but we would have to log user if they found enter wrong topic name later - if options.AutoCreate { - log.Warn("topic already exist, TiCDC will not create the topic", - zap.String("topic", topic), zap.Any("detail", info)) - } - - if err = options.setPartitionNum(info.NumPartitions); err != nil { - return errors.Trace(err) - } + options.MaxBatchedBytes = min(options.MaxBatchedBytes, options.MaxMessageBytes) + return nil +} +func validateRequiredAcks( + ctx context.Context, + admin ClusterAdminClient, + topics map[string]TopicDetail, + topic string, + options *options, +) error { + // Only check replicationFactor >= minInsyncReplicas when producer's required acks is -1. + // If we don't check it, the producer probably can not send message to the topic. + // Because it will wait for the ack from all replicas. But we do not have enough replicas. + if options.RequiredAcks != WaitForAll { return nil } + return validateMinInsyncReplicas(ctx, admin, topics, topic, int(options.ReplicationFactor)) +} +<<<<<<< HEAD brokerMessageMaxBytesStr, err := admin.GetBrokerConfig(BrokerMessageMaxBytesConfigName) if err != nil { log.Warn("TiCDC cannot find `message.max.bytes` from broker's configuration") @@ -651,33 +661,95 @@ func adjustOptions( brokerMessageMaxBytes, err := strconv.Atoi(brokerMessageMaxBytesStr) if err != nil { return errors.Trace(err) +======= +func adjustExistingTopicOption( + ctx context.Context, + changefeedID common.ChangeFeedID, + admin ClusterAdminClient, + options *options, + topic string, + info TopicDetail, +) error { + maxMessageBytes, err := getTopicMaxMessageBytes(ctx, admin, info.Name) + if err != nil { + log.Warn("`max.message.bytes` not found from topic's configuration, use the option `MaxMessageBytes` as default", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), + zap.Int("maxMessageBytes", options.MaxMessageBytes), zap.Error(err)) + maxMessageBytes = options.MaxMessageBytes } + options.MaxMessageBytes = maxMessageBytes + // no need to create the topic, + // but we would have to log user if they found enter wrong topic name later + if options.AutoCreate { + log.Warn("topic already exist, TiCDC will not create the topic", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), + zap.String("topic", topic), zap.Any("detail", info)) +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) + } + + if err = options.setPartitionNum(changefeedID, info.NumPartitions); err != nil { + return errors.Trace(err) + } + return nil +} + +func adjustNewTopicOptions( + admin ClusterAdminClient, + changefeedID common.ChangeFeedID, + options *options, + topic string, +) { // when create the topic, `max.message.bytes` is decided by the broker, // it would use broker's `message.max.bytes` to set topic's `max.message.bytes`. - // TiCDC need to make sure that the producer's `MaxMessageBytes` won't larger than - // broker's `message.max.bytes`. - maxMessageBytes := brokerMessageMaxBytes - maxMessageBytesOverhead - if brokerMessageMaxBytes <= options.MaxMessageBytes { - log.Warn("broker's `message.max.bytes` less than the `max-message-bytes`,"+ - "use broker's `message.max.bytes` to initialize the Kafka producer", - zap.Int("message.max.bytes", brokerMessageMaxBytes), - zap.Int("max-message-bytes", options.MaxMessageBytes), - zap.Int("real-max-message-bytes", maxMessageBytes)) - options.MaxMessageBytes = maxMessageBytes - } else { - if maxMessageBytes < options.MaxMessageBytes { - options.MaxMessageBytes = maxMessageBytes - } + messageMaxBytes, err := getBrokerMaxMessageBytes(admin) + if err != nil { + log.Warn("`message.max.bytes` not found from broker's configuration, use the option `MaxMessageBytes` as default", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), + zap.Int("maxMessageBytes", options.MaxMessageBytes), zap.Error(err)) + messageMaxBytes = options.MaxMessageBytes } + options.MaxMessageBytes = messageMaxBytes // topic not exists yet, and user does not specify the `partition-num` in the sink uri. if options.PartitionNum == 0 { options.PartitionNum = defaultPartitionNum log.Warn("partition-num is not set, use the default partition count", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), zap.String("topic", topic), zap.Int32("partitions", options.PartitionNum)) } - return nil +} + +func getTopicMaxMessageBytes( + ctx context.Context, + admin ClusterAdminClient, + topic string, +) (int, error) { + raw, err := getTopicConfig( + ctx, admin, topic, + TopicMaxMessageBytesConfigName, + BrokerMessageMaxBytesConfigName, + ) + if err != nil { + return 0, errors.Trace(err) + } + maxMessageBytes, err := strconv.Atoi(raw) + if err != nil { + return 0, errors.Trace(err) + } + return maxMessageBytes, nil +} + +func getBrokerMaxMessageBytes(admin ClusterAdminClient) (int, error) { + raw, err := admin.GetBrokerConfig(BrokerMessageMaxBytesConfigName) + if err != nil { + return 0, errors.Trace(err) + } + messageMaxBytes, err := strconv.Atoi(raw) + if err != nil { + return 0, errors.Trace(err) + } + return messageMaxBytes, nil } func validateMinInsyncReplicas( @@ -711,7 +783,7 @@ func validateMinInsyncReplicas( minInsyncReplicasStr, exists, err := minInsyncReplicasConfigGetter() if err != nil { // 'min.insync.replica' is invisible to us in Confluent Cloud Kafka. - if cerror.ErrKafkaConfigNotFound.Equal(err) { + if errors.ErrKafkaConfigNotFound.Equal(err) { log.Warn("TiCDC cannot find `min.insync.replicas` from broker's configuration, " + "please make sure that the replication factor is greater than or equal " + "to the minimum number of in-sync replicas" + @@ -736,7 +808,7 @@ func validateMinInsyncReplicas( MinInsyncReplicasConfigName, configFrom) log.Error(msg, zap.Int("replication-factor", replicationFactor), zap.Int("min.insync.replicas", minInsyncReplicas)) - return cerror.ErrKafkaInvalidConfig.GenWithStack( + return errors.ErrKafkaInvalidConfig.GenWithStack( "TiCDC Kafka sink's `request.required.acks` defaults to -1, "+ "TiCDC cannot deliver messages when the `replication-factor` %d "+ "is smaller than the `min.insync.replicas` %d of %s", diff --git a/pkg/sink/kafka/options_test.go b/pkg/sink/kafka/options_test.go index 8f64d49762..6ddda7cfc6 100644 --- a/pkg/sink/kafka/options_test.go +++ b/pkg/sink/kafka/options_test.go @@ -27,10 +27,147 @@ import ( commonType "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/errors" - "github.com/pingcap/ticdc/pkg/sink/codec/common" "github.com/stretchr/testify/require" ) +<<<<<<< HEAD +======= +const ( + defaultMockTopicName = "mock_topic" + + // These values model Kafka admin responses, not TiCDC option defaults. + mockClusterReplicationFactor int16 = 3 + mockBrokerMessageMaxBytes = "1048588" + mockTopicMessageMaxBytes = "1048588" + mockMinInsyncReplicas = "1" +) + +type kafkaAdminFixture struct { + admin *MockClusterAdminClient + topics map[string]TopicDetail + brokerConfig map[string]string + topicConfig map[string]map[string]string +} + +func newKafkaAdminFixture(t *testing.T) *kafkaAdminFixture { + t.Helper() + + ctrl := gomock.NewController(t) + fixture := &kafkaAdminFixture{ + admin: NewMockClusterAdminClient(ctrl), + topics: make(map[string]TopicDetail), + brokerConfig: map[string]string{ + BrokerMessageMaxBytesConfigName: mockBrokerMessageMaxBytes, + MinInsyncReplicasConfigName: mockMinInsyncReplicas, + }, + topicConfig: make(map[string]map[string]string), + } + fixture.addTopic(defaultMockTopicName, defaultPartitionNum) + fixture.topicConfig[defaultMockTopicName] = map[string]string{ + TopicMaxMessageBytesConfigName: mockTopicMessageMaxBytes, + MinInsyncReplicasConfigName: mockMinInsyncReplicas, + } + + fixture.admin.EXPECT().Close().AnyTimes() + fixture.admin.EXPECT().GetTopicsMeta(gomock.Any(), gomock.Any()). + DoAndReturn(fixture.getTopicsMeta).AnyTimes() + fixture.admin.EXPECT().GetTopicsPartitionsNum(gomock.Any()). + DoAndReturn(fixture.getTopicsPartitionsNum).AnyTimes() + fixture.admin.EXPECT().GetBrokerConfig(gomock.Any()). + DoAndReturn(fixture.getBrokerConfig).AnyTimes() + fixture.admin.EXPECT().GetTopicConfig(gomock.Any(), gomock.Any()). + DoAndReturn(fixture.getTopicConfig).AnyTimes() + fixture.admin.EXPECT().CreateTopic(gomock.Any(), gomock.Any()). + DoAndReturn(fixture.createTopic).AnyTimes() + + return fixture +} + +func (f *kafkaAdminFixture) addTopic(name string, partitionNum int32) { + f.topics[name] = TopicDetail{Name: name, NumPartitions: partitionNum} +} + +func (f *kafkaAdminFixture) getTopicsMeta( + topics []string, _ bool, +) (map[string]TopicDetail, error) { + result := make(map[string]TopicDetail, len(topics)) + for _, topic := range topics { + if detail, ok := f.topics[topic]; ok { + result[topic] = detail + } + } + return result, nil +} + +func (f *kafkaAdminFixture) getTopicsPartitionsNum( + topics []string, +) (map[string]int32, error) { + result := make(map[string]int32, len(topics)) + for _, topic := range topics { + if detail, ok := f.topics[topic]; ok { + result[topic] = detail.NumPartitions + } + } + return result, nil +} + +func (f *kafkaAdminFixture) getBrokerConfig(configName string) (string, error) { + if value, ok := f.brokerConfig[configName]; ok { + return value, nil + } + return "", errors.ErrKafkaConfigNotFound.GenWithStack( + "cannot find the `%s` from the broker's configuration", configName) +} + +func (f *kafkaAdminFixture) getTopicConfig(topicName string, configName string) (string, error) { + if _, ok := f.topics[topicName]; !ok { + return "", errors.ErrKafkaConfigNotFound.GenWithStack( + "cannot find the `%s` from the topic's configuration", topicName) + } + if value, ok := f.topicConfig[topicName][configName]; ok { + return value, nil + } + return "", errors.ErrKafkaConfigNotFound.GenWithStack( + "cannot find the `%s` from the topic's configuration", configName) +} + +func (f *kafkaAdminFixture) createTopic(detail *TopicDetail, _ bool) error { + if detail.ReplicationFactor > mockClusterReplicationFactor { + return sarama.ErrInvalidReplicationFactor + } + if _, ok := f.brokerConfig[MinInsyncReplicasConfigName]; !ok && + detail.ReplicationFactor != mockClusterReplicationFactor { + return sarama.ErrPolicyViolation + } + f.topics[detail.Name] = *detail + return nil +} + +func (f *kafkaAdminFixture) brokerMessageMaxBytes() int { + value, _ := strconv.Atoi(f.brokerConfig[BrokerMessageMaxBytesConfigName]) + return value +} + +func (f *kafkaAdminFixture) topicMaxMessageBytes(topicName string) int { + value, _ := strconv.Atoi(f.topicConfig[topicName][TopicMaxMessageBytesConfigName]) + return value +} + +func (f *kafkaAdminFixture) setMessageMaxBytes(brokerValue, topicValue string) { + f.brokerConfig[BrokerMessageMaxBytesConfigName] = brokerValue + f.topicConfig[defaultMockTopicName][TopicMaxMessageBytesConfigName] = topicValue +} + +func (f *kafkaAdminFixture) setMinInsyncReplicas(minInsyncReplicas string) { + f.topicConfig[defaultMockTopicName][MinInsyncReplicasConfigName] = minInsyncReplicas + f.brokerConfig[MinInsyncReplicasConfigName] = minInsyncReplicas +} + +func (f *kafkaAdminFixture) dropBrokerConfig(configName string) { + delete(f.brokerConfig, configName) +} + +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) func TestCompleteOptions(t *testing.T) { options := NewOptions() @@ -49,6 +186,7 @@ func TestCompleteOptions(t *testing.T) { require.Equal(t, int16(3), options.ReplicationFactor) require.Equal(t, "2.6.0", options.Version) require.Equal(t, 4096, options.MaxMessageBytes) + require.Equal(t, 4096, options.MaxBatchedBytes) require.Equal(t, WaitForLocal, options.RequiredAcks) require.Equal(t, defaultMaxRetry, options.MaxRetry) @@ -145,19 +283,75 @@ func TestCompleteOptions(t *testing.T) { require.Equal(t, defaultMaxRetry, options.MaxRetry) } +func TestApplyRejectsNonPositiveMaxMessageBytes(t *testing.T) { + tests := []struct { + name string + uri string + configValue *int + expected int + }{ + { + name: "zero from URI", + uri: "kafka://127.0.0.1:9092/test-topic?max-message-bytes=0", + expected: 0, + }, + { + name: "negative from URI", + uri: "kafka://127.0.0.1:9092/test-topic?max-message-bytes=-1", + expected: -1, + }, + { + name: "zero from sink config", + uri: "kafka://127.0.0.1:9092/test-topic", + configValue: aws.Int(0), + expected: 0, + }, + { + name: "negative from sink config", + uri: "kafka://127.0.0.1:9092/test-topic", + configValue: aws.Int(-1), + expected: -1, + }, + } + + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + sinkURI, err := url.Parse(test.uri) + require.NoError(t, err) + + sinkConfig := config.GetDefaultReplicaConfig().Sink + if test.configValue != nil { + sinkConfig.KafkaConfig = &config.KafkaConfig{ + MaxMessageBytes: test.configValue, + } + } + + options := NewOptions() + err = options.Apply(changefeedID, sinkURI, sinkConfig) + require.ErrorContains( + t, err, fmt.Sprintf("invalid max-message-bytes %d", test.expected)) + errCode, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrKafkaInvalidConfig.RFCCode(), errCode) + }) + } +} + func TestSetPartitionNum(t *testing.T) { options := NewOptions() - err := options.setPartitionNum(2) + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") + err := options.setPartitionNum(changefeedID, 2) require.NoError(t, err) require.Equal(t, int32(2), options.PartitionNum) options.PartitionNum = 1 - err = options.setPartitionNum(2) + err = options.setPartitionNum(changefeedID, 2) require.NoError(t, err) require.Equal(t, int32(1), options.PartitionNum) options.PartitionNum = 3 - err = options.setPartitionNum(2) + err = options.setPartitionNum(changefeedID, 2) require.True(t, errors.ErrKafkaInvalidPartitionNum.Equal(err)) } @@ -225,10 +419,37 @@ func TestTimeout(t *testing.T) { require.Equal(t, 2*time.Minute, options.WriteTimeout) } +<<<<<<< HEAD func TestAdjustConfigTopicNotExist(t *testing.T) { // When the topic does not exist, use the broker's configuration to create the topic. adminClient := NewClusterAdminClientMockImpl() defer adminClient.Close() +======= +func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *testing.T) { + tests := []struct { + name string + configuredMaxMessageBytes func(*kafkaAdminFixture) int + }{ + { + name: "uses broker limit when configured value is below broker", + configuredMaxMessageBytes: func(*kafkaAdminFixture) int { + return 1024 + }, + }, + { + name: "uses broker limit when configured value is below broker by one byte", + configuredMaxMessageBytes: func(f *kafkaAdminFixture) int { + return f.brokerMessageMaxBytes() - 1 + }, + }, + { + name: "uses broker limit when configured value is above broker", + configuredMaxMessageBytes: func(f *kafkaAdminFixture) int { + return f.brokerMessageMaxBytes() + 1 + }, + }, + } +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) options := NewOptions() options.BrokerEndpoints = []string{"127.0.0.1:9092"} @@ -321,9 +542,55 @@ func TestAdjustConfigTopicExist(t *testing.T) { // When the topic exists, but the topic does not have `max.message.bytes` // create a topic without `max.message.bytes` topicName := "test-topic" +<<<<<<< HEAD detail := &TopicDetail{ Name: topicName, NumPartitions: 3, +======= + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + adminFixture := newKafkaAdminFixture(t) + adminClient := adminFixture.admin + + detail := &TopicDetail{ + Name: topicName, + NumPartitions: 3, + } + err := adminClient.CreateTopic(detail, false) + require.NoError(t, err) + + configuredMaxMessageBytes := test.configuredMaxMessageBytes(adminFixture) + sinkURI, err := url.Parse(fmt.Sprintf( + "kafka://127.0.0.1:9092/%s?max-message-bytes=%d", + topicName, configuredMaxMessageBytes, + )) + require.NoError(t, err) + + options := NewOptions() + err = options.Apply(changefeedID, sinkURI, config.GetDefaultReplicaConfig().Sink) + require.NoError(t, err) + require.Equal(t, configuredMaxMessageBytes, options.MaxMessageBytes) + require.Equal(t, configuredMaxMessageBytes, options.MaxBatchedBytes) + expectedProducerLimit := adminFixture.brokerMessageMaxBytes() + + ctx := context.Background() + err = adjustOptions(ctx, changefeedID, adminClient, options, topicName) + require.NoError(t, err) + + saramaConfig, err := newSaramaConfig(ctx, options) + require.NoError(t, err) + + require.NotEqual(t, configuredMaxMessageBytes, options.MaxMessageBytes) + require.Equal(t, expectedProducerLimit, options.MaxMessageBytes) + require.Equal( + t, + min(configuredMaxMessageBytes, expectedProducerLimit), + options.MaxBatchedBytes, + ) + require.Equal(t, expectedProducerLimit, saramaConfig.Producer.MaxMessageBytes) + }) +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) } err = adminClient.CreateTopic(detail, false) require.NoError(t, err) @@ -362,11 +629,17 @@ func TestAdjustConfigMinInsyncReplicas(t *testing.T) { // Report an error if the replication-factor is less than min.insync.replicas // when the topic does not exist. +<<<<<<< HEAD adminClient.SetMinInsyncReplicas("2") +======= + adminFixture.setMinInsyncReplicas("2") + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) ctx := context.Background() err := adjustOptions( ctx, + changefeedID, adminClient, options, "create-new-fail-invalid-min-insync-replicas", @@ -380,7 +653,7 @@ func TestAdjustConfigMinInsyncReplicas(t *testing.T) { // topic not exist, and `min.insync.replicas` not found in broker's configuration adminClient.DropBrokerConfig(MinInsyncReplicasConfigName) topicName := "no-topic-no-min-insync-replicas" - err = adjustOptions(ctx, adminClient, options, "no-topic-no-min-insync-replicas") + err = adjustOptions(ctx, changefeedID, adminClient, options, "no-topic-no-min-insync-replicas") require.Nil(t, err) err = adminClient.CreateTopic(&TopicDetail{ Name: topicName, @@ -399,12 +672,17 @@ func TestAdjustConfigMinInsyncReplicas(t *testing.T) { NumPartitions: 3, }, false) require.Nil(t, err) - err = adjustOptions(ctx, adminClient, options, topicName) + 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`. +<<<<<<< HEAD adminClient.SetMinInsyncReplicas("2") err = adjustOptions(ctx, adminClient, options, adminClient.GetDefaultMockTopicName()) +======= + adminFixture.setMinInsyncReplicas("2") + err = adjustOptions(ctx, changefeedID, adminClient, options, defaultMockTopicName) +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) require.Regexp(t, ".*`replication-factor` 1 is smaller than the `min.insync.replicas` 2 of topic.*", errors.Cause(err), @@ -419,10 +697,13 @@ func TestSkipAdjustConfigMinInsyncReplicasWhenRequiredAcksIsNotWailAll(t *testin options.BrokerEndpoints = []string{"127.0.0.1:9092"} options.RequiredAcks = WaitForLocal + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") + // Do not report an error if the replication-factor is less than min.insync.replicas(1<2). adminClient.SetMinInsyncReplicas("2") err := adjustOptions( context.Background(), + changefeedID, adminClient, options, "skip-check-min-insync-replicas", @@ -499,6 +780,10 @@ func TestConfigurationCombinations(t *testing.T) { // topic not created // `message.max.bytes` < user set `max-message-bytes` < default `max-message-bytes` { +<<<<<<< HEAD +======= + "new topic broker below user", +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) "kafka://127.0.0.1:9092/%s?max-message-bytes=%s", []interface{}{"not-created-topic", strconv.Itoa(1024*1024 + 1)}, BrokerMessageMaxBytes, @@ -621,6 +906,10 @@ func TestConfigurationCombinations(t *testing.T) { // topic created // default `max-message-bytes` < `max.message.bytes` < user set `max-message-bytes` { +<<<<<<< HEAD +======= + "existing topic topic below user", +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) "kafka://127.0.0.1:9092/%s?max-message-bytes=%s", []interface{}{ DefaultMockTopicName, @@ -640,15 +929,24 @@ func TestConfigurationCombinations(t *testing.T) { sinkURI, err := url.Parse(uri) require.Nil(t, err) +<<<<<<< HEAD ctx := context.Background() options := NewOptions() err = options.Apply(commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test"), sinkURI, config.GetDefaultReplicaConfig().Sink) require.Nil(t, err) +======= + ctx := context.Background() + options := NewOptions() + err = options.Apply(commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test"), sinkURI, config.GetDefaultReplicaConfig().Sink) + require.Nil(t, err) + configuredMaxMessageBytes := options.MaxMessageBytes +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) changefeed := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "changefeed-test") factory, err := NewMockFactory(ctx, options, changefeed) require.NoError(t, err) +<<<<<<< HEAD adminClient, err := factory.AdminClient(ctx) require.NoError(t, err) @@ -663,6 +961,24 @@ func TestConfigurationCombinations(t *testing.T) { KafkaConfig: &config.KafkaConfig{ LargeMessageHandle: config.NewDefaultLargeMessageHandleConfig(), }, +======= + sourceMaxMessageBytes := adminFixture.brokerMessageMaxBytes() + if _, exists := adminFixture.topics[topic]; exists { + sourceMaxMessageBytes = adminFixture.topicMaxMessageBytes(topic) + } + + changefeedID := commonType.NewChangefeedID4Test(commonType.DefaultKeyspaceName, "test") + err = adjustOptions(ctx, changefeedID, adminClient, options, topic) + require.Nil(t, err) + require.Equal(t, sourceMaxMessageBytes, options.MaxMessageBytes) + require.Equal( + t, + min(configuredMaxMessageBytes, sourceMaxMessageBytes), + options.MaxBatchedBytes, + ) + + adminClient.Close() +>>>>>>> d480b05fa (kafka: decouple batch size from Kafka message size limit (#5420)) }) require.Nil(t, err) encoderConfig.WithMaxMessageBytes(options.MaxMessageBytes) @@ -715,6 +1031,7 @@ func TestMerge(t *testing.T) { require.Equal(t, int16(5), c.ReplicationFactor) require.Equal(t, "3.1.2", c.Version) require.Equal(t, 1024*1024, c.MaxMessageBytes) + require.Equal(t, 1024*1024, c.MaxBatchedBytes) require.Equal(t, "gzip", c.Compression) require.Equal(t, "test-id", c.ClientID) require.Equal(t, true, c.AutoCreate) @@ -796,6 +1113,7 @@ func TestMerge(t *testing.T) { require.Equal(t, int16(5), c.ReplicationFactor) require.Equal(t, "3.1.2", c.Version) require.Equal(t, 1024*1024, c.MaxMessageBytes) + require.Equal(t, 1024*1024, c.MaxBatchedBytes) require.Equal(t, "gzip", c.Compression) require.Equal(t, "test-id", c.ClientID) require.Equal(t, true, c.AutoCreate) diff --git a/pkg/sink/kafka/sarama_config.go b/pkg/sink/kafka/sarama_config.go index b53dc47b37..d18e8b0c56 100644 --- a/pkg/sink/kafka/sarama_config.go +++ b/pkg/sink/kafka/sarama_config.go @@ -62,7 +62,7 @@ func newSaramaConfig(ctx context.Context, o *options) (*sarama.Config, error) { config.Producer.Flush.Bytes = 0 config.Producer.Flush.Messages = 0 config.Producer.Flush.Frequency = time.Duration(0) - config.Producer.Flush.MaxMessages = o.MaxMessages + config.Producer.Flush.MaxMessages = 0 config.Net.MaxOpenRequests = 1 config.Net.DialTimeout = o.DialTimeout diff --git a/pkg/sink/kafka/sarama_config_test.go b/pkg/sink/kafka/sarama_config_test.go index bfb0147a1c..5e1e947f74 100644 --- a/pkg/sink/kafka/sarama_config_test.go +++ b/pkg/sink/kafka/sarama_config_test.go @@ -58,6 +58,7 @@ func TestNewSaramaConfig(t *testing.T) { cfg, err := newSaramaConfig(ctx, options) require.NoError(t, err) require.Equal(t, defaultMaxRetry, cfg.Producer.Retry.Max) + require.Equal(t, options.MaxMessageBytes, cfg.Producer.MaxMessageBytes) options.EnableTLS = true options.Credential = &security.Credential{ diff --git a/pkg/sink/kafka/sarama_factory.go b/pkg/sink/kafka/sarama_factory.go index 650f346b4c..39c69c0c0b 100644 --- a/pkg/sink/kafka/sarama_factory.go +++ b/pkg/sink/kafka/sarama_factory.go @@ -57,7 +57,7 @@ func NewSaramaFactory( admin.Close() }() - if err = adjustOptions(ctx, admin, o, o.Topic); err != nil { + if err = adjustOptions(ctx, changefeedID, admin, o, o.Topic); err != nil { return nil, errors.Trace(err) } diff --git a/tests/integration_tests/_utils/kafka_topic b/tests/integration_tests/_utils/kafka_topic new file mode 100755 index 0000000000..9f9a79a1cd --- /dev/null +++ b/tests/integration_tests/_utils/kafka_topic @@ -0,0 +1,12 @@ +#!/bin/bash + +set -eu + +CUR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +UTILITY_DIR="$CUR/../../utils/kafka_topic" + +if [ ! -f "$UTILITY_DIR/kafka_topic" ]; then + (cd "$UTILITY_DIR" && GO111MODULE=on go build) +fi + +"$UTILITY_DIR/kafka_topic" "$@" diff --git a/tests/integration_tests/canal_json_claim_check/run.sh b/tests/integration_tests/canal_json_claim_check/run.sh index 10f822c98b..a354dc589a 100755 --- a/tests/integration_tests/canal_json_claim_check/run.sh +++ b/tests/integration_tests/canal_json_claim_check/run.sh @@ -18,7 +18,10 @@ function run() { start_tidb_cluster --workdir $WORK_DIR - TOPIC_NAME="canal-json-claim-check" + TOPIC_NAME="canal-json-claim-check-$RANDOM" + CLAIM_CHECK_DIR="/tmp/canal-json-claim-check" + rm -rf "$CLAIM_CHECK_DIR" + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 1000 # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) @@ -36,6 +39,10 @@ function run() { # sync_diff can't check non-exist table, so we check expected tables are created in downstream first check_table_exists test.finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 200 check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml + if ! find "$CLAIM_CHECK_DIR" -type f -print -quit | grep -q .; then + echo "claim-check did not write any file to $CLAIM_CHECK_DIR" + exit 1 + fi cleanup_process $CDC_BINARY } diff --git a/tests/integration_tests/canal_json_handle_key_only/run.sh b/tests/integration_tests/canal_json_handle_key_only/run.sh index 372dff24fe..93ae5adfba 100755 --- a/tests/integration_tests/canal_json_handle_key_only/run.sh +++ b/tests/integration_tests/canal_json_handle_key_only/run.sh @@ -19,6 +19,7 @@ function run() { start_tidb_cluster --workdir $WORK_DIR TOPIC_NAME="canal-json-handle-key-only-$RANDOM" + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 1000 # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) diff --git a/tests/integration_tests/kafka_big_messages/conf/diff_config.toml b/tests/integration_tests/kafka_big_messages/conf/diff_config.toml index 0082a37028..bf73beb595 100644 --- a/tests/integration_tests/kafka_big_messages/conf/diff_config.toml +++ b/tests/integration_tests/kafka_big_messages/conf/diff_config.toml @@ -13,7 +13,7 @@ source-instances = ["mysql1"] target-instance = "tidb0" -target-check-tables = ["kafka_big_messages.test"] +target-check-tables = ["database_name.*"] [data-sources] [data-sources.mysql1] diff --git a/tests/integration_tests/kafka_big_messages/run.sh b/tests/integration_tests/kafka_big_messages/run.sh index 0628eaa92e..7225decaaa 100755 --- a/tests/integration_tests/kafka_big_messages/run.sh +++ b/tests/integration_tests/kafka_big_messages/run.sh @@ -3,53 +3,198 @@ set -eu CUR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -source $CUR/../_utils/test_prepare +source "$CUR/../_utils/test_prepare" WORK_DIR=$OUT_DIR/$TEST_NAME CDC_BINARY=cdc.test SINK_TYPE=$1 -function run() { - # test kafka sink only in this case - if [ "$SINK_TYPE" != "kafka" ]; then +STATE_WAIT_TIMEOUT_SECONDS=30 +STATE_CHECK_INTERVAL_SECONDS=1 +TABLE_CHECK_RETRIES=15 +BATCH_LIMIT=262144 +SMALL_TOPIC_LIMIT=524288 +LARGE_TOPIC_LIMIT=2097152 +ROW_BYTES=1048576 +SCHEMA_REGISTRY_URI=http://127.0.0.1:8088 +GENERATOR_DIR=$CUR/../../utils/gen_kafka_big_messages +consumer_pid="" + +function start_schema_registry() { + if curl -o /dev/null -s "$SCHEMA_REGISTRY_URI"; then return fi - rm -rf $WORK_DIR && mkdir -p $WORK_DIR - start_tidb_cluster --workdir $WORK_DIR + echo "Starting schema registry..." + ./bin/bin/schema-registry-start -daemon ./bin/etc/schema-registry/schema-registry.properties + local i=0 + while ! curl -o /dev/null -s "$SCHEMA_REGISTRY_URI"; do + i=$((i + 1)) + if [ "$i" -gt 30 ]; then + echo "Failed to start schema registry" + exit 1 + fi + sleep 2 + done + curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" --data '{"compatibility": "NONE"}' "$SCHEMA_REGISTRY_URI/config" +} + +function build_message_generator() { + if [ ! -f "$GENERATOR_DIR/gen_kafka_big_messages" ]; then + (cd "$GENERATOR_DIR" && GO111MODULE=on go build) + fi +} + +function kafka_sink_uri() { + local topic_name=$1 + local protocol=$2 + local extra_params=$3 + local sink_uri="kafka://127.0.0.1:9092/${topic_name}?protocol=${protocol}&partition-num=1&kafka-version=${KAFKA_VERSION}&max-message-bytes=${BATCH_LIMIT}" + if [ "$extra_params" != "" ]; then + sink_uri="${sink_uri}&${extra_params}" + fi + echo "$sink_uri" +} + +function start_kafka_consumer() { + local work_dir=$1 + local sink_uri=$2 + local schema_registry_uri=$3 + local protocol_case=$4 + local downstream_uri="mysql://root@${DOWN_TIDB_HOST}:${DOWN_TIDB_PORT}/?safe-mode=true&batch-dml-enable=false&enable-ddl-ts=false" + local args=( + --log-file "$work_dir/cdc_kafka_consumer.log" + --log-level debug + --upstream-uri "$sink_uri" + --downstream-uri "$downstream_uri" + ) + if [ "$schema_registry_uri" != "" ]; then + args+=(--schema-registry-uri "$schema_registry_uri") + fi + if [[ "$protocol_case" == simple_* ]]; then + args+=(--upstream-tidb-dsn "root@tcp(${UP_TIDB_HOST}:${UP_TIDB_PORT})/?") + fi + + cdc_kafka_consumer "${args[@]}" >>"$work_dir/cdc_kafka_consumer_stdout.log" 2>&1 & + consumer_pid=$! +} + +function stop_kafka_consumer() { + if [ "$consumer_pid" != "" ]; then + kill -9 "$consumer_pid" 2>/dev/null || true + wait "$consumer_pid" 2>/dev/null || true + consumer_pid="" + fi +} + +function wait_changefeed_state() { + local pd_addr=$1 + local changefeed_id=$2 + local expected_state=$3 + local expected_error=$4 + local deadline=$((SECONDS + STATE_WAIT_TIMEOUT_SECONDS)) - TOPIC_NAME="big-message-test-$RANDOM" + while true; do + if check_changefeed_state "$pd_addr" "$changefeed_id" "$expected_state" "$expected_error" ""; then + return + fi + if [ "$SECONDS" -ge "$deadline" ]; then + echo "changefeed $changefeed_id did not reach state $expected_state within ${STATE_WAIT_TIMEOUT_SECONDS}s" + return 1 + fi + sleep "$STATE_CHECK_INTERVAL_SECONDS" + done +} - # record tso before we create tables to skip the system table DDLs - start_ts=$(run_cdc_cli_tso_query $UP_PD_HOST_1 $UP_PD_PORT_1) +function render_diff_config() { + local work_dir=$1 + local database_name=$2 + local diff_config=$3 + + sed -e "s/database_name/${database_name}/g" \ + -e "s|/tmp/tidb_cdc_test/kafka_big_messages/sync_diff/output|${work_dir}/sync_diff/output|g" \ + "$CUR/conf/diff_config.toml" >"$diff_config" +} - run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY +function run_protocol_case() { + local protocol_case=$1 + local protocol=$2 + local schema_registry_uri=$3 + local extra_params=$4 + local topic_case=${protocol_case//_/-} + local topic_name="big-message-${topic_case}-${RANDOM}" + local changefeed_id="kafka-big-messages-${topic_case}" + local database_name="kafka_big_messages_${protocol_case}" + local work_dir="$WORK_DIR/$protocol_case" + local sql_file="$work_dir/test.sql" + local diff_config="$work_dir/diff_config.toml" + local pd_addr="http://${UP_PD_HOST_1}:${UP_PD_PORT_1}" + local sink_uri - # Use a max-message-bytes parameter that is larger than the kafka topic max message bytes. - # Test if TiCDC automatically uses the max-message-bytes of the topic. - # See: https://github.com/PingCAP-QE/ci/blob/ddde195ebf4364a0028d53405d1194aa37a4d853/jenkins/pipelines/ci/ticdc/cdc_ghpr_kafka_integration_test.groovy#L178 - # Use a topic that has already been created. - # See: https://github.com/PingCAP-QE/ci/blob/ddde195ebf4364a0028d53405d1194aa37a4d853/jenkins/pipelines/ci/ticdc/cdc_ghpr_kafka_integration_test.groovy#L180 - SINK_URI="kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=open-protocol&partition-num=1&kafka-version=${KAFKA_VERSION}&max-message-bytes=12582912" - cdc_cli_changefeed create --start-ts=$start_ts --sink-uri="$SINK_URI" - run_kafka_consumer $WORK_DIR "kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=open-protocol&partition-num=1&version=${KAFKA_VERSION}" + mkdir -p "$work_dir" + render_diff_config "$work_dir" "$database_name" "$diff_config" + kafka_topic --topic "$topic_name" --max-message-bytes "$SMALL_TOPIC_LIMIT" + local start_ts + start_ts=$(run_cdc_cli_tso_query "$UP_PD_HOST_1" "$UP_PD_PORT_1") + sink_uri=$(kafka_sink_uri "$topic_name" "$protocol" "$extra_params") - echo "Starting generate kafka big messages..." - cd $CUR/../../utils/gen_kafka_big_messages - if [ ! -f ./gen_kafka_big_messages ]; then - GO111MODULE=on go build + if [ "$schema_registry_uri" != "" ]; then + cdc_cli_changefeed create --start-ts="$start_ts" --sink-uri="$sink_uri" --schema-registry="$schema_registry_uri" -c "$changefeed_id" + else + cdc_cli_changefeed create --start-ts="$start_ts" --sink-uri="$sink_uri" -c "$changefeed_id" fi - # Generate data larger than kafka broker max.message.bytes. We can send this data correctly. - ./gen_kafka_big_messages --row-count=15 --sql-file-path=$CUR/test.sql + start_kafka_consumer "$work_dir" "$sink_uri" "$schema_registry_uri" "$protocol_case" + wait_changefeed_state "$pd_addr" "$changefeed_id" "normal" "null" + + "$GENERATOR_DIR/gen_kafka_big_messages" --row-bytes="$ROW_BYTES" --row-count=1 --database-name="$database_name" --table-name=test --sql-file-path="$sql_file" + run_sql_file "$sql_file" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + run_sql "CREATE TABLE ${database_name}.finish_mark(id INT PRIMARY KEY)" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + + # The encoded row is larger than the topic limit, so the changefeed must + # enter the retryable warning state with ErrMessageTooLarge. + wait_changefeed_state "$pd_addr" "$changefeed_id" "warning" "ErrMessageTooLarge" + + # Only increase Kafka's topic limit. TiCDC must recreate the sink, read the + # new limit, and resume without updating, pausing, or resuming the changefeed. + kafka_topic --topic "$topic_name" --max-message-bytes "$LARGE_TOPIC_LIMIT" --alter + wait_changefeed_state "$pd_addr" "$changefeed_id" "normal" "null" + check_table_exists "${database_name}.finish_mark" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" "$TABLE_CHECK_RETRIES" + check_sync_diff "$work_dir" "$diff_config" + + cdc_cli_changefeed remove -c "$changefeed_id" + stop_kafka_consumer +} + +function run() { + # Test Kafka sink only in this case. + if [ "$SINK_TYPE" != "kafka" ]; then + return + fi + + local cases=( + "canal_json|canal-json||enable-tidb-extension=true" + "open_protocol|open-protocol||" + "simple_json|simple||" + "simple_avro|simple||encoding-format=avro" + "avro|avro|$SCHEMA_REGISTRY_URI|enable-tidb-extension=true&avro-enable-watermark=true&avro-decimal-handling-mode=string&avro-bigint-unsigned-handling-mode=string" + ) + + rm -rf "$WORK_DIR" && mkdir -p "$WORK_DIR" + start_schema_registry + build_message_generator + start_tidb_cluster --workdir "$WORK_DIR" + run_cdc_server --workdir "$WORK_DIR" --binary "$CDC_BINARY" - run_sql_file $CUR/test.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT} - table="kafka_big_messages.test" - check_table_exists $table ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} - check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml + local case_entry + for case_entry in "${cases[@]}"; do + local protocol_case protocol schema_registry_uri extra_params + IFS='|' read -r protocol_case protocol schema_registry_uri extra_params <<<"$case_entry" + run_protocol_case "$protocol_case" "$protocol" "$schema_registry_uri" "$extra_params" + done - cleanup_process $CDC_BINARY + cleanup_process "$CDC_BINARY" } -trap 'stop_test $WORK_DIR' EXIT -run $* -check_logs $WORK_DIR +trap 'stop_kafka_consumer; stop_test "$WORK_DIR"' EXIT +run "$@" +check_logs "$WORK_DIR" echo "[$(date)] <<<<<< run test case $TEST_NAME success! >>>>>>" diff --git a/tests/integration_tests/kafka_simple_claim_check/data/data.sql b/tests/integration_tests/kafka_simple_claim_check/data/data.sql index 2730d96d71..c753734f2e 100644 --- a/tests/integration_tests/kafka_simple_claim_check/data/data.sql +++ b/tests/integration_tests/kafka_simple_claim_check/data/data.sql @@ -1,4 +1,6 @@ use test; +-- Keep the encoded row larger than max-message-bytes after Snappy compression, +-- so this case exercises claim-check instead of sending the full row to Kafka. insert into t values ( 1, 1, 2, 3, 4, 5, @@ -7,7 +9,7 @@ insert into t values ( 3.1415, 2.7182, 8000, 179394.233, '2020-02-20', '2020-02-20 02:20:20', '2020-02-20 02:20:20', '02:20:20', '2020', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A', - x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', + x'89504E470D0A1A0A', RANDOM_BYTES(1024), RANDOM_BYTES(1024), RANDOM_BYTES(1024), '89504E470D0A1A0A', '89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', 'b', 'b,c', b'1000001', '{ "key1": "value1", @@ -28,7 +30,7 @@ insert into t values ( 3.1415, 2.7182, 8000, 179394.233, '2020-02-20', '2020-02-20 02:20:20', '2020-02-20 02:20:20', '02:20:20', '2020', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A', - x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', + x'89504E470D0A1A0A', RANDOM_BYTES(1024), RANDOM_BYTES(1024), RANDOM_BYTES(1024), '89504E470D0A1A0A', '89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', 'b', 'b,c', b'1000001', '{ "key1": "value1", diff --git a/tests/integration_tests/kafka_simple_claim_check/run.sh b/tests/integration_tests/kafka_simple_claim_check/run.sh index c8414aee56..a0ff8de268 100755 --- a/tests/integration_tests/kafka_simple_claim_check/run.sh +++ b/tests/integration_tests/kafka_simple_claim_check/run.sh @@ -24,6 +24,8 @@ function run() { run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY TOPIC_NAME="kafka-simple-claim-check-$RANDOM" + CLAIM_CHECK_DIR="/tmp/kafka-simple-claim-check" + rm -rf "$CLAIM_CHECK_DIR" # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) @@ -37,6 +39,7 @@ function run() { cdc_cli_changefeed pause -c ${changefeed_id} + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 2048 --alter SINK_URI="kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=simple&max-message-bytes=2048" cdc_cli_changefeed update -c ${changefeed_id} --sink-uri="$SINK_URI" --config="$CUR/conf/changefeed.toml" --no-confirm cdc_cli_changefeed resume -c ${changefeed_id} @@ -48,6 +51,10 @@ function run() { # sync_diff can't check non-exist table, so we check expected tables are created in downstream first check_table_exists test.finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 200 check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml + if ! find "$CLAIM_CHECK_DIR" -type f -print -quit | grep -q .; then + echo "claim-check did not write any file to $CLAIM_CHECK_DIR" + exit 1 + fi cleanup_process $CDC_BINARY } diff --git a/tests/integration_tests/kafka_simple_claim_check_avro/data/data.sql b/tests/integration_tests/kafka_simple_claim_check_avro/data/data.sql index 2730d96d71..c753734f2e 100644 --- a/tests/integration_tests/kafka_simple_claim_check_avro/data/data.sql +++ b/tests/integration_tests/kafka_simple_claim_check_avro/data/data.sql @@ -1,4 +1,6 @@ use test; +-- Keep the encoded row larger than max-message-bytes after Snappy compression, +-- so this case exercises claim-check instead of sending the full row to Kafka. insert into t values ( 1, 1, 2, 3, 4, 5, @@ -7,7 +9,7 @@ insert into t values ( 3.1415, 2.7182, 8000, 179394.233, '2020-02-20', '2020-02-20 02:20:20', '2020-02-20 02:20:20', '02:20:20', '2020', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A', - x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', + x'89504E470D0A1A0A', RANDOM_BYTES(1024), RANDOM_BYTES(1024), RANDOM_BYTES(1024), '89504E470D0A1A0A', '89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', 'b', 'b,c', b'1000001', '{ "key1": "value1", @@ -28,7 +30,7 @@ insert into t values ( 3.1415, 2.7182, 8000, 179394.233, '2020-02-20', '2020-02-20 02:20:20', '2020-02-20 02:20:20', '02:20:20', '2020', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A', '89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A89504E470D0A1A0A', - x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', + x'89504E470D0A1A0A', RANDOM_BYTES(1024), RANDOM_BYTES(1024), RANDOM_BYTES(1024), '89504E470D0A1A0A', '89504E470D0A1A0A', x'89504E470D0A1A0A', x'89504E470D0A1A0A', 'b', 'b,c', b'1000001', '{ "key1": "value1", diff --git a/tests/integration_tests/kafka_simple_claim_check_avro/run.sh b/tests/integration_tests/kafka_simple_claim_check_avro/run.sh index 259d526d59..ac3626634e 100755 --- a/tests/integration_tests/kafka_simple_claim_check_avro/run.sh +++ b/tests/integration_tests/kafka_simple_claim_check_avro/run.sh @@ -24,6 +24,8 @@ function run() { run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY TOPIC_NAME="kafka-simple-claim-check-avro-$RANDOM" + CLAIM_CHECK_DIR="/tmp/kafka-simple-avro-claim-check" + rm -rf "$CLAIM_CHECK_DIR" # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) @@ -37,6 +39,7 @@ function run() { cdc_cli_changefeed pause -c ${changefeed_id} + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 2048 --alter SINK_URI="kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=simple&encoding-format=avro&max-message-bytes=2048" cdc_cli_changefeed update -c ${changefeed_id} --sink-uri="$SINK_URI" --config="$CUR/conf/changefeed.toml" --no-confirm cdc_cli_changefeed resume -c ${changefeed_id} @@ -48,6 +51,10 @@ function run() { # sync_diff can't check non-exist table, so we check expected tables are created in downstream first check_table_exists test.finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 200 check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml + if ! find "$CLAIM_CHECK_DIR" -type f -print -quit | grep -q .; then + echo "claim-check did not write any file to $CLAIM_CHECK_DIR" + exit 1 + fi cleanup_process $CDC_BINARY } diff --git a/tests/integration_tests/kafka_simple_handle_key_only/run.sh b/tests/integration_tests/kafka_simple_handle_key_only/run.sh index 32f7ecc6e3..e7b9f38884 100755 --- a/tests/integration_tests/kafka_simple_handle_key_only/run.sh +++ b/tests/integration_tests/kafka_simple_handle_key_only/run.sh @@ -36,6 +36,7 @@ function run() { cdc_cli_changefeed pause -c ${changefeed_id} + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 700 --alter SINK_URI="kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=simple&max-message-bytes=700" cdc_cli_changefeed update -c ${changefeed_id} --sink-uri="$SINK_URI" --config="$CUR/conf/changefeed.toml" --no-confirm cdc_cli_changefeed resume -c ${changefeed_id} diff --git a/tests/integration_tests/kafka_simple_handle_key_only_avro/run.sh b/tests/integration_tests/kafka_simple_handle_key_only_avro/run.sh index 717d3924d3..94ea60d97b 100755 --- a/tests/integration_tests/kafka_simple_handle_key_only_avro/run.sh +++ b/tests/integration_tests/kafka_simple_handle_key_only_avro/run.sh @@ -36,6 +36,7 @@ function run() { cdc_cli_changefeed pause -c ${changefeed_id} + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 650 --alter SINK_URI="kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=simple&encoding-format=avro&max-message-bytes=650" cdc_cli_changefeed update -c ${changefeed_id} --sink-uri="$SINK_URI" --config="$CUR/conf/changefeed.toml" --no-confirm cdc_cli_changefeed resume -c ${changefeed_id} diff --git a/tests/integration_tests/open_protocol_claim_check/data/data.sql b/tests/integration_tests/open_protocol_claim_check/data/data.sql index 14ae2db77e..dbacc55cf2 100644 --- a/tests/integration_tests/open_protocol_claim_check/data/data.sql +++ b/tests/integration_tests/open_protocol_claim_check/data/data.sql @@ -93,6 +93,7 @@ insert into t values ( ); update t set c_float = 3.1415, c_double = 2.7182, c_decimal = 8000, c_decimal_2 = 179394.233 where id = 2; +update t set c_longblob = concat(random_bytes(1024), random_bytes(1024), random_bytes(1024)) where id = 2; begin; diff --git a/tests/integration_tests/open_protocol_claim_check/run.sh b/tests/integration_tests/open_protocol_claim_check/run.sh index 2b262fd3df..7f9f94e3be 100755 --- a/tests/integration_tests/open_protocol_claim_check/run.sh +++ b/tests/integration_tests/open_protocol_claim_check/run.sh @@ -18,7 +18,10 @@ function run() { start_tidb_cluster --workdir $WORK_DIR - TOPIC_NAME="open-protocol-claim-check" + TOPIC_NAME="open-protocol-claim-check-$RANDOM" + CLAIM_CHECK_DIR="/tmp/open-protocol-claim-check" + rm -rf "$CLAIM_CHECK_DIR" + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 2048 # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) @@ -40,6 +43,10 @@ function run() { # sync_diff can't check non-exist table, so we check expected tables are created in downstream first check_table_exists test.finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 200 check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml + if ! find "$CLAIM_CHECK_DIR" -type f -print -quit | grep -q .; then + echo "claim-check did not write any file to $CLAIM_CHECK_DIR" + exit 1 + fi cleanup_process $CDC_BINARY } diff --git a/tests/integration_tests/open_protocol_handle_key_only/data/data.sql b/tests/integration_tests/open_protocol_handle_key_only/data/data.sql index 2977b9aa12..2c79413baf 100644 --- a/tests/integration_tests/open_protocol_handle_key_only/data/data.sql +++ b/tests/integration_tests/open_protocol_handle_key_only/data/data.sql @@ -93,6 +93,7 @@ insert into t values ( ); update t set c_float = 3.1415, c_double = 2.7182, c_decimal = 8000, c_decimal_2 = 179394.233 where id = 2; +update t set c_longblob = concat(random_bytes(1024), random_bytes(1024), random_bytes(1024)) where id = 2; create table finish_mark ( diff --git a/tests/integration_tests/open_protocol_handle_key_only/run.sh b/tests/integration_tests/open_protocol_handle_key_only/run.sh index a416274e1d..01aab001dc 100755 --- a/tests/integration_tests/open_protocol_handle_key_only/run.sh +++ b/tests/integration_tests/open_protocol_handle_key_only/run.sh @@ -19,6 +19,7 @@ function run() { start_tidb_cluster --workdir $WORK_DIR TOPIC_NAME="open-protocol-handle-key-only-$RANDOM" + kafka_topic --topic "$TOPIC_NAME" --max-message-bytes 2048 # record tso before we create tables to skip the system table DDLs start_ts=$(run_cdc_cli_tso_query ${UP_PD_HOST_1} ${UP_PD_PORT_1}) diff --git a/tests/utils/kafka_topic/main.go b/tests/utils/kafka_topic/main.go new file mode 100644 index 0000000000..6227492cf9 --- /dev/null +++ b/tests/utils/kafka_topic/main.go @@ -0,0 +1,68 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "flag" + "log" + "strconv" + "strings" + + "github.com/IBM/sarama" +) + +func main() { + brokers := flag.String("brokers", "127.0.0.1:9092", "Comma-separated Kafka broker addresses.") + topic := flag.String("topic", "", "Kafka topic name.") + maxMessageBytes := flag.Int("max-message-bytes", 0, "Topic max.message.bytes value.") + alter := flag.Bool("alter", false, "Alter an existing topic instead of creating it.") + flag.Parse() + + if *topic == "" { + log.Fatal("topic must not be empty") + } + if *maxMessageBytes <= 0 { + log.Fatal("max-message-bytes must be greater than zero") + } + + value := strconv.Itoa(*maxMessageBytes) + config := sarama.NewConfig() + config.ClientID = "ticdc-integration-test-kafka-topic" + admin, err := sarama.NewClusterAdmin(strings.Split(*brokers, ","), config) + if err != nil { + log.Fatalf("create Kafka admin client: %v", err) + } + defer func() { + if err := admin.Close(); err != nil { + log.Printf("close Kafka admin client: %v", err) + } + }() + + configEntries := map[string]*string{"max.message.bytes": &value} + if *alter { + if err := admin.AlterConfig(sarama.TopicResource, *topic, configEntries, false); err != nil { + log.Fatalf("alter Kafka topic %s: %v", *topic, err) + } + return + } + + detail := &sarama.TopicDetail{ + NumPartitions: 1, + ReplicationFactor: 1, + ConfigEntries: configEntries, + } + if err := admin.CreateTopic(*topic, detail, false); err != nil { + log.Fatalf("create Kafka topic %s: %v", *topic, err) + } +} From ab1d7ca1bf1bd0722859e841420129b338bfc783 Mon Sep 17 00:00:00 2001 From: Ling Jin <7138436+3AceShowHand@users.noreply.github.com> Date: Thu, 30 Jul 2026 17:46:37 +0800 Subject: [PATCH 2/5] kafka: improve topic validation, timeout checks, and logging (#5818) close pingcap/ticdc#5819 --- downstreamadapter/sink/kafka/sink.go | 45 ++------- .../sink/topicmanager/kafka_topic_manager.go | 74 +++++++-------- .../topicmanager/kafka_topic_manager_test.go | 4 +- pkg/sink/kafka/admin.go | 21 +---- pkg/sink/kafka/claimcheck/claim_check.go | 2 +- pkg/sink/kafka/options.go | 72 +++++++-------- pkg/sink/kafka/options_test.go | 39 ++++++-- pkg/sink/kafka/sarama_async_producer.go | 15 ++- pkg/sink/kafka/sarama_config.go | 74 +++++++-------- pkg/sink/kafka/sarama_config_test.go | 57 ++++++++++++ pkg/sink/kafka/sarama_factory.go | 45 ++++++--- pkg/sink/kafka/sarama_sync_producer.go | 12 +-- .../kafka_compression/run.sh | 5 - tests/integration_tests/log_redaction/run.sh | 91 ------------------- tests/integration_tests/run_light_it_in_ci.sh | 2 +- 15 files changed, 251 insertions(+), 307 deletions(-) diff --git a/downstreamadapter/sink/kafka/sink.go b/downstreamadapter/sink/kafka/sink.go index daec24cf7d..195a7e3c25 100644 --- a/downstreamadapter/sink/kafka/sink.go +++ b/downstreamadapter/sink/kafka/sink.go @@ -256,7 +256,7 @@ func (s *sink) WriteBlockEvent(event commonEvent.BlockEvent) error { case *commonEvent.DDLEvent: err = s.sendDDLEvent(v) default: - log.Error("kafka sink doesn't support this type of block event", + log.Error("unsupported kafka sink block event type", zap.String("namespace", s.changefeedID.Keyspace()), zap.String("changefeed", s.changefeedID.Name()), zap.String("eventType", commonEvent.TypeToString(event.GetType()))) @@ -310,9 +310,6 @@ func (s *sink) calculateKeyPartitions(ctx context.Context) error { default: event, ok := s.eventChan.Get() if !ok { - log.Info("kafka sink event channel closed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name())) return nil } schema := event.TableInfo.GetSchemaName() @@ -372,9 +369,6 @@ func (s *sink) nonBatchEncodeRun(ctx context.Context) error { default: event, ok := s.rowChan.Get() if !ok { - log.Info("kafka sink event channel closed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name())) return nil } if err := s.comp.encoderGroup.AddEvents(ctx, event.Key, &event.RowEvent); err != nil { @@ -397,10 +391,6 @@ func (s *sink) batchEncodeRun(ctx context.Context) error { start := time.Now() msgs, err := s.batch(ctx, msgsBuf) if err != nil { - log.Error("kafka sink batch dml events failed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name()), - zap.Error(err)) return err } if len(msgs) == 0 { @@ -430,9 +420,6 @@ func (s *sink) batch(ctx context.Context, buffer []*commonEvent.MQRowEvent) ([]* default: msgs, ok := s.rowChan.GetMultipleNoGroup(buffer) if !ok { - log.Info("kafka sink event channel closed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name())) return nil, nil } buffer = buffer[:0] @@ -464,9 +451,6 @@ func (s *sink) sendMessages(ctx context.Context) error { return context.Cause(ctx) case future, ok := <-outCh: if !ok { - log.Info("kafka sink encoder's output channel closed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name())) return nil } if err = future.Ready(ctx); err != nil { @@ -476,16 +460,11 @@ func (s *sink) sendMessages(ctx context.Context) error { start := time.Now() if err = s.statistics.RecordBatchExecution(func() (int, int64, error) { message.SetPartitionKey(future.Key.PartitionKey) - log.Debug("send message to kafka", zap.String("messageKey", util.RedactBytes(message.Key)), zap.String("messageValue", util.RedactBytes(message.Value))) if err = s.dmlProducer.AsyncSend( ctx, future.Key.Topic, future.Key.Partition, message); err != nil { - log.Error("kafka sink send message failed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name()), - zap.Error(err)) return 0, 0, err } return message.GetRowsCount(), int64(message.Length()), nil @@ -505,9 +484,10 @@ func (s *sink) sendDDLEvent(event *commonEvent.DDLEvent) error { return err } if message == nil { - log.Info("Skip ddl event", zap.Uint64("startTs", event.GetStartTs()), zap.Uint64("commitTs", e.GetCommitTs()), - zap.String("query", e.Query), - zap.Stringer("changefeed", s.changefeedID)) + log.Info("kafka ddl event skipped", + zap.String("keyspace", s.changefeedID.Keyspace()), zap.String("changefeed", s.changefeedID.Name()), + zap.Uint64("startTs", e.GetStartTs()), zap.Uint64("commitTs", e.GetCommitTs()), + zap.String("query", e.Query)) continue } codecCommon.SetDDLMessageLogInfo(message, e) @@ -533,11 +513,11 @@ func (s *sink) sendDDLEvent(event *commonEvent.DDLEvent) error { if err != nil { return err } + log.Info("kafka ddl event sent", + zap.String("keyspace", s.changefeedID.Keyspace()), zap.String("changefeed", s.changefeedID.Name()), + zap.Uint64("startTs", e.GetStartTs()), zap.Uint64("commitTs", e.GetCommitTs()), + zap.String("query", e.GetDDLQuery())) } - log.Info("kafka sink send DDL event", - zap.String("keyspace", s.changefeedID.Keyspace()), zap.String("changefeed", s.changefeedID.Name()), - zap.Any("startTs", event.GetStartTs()), zap.Any("commitTs", event.GetCommitTs()), zap.Any("event", event.GetDDLQuery()), - zap.String("schema", event.GetSchemaName()), zap.String("table", event.GetTableName())) return nil } @@ -570,9 +550,6 @@ func (s *sink) sendCheckpoint(ctx context.Context) error { return context.Cause(ctx) case ts, ok := <-s.checkpointChan: if !ok { - log.Warn("kafka sink checkpoint channel closed", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name())) return nil } @@ -625,10 +602,6 @@ func (s *sink) SetTableSchemaStore(tableSchemaStore *commonEvent.TableSchemaStor func (s *sink) getAllTableNames(ts uint64) []*commonEvent.SchemaTableName { if s.tableSchemaStore == nil { - log.Warn("kafka sink table schema store is not set", - zap.String("keyspace", s.changefeedID.Keyspace()), - zap.String("changefeed", s.changefeedID.Name()), - zap.Uint64("ts", ts)) return nil } return s.tableSchemaStore.GetAllTableNames(ts) diff --git a/downstreamadapter/sink/topicmanager/kafka_topic_manager.go b/downstreamadapter/sink/topicmanager/kafka_topic_manager.go index e33929d484..3db0938012 100644 --- a/downstreamadapter/sink/topicmanager/kafka_topic_manager.go +++ b/downstreamadapter/sink/topicmanager/kafka_topic_manager.go @@ -114,10 +114,6 @@ func (m *kafkaTopicManager) backgroundRefreshMeta(ctx context.Context) { for { select { case <-ctx.Done(): - log.Info("Background refresh Kafka metadata goroutine exit.", - zap.String("keyspace", m.changefeedID.Keyspace()), - zap.String("changefeed", m.changefeedID.Name()), - ) return case <-ticker.C: // We ignore the error here, because the error may be caused by the @@ -137,23 +133,16 @@ func (m *kafkaTopicManager) tryUpdatePartitionsAndLogging(topic string, partitio if oldPartitions.(int32) != partitions { m.topics.Store(topic, partitions) log.Info( - "update topic partition number", + "kafka topic partition count changed", zap.String("keyspace", m.changefeedID.Keyspace()), zap.String("changefeed", m.changefeedID.Name()), zap.String("topic", topic), - zap.Int32("oldPartitionNumber", oldPartitions.(int32)), - zap.Int32("newPartitionNumber", partitions), + zap.Int32("oldPartitionNum", oldPartitions.(int32)), + zap.Int32("newPartitionNum", partitions), ) } } else { m.topics.Store(topic, partitions) - log.Info( - "store topic partition number", - zap.String("keyspace", m.changefeedID.Keyspace()), - zap.String("changefeed", m.changefeedID.Name()), - zap.String("topic", topic), - zap.Int32("partitionNumber", partitions), - ) } } @@ -172,7 +161,7 @@ func (m *kafkaTopicManager) fetchAllTopicsPartitionsNum() (map[string]int32, err numPartitions, err := m.admin.GetTopicsPartitionsNum(topics) if err != nil { log.Warn( - "Kafka admin client describe topics failed", + "kafka topic metadata refresh failed", zap.String("keyspace", m.changefeedID.Keyspace()), zap.String("changefeed", m.changefeedID.Name()), zap.Duration("duration", time.Since(start)), @@ -201,33 +190,32 @@ func (m *kafkaTopicManager) waitUntilTopicVisible( ctx context.Context, topicName string, ) error { + start := time.Now() topics := []string{topicName} err := retry.Do(ctx, func() error { - start := time.Now() // ignoreTopicError is set to false since we just create the topic, // make sure the topic is visible. meta, err := m.admin.GetTopicsMeta(topics, false) if err != nil { - log.Warn("topic not found, retry it", - zap.String("keyspace", m.changefeedID.Keyspace()), - zap.String("changefeed", m.changefeedID.Name()), - zap.Error(err), - zap.Duration("duration", time.Since(start)), - ) return err } - log.Info("topic found", - zap.String("keyspace", m.changefeedID.Keyspace()), - zap.String("changefeed", m.changefeedID.Name()), - zap.String("topic", topicName), - zap.Int32("partitionNumber", meta[topicName].NumPartitions), - zap.Duration("duration", time.Since(start))) + _, ok := meta[topicName] + if !ok { + return errors.ErrKafkaAdminAPI.GenWithStackByArgs("describe-topic", topicName) + } return nil }, retry.WithBackoffBaseDelay(500), retry.WithBackoffMaxDelay(1000), retry.WithMaxTries(6), ) - + if err != nil { + log.Warn("kafka topic metadata refresh failed", + zap.String("keyspace", m.changefeedID.Keyspace()), + zap.String("changefeed", m.changefeedID.Name()), + zap.String("topic", topicName), + zap.Duration("duration", time.Since(start)), + zap.Error(err)) + } return err } @@ -253,11 +241,11 @@ func (m *kafkaTopicManager) createTopic( }, false) if err != nil { log.Error( - "Kafka admin client create the topic failed", + "kafka topic creation failed", zap.String("keyspace", m.changefeedID.Keyspace()), zap.String("changefeed", m.changefeedID.Name()), zap.String("topic", topicName), - zap.Int32("partitionNumber", m.cfg.PartitionNum), + zap.Int32("partitionNum", m.cfg.PartitionNum), zap.Int16("replicationFactor", m.cfg.ReplicationFactor), zap.Error(err), zap.Duration("duration", time.Since(start)), @@ -265,15 +253,6 @@ func (m *kafkaTopicManager) createTopic( return 0, err } - log.Info( - "Kafka admin client create the topic success", - zap.String("keyspace", m.changefeedID.Keyspace()), - zap.String("changefeed", m.changefeedID.Name()), - zap.String("topic", topicName), - zap.Int32("partitionNumber", m.cfg.PartitionNum), - zap.Int16("replicationFactor", m.cfg.ReplicationFactor), - zap.Duration("duration", time.Since(start)), - ) m.tryUpdatePartitionsAndLogging(topicName, m.cfg.PartitionNum) return m.cfg.PartitionNum, nil @@ -306,6 +285,7 @@ func (m *kafkaTopicManager) CreateTopicAndWaitUntilVisible( return numPartition, nil } + start := time.Now() partitionNum, err := m.createTopic(ctx, topicName) if err != nil { if kafka.IsAdminAuthorizationFailed(err) { @@ -319,6 +299,16 @@ func (m *kafkaTopicManager) CreateTopicAndWaitUntilVisible( return 0, err } + log.Info( + "kafka topic created", + zap.String("keyspace", m.changefeedID.Keyspace()), + zap.String("changefeed", m.changefeedID.Name()), + zap.String("topic", topicName), + zap.Int32("partitionNum", partitionNum), + zap.Int16("replicationFactor", m.cfg.ReplicationFactor), + zap.Duration("duration", time.Since(start)), + ) + return partitionNum, nil } @@ -338,11 +328,11 @@ func (m *kafkaTopicManager) tryStoreTopicMeta( } func (m *kafkaTopicManager) useConfiguredPartitionNum(topicName string, cause error) int32 { - log.Warn("skip Kafka topic creation because topic authorization failed", + log.Warn("kafka topic creation skipped due to authorization failure", zap.String("keyspace", m.changefeedID.Keyspace()), zap.String("changefeed", m.changefeedID.Name()), zap.String("topic", topicName), - zap.Int32("partitionNumber", m.cfg.PartitionNum), + zap.Int32("partitionNum", m.cfg.PartitionNum), zap.Error(cause)) m.tryUpdatePartitionsAndLogging(topicName, m.cfg.PartitionNum) return m.cfg.PartitionNum diff --git a/downstreamadapter/sink/topicmanager/kafka_topic_manager_test.go b/downstreamadapter/sink/topicmanager/kafka_topic_manager_test.go index 4ee0be636a..3708d77668 100644 --- a/downstreamadapter/sink/topicmanager/kafka_topic_manager_test.go +++ b/downstreamadapter/sink/topicmanager/kafka_topic_manager_test.go @@ -248,9 +248,7 @@ func TestCreateTopicWaitsUntilVisible(t *testing.T) { return nil }), adminClient.EXPECT().GetTopicsMeta([]string{topic}, false).Return( - nil, sarama.ErrUnknownTopicOrPartition), - adminClient.EXPECT().GetTopicsMeta([]string{topic}, false).Return( - nil, sarama.ErrUnknownTopicOrPartition), + map[string]kafka.TopicDetail{}, nil), adminClient.EXPECT().GetTopicsMeta([]string{topic}, false).Return( map[string]kafka.TopicDetail{ topic: { diff --git a/pkg/sink/kafka/admin.go b/pkg/sink/kafka/admin.go index 13833516ba..98e3b154d1 100644 --- a/pkg/sink/kafka/admin.go +++ b/pkg/sink/kafka/admin.go @@ -81,11 +81,6 @@ func (a *saramaAdminClient) GetBrokerConfig(configName string) (string, bool, er return entry.Value, true, nil } } - - log.Warn("Kafka config item not found", - zap.String("keyspace", a.changefeed.Keyspace()), - zap.String("changefeed", a.changefeed.Name()), - zap.String("configName", configName)) return "", false, nil } @@ -104,19 +99,9 @@ func (a *saramaAdminClient) GetTopicConfig(topicName string, configName string) // 2. Kop returns all configs. for _, entry := range configEntries { if entry.Name == configName { - log.Info("Kafka config item found", - zap.String("keyspace", a.changefeed.Keyspace()), - zap.String("changefeed", a.changefeed.Name()), - zap.String("configName", configName), - zap.String("configValue", entry.Value)) return entry.Value, true, nil } } - - log.Warn("Kafka config item not found", - zap.String("keyspace", a.changefeed.Keyspace()), - zap.String("changefeed", a.changefeed.Name()), - zap.String("configName", configName)) return "", false, nil } @@ -136,7 +121,7 @@ func (a *saramaAdminClient) GetTopicsMeta(topics []string, ignoreTopicError bool if !ignoreTopicError { return nil, errors.WrapError(errors.ErrKafkaAdminAPI, meta.Err, "describe-topic", meta.Name) } - log.Warn("fetch topic meta failed", + log.Warn("kafka topic metadata refresh failed", zap.String("keyspace", a.changefeed.Keyspace()), zap.String("changefeed", a.changefeed.Name()), zap.String("topic", meta.Name), @@ -190,7 +175,7 @@ func (a *saramaAdminClient) Close() { // only when admin is unexpectedly nil. if a.admin != nil { if err := a.admin.Close(); err != nil { - log.Warn("close admin client meet error", + log.Warn("kafka admin client close failed", zap.String("keyspace", a.changefeed.Keyspace()), zap.String("changefeed", a.changefeed.Name()), zap.Error(err)) @@ -199,7 +184,7 @@ func (a *saramaAdminClient) Close() { } if a.client != nil { if err := a.client.Close(); err != nil { - log.Warn("close kafka client meet error", + log.Warn("kafka client close failed", zap.String("keyspace", a.changefeed.Keyspace()), zap.String("changefeed", a.changefeed.Name()), zap.Error(err)) diff --git a/pkg/sink/kafka/claimcheck/claim_check.go b/pkg/sink/kafka/claimcheck/claim_check.go index 4f8ecc2a42..7c49bd1bbe 100644 --- a/pkg/sink/kafka/claimcheck/claim_check.go +++ b/pkg/sink/kafka/claimcheck/claim_check.go @@ -52,7 +52,7 @@ func New(ctx context.Context, config *config.LargeMessageHandleConfig, changefee start := time.Now() externalStorage, err := util.GetExternalStorageWithDefaultTimeout(ctx, config.ClaimCheckStorageURI) if err != nil { - log.Error("create external storage failed", + log.Error("external storage creation failed", zap.String("keyspace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), zap.String("storageURI", util.MaskSensitiveDataInURI(config.ClaimCheckStorageURI)), diff --git a/pkg/sink/kafka/options.go b/pkg/sink/kafka/options.go index 9b77ddc84b..094f970d79 100644 --- a/pkg/sink/kafka/options.go +++ b/pkg/sink/kafka/options.go @@ -14,7 +14,6 @@ package kafka import ( - "context" "encoding/base64" "fmt" "net/http" @@ -39,6 +38,8 @@ const ( defaultPartitionNum = 3 // defaultMaxRetry is the default retry budget for Kafka producers. defaultMaxRetry = 5 + // defaultTimeout is the default timeout for Kafka connections. + defaultTimeout = 10 * time.Second ) const ( @@ -189,27 +190,25 @@ func NewOptions() *options { InsecureSkipVerify: false, SASL: &security.SASL{}, AutoCreate: true, - DialTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - ReadTimeout: 10 * time.Second, + DialTimeout: defaultTimeout, + WriteTimeout: defaultTimeout, + ReadTimeout: defaultTimeout, } } // setPartitionNum set the partition-num by the topic's partition count. -func (o *options) setPartitionNum(realPartitionCount int32) error { +func (o *options) setPartitionNum(changefeedID common.ChangeFeedID, realPartitionCount int32) error { // user does not specify the `partition-num` in the sink-uri if o.PartitionNum == 0 { o.PartitionNum = realPartitionCount - log.Info("partitionNum is not set, set by topic's partition-num", - zap.Int32("partitionNum", realPartitionCount)) return nil } if o.PartitionNum < realPartitionCount { - log.Warn("number of partition specified in sink-uri is less than that of the actual topic. "+ - "Some partitions will not have messages dispatched to", - zap.Int32("sinkUriPartitions", o.PartitionNum), - zap.Int32("topicPartitions", realPartitionCount)) + log.Warn("configured kafka partition count is lower than topic partition count", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), + zap.Int32("configuredPartitionNum", o.PartitionNum), + zap.Int32("topicPartitionNum", realPartitionCount)) return nil } @@ -297,6 +296,9 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, if err != nil { return errors.WrapError(errors.ErrKafkaInvalidConfig, err) } + if a <= 0 { + return errors.ErrKafkaInvalidConfig.GenWithStack("dial-timeout must be greater than zero") + } o.DialTimeout = a } @@ -305,6 +307,9 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, if err != nil { return errors.WrapError(errors.ErrKafkaInvalidConfig, err) } + if a <= 0 { + return errors.ErrKafkaInvalidConfig.GenWithStack("write-timeout must be greater than zero") + } o.WriteTimeout = a } @@ -313,6 +318,9 @@ func (o *options) Apply(changefeedID common.ChangeFeedID, if err != nil { return errors.WrapError(errors.ErrKafkaInvalidConfig, err) } + if a <= 0 { + return errors.ErrKafkaInvalidConfig.GenWithStack("read-timeout must be greater than zero") + } o.ReadTimeout = a } @@ -496,7 +504,6 @@ func (o *options) applySASL(urlParameter *urlConfig, sinkConfig *config.SinkConf // BASE64 decode the client secret decodedClientSecret, err := base64.StdEncoding.DecodeString(clientSecret) if err != nil { - log.Error("OAuth2 client secret is not base64 encoded", zap.Error(err)) return errors.ErrKafkaInvalidConfig.GenWithStack("OAuth2 client secret is not base64 encoded") } o.SASL.OAuth2.ClientSecret = string(decodedClientSecret) @@ -566,14 +573,14 @@ func (c *AutoCreateTopicConfig) ValidateReplicationFactor(admin ClusterAdminClie raw, found, err := admin.GetBrokerConfig(MinInsyncReplicasConfigName) if err != nil { - log.Warn("cannot get Kafka broker configuration, assume replication factor is valid", + log.Warn("kafka broker configuration lookup failed, skipping replication factor validation", zap.String("configName", MinInsyncReplicasConfigName), zap.Int16("replicationFactor", c.ReplicationFactor), zap.Error(err)) return nil } if !found { - log.Warn("Kafka broker configuration not found, assume replication factor is valid", + log.Warn("kafka broker configuration not found, skipping replication factor validation", zap.String("configName", MinInsyncReplicasConfigName), zap.Int16("replicationFactor", c.ReplicationFactor)) return nil @@ -622,7 +629,7 @@ func NewKafkaClientID(captureAddr string, // It overwrites MaxMessageBytes with the final producer message limit derived // from the topic or broker configuration. func adjustOptions( - ctx context.Context, + changefeedID common.ChangeFeedID, admin ClusterAdminClient, options *options, topic string, @@ -636,9 +643,9 @@ func adjustOptions( // once we have found the topic, no matter `auto-create-topic`, // make sure user input parameters are valid. if exists { - err = adjustExistingTopicOption(ctx, admin, options, topic, info) + err = adjustExistingTopicOption(changefeedID, admin, options, info) } else { - adjustNewTopicOptions(admin, options, topic) + adjustNewTopicOptions(admin, changefeedID, options) } if err != nil { return err @@ -649,60 +656,54 @@ func adjustOptions( } func adjustExistingTopicOption( - ctx context.Context, + changefeedID common.ChangeFeedID, admin ClusterAdminClient, options *options, - topic string, info TopicDetail, ) error { - maxMessageBytes, found, err := getTopicMaxMessageBytes(ctx, admin, info.Name) + maxMessageBytes, found, err := getTopicMaxMessageBytes(admin, info.Name) if err != nil || !found { log.Warn("kafka topic `max.message.bytes` unavailable, using configured value", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), zap.Int("maxMessageBytes", options.MaxMessageBytes), zap.Error(err)) maxMessageBytes = options.MaxMessageBytes } options.MaxMessageBytes = maxMessageBytes - // no need to create the topic, - // but we would have to log user if they found enter wrong topic name later - if options.AutoCreate { - log.Warn("topic already exist, TiCDC will not create the topic", - zap.String("topic", topic), zap.Any("detail", info)) + if err = options.setPartitionNum(changefeedID, info.NumPartitions); err != nil { + return err } - - return options.setPartitionNum(info.NumPartitions) + return nil } func adjustNewTopicOptions( admin ClusterAdminClient, + changefeedID common.ChangeFeedID, options *options, - topic string, ) { + // when create the topic, `max.message.bytes` is decided by the broker, + // it would use broker's `message.max.bytes` to set topic's `max.message.bytes`. messageMaxBytes, found, err := getBrokerMaxMessageBytes(admin) if err != nil || !found { log.Warn("kafka broker `message.max.bytes` unavailable, using configured value", + zap.String("namespace", changefeedID.Keyspace()), zap.String("changefeed", changefeedID.Name()), zap.Int("maxMessageBytes", options.MaxMessageBytes), zap.Error(err)) messageMaxBytes = options.MaxMessageBytes } options.MaxMessageBytes = messageMaxBytes - // when create the topic, `max.message.bytes` is decided by the broker, - // it would use broker's `message.max.bytes` to set topic's `max.message.bytes`. // topic not exists yet, and user does not specify the `partition-num` in the sink uri. if options.PartitionNum == 0 { options.PartitionNum = defaultPartitionNum - log.Warn("partition-num is not set, use the default partition count", - zap.String("topic", topic), zap.Int32("partitions", options.PartitionNum)) } } func getTopicMaxMessageBytes( - ctx context.Context, admin ClusterAdminClient, topic string, ) (int, bool, error) { raw, found, err := getTopicConfig( - ctx, admin, topic, + admin, topic, TopicMaxMessageBytesConfigName, BrokerMessageMaxBytesConfigName, ) @@ -741,7 +742,6 @@ func getBrokerMaxMessageBytes(admin ClusterAdminClient) (int, bool, error) { // we will try to get it from the broker's configuration. // NOTICE: The configuration names of topic and broker may be different for the same configuration. func getTopicConfig( - _ context.Context, admin ClusterAdminClient, topicName string, topicConfigName string, @@ -752,7 +752,5 @@ func getTopicConfig( return c, true, nil } - log.Info("kafka sink cannot get the configuration from topic, try to get it from broker", - zap.String("topic", topicName), zap.String("config", topicConfigName), zap.Error(err)) return admin.GetBrokerConfig(brokerConfigName) } diff --git a/pkg/sink/kafka/options_test.go b/pkg/sink/kafka/options_test.go index 42ad0a4990..7f49c29402 100644 --- a/pkg/sink/kafka/options_test.go +++ b/pkg/sink/kafka/options_test.go @@ -346,17 +346,18 @@ func TestApplyRejectsNonPositiveMaxMessageBytes(t *testing.T) { func TestSetPartitionNum(t *testing.T) { options := NewOptions() - err := options.setPartitionNum(2) + changefeedID := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test") + err := options.setPartitionNum(changefeedID, 2) require.NoError(t, err) require.Equal(t, int32(2), options.PartitionNum) options.PartitionNum = 1 - err = options.setPartitionNum(2) + err = options.setPartitionNum(changefeedID, 2) require.NoError(t, err) require.Equal(t, int32(1), options.PartitionNum) options.PartitionNum = 3 - err = options.setPartitionNum(2) + err = options.setPartitionNum(changefeedID, 2) require.True(t, errors.ErrKafkaInvalidConfig.Equal(err)) } @@ -424,6 +425,30 @@ func TestTimeout(t *testing.T) { require.Equal(t, 2*time.Minute, options.WriteTimeout) } +func TestApplyRejectsNonPositiveTimeout(t *testing.T) { + t.Parallel() + + changefeedID := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test") + for _, parameter := range []string{"dial-timeout", "read-timeout", "write-timeout"} { + for _, value := range []string{"0s", "-1s"} { + t.Run(parameter+"="+value, func(t *testing.T) { + t.Parallel() + + sinkURI, err := url.Parse( + "kafka://127.0.0.1:9092/kafka-test?" + parameter + "=" + value) + require.NoError(t, err) + + err = NewOptions().Apply( + changefeedID, sinkURI, config.GetDefaultReplicaConfig().Sink) + require.ErrorContains(t, err, parameter+" must be greater than zero") + errCode, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrKafkaInvalidConfig.RFCCode(), errCode) + }) + } + } +} + func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *testing.T) { tests := []struct { name string @@ -450,6 +475,7 @@ func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *t } topicName := "test-topic" + changefeedID := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test") for _, test := range tests { t.Run(test.name, func(t *testing.T) { adminFixture := newKafkaAdminFixture(t) @@ -471,7 +497,7 @@ func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *t options := NewOptions() err = options.Apply( - common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test"), + changefeedID, sinkURI, config.GetDefaultReplicaConfig().Sink, ) @@ -481,7 +507,7 @@ func TestAdjustConfigFallsBackToBrokerMessageMaxBytesWhenTopicConfigMissing(t *t expectedProducerLimit := adminFixture.brokerMessageMaxBytes() ctx := context.Background() - err = adjustOptions(ctx, adminClient, options, topicName) + err = adjustOptions(changefeedID, adminClient, options, topicName) require.NoError(t, err) saramaConfig, err := newSaramaConfig(ctx, options) @@ -713,7 +739,8 @@ func TestConfigurationCombinations(t *testing.T) { if _, exists := adminFixture.topics[topic]; exists { sourceMaxMessageBytes = adminFixture.topicMaxMessageBytes(topic) } - err = adjustOptions(context.Background(), adminClient, options, topic) + changefeedID := common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test") + err = adjustOptions(changefeedID, adminClient, options, topic) require.Nil(t, err) require.Equal(t, sourceMaxMessageBytes, options.MaxMessageBytes) require.Equal( diff --git a/pkg/sink/kafka/sarama_async_producer.go b/pkg/sink/kafka/sarama_async_producer.go index f0c0f6b5d1..d3e1781c71 100644 --- a/pkg/sink/kafka/sarama_async_producer.go +++ b/pkg/sink/kafka/sarama_async_producer.go @@ -62,13 +62,13 @@ func (p *saramaAsyncProducer) Close() { // To prevent the scenario mentioned above, close the client first. start := time.Now() if err := p.client.Close(); err != nil { - log.Warn("Close kafka async producer client error", + log.Warn("kafka async producer client close failed", zap.String("keyspace", p.changefeedID.Keyspace()), zap.String("changefeed", p.changefeedID.Name()), zap.Duration("duration", time.Since(start)), zap.Error(err)) } else { - log.Info("Close kafka async producer client success", + log.Info("kafka async producer client closed", zap.String("keyspace", p.changefeedID.Keyspace()), zap.String("changefeed", p.changefeedID.Name()), zap.Duration("duration", time.Since(start))) @@ -76,13 +76,13 @@ func (p *saramaAsyncProducer) Close() { start = time.Now() if err := p.producer.Close(); err != nil { - log.Warn("Close kafka async producer error", + log.Warn("kafka async producer close failed", zap.String("keyspace", p.changefeedID.Keyspace()), zap.String("changefeed", p.changefeedID.Name()), zap.Duration("duration", time.Since(start)), zap.Error(err)) } else { - log.Info("Close kafka async producer success", + log.Info("kafka async producer closed", zap.String("keyspace", p.changefeedID.Keyspace()), zap.String("changefeed", p.changefeedID.Name()), zap.Duration("duration", time.Since(start))) @@ -97,9 +97,6 @@ func (p *saramaAsyncProducer) AsyncRunCallback( for { select { case <-ctx.Done(): - log.Info("async producer exit since context is done", - zap.String("keyspace", p.changefeedID.Keyspace()), - zap.String("changefeed", p.changefeedID.Name())) return context.Cause(ctx) case ack := <-p.producer.Successes(): if ack != nil { @@ -109,7 +106,7 @@ func (p *saramaAsyncProducer) AsyncRunCallback( meta.callback() } default: - log.Error("unknown message metadata type in async producer", + log.Error("kafka producer received unknown message metadata type", zap.Any("metadata", ack.Metadata)) } } @@ -128,7 +125,7 @@ func (p *saramaAsyncProducer) AsyncRunCallback( } func (p *saramaAsyncProducer) handleProducerError(err *sarama.ProducerError) error { - log.Error("send message to kafka failed", + log.Error("kafka message send failed", zap.String("keyspace", p.changefeedID.Keyspace()), zap.String("changefeed", p.changefeedID.Name()), zap.String("eventContext", BuildEventLogContext( diff --git a/pkg/sink/kafka/sarama_config.go b/pkg/sink/kafka/sarama_config.go index 6f2d56456e..51dbd2384e 100644 --- a/pkg/sink/kafka/sarama_config.go +++ b/pkg/sink/kafka/sarama_config.go @@ -87,12 +87,9 @@ func newSaramaConfig(ctx context.Context, o *options) (*sarama.Config, error) { case "zstd": config.Producer.Compression = sarama.CompressionZSTD default: - log.Warn("Unsupported compression algorithm", zap.String("compression", o.Compression)) + log.Warn("unsupported kafka compression algorithm", zap.String("compression", o.Compression)) config.Producer.Compression = sarama.CompressionNone } - if config.Producer.Compression != sarama.CompressionNone { - log.Info("Kafka producer uses " + compression + " compression algorithm") - } if o.EnableTLS { // for SSL encryption with a trust CA certificate, we must populate the @@ -120,27 +117,27 @@ func newSaramaConfig(ctx context.Context, o *options) (*sarama.Config, error) { return nil, err } - kafkaVersion, err := getKafkaVersion(config, o) + err = completeSaramaKafkaVersion(config, o) if err != nil { - log.Warn("Can't get Kafka version by broker. ticdc will use default version", - zap.String("defaultVersion", kafkaVersion.String())) + return nil, err } - config.Version = kafkaVersion + return config, nil +} - if o.IsAssignedVersion { - version, err := sarama.ParseKafkaVersion(o.Version) - if err != nil { - return nil, errors.WrapError(errors.ErrKafkaInvalidConfig, err) - } - config.Version = version - if !version.IsAtLeast(maxKafkaVersion) && version.String() != kafkaVersion.String() { - log.Warn("The Kafka version you assigned may not be correct. "+ - "Please assign a version equal to or less than the specified version", - zap.String("assignedVersion", version.String()), - zap.String("desiredVersion", kafkaVersion.String())) - } +func completeSaramaKafkaVersion(config *sarama.Config, o *options) error { + detectedVersion, err := detectKafkaVersion(config, o) + if err != nil { + log.Warn("kafka version detection failed, using fallback version", + zap.Strings("brokers", o.BrokerEndpoints), + zap.String("fallbackVersion", detectedVersion.String()), + zap.Error(err)) } - return config, nil + kafkaVersion, err := selectKafkaVersion(detectedVersion, o) + if err != nil { + return err + } + config.Version = kafkaVersion + return nil } func completeSaramaSASLConfig(ctx context.Context, config *sarama.Config, o *options) error { @@ -186,7 +183,7 @@ func completeSaramaSASLConfig(ctx context.Context, config *sarama.Config, o *opt return nil } -func getKafkaVersion(config *sarama.Config, o *options) (sarama.KafkaVersion, error) { +func detectKafkaVersion(config *sarama.Config, o *options) (sarama.KafkaVersion, error) { addrs := o.BrokerEndpoints if len(addrs) > 1 { // Shuffle the list of addresses to randomize the order in which @@ -208,25 +205,26 @@ func getKafkaVersion(config *sarama.Config, o *options) (sarama.KafkaVersion, er } } if err != nil { - log.Warn("kafka sink use the default kafka version since cannot find it from the brokers", - zap.String("defaultVersion", defaultKafkaVersion.String())) targetVersion = defaultKafkaVersion } + return targetVersion, err +} - if o.IsAssignedVersion { - assignedVersion, err := sarama.ParseKafkaVersion(o.Version) - if err != nil { - return assignedVersion, errors.WrapError(errors.ErrKafkaInvalidConfig, err) - } - if !assignedVersion.IsAtLeast(maxKafkaVersion) && assignedVersion.String() != targetVersion.String() { - log.Warn("The Kafka version you assigned may not be correct. "+ - "Please assign a version equal to or less than the specified version", - zap.String("assignedVersion", assignedVersion.String()), - zap.String("desiredVersion", targetVersion.String())) - } - targetVersion = assignedVersion +func selectKafkaVersion(detectedVersion sarama.KafkaVersion, o *options) (sarama.KafkaVersion, error) { + if !o.IsAssignedVersion { + return detectedVersion, nil + } + assignedVersion, err := sarama.ParseKafkaVersion(o.Version) + if err != nil { + return assignedVersion, errors.WrapError(errors.ErrKafkaInvalidConfig, err) + } + if !assignedVersion.IsAtLeast(maxKafkaVersion) && + assignedVersion.String() != detectedVersion.String() { + log.Warn("configured kafka version differs from detected version", + zap.String("assignedVersion", assignedVersion.String()), + zap.String("desiredVersion", detectedVersion.String())) } - return targetVersion, nil + return assignedVersion, nil } func getKafkaVersionFromBroker(config *sarama.Config, requestVersion int16, addr string) (sarama.KafkaVersion, error) { @@ -237,12 +235,10 @@ func getKafkaVersionFromBroker(config *sarama.Config, requestVersion int16, addr _ = broker.Close() }() if err != nil { - log.Warn("Kafka fail to open broker", zap.String("addr", addr), zap.Error(err)) return KafkaVersion, err } apiResponse, err := broker.ApiVersions(&sarama.ApiVersionsRequest{Version: requestVersion}) if err != nil { - log.Warn("Kafka fail to get ApiVersions", zap.String("addr", addr), zap.Error(err)) return KafkaVersion, err } // ApiKey method diff --git a/pkg/sink/kafka/sarama_config_test.go b/pkg/sink/kafka/sarama_config_test.go index 1ddac4aa65..f85d688edc 100644 --- a/pkg/sink/kafka/sarama_config_test.go +++ b/pkg/sink/kafka/sarama_config_test.go @@ -86,6 +86,63 @@ func TestNewSaramaConfig(t *testing.T) { require.Equal(t, sarama.SASLMechanism("SCRAM-SHA-256"), cfg.Net.SASL.Mechanism) } +func TestSelectKafkaVersion(t *testing.T) { + tests := []struct { + name string + detectedVersion sarama.KafkaVersion + assignedVersion string + expectedVersion sarama.KafkaVersion + expectedErr error + }{ + { + name: "use detected version", + detectedVersion: sarama.V2_4_0_0, + expectedVersion: sarama.V2_4_0_0, + }, + { + name: "use fallback version", + detectedVersion: defaultKafkaVersion, + expectedVersion: defaultKafkaVersion, + }, + { + name: "assigned version overrides detected version", + detectedVersion: sarama.V2_4_0_0, + assignedVersion: "2.6.0", + expectedVersion: sarama.V2_6_0_0, + }, + { + name: "assigned version overrides fallback version", + detectedVersion: defaultKafkaVersion, + assignedVersion: "2.6.0", + expectedVersion: sarama.V2_6_0_0, + }, + { + name: "reject invalid assigned version", + detectedVersion: sarama.V2_4_0_0, + assignedVersion: "invalid", + expectedErr: errors.ErrKafkaInvalidConfig, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + options := NewOptions() + if test.assignedVersion != "" { + options.IsAssignedVersion = true + options.Version = test.assignedVersion + } + + version, err := selectKafkaVersion(test.detectedVersion, options) + if test.expectedErr != nil { + require.ErrorIs(t, err, test.expectedErr) + return + } + require.NoError(t, err) + require.Equal(t, test.expectedVersion, version) + }) + } +} + func TestNewSaramaConfigInvalidOAuthTokenURL(t *testing.T) { options := NewOptions() options.SASL = &security.SASL{ diff --git a/pkg/sink/kafka/sarama_factory.go b/pkg/sink/kafka/sarama_factory.go index 57bf5ef27c..8f73ca70b5 100644 --- a/pkg/sink/kafka/sarama_factory.go +++ b/pkg/sink/kafka/sarama_factory.go @@ -40,10 +40,12 @@ func NewSaramaFactory( ) (Factory, error) { start := time.Now() config, err := newSaramaConfig(ctx, o) - duration := time.Since(start).Seconds() - if duration > 2 { - log.Warn("new sarama config cost too much time", - zap.Stringer("changefeedID", changefeedID), zap.Any("duration", duration)) + duration := time.Since(start) + if duration > 2*time.Second { + log.Warn("kafka configuration initialization is slow", + zap.String("keyspace", changefeedID.Keyspace()), + zap.String("changefeed", changefeedID.Name()), + zap.Duration("duration", duration)) } if err != nil { return nil, err @@ -57,9 +59,22 @@ func NewSaramaFactory( admin.Close() }() - if err = adjustOptions(ctx, admin, o, o.Topic); err != nil { + if err = adjustOptions(changefeedID, admin, o, o.Topic); err != nil { return nil, err } + log.Info("kafka sink configuration resolved", + zap.String("namespace", changefeedID.Keyspace()), + zap.String("changefeed", changefeedID.Name()), + zap.String("topic", o.Topic), + zap.Int32("partitionNum", o.PartitionNum), + zap.Int("maxMessageBytes", o.MaxMessageBytes), + zap.Int("maxBatchedBytes", o.MaxBatchedBytes), + zap.String("compression", config.Producer.Compression.String()), + zap.Int16("requiredAcks", int16(o.RequiredAcks)), + zap.Int("maxRetry", o.MaxRetry), + zap.Duration("dialTimeout", o.DialTimeout), + zap.Duration("readTimeout", o.ReadTimeout), + zap.Duration("writeTimeout", o.WriteTimeout)) return &saramaFactory{ changefeedID: changefeedID, @@ -71,10 +86,12 @@ func NewSaramaFactory( func newAdminClient(changefeedID common.ChangeFeedID, endpoints []string, config *sarama.Config) (ClusterAdminClient, error) { start := time.Now() client, err := sarama.NewClient(endpoints, config) - duration := time.Since(start).Seconds() - if duration > 2 { - log.Warn("new sarama client cost too much time", - zap.Any("duration", duration), zap.Stringer("changefeedID", changefeedID)) + duration := time.Since(start) + if duration > 2*time.Second { + log.Warn("kafka client initialization is slow", + zap.String("keyspace", changefeedID.Keyspace()), + zap.String("changefeed", changefeedID.Name()), + zap.Duration("duration", duration)) } if err != nil { return nil, errors.WrapError(errors.ErrNewKafkaSink, err) @@ -82,10 +99,12 @@ func newAdminClient(changefeedID common.ChangeFeedID, endpoints []string, config start = time.Now() admin, err := sarama.NewClusterAdminFromClient(client) - duration = time.Since(start).Seconds() - if duration > 2 { - log.Warn("new sarama cluster admin cost too much time", - zap.Any("duration", duration), zap.Stringer("changefeedID", changefeedID)) + duration = time.Since(start) + if duration > 2*time.Second { + log.Warn("kafka admin client initialization is slow", + zap.String("keyspace", changefeedID.Keyspace()), + zap.String("changefeed", changefeedID.Name()), + zap.Duration("duration", duration)) } if err != nil { // `sarama.NewClusterAdminFromClient` does not take ownership of the client, diff --git a/pkg/sink/kafka/sarama_sync_producer.go b/pkg/sink/kafka/sarama_sync_producer.go index 754d1db9e1..fcf1c9c258 100644 --- a/pkg/sink/kafka/sarama_sync_producer.go +++ b/pkg/sink/kafka/sarama_sync_producer.go @@ -58,7 +58,7 @@ func (p *saramaSyncProducer) SendMessage(topic string, partitionNum int32, messa if err == nil { return nil } - log.Error("send message to kafka failed", + log.Error("kafka message send failed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name()), zap.String("eventContext", BuildEventLogContext(p.id.Keyspace(), p.id.Name(), message.LogInfo)), @@ -84,7 +84,7 @@ func (p *saramaSyncProducer) SendMessages(topic string, partitionNum int32, mess if err == nil { return nil } - log.Error("send message to kafka failed", + log.Error("kafka message send failed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name()), zap.String("eventContext", BuildEventLogContext(p.id.Keyspace(), p.id.Name(), message.LogInfo)), @@ -94,7 +94,7 @@ func (p *saramaSyncProducer) SendMessages(topic string, partitionNum int32, mess func (p *saramaSyncProducer) Close() { if p.closed.Load() { - log.Warn("kafka DDL producer already closed", + log.Warn("kafka ddl producer already closed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name())) return @@ -106,7 +106,7 @@ func (p *saramaSyncProducer) Close() { // so producer.Close() alone won't release the underlying client resources. if p.client != nil { if err := p.client.Close(); err != nil { - log.Warn("Close Kafka DDL producer client with error", + log.Warn("kafka ddl producer client close failed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name()), zap.Duration("duration", time.Since(start)), @@ -115,7 +115,7 @@ func (p *saramaSyncProducer) Close() { } if p.producer != nil { if err := p.producer.Close(); err != nil { - log.Error("Close Kafka DDL producer with error", + log.Error("kafka ddl producer close failed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name()), zap.Duration("duration", time.Since(start)), @@ -123,7 +123,7 @@ func (p *saramaSyncProducer) Close() { return } } - log.Info("Kafka DDL producer closed", + log.Info("kafka ddl producer closed", zap.String("keyspace", p.id.Keyspace()), zap.String("changefeed", p.id.Name()), zap.Duration("duration", time.Since(start))) diff --git a/tests/integration_tests/kafka_compression/run.sh b/tests/integration_tests/kafka_compression/run.sh index e0f85df648..a57cd937b1 100755 --- a/tests/integration_tests/kafka_compression/run.sh +++ b/tests/integration_tests/kafka_compression/run.sh @@ -18,11 +18,6 @@ function test_compression() { run_kafka_consumer $WORK_DIR "kafka://127.0.0.1:9092/$TOPIC_NAME?protocol=canal-json&version=${KAFKA_VERSION}&enable-tidb-extension=true" run_sql_file $CUR/data/$1_data.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT} - compression_algorithm=$(grep "Kafka producer uses $1 compression algorithm" "$WORK_DIR/cdc.log") - if [[ "$compression_algorithm" -ne 1 ]]; then - echo "can't found producer compression algorithm" - exit 1 - fi check_table_exists test.$1_finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 200 check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml cdc_cli_changefeed pause -c $1 diff --git a/tests/integration_tests/log_redaction/run.sh b/tests/integration_tests/log_redaction/run.sh index b99fe5da90..71b7e1e656 100755 --- a/tests/integration_tests/log_redaction/run.sh +++ b/tests/integration_tests/log_redaction/run.sh @@ -372,97 +372,6 @@ function run() { echo "[$(date)] ✓ MySQL sink: All redaction modes validated" fi - # ========================================================================== - # Test 4b: Kafka sink validation (tests Kafka-specific redaction) - # ========================================================================== - if [ "$SINK_TYPE" = "kafka" ]; then - echo "" - echo "=== Test 4b: Kafka sink redaction validation ===" - - # Kafka sink logs message key/value at DEBUG level - # Log message: "send message to kafka" with messageKey and messageValue fields - - # Test ON mode with Kafka sink (most important - full redaction) - echo " [4b-1] ON mode with Kafka sink:" - run_sql "DROP DATABASE IF EXISTS log_redaction_test;" - run_sql "CREATE DATABASE log_redaction_test;" - - KAFKA_TOPIC="log-redaction-test-$RANDOM" - KAFKA_SINK_URI="kafka://127.0.0.1:9092/$KAFKA_TOPIC?protocol=open-protocol" - - run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY --redact-info-log on --logsuffix "_on_kafka" - - cdc_cli_changefeed create --sink-uri="$KAFKA_SINK_URI" --changefeed-id="kafka-on-test" --config=$CUR/conf/changefeed.toml - - run_sql_file $CUR/data/test.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT} - - echo " Waiting for Kafka sink to process events..." - wait_for_log_content "$WORK_DIR/cdc_on_kafka.log" "send message to kafka" "Kafka message logs" 30 - - echo " [Validation] ON mode with Kafka sink:" - echo "" - - # Capture Kafka logs once for all validations - captured_logs=$(grep "send message to kafka" "$WORK_DIR/cdc_on_kafka.log" 2>/dev/null || echo "") - log_raw_content "Kafka message logs (ON mode)" "$captured_logs" - - # STRICT POSITIVE VALIDATION: messageKey and messageValue must show redacted format - echo " [1/2] Verifying Kafka logs show redacted '?' placeholder:" - require_log_pattern "$WORK_DIR/cdc_on_kafka.log" \ - "send message to kafka.*messageKey.*\?.*messageValue.*\?" \ - "Kafka messageKey and messageValue redacted to '?'" \ - "ON mode should redact both messageKey and messageValue" - - # STRICT NEGATIVE VALIDATION: No sensitive data should leak in Kafka logs - echo " [2/2] Verifying NO sensitive data leaks in Kafka logs:" - sensitive_patterns=("Password1!" "SecretPass1!" "user1@example.com" "4532-1000-1000") - for pattern in "${sensitive_patterns[@]}"; do - require_no_log_pattern "$WORK_DIR/cdc_on_kafka.log" \ - "$pattern" \ - "No leak of sensitive value in Kafka logs: $pattern" - done - - captured_logs="" - cleanup_process $CDC_BINARY - - # Test MARKER mode with Kafka sink - echo "" - echo " [4b-2] MARKER mode with Kafka sink:" - run_sql "DROP DATABASE IF EXISTS log_redaction_test;" - run_sql "CREATE DATABASE log_redaction_test;" - - KAFKA_TOPIC="log-redaction-marker-$RANDOM" - KAFKA_SINK_URI="kafka://127.0.0.1:9092/$KAFKA_TOPIC?protocol=open-protocol" - - run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY --redact-info-log marker --logsuffix "_marker_kafka" - - cdc_cli_changefeed create --sink-uri="$KAFKA_SINK_URI" --changefeed-id="kafka-marker-test" --config=$CUR/conf/changefeed.toml - - run_sql_file $CUR/data/test.sql ${UP_TIDB_HOST} ${UP_TIDB_PORT} - - echo " Waiting for Kafka sink to process events..." - wait_for_log_content "$WORK_DIR/cdc_marker_kafka.log" "send message to kafka" "Kafka message logs" 30 - - echo " [Validation] MARKER mode with Kafka sink:" - echo "" - - # Capture Kafka logs once for all validations - captured_logs=$(grep "send message to kafka" "$WORK_DIR/cdc_marker_kafka.log" 2>/dev/null || echo "") - log_raw_content "Kafka message logs (MARKER mode)" "$captured_logs" - - # STRICT POSITIVE VALIDATION: messageKey and messageValue must have markers - echo " [1/1] Verifying Kafka logs have ‹› markers:" - require_log_pattern "$WORK_DIR/cdc_marker_kafka.log" \ - "send message to kafka.*‹" \ - "Kafka message values wrapped with ‹› markers" \ - "MARKER mode should wrap Kafka message data with ‹› markers" - - captured_logs="" - cleanup_process $CDC_BINARY - - echo "[$(date)] ✓ Kafka sink: Redaction modes validated" - fi - # ========================================================================== # Test 5: API mode switching # ========================================================================== diff --git a/tests/integration_tests/run_light_it_in_ci.sh b/tests/integration_tests/run_light_it_in_ci.sh index b3f53dd968..032f99f87e 100755 --- a/tests/integration_tests/run_light_it_in_ci.sh +++ b/tests/integration_tests/run_light_it_in_ci.sh @@ -93,7 +93,7 @@ kafka_groups=( # G08 'capture_session_done_during_task fail_over_ddl_I table_route' # G09 - 'cdc_server_tips ddl_sequence log_redaction fail_over_ddl_J' + 'cdc_server_tips ddl_sequence fail_over_ddl_J' # G10 'changefeed_error batch_add_table fail_over_ddl_K split_table_check' # G11 From 58dc20063a454b379621b25b5a04f07d426338ce Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Fri, 31 Jul 2026 10:34:34 +0800 Subject: [PATCH 3/5] fix typo on the comment --- pkg/sink/codec/common/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/sink/codec/common/config.go b/pkg/sink/codec/common/config.go index ecba3412b1..415e864a05 100644 --- a/pkg/sink/codec/common/config.go +++ b/pkg/sink/codec/common/config.go @@ -45,7 +45,7 @@ type Config struct { // MaxBatchedBytes controls open-protocol encoder's maximum number of bytes for a batched message. MaxBatchedBytes int - // MaxBatchedBytes controls open-protocol encoder's maximum number of events for a batched message. + // MaxBatchedSize controls open-protocol encoder's maximum number of events for a batched message. MaxBatchSize int // DeleteOnlyHandleKeyColumns is true, for the delete event only output the handle key columns. From 8d3eb2cbf8ca3023e2b54a7349bfbefb946f148a Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Fri, 31 Jul 2026 11:10:52 +0800 Subject: [PATCH 4/5] also add aysnc error integration test --- pkg/sink/kafka/options.go | 3 --- .../kafka_big_messages/run.sh | 22 +++++++++++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/pkg/sink/kafka/options.go b/pkg/sink/kafka/options.go index 094f970d79..7864644aac 100644 --- a/pkg/sink/kafka/options.go +++ b/pkg/sink/kafka/options.go @@ -160,9 +160,6 @@ type options struct { Compression string ClientID string RequiredAcks RequiredAcks - // Only for test. User can not set this value. - // The current prod default value is 0. - MaxMessages int // Credential is used to connect to kafka cluster. EnableTLS bool diff --git a/tests/integration_tests/kafka_big_messages/run.sh b/tests/integration_tests/kafka_big_messages/run.sh index 7225decaaa..b9a4b646fb 100755 --- a/tests/integration_tests/kafka_big_messages/run.sh +++ b/tests/integration_tests/kafka_big_messages/run.sh @@ -129,10 +129,16 @@ function run_protocol_case() { local diff_config="$work_dir/diff_config.toml" local pd_addr="http://${UP_PD_HOST_1}:${UP_PD_PORT_1}" local sink_uri + local initial_topic_limit=$SMALL_TOPIC_LIMIT + local expected_error=ErrMessageTooLarge + if [ "$protocol_case" = "async_error" ]; then + initial_topic_limit=$LARGE_TOPIC_LIMIT + expected_error=ErrKafkaSendMessage + fi mkdir -p "$work_dir" render_diff_config "$work_dir" "$database_name" "$diff_config" - kafka_topic --topic "$topic_name" --max-message-bytes "$SMALL_TOPIC_LIMIT" + kafka_topic --topic "$topic_name" --max-message-bytes "$initial_topic_limit" local start_ts start_ts=$(run_cdc_cli_tso_query "$UP_PD_HOST_1" "$UP_PD_PORT_1") sink_uri=$(kafka_sink_uri "$topic_name" "$protocol" "$extra_params") @@ -145,13 +151,20 @@ function run_protocol_case() { start_kafka_consumer "$work_dir" "$sink_uri" "$schema_registry_uri" "$protocol_case" wait_changefeed_state "$pd_addr" "$changefeed_id" "normal" "null" + # Lower the topic limit after the producer has started. The encoder and + # producer still accept the message, then Kafka rejects it asynchronously. + if [ "$protocol_case" = "async_error" ]; then + local ready_database="${database_name}_ready" + run_sql "CREATE DATABASE ${ready_database}; CREATE TABLE ${ready_database}.ready(id INT PRIMARY KEY); INSERT INTO ${ready_database}.ready VALUES (1)" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + ensure "$TABLE_CHECK_RETRIES" "run_sql 'SELECT id FROM ${ready_database}.ready' '$DOWN_TIDB_HOST' '$DOWN_TIDB_PORT' && check_contains 'id: 1'" + kafka_topic --topic "$topic_name" --max-message-bytes "$SMALL_TOPIC_LIMIT" --alter + fi + "$GENERATOR_DIR/gen_kafka_big_messages" --row-bytes="$ROW_BYTES" --row-count=1 --database-name="$database_name" --table-name=test --sql-file-path="$sql_file" run_sql_file "$sql_file" "$UP_TIDB_HOST" "$UP_TIDB_PORT" run_sql "CREATE TABLE ${database_name}.finish_mark(id INT PRIMARY KEY)" "$UP_TIDB_HOST" "$UP_TIDB_PORT" - # The encoded row is larger than the topic limit, so the changefeed must - # enter the retryable warning state with ErrMessageTooLarge. - wait_changefeed_state "$pd_addr" "$changefeed_id" "warning" "ErrMessageTooLarge" + wait_changefeed_state "$pd_addr" "$changefeed_id" "warning" "$expected_error" # Only increase Kafka's topic limit. TiCDC must recreate the sink, read the # new limit, and resume without updating, pausing, or resuming the changefeed. @@ -173,6 +186,7 @@ function run() { local cases=( "canal_json|canal-json||enable-tidb-extension=true" "open_protocol|open-protocol||" + "async_error|open-protocol||max-retry=0" "simple_json|simple||" "simple_avro|simple||encoding-format=avro" "avro|avro|$SCHEMA_REGISTRY_URI|enable-tidb-extension=true&avro-enable-watermark=true&avro-decimal-handling-mode=string&avro-bigint-unsigned-handling-mode=string" From c3a10276b3c420add69e98239a11edfe809ec75d Mon Sep 17 00:00:00 2001 From: 3AceShowHand Date: Fri, 31 Jul 2026 11:39:20 +0800 Subject: [PATCH 5/5] adjust code --- pkg/sink/kafka/options.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/sink/kafka/options.go b/pkg/sink/kafka/options.go index 7864644aac..1e64238f9b 100644 --- a/pkg/sink/kafka/options.go +++ b/pkg/sink/kafka/options.go @@ -642,7 +642,7 @@ func adjustOptions( if exists { err = adjustExistingTopicOption(changefeedID, admin, options, info) } else { - adjustNewTopicOptions(admin, changefeedID, options) + adjustNewTopicOptions(changefeedID, admin, options) } if err != nil { return err @@ -674,8 +674,8 @@ func adjustExistingTopicOption( } func adjustNewTopicOptions( - admin ClusterAdminClient, changefeedID common.ChangeFeedID, + admin ClusterAdminClient, options *options, ) { // when create the topic, `max.message.bytes` is decided by the broker,