Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions api/middleware/changefeed_operation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package middleware

import (
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"

"github.com/gin-gonic/gin"
"github.com/pingcap/log"
"github.com/pingcap/ticdc/pkg/api"
"github.com/pingcap/ticdc/pkg/metrics"
"go.uber.org/zap"
)

const (
changefeedOperationContextKey = "changefeed-operation-info"
changefeedOperationHistoryLimit = 100
changefeedOperationMetricTextLimit = 256
)

var (
recentChangefeedOperations = newRecentChangefeedOperationStore(changefeedOperationHistoryLimit)
changefeedOperationEventID uint64
)

type changefeedOperationInfo struct {
keyspace string
changefeed string
details string
}

type changefeedOperationMetricLabels struct {
keyspace string
changefeed string
operation string
result string
username string
details string
err string
eventID string
}

func (l changefeedOperationMetricLabels) labelValues() []string {
return []string{
l.keyspace,
l.changefeed,
l.operation,
l.result,
l.username,
l.details,
l.err,
l.eventID,
}
}

type recentChangefeedOperationStore struct {
mu sync.Mutex
limit int
events []changefeedOperationMetricLabels
}

func newRecentChangefeedOperationStore(limit int) *recentChangefeedOperationStore {
return &recentChangefeedOperationStore{limit: limit}
}

func (s *recentChangefeedOperationStore) record(
labels changefeedOperationMetricLabels,
operationTime time.Time,
) {
s.mu.Lock()
defer s.mu.Unlock()

// The dashboard only needs a recent investigation window. Keep this cache
// bounded so user names and detail strings do not become unbounded metric
// cardinality over long-running clusters.
metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...).Set(float64(operationTime.UnixMilli()))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Prometheus best practices generally recommend using seconds for timestamps in gauges. While the dashboard is configured for dateTimeAsIso, Grafana usually expects the value to be in seconds for this unit. Using milliseconds might result in incorrect date displays in some Grafana versions or configurations unless explicitly handled.

Suggested change
metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...).Set(float64(operationTime.UnixMilli()))
metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...).Set(float64(operationTime.Unix()))

s.events = append(s.events, labels)
if len(s.events) <= s.limit {
return
}

oldest := s.events[0]
s.events = s.events[1:]
metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(oldest.labelValues()...)
}

// ChangefeedOperationMiddleware records user initiated changefeed mutations for
// logs and the bounded recent-operation Grafana panel.
func ChangefeedOperationMiddleware(operation string) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()

statusCode := c.Writer.Status()
lastError := c.Errors.Last()
result := "success"
if statusCode >= http.StatusBadRequest || lastError != nil {
result = "failed"
}

info := getChangefeedOperationInfo(c)
if info.keyspace == "" {
info.keyspace = c.Query(api.APIOpVarKeyspace)
}
if info.changefeed == "" {
info.changefeed = c.Param(api.APIOpVarChangefeedID)
}

username, _, _ := c.Request.BasicAuth()
if username == "" {
username = "anonymous"
}

var operationErr error
if lastError != nil {
operationErr = lastError.Err
}

operationTime := time.Now()
eventID := atomic.AddUint64(&changefeedOperationEventID, 1)
labels := changefeedOperationMetricLabels{
keyspace: normalizeChangefeedOperationMetricText(info.keyspace),
changefeed: normalizeChangefeedOperationMetricText(info.changefeed),
operation: operation,
result: result,
username: normalizeChangefeedOperationMetricText(username),
details: normalizeChangefeedOperationMetricText(info.details),
err: normalizeChangefeedOperationMetricError(operationErr),
eventID: fmt.Sprintf("%d", eventID),
}
recentChangefeedOperations.record(labels, operationTime)

log.Info("changefeed operation",
zap.String("operation", operation),
zap.String("result", result),
zap.String("keyspace", info.keyspace),
zap.String("changefeedID", info.changefeed),
zap.String("details", info.details),
zap.Int("status", statusCode),
zap.String("username", username),
zap.String("ip", c.ClientIP()),
zap.String("userAgent", c.Request.UserAgent()),
zap.String("clientVersion", c.Request.Header.Get(ClientVersionHeader)),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The constant ClientVersionHeader is used but not defined in this file or imported. If it is defined in pkg/api, it should be referenced as api.ClientVersionHeader.

Suggested change
zap.String("clientVersion", c.Request.Header.Get(ClientVersionHeader)),
zap.String("clientVersion", c.Request.Header.Get(api.ClientVersionHeader)),

zap.Duration("duration", time.Since(start)),
zap.Error(operationErr),
)
}
}

// SetChangefeedOperationTarget attaches the logical changefeed identity that the
// current mutation request targets.
func SetChangefeedOperationTarget(c *gin.Context, keyspace, changefeed string) {
info := getChangefeedOperationInfo(c)
info.keyspace = keyspace
info.changefeed = changefeed
c.Set(changefeedOperationContextKey, info)
}

// SetChangefeedOperationDetails attaches a concise, non-sensitive summary for
// the current mutation request.
func SetChangefeedOperationDetails(c *gin.Context, details string) {
info := getChangefeedOperationInfo(c)
info.details = details
c.Set(changefeedOperationContextKey, info)
}

func getChangefeedOperationInfo(c *gin.Context) changefeedOperationInfo {
raw, ok := c.Get(changefeedOperationContextKey)
if !ok {
return changefeedOperationInfo{}
}
info, ok := raw.(changefeedOperationInfo)
if !ok {
return changefeedOperationInfo{}
}
return info
}

func normalizeChangefeedOperationMetricError(err error) string {
if err == nil {
return ""
}
return normalizeChangefeedOperationMetricText(err.Error())
}

func normalizeChangefeedOperationMetricText(value string) string {
value = strings.Join(strings.Fields(value), " ")
if utf8.RuneCountInString(value) <= changefeedOperationMetricTextLimit {
return value
}

runes := []rune(value)
return string(runes[:changefeedOperationMetricTextLimit-3]) + "..."
}
139 changes: 139 additions & 0 deletions api/middleware/changefeed_operation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package middleware

import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/gin-gonic/gin"
"github.com/pingcap/ticdc/pkg/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/require"
)

// TestChangefeedOperationMiddlewareRecordsSuccessfulMutation verifies that a
// successful request keeps the logical target, normalized detail summary, and
// authenticated user for the dashboard history row.
func TestChangefeedOperationMiddlewareRecordsSuccessfulMutation(t *testing.T) {
resetRecentChangefeedOperationStateForTest(t)

router := gin.New()
router.POST("/api/v2/changefeeds/:changefeed_id/resume",
ChangefeedOperationMiddleware("resume"),
func(c *gin.Context) {
SetChangefeedOperationTarget(c, "ks1", "test")
SetChangefeedOperationDetails(c, "overwrite_checkpoint_ts=true\nnew_checkpoint_ts=123")
c.Status(http.StatusOK)
},
)

recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v2/changefeeds/test/resume?keyspace=ks1", nil)
req.SetBasicAuth("alice", "secret")
router.ServeHTTP(recorder, req)

require.Len(t, recentChangefeedOperations.events, 1)
require.Equal(t, changefeedOperationMetricLabels{
keyspace: "ks1",
changefeed: "test",
operation: "resume",
result: "success",
username: "alice",
details: "overwrite_checkpoint_ts=true new_checkpoint_ts=123",
err: "",
eventID: "1",
}, recentChangefeedOperations.events[0])
}

// TestChangefeedOperationMiddlewareRecordsFailedMutation verifies that a failed
// request is still retained with its normalized error summary so oncall can see
// rejected user attempts as well as successful changes.
func TestChangefeedOperationMiddlewareRecordsFailedMutation(t *testing.T) {
resetRecentChangefeedOperationStateForTest(t)

router := gin.New()
router.PUT("/api/v2/changefeeds/:changefeed_id",
ChangefeedOperationMiddleware("update"),
func(c *gin.Context) {
_ = c.Error(errors.New("update rejected\nbecause state is normal"))
c.Status(http.StatusBadRequest)
},
)

recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/api/v2/changefeeds/test?keyspace=ks1", nil)
router.ServeHTTP(recorder, req)

require.Len(t, recentChangefeedOperations.events, 1)
require.Equal(t, "failed", recentChangefeedOperations.events[0].result)
require.Equal(t, "anonymous", recentChangefeedOperations.events[0].username)
require.Equal(t, "update rejected because state is normal", recentChangefeedOperations.events[0].err)
}

// TestRecentChangefeedOperationStoreEvictsOldestMetric verifies that the recent
// operation cache preserves only the newest bounded rows and removes the evicted
// metric series to avoid unbounded label cardinality.
func TestRecentChangefeedOperationStoreEvictsOldestMetric(t *testing.T) {
resetRecentChangefeedOperationStateForTest(t)
store := newRecentChangefeedOperationStore(2)
now := time.UnixMilli(1_700_000_000_000)

first := changefeedOperationMetricLabels{eventID: "1"}
second := changefeedOperationMetricLabels{eventID: "2"}
third := changefeedOperationMetricLabels{eventID: "3"}
t.Cleanup(func() {
for _, labels := range []changefeedOperationMetricLabels{first, second, third} {
metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(labels.labelValues()...)
}
})
store.record(first, now)
store.record(second, now.Add(time.Millisecond))
store.record(third, now.Add(2*time.Millisecond))

require.Equal(t, []changefeedOperationMetricLabels{second, third}, store.events)
require.Equal(t, float64(0), testutil.ToFloat64(metricsGaugeForTest(first)))
require.Equal(t, float64(now.Add(time.Millisecond).UnixMilli()), testutil.ToFloat64(metricsGaugeForTest(second)))
require.Equal(t, float64(now.Add(2*time.Millisecond).UnixMilli()), testutil.ToFloat64(metricsGaugeForTest(third)))
}

// TestNormalizeChangefeedOperationMetricText verifies that dashboard labels are
// kept single-line and bounded so a malformed request cannot create oversized
// operation-history fields.
func TestNormalizeChangefeedOperationMetricText(t *testing.T) {
longText := strings.Repeat("a", changefeedOperationMetricTextLimit+10)
require.Equal(t, "a b", normalizeChangefeedOperationMetricText("a\n b"))
require.Equal(t, changefeedOperationMetricTextLimit, len(normalizeChangefeedOperationMetricText(longText)))
require.True(t, strings.HasSuffix(normalizeChangefeedOperationMetricText(longText), "..."))
}

func resetRecentChangefeedOperationStateForTest(t *testing.T) {
t.Helper()
for _, labels := range recentChangefeedOperations.events {
metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(labels.labelValues()...)
}
recentChangefeedOperations = newRecentChangefeedOperationStore(changefeedOperationHistoryLimit)
atomic.StoreUint64(&changefeedOperationEventID, 0)
}

func metricsGaugeForTest(labels changefeedOperationMetricLabels) prometheus.Gauge {
return metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...)
}
10 changes: 5 additions & 5 deletions api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ func RegisterOpenAPIV1Routes(router *gin.Engine, api OpenAPIV1) {
changefeedGroup.GET("/:changefeed_id", coordinatorMiddleware, setV1Header, api.v2.GetChangeFeed)

// These two APIs need to be adjusted to be compatible with the API v1.
changefeedGroup.POST("", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.createChangefeed)
changefeedGroup.PUT("/:changefeed_id", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.updateChangefeed)
changefeedGroup.POST("", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("create"), authenticateMiddleware, setV1Header, api.createChangefeed)
changefeedGroup.PUT("/:changefeed_id", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("update"), authenticateMiddleware, setV1Header, api.updateChangefeed)

changefeedGroup.POST("/:changefeed_id/pause", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.v2.PauseChangefeed)
changefeedGroup.POST("/:changefeed_id/resume", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.v2.ResumeChangefeed)
changefeedGroup.DELETE("/:changefeed_id", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.v2.DeleteChangefeed)
changefeedGroup.POST("/:changefeed_id/pause", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("pause"), authenticateMiddleware, setV1Header, api.v2.PauseChangefeed)
changefeedGroup.POST("/:changefeed_id/resume", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("resume"), authenticateMiddleware, setV1Header, api.v2.ResumeChangefeed)
changefeedGroup.DELETE("/:changefeed_id", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("delete"), authenticateMiddleware, setV1Header, api.v2.DeleteChangefeed)

// These two APIs are not useful in new arch cdc, we implement them for compatibility with old arch cdc only.
changefeedGroup.POST("/:changefeed_id/tables/rebalance_table", coordinatorMiddleware, authenticateMiddleware, setV1Header, api.rebalanceTables)
Expand Down
10 changes: 5 additions & 5 deletions api/v2/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ func RegisterOpenAPIV2Routes(router *gin.Engine, api OpenAPIV2) {
// The authenticateMiddleware will retire the KeyspaceMeta from the context,
// which is set by the keyspaceCheckerMiddleware.
// Therefore, the The authenticateMiddleware must be called after the keyspaceCheckerMiddleware.
changefeedGroup.POST("", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.CreateChangefeed)
changefeedGroup.POST("", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("create"), keyspaceCheckerMiddleware, authenticateMiddleware, api.CreateChangefeed)
changefeedGroup.GET("", coordinatorMiddleware, keyspaceCheckerMiddleware, api.ListChangeFeeds)
changefeedGroup.PUT("/:changefeed_id", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.UpdateChangefeed)
changefeedGroup.POST("/:changefeed_id/resume", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.ResumeChangefeed)
changefeedGroup.POST("/:changefeed_id/pause", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.PauseChangefeed)
changefeedGroup.DELETE("/:changefeed_id", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.DeleteChangefeed)
changefeedGroup.PUT("/:changefeed_id", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("update"), keyspaceCheckerMiddleware, authenticateMiddleware, api.UpdateChangefeed)
changefeedGroup.POST("/:changefeed_id/resume", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("resume"), keyspaceCheckerMiddleware, authenticateMiddleware, api.ResumeChangefeed)
changefeedGroup.POST("/:changefeed_id/pause", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("pause"), keyspaceCheckerMiddleware, authenticateMiddleware, api.PauseChangefeed)
changefeedGroup.DELETE("/:changefeed_id", coordinatorMiddleware, middleware.ChangefeedOperationMiddleware("delete"), keyspaceCheckerMiddleware, authenticateMiddleware, api.DeleteChangefeed)
changefeedGroup.GET("/:changefeed_id/status", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.status)
changefeedGroup.GET("/:changefeed_id/synced", coordinatorMiddleware, keyspaceCheckerMiddleware, authenticateMiddleware, api.synced)

Expand Down
Loading
Loading