Skip to content

Commit b9c5da7

Browse files
committed
simplify code
1 parent aed789a commit b9c5da7

9 files changed

Lines changed: 257 additions & 61 deletions

File tree

‎cmd/consumer/conductor/conductor.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
// See the License for the specific language governing permissions and
1213
// limitations under the License.
1314

@@ -382,14 +383,13 @@ func (c *Conductor) queueDDL(ddlEvent *event.DDLEvent) {
382383
c.queuedDDLs[key] = struct{}{}
383384

384385
ts := ddlEvent.GetCommitTs()
385-
if len(c.pendingDDL) == 0 || ts >= c.pendingDDL[len(c.pendingDDL)-1].GetCommitTs() {
386-
c.pendingDDL = append(c.pendingDDL, ddlEvent)
387-
} else {
388-
index := sort.Search(len(c.pendingDDL), func(i int) bool {
386+
index := len(c.pendingDDL)
387+
if index != 0 && ts < c.pendingDDL[index-1].GetCommitTs() {
388+
index = sort.Search(index, func(i int) bool {
389389
return c.pendingDDL[i].GetCommitTs() > ts
390390
})
391-
c.pendingDDL = slices.Insert(c.pendingDDL, index, ddlEvent)
392391
}
392+
c.pendingDDL = slices.Insert(c.pendingDDL, index, ddlEvent)
393393

394394
// Rows already buffered above the DDL commit timestamp wait for it.
395395
var blocked []*tableQueue

‎cmd/consumer/decode/decode_test.go‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,19 @@ import (
4343
"github.com/stretchr/testify/require"
4444
)
4545

46+
func waitReady(t *testing.T, f *Future, runDone chan error) {
47+
t.Helper()
48+
select {
49+
case <-f.done:
50+
case err := <-runDone:
51+
runDone <- err
52+
require.NoError(t, err, "decoder group exited before future became ready")
53+
t.Fatal("decoder group exited before future became ready")
54+
case <-t.Context().Done():
55+
require.NoError(t, context.Cause(t.Context()))
56+
}
57+
}
58+
4659
func TestDecodeStorageCanalJSONSharesAlignedTableInfo(t *testing.T) {
4760
cfg := common.NewConfig(config.ProtocolCanalJSON)
4861
cfg.EnableTiDBExtension = true
@@ -204,7 +217,7 @@ func TestDecodeGroupConcurrentPoolPreservesOrderAndDynamicPartitions(t *testing.
204217

205218
for i, part := range partitions {
206219
f := <-group.Output()
207-
require.NoError(t, f.Ready(t.Context()))
220+
waitReady(t, f, runDone)
208221
require.Equal(t, part, f.Payload.Partition)
209222
require.Len(t, f.Events, 1)
210223
dml := f.Events[0].(*event.DMLEvent)
@@ -256,7 +269,7 @@ func TestDecodeGroupConcurrentPoolPreservesOrderAndDynamicPartitions(t *testing.
256269

257270
for i := range 4 {
258271
f := <-storageGroup.Output()
259-
require.NoError(t, f.Ready(t.Context()))
272+
waitReady(t, f, storageDone)
260273
dml := f.Events[0].(*event.DMLEvent)
261274
dml.PostFlush()
262275
require.Equal(t, uint64(200+i), dml.CommitTs)
@@ -350,7 +363,7 @@ func TestDecodeGroupDebeziumAvroSharesSchemaManagerAndCloses(t *testing.T) {
350363

351364
for range payloads {
352365
f := <-group.Output()
353-
require.NoError(t, f.Ready(t.Context()))
366+
waitReady(t, f, runDone)
354367
require.Len(t, f.Events, 1)
355368
resolved := f.Events[0].(*event.ResolvedEvent)
356369
require.Equal(t, uint64(12345), resolved.ResolvedTs)
@@ -454,16 +467,16 @@ func TestDecodeGroupSimpleCrossPartitionWakeupOutOfOrderAndOver128(t *testing.T)
454467
t2Pending := make(map[uint64]int64, t2Count)
455468
for range t1Count + t2Count {
456469
f := <-group.Output()
457-
require.NoError(t, f.Ready(t.Context()))
470+
waitReady(t, f, runDone)
458471
require.Empty(t, f.Events)
459472
require.Len(t, f.Pending, 1)
460473
if f.Payload.Partition == 0 {
461474
require.Equal(t, uint64(200), f.Pending[0].CommitTs)
462475
t1Pending[f.Pending[0].ID] = f.Payload.Offset
463-
} else {
464-
require.Equal(t, uint64(210), f.Pending[0].CommitTs)
465-
t2Pending[f.Pending[0].ID] = f.Payload.Offset
476+
continue
466477
}
478+
require.Equal(t, uint64(210), f.Pending[0].CommitTs)
479+
t2Pending[f.Pending[0].ID] = f.Payload.Offset
467480
}
468481
require.NoError(t, <-addErr)
469482

@@ -474,7 +487,7 @@ func TestDecodeGroupSimpleCrossPartitionWakeupOutOfOrderAndOver128(t *testing.T)
474487
}))
475488

476489
fBoot2 := <-group.Output()
477-
require.NoError(t, fBoot2.Ready(t.Context()))
490+
waitReady(t, fBoot2, runDone)
478491
require.Empty(t, fBoot2.Events)
479492
require.Len(t, fBoot2.Resolved, t2Count)
480493
for _, r := range fBoot2.Resolved {
@@ -488,7 +501,7 @@ func TestDecodeGroupSimpleCrossPartitionWakeupOutOfOrderAndOver128(t *testing.T)
488501
require.Empty(t, t2Pending)
489502

490503
fBoot1 := <-group.Output()
491-
require.NoError(t, fBoot1.Ready(t.Context()))
504+
waitReady(t, fBoot1, runDone)
492505
require.Empty(t, fBoot1.Events)
493506
require.Len(t, fBoot1.Resolved, t1Count)
494507
for _, r := range fBoot1.Resolved {
@@ -578,11 +591,11 @@ func TestDecodeGroupSimpleDDLWakesPreAndPostSchemaWaiters(t *testing.T) {
578591
}))
579592

580593
fPre := <-group.Output()
581-
require.NoError(t, fPre.Ready(t.Context()))
594+
waitReady(t, fPre, runDone)
582595
require.Len(t, fPre.Pending, 1)
583596

584597
fPost := <-group.Output()
585-
require.NoError(t, fPost.Ready(t.Context()))
598+
waitReady(t, fPost, runDone)
586599
require.Len(t, fPost.Pending, 1)
587600

588601
require.NoError(t, group.Add(t.Context(), []*source.Payload{
@@ -591,7 +604,7 @@ func TestDecodeGroupSimpleDDLWakesPreAndPostSchemaWaiters(t *testing.T) {
591604

592605
// First ALTER arrival wakes both PreTableSchema and post-DDL waiters and forwards the DDL.
593606
fAlter := <-group.Output()
594-
require.NoError(t, fAlter.Ready(t.Context()))
607+
waitReady(t, fAlter, runDone)
595608
require.Zero(t, fAlter.Marker)
596609
require.Len(t, fAlter.Events, 1)
597610
forwardedDDL := fAlter.Events[0].(*event.DDLEvent)
@@ -618,7 +631,7 @@ func TestDecodeGroupSimpleDDLWakesPreAndPostSchemaWaiters(t *testing.T) {
618631
{Partition: 3, Offset: 40, Value: alterMsg.Value},
619632
}))
620633
fDup := <-group.Output()
621-
require.NoError(t, fDup.Ready(t.Context()))
634+
waitReady(t, fDup, runDone)
622635
require.Empty(t, fDup.Events)
623636
require.Equal(t, uint64(200), fDup.Marker)
624637
require.Empty(t, fDup.Resolved)

‎cmd/consumer/source/kafka.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
// See the License for the specific language governing permissions and
1213
// limitations under the License.
1314

@@ -18,6 +19,7 @@ import (
1819
"context"
1920
"crypto/tls"
2021
"crypto/x509"
22+
"math"
2123
"os"
2224
"strings"
2325
"time"
@@ -57,6 +59,7 @@ func newKafkaReader(ctx context.Context, opts Options) *kafkaReader {
5759
log.Panic("kafka event routing configuration is invalid", zap.Error(err))
5860
}
5961

62+
brokerMaxReadBytes := int32(min(max(int64(32<<20), int64(codecConfig.MaxMessageBytes)+(4<<20)), math.MaxInt32))
6063
kafkaOptions := []kgo.Opt{
6164
kgo.SeedBrokers(strings.Split(upstreamURI.Host, ",")...),
6265
kgo.ConsumerGroup(opts.ConsumerID),
@@ -67,7 +70,7 @@ func newKafkaReader(ctx context.Context, opts Options) *kafkaReader {
6770
kgo.FetchMaxBytes(4 << 20),
6871
kgo.FetchMaxPartitionBytes(1 << 20),
6972
kgo.FetchMaxWait(100 * time.Millisecond),
70-
kgo.BrokerMaxReadBytes(32 << 20),
73+
kgo.BrokerMaxReadBytes(brokerMaxReadBytes),
7174
}
7275

7376
query := upstreamURI.Query()

‎cmd/consumer/source/pulsar.go‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
// See the License for the specific language governing permissions and
1213
// limitations under the License.
1314

@@ -184,21 +185,21 @@ func (c *pulsarReader) Partitions() int32 {
184185
}
185186

186187
func (c *pulsarReader) Read(ctx context.Context) ([]*Payload, error) {
187-
var message pulsar.ConsumerMessage
188-
189-
select {
190-
case <-ctx.Done():
191-
return nil, context.Cause(ctx)
192-
case message = <-c.consumer.Chan():
188+
msg, err := c.consumer.Receive(ctx)
189+
if err != nil {
190+
if ctx.Err() != nil {
191+
return nil, context.Cause(ctx)
192+
}
193+
return nil, err
193194
}
194195

195196
batch := make([]*Payload, 1, min(len(c.consumer.Chan())+1, readBatchRows))
196-
batch[0] = c.toPayload(message)
197+
batch[0] = c.toPayload(msg)
197198

198199
for len(batch) < readBatchRows {
199200
select {
200-
case message = <-c.consumer.Chan():
201-
batch = append(batch, c.toPayload(message))
201+
case cm := <-c.consumer.Chan():
202+
batch = append(batch, c.toPayload(cm.Message))
202203
default:
203204
return batch, nil
204205
}
@@ -207,7 +208,7 @@ func (c *pulsarReader) Read(ctx context.Context) ([]*Payload, error) {
207208
return batch, nil
208209
}
209210

210-
func (c *pulsarReader) toPayload(message pulsar.ConsumerMessage) *Payload {
211+
func (c *pulsarReader) toPayload(message pulsar.Message) *Payload {
211212
id := message.ID()
212213
key := []byte(message.Key())
213214
value := message.Payload()

‎cmd/consumer/source/storage.go‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import (
4242
"github.com/pingcap/ticdc/pkg/config"
4343
"github.com/pingcap/ticdc/pkg/errors"
4444
"github.com/pingcap/ticdc/pkg/util"
45+
"github.com/pingcap/tidb/pkg/objstore"
4546
"github.com/pingcap/tidb/pkg/objstore/storeapi"
4647
"go.uber.org/zap"
4748
)
@@ -168,13 +169,14 @@ func (c *storageReader) scanFiles(ctx context.Context) (map[cloudstorage.DMLPath
168169

169170
files := make(map[cloudstorage.DMLPathKey]map[cloudstorage.FileIndexKey]storageIndexRange)
170171

171-
var err error
172172
if c.localPath != "" || c.s3Client != nil {
173-
err = c.discoverDir(ctx, "", 0, files)
174-
} else {
175-
err = c.walkStorage(ctx, files)
173+
if err := c.discoverDir(ctx, "", 0, files); err != nil {
174+
return nil, err
175+
}
176+
return files, nil
176177
}
177-
if err != nil {
178+
179+
if err := c.walkStorage(ctx, files); err != nil {
178180
return nil, err
179181
}
180182

@@ -351,9 +353,9 @@ func (c *storageReader) listEntries(ctx context.Context, dir string) ([]string,
351353
for _, entry := range entries {
352354
if entry.IsDir() {
353355
dirs = append(dirs, entry.Name())
354-
} else {
355-
files = append(files, entry.Name())
356+
continue
356357
}
358+
files = append(files, entry.Name())
357359
}
358360

359361
slices.Sort(dirs)
@@ -682,14 +684,23 @@ func (c *storageReader) Close() {
682684
}
683685

684686
func newS3Client(ctx context.Context, uri *url.URL) *s3.Client {
685-
values := uri.Query()
686-
region := cmp.Or(values.Get("s3.region"), values.Get("region"))
687+
backend, err := objstore.ParseBackend(uri.String(), nil)
688+
if err != nil {
689+
log.Panic("storage client initialization failed", zap.String("uri", util.MaskSensitiveDataInURIForError(uri.String())))
690+
}
691+
692+
s3Backend := backend.GetS3()
693+
if s3Backend == nil {
694+
log.Panic("storage client initialization failed", zap.String("uri", util.MaskSensitiveDataInURIForError(uri.String())))
695+
}
696+
697+
region := s3Backend.GetRegion()
687698
cfgOpts := []func(*awsconfig.LoadOptions) error{
688699
awsconfig.WithRegion(cmp.Or(region, defaultS3Region)),
689700
}
690-
accessKey := values.Get("access-key")
691-
secretKey := values.Get("secret-access-key")
692-
sessionToken := values.Get("session-token")
701+
accessKey := s3Backend.GetAccessKey()
702+
secretKey := s3Backend.GetSecretAccessKey()
703+
sessionToken := s3Backend.GetSessionToken()
693704
if cmp.Or(accessKey, secretKey, sessionToken) != "" {
694705
cfgOpts = append(cfgOpts, awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
695706
accessKey,
@@ -704,25 +715,30 @@ func newS3Client(ctx context.Context, uri *url.URL) *s3.Client {
704715
}
705716

706717
var options []func(*s3.Options)
707-
endpoint := cmp.Or(values.Get("s3.endpoint"), values.Get("endpoint"))
718+
endpoint := s3Backend.GetEndpoint()
708719
if endpoint != "" {
709720
options = append(options, func(o *s3.Options) {
710721
o.BaseEndpoint = aws.String(endpoint)
722+
})
723+
}
724+
if endpoint != "" || s3Backend.GetForcePathStyle() {
725+
options = append(options, func(o *s3.Options) {
711726
o.UsePathStyle = true
712727
})
713728
}
714729

715730
client := s3.NewFromConfig(cfg, options...)
716731

717732
// Only an AWS bucket served without an endpoint needs region detection.
718-
provider := cmp.Or(values.Get("s3.provider"), values.Get("provider"))
733+
provider := s3Backend.GetProvider()
719734
if region != "" || endpoint != "" || (provider != "" && !strings.EqualFold(provider, "aws")) {
720735
return client
721736
}
722737

723-
detected, err := manager.GetBucketRegion(ctx, client, uri.Host)
738+
bucket := cmp.Or(s3Backend.GetBucket(), uri.Host)
739+
detected, err := manager.GetBucketRegion(ctx, client, bucket)
724740
if err != nil {
725-
log.Panic("detect Storage bucket region failed", zap.String("bucket", uri.Host), zap.Error(err))
741+
log.Panic("detect storage bucket region failed", zap.String("bucket", bucket), zap.Error(err))
726742
}
727743

728744
if detected == "" || detected == cfg.Region {

‎cmd/consumer/writer/writer.go‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
// See the License for the specific language governing permissions and
1213
// limitations under the License.
1314

@@ -180,9 +181,10 @@ func mergeDMLEvent(dst, src *event.DMLEvent) {
180181
dstRowTypeCount := len(dst.RowTypes)
181182
srcRowTypeCount := len(src.RowTypes)
182183
if src.Rows != nil && src.Rows.NumRows() > 0 {
183-
if dst.Rows == nil {
184+
switch dst.Rows {
185+
case nil:
184186
dst.Rows = src.Rows
185-
} else {
187+
default:
186188
dst.Rows.Append(src.Rows, 0, src.Rows.NumRows())
187189
}
188190
}
@@ -200,9 +202,10 @@ func appendOptionalDMLValues[T any](dst, src []T, dstCount, srcCount int) []T {
200202
if len(dst) == 0 && len(src) == 0 {
201203
return nil
202204
}
203-
if len(dst) == 0 && len(src) != 0 {
205+
if len(dst) == 0 {
204206
dst = make([]T, dstCount)
205-
} else if len(dst) != 0 && len(src) == 0 {
207+
}
208+
if len(src) == 0 {
206209
src = make([]T, srcCount)
207210
}
208211
return append(dst, src...)
@@ -462,9 +465,9 @@ func (w *Writer) filterRows(dml *event.DMLEvent) *event.DMLEvent {
462465
rowType: row.RowType,
463466
handle: string(handle),
464467
}
465-
if _, exists := w.mutations[key]; exists {
466-
retain = false
467-
} else {
468+
_, exists := w.mutations[key]
469+
retain = !exists
470+
if retain {
468471
if w.mutations == nil {
469472
w.mutations = make(map[mutationKey]bool)
470473
}

0 commit comments

Comments
 (0)