// Copyright 2025 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 cloudstorage import ( "context" "path" "strconv" "time" "github.com/pingcap/log" "github.com/pingcap/ticdc/downstreamadapter/sink/statistics" "github.com/pingcap/ticdc/pkg/cloudstorage" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/sink/spool" "github.com/pingcap/ticdc/pkg/writelease" "github.com/pingcap/tidb/pkg/objstore/storeapi" "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" "golang.org/x/sync/errgroup" ) type writer struct { shardID int changeFeedID common.ChangeFeedID storage storeapi.Storage config *cloudstorage.Config spool *spool.Spool bufferManager *bufferManager // flushCh is owned by writer. bufferManager emits flush work only through // writer methods. Both writer and bufferManager stop on the shared ctx, so // the channel does not need to be closed explicitly. flushCh chan flushTask statistics *statistics.Statistics filePathGenerator *cloudstorage.FilePathGenerator metricFlushBytes prometheus.Observer metricFlushDuration prometheus.Observer writeGate *writelease.Gate } func (d *writer) setWriteGate(gate *writelease.Gate) { d.writeGate = gate d.filePathGenerator.SetWriteGate(gate) } // flushTask is internal and never crosses component boundary. // marker task and data batch are mutually exclusive in normal flow. type flushTask struct { batch tableBatches marker *flushMarker } type payload struct { tableInfo *common.TableInfo data []byte rowsCount int nBytes int64 entries []*spool.Entry postFlushCallbacks []func() } func newWriter( id int, changefeedID common.ChangeFeedID, storage storeapi.Storage, config *cloudstorage.Config, extension string, stats *statistics.Statistics, spoolBuffer *spool.Spool, ) *writer { var ( keyspace = changefeedID.Keyspace() changefeed = changefeedID.Name() ) d := &writer{ shardID: id, changeFeedID: changefeedID, storage: storage, config: config, spool: spoolBuffer, flushCh: make(chan flushTask, 64), statistics: stats, filePathGenerator: cloudstorage.NewFilePathGenerator(changefeedID, config, storage, extension), metricFlushBytes: cloudStorageFlushBytesHist.WithLabelValues(keyspace, changefeed), metricFlushDuration: cloudStorageFlushDurationHistogram.WithLabelValues(keyspace, changefeed), } d.bufferManager = newBufferManager(d.changeFeedID, d.config, d.spool, d.enqueueFlushTask) return d } func (d *writer) run(ctx context.Context) error { g, ctx := errgroup.WithContext(ctx) g.Go(func() error { return d.flushMessages(ctx) }) g.Go(func() error { return d.bufferManager.run(ctx) }) return g.Wait() } func (d *writer) flushMessages(ctx context.Context) error { var flushTimeSlice time.Duration keyspace := d.changeFeedID.Keyspace() changefeed := d.changeFeedID.Name() overseerTicker := time.NewTicker(d.config.FlushInterval * 2) writerLabel := strconv.Itoa(d.shardID) metricBusyRatio := cloudStorageWorkerBusyRatio.WithLabelValues(keyspace, changefeed, writerLabel) defer func() { overseerTicker.Stop() cloudStorageWorkerBusyRatio.DeleteLabelValues(keyspace, changefeed, writerLabel) }() for { select { case <-ctx.Done(): return errors.Trace(context.Cause(ctx)) case <-overseerTicker.C: metricBusyRatio.Add(flushTimeSlice.Seconds()) flushTimeSlice = 0 case task := <-d.flushCh: if task.marker != nil { // Flush marker ack point: // marker is emitted only after the pending batch of the same dispatcher // is emitted by bufferManager. task.marker.finish() continue } if task.batch.isEmpty() { continue } start := time.Now() for table, tableTask := range task.batch.tables { if tableTask == nil || len(tableTask.entries) == 0 { continue } tableVersion, err := d.filePathGenerator.CheckOrWriteSchema(ctx, table, tableTask.tableInfo) if err != nil { log.Error("failed to write schema file to external storage", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.Int("shardID", d.shardID), zap.Error(err)) return err } table.TableInfoVersion = tableVersion date := d.filePathGenerator.GenerateDateStr() dataFilePath, err := d.filePathGenerator.GenerateDataFilePath(ctx, table, date) if err != nil { log.Error("failed to generate data file path", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.Int("shardID", d.shardID), zap.Error(err)) return err } indexFilePath := d.filePathGenerator.GenerateIndexFilePath(table, date) payload, err := buildPayload(d.spool, tableTask) if err != nil { return err } if err := d.writeDataFile(ctx, dataFilePath, indexFilePath, payload); err != nil { log.Error("failed to write data file to external storage", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.String("path", dataFilePath), zap.Int("shardID", d.shardID), zap.Error(err)) return err } tableTask.entries = nil } flushDuration := time.Since(start) flushTimeSlice += flushDuration } } } func (d *writer) writeDataFile(ctx context.Context, dataFilePath, indexFilePath string, payload *payload) error { keyspace := d.changeFeedID.Keyspace() changefeed := d.changeFeedID.Name() if err := writelease.WaitForWrite(ctx, d.writeGate); err != nil { return err } start := time.Now() if err := d.writeFile(ctx, dataFilePath, payload.data); err != nil { d.statistics.RecordDMLError() return err } if err := writelease.WaitForWrite(ctx, d.writeGate); err != nil { return err } if err := d.storage.WriteFile(ctx, indexFilePath, []byte(path.Base(dataFilePath)+"\n")); err != nil { log.Error("failed to write index file to external storage", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.String("path", indexFilePath), zap.Int("shardID", d.shardID), zap.Error(err)) d.statistics.RecordDMLError() return err } d.statistics.RecordDMLBatch(payload.rowsCount, payload.nBytes) d.metricFlushDuration.Observe(time.Since(start).Seconds()) d.metricFlushBytes.Observe(float64(payload.nBytes)) for _, postFlushCallback := range payload.postFlushCallbacks { if postFlushCallback != nil { postFlushCallback() } } for _, entry := range payload.entries { d.spool.Release(entry) } // Help GC release the potentially large encoded payload buffer before returning. payload.data = nil return nil } func (d *writer) writeFile(ctx context.Context, filePath string, data []byte) error { if d.config.FlushConcurrency <= 1 { return d.storage.WriteFile(ctx, filePath, data) } writer, err := d.storage.Create(ctx, filePath, &storeapi.WriterOption{ Concurrency: d.config.FlushConcurrency, }) if err != nil { return err } keyspace := d.changeFeedID.Keyspace() changefeed := d.changeFeedID.Name() if _, err = writer.Write(ctx, data); err != nil { if closeErr := writer.Close(ctx); closeErr != nil { log.Warn("failed to close writer after write failure", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.String("path", filePath), zap.Error(closeErr)) } return err } if err = writer.Close(ctx); err != nil { log.Error("failed to close concurrency writer", zap.String("keyspace", keyspace), zap.String("changefeed", changefeed), zap.String("path", filePath), zap.Error(err)) return err } return nil } func (d *writer) enqueueTask(ctx context.Context, t *task) error { return d.bufferManager.enqueueTask(ctx, t) } func (d *writer) enqueueFlushTask(ctx context.Context, task flushTask) error { select { case <-ctx.Done(): return errors.Trace(context.Cause(ctx)) case d.flushCh <- task: return nil } }