diff --git a/.golangci.yml b/.golangci.yml index 547c742d89..fffa4af1ab 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -57,6 +57,11 @@ linters: - pkg: github.com/pingcap/ticdc/pkg/errors alias: "" + modernize: + # Keep pointer construction consistent with the repository's util.AddressOf convention. + disable: + - newexpr + revive: rules: - name: blank-imports diff --git a/api/v2/model.go b/api/v2/model.go index d10e09a8fb..e756ab2800 100644 --- a/api/v2/model.go +++ b/api/v2/model.go @@ -223,6 +223,9 @@ type ReplicaConfig struct { EnableSyncPoint *bool `json:"enable_sync_point,omitempty" toml:"enable-sync-point,omitempty"` EnableTableMonitor *bool `json:"enable_table_monitor,omitempty" toml:"enable-table-monitor,omitempty"` BDRMode *bool `json:"bdr_mode,omitempty" toml:"bdr-mode,omitempty"` + // AllowSameCluster allows the downstream to be the same TiDB logical cluster as the upstream. + // By default TiCDC rejects such a changefeed to avoid self-replication loops. + AllowSameCluster *bool `json:"allow_same_cluster,omitempty" toml:"allow-same-cluster,omitempty"` // EnableActiveActive enables active-active replication mode on top of BDR. // It requires BDRMode to be true and is only supported by TiDB and storage sinks. EnableActiveActive *bool `json:"enable_active_active,omitempty" toml:"enable-active-active,omitempty"` @@ -295,6 +298,9 @@ func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig( if c.BDRMode != nil { res.BDRMode = c.BDRMode } + if c.AllowSameCluster != nil { + res.AllowSameCluster = c.AllowSameCluster + } if c.EnableActiveActive != nil { res.EnableActiveActive = c.EnableActiveActive } @@ -366,7 +372,13 @@ func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig( } if c.Sink != nil { var dispatchRules []*config.DispatchRule + if c.Sink.DispatchRules != nil { + dispatchRules = make([]*config.DispatchRule, 0, len(c.Sink.DispatchRules)) + } for _, rule := range c.Sink.DispatchRules { + if rule == nil { + continue + } dispatchRules = append(dispatchRules, &config.DispatchRule{ Matcher: rule.Matcher, DispatcherRule: "", @@ -728,6 +740,7 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig { EnableSyncPoint: cloned.EnableSyncPoint, EnableTableMonitor: cloned.EnableTableMonitor, BDRMode: cloned.BDRMode, + AllowSameCluster: cloned.AllowSameCluster, EnableActiveActive: cloned.EnableActiveActive, } @@ -759,7 +772,14 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig { } if cloned.Sink != nil { var dispatchRules []*DispatchRule + // Clone omits empty slices; use the original to preserve an explicit clear. + if c.Sink.DispatchRules != nil { + dispatchRules = make([]*DispatchRule, 0, len(c.Sink.DispatchRules)) + } for _, rule := range cloned.Sink.DispatchRules { + if rule == nil { + continue + } dispatchRules = append(dispatchRules, &DispatchRule{ Matcher: rule.Matcher, PartitionRule: rule.PartitionRule, @@ -1232,11 +1252,12 @@ type Table struct { // SinkConfig represents sink config for a changefeed // This is a duplicate of config.SinkConfig +// Nil dispatchers preserve stored routes on update; an empty list clears them. type SinkConfig struct { Protocol *string `json:"protocol,omitempty" toml:"protocol,omitempty"` SchemaRegistry *string `json:"schema_registry,omitempty" toml:"schema-registry,omitempty"` CSVConfig *CSVConfig `json:"csv,omitempty" toml:"csv,omitempty"` - DispatchRules []*DispatchRule `json:"dispatchers,omitempty" toml:"dispatchers,omitempty"` + DispatchRules []*DispatchRule `json:"dispatchers,omitzero" toml:"dispatchers,omitempty"` ColumnSelectors []*ColumnSelector `json:"column_selectors,omitempty" toml:"column-selectors,omitempty"` TxnAtomicity *string `json:"transaction_atomicity,omitempty" toml:"transaction-atomicity,omitempty"` EncoderConcurrency *int `json:"encoder_concurrency,omitempty" toml:"encoder-concurrency,omitempty"` diff --git a/api/v2/model_test.go b/api/v2/model_test.go index bcfb7f9c54..0d99dd46f2 100644 --- a/api/v2/model_test.go +++ b/api/v2/model_test.go @@ -33,6 +33,38 @@ func TestSinkConfigDateSeparator(t *testing.T) { require.ErrorContains(t, err, "CDC:ErrStorageSinkInvalidConfig") } +func TestSinkDispatchRulesUpdate(t *testing.T) { + storedRules := []*DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst"}} + for _, tc := range []struct { + name string + rules []*DispatchRule + }{ + {name: "omitted"}, + {name: "clear", rules: []*DispatchRule{}}, + {name: "replace", rules: []*DispatchRule{{Matcher: []string{"new_src.*"}, TargetSchema: "new_dst"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &ReplicaConfig{Sink: &SinkConfig{DispatchRules: tc.rules}} + converted := ToAPIReplicaConfig(cfg.ToInternalReplicaConfig()) + require.Equal(t, tc.rules, converted.Sink.DispatchRules) + + info, err := (&ChangeFeedInfo{Config: converted}).Clone() + require.NoError(t, err) + require.Equal(t, tc.rules, info.Config.Sink.DispatchRules) + + body, err := json.Marshal(info.Config) + require.NoError(t, err) + stored := &ReplicaConfig{Sink: &SinkConfig{DispatchRules: storedRules}} + require.NoError(t, json.Unmarshal(body, stored)) + want := tc.rules + if tc.rules == nil { + want = storedRules + } + require.Equal(t, want, stored.Sink.DispatchRules) + }) + } +} + func TestChangeFeedInfoCloneWithMaskedSensitiveData(t *testing.T) { info := &ChangeFeedInfo{ ID: "test", @@ -97,6 +129,7 @@ func TestReplicaConfigConversion(t *testing.T) { EnableSyncPoint: util.AddressOf(true), EnableTableMonitor: util.AddressOf(true), BDRMode: util.AddressOf(true), + AllowSameCluster: util.AddressOf(true), Sink: &SinkConfig{ CloudStorageConfig: &CloudStorageConfig{ UseTableIDAsPath: util.AddressOf(true), @@ -115,6 +148,18 @@ func TestReplicaConfigConversion(t *testing.T) { KafkaConfig: &KafkaConfig{ SASLOAuthCA: util.AddressOf("/etc/ssl/oauth-ca.pem"), }, + DispatchRules: []*DispatchRule{ + nil, + { + Matcher: []string{"src.orders"}, + TargetSchema: "dst_orders", + }, + nil, + { + Matcher: []string{"src.customers"}, + TargetSchema: "dst_customers", + }, + }, }, Mounter: &MounterConfig{ WorkerNum: util.AddressOf(16), @@ -147,6 +192,7 @@ func TestReplicaConfigConversion(t *testing.T) { require.True(t, util.GetOrZero(internalCfg.EnableSyncPoint)) require.True(t, util.GetOrZero(internalCfg.EnableTableMonitor)) require.True(t, util.GetOrZero(internalCfg.BDRMode)) + require.True(t, util.GetOrZero(internalCfg.AllowSameCluster)) require.True(t, util.GetOrZero(internalCfg.Sink.CloudStorageConfig.UseTableIDAsPath)) require.Equal(t, int64(1024), util.GetOrZero(internalCfg.Sink.CloudStorageConfig.SpoolDiskQuota)) require.Equal(t, "/tmp/ticdc-spool", util.GetOrZero(internalCfg.Sink.CloudStorageConfig.SpoolBaseDir)) @@ -156,6 +202,16 @@ func TestReplicaConfigConversion(t *testing.T) { require.Equal(t, "hex", util.GetOrZero(internalCfg.Sink.Debezium.BinaryHandlingMode)) require.True(t, util.GetOrZero(internalCfg.Sink.Simple.IncludeStartTs)) require.Equal(t, "/etc/ssl/oauth-ca.pem", util.GetOrZero(internalCfg.Sink.KafkaConfig.SASLOAuthCA)) + require.Equal(t, []*config.DispatchRule{ + { + Matcher: []string{"src.orders"}, + TargetSchema: "dst_orders", + }, + { + Matcher: []string{"src.customers"}, + TargetSchema: "dst_customers", + }, + }, internalCfg.Sink.DispatchRules) require.Equal(t, internalCfg.Mounter.WorkerNum, *apiCfg.Mounter.WorkerNum) require.True(t, util.GetOrZero(internalCfg.Scheduler.EnableTableAcrossNodes)) require.Equal(t, 1000, util.GetOrZero(internalCfg.Scheduler.RegionThreshold)) @@ -194,11 +250,15 @@ func TestReplicaConfigConversion(t *testing.T) { require.Equal(t, util.GetOrZero(defaultCfg.CaseSensitive), util.GetOrZero(internalCfgNil.CaseSensitive)) // Test case 3: Conversion back to API config + internalCfg.Sink.DispatchRules = append( + []*config.DispatchRule{nil}, internalCfg.Sink.DispatchRules...) + internalCfg.Sink.DispatchRules = append(internalCfg.Sink.DispatchRules, nil) apiCfgBack := ToAPIReplicaConfig(internalCfg) require.Equal(t, config.PerformanceModeLowLatency, util.GetOrZero(apiCfgBack.PerformanceMode)) require.Equal(t, uint64(1024), *apiCfgBack.MemoryQuota) require.True(t, *apiCfgBack.CaseSensitive) require.True(t, *apiCfgBack.ForceReplicate) + require.True(t, *apiCfgBack.AllowSameCluster) require.True(t, *apiCfgBack.IgnoreIneligibleTable) require.True(t, *apiCfgBack.Sink.CloudStorageConfig.UseTableIDAsPath) require.Equal(t, int64(1024), *apiCfgBack.Sink.CloudStorageConfig.SpoolDiskQuota) @@ -210,6 +270,16 @@ func TestReplicaConfigConversion(t *testing.T) { require.True(t, util.GetOrZero(apiCfgBack.Sink.SimpleConfig.IncludeStartTs)) require.True(t, util.GetOrZero(apiCfgBack.Sink.DebeziumConfig.OutputOldValue)) require.Equal(t, "/etc/ssl/oauth-ca.pem", util.GetOrZero(apiCfgBack.Sink.KafkaConfig.SASLOAuthCA)) + require.Equal(t, []*DispatchRule{ + { + Matcher: []string{"src.orders"}, + TargetSchema: "dst_orders", + }, + { + Matcher: []string{"src.customers"}, + TargetSchema: "dst_customers", + }, + }, apiCfgBack.Sink.DispatchRules) require.Equal(t, 16, *apiCfgBack.Mounter.WorkerNum) require.True(t, *apiCfgBack.Scheduler.EnableTableAcrossNodes) require.Equal(t, "correctness", *apiCfgBack.Integrity.IntegrityCheckLevel) diff --git a/cmd/cdc/cli/cli_changefeed_update_test.go b/cmd/cdc/cli/cli_changefeed_update_test.go index f14f67c6ec..1839cfd2c4 100644 --- a/cmd/cdc/cli/cli_changefeed_update_test.go +++ b/cmd/cdc/cli/cli_changefeed_update_test.go @@ -16,6 +16,7 @@ package cli import ( "bytes" "context" + "encoding/json" "os" "path/filepath" "strings" @@ -24,6 +25,7 @@ import ( "github.com/golang/mock/gomock" "github.com/pingcap/log" v2 "github.com/pingcap/ticdc/api/v2" + "github.com/pingcap/ticdc/pkg/check" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/util" @@ -191,6 +193,92 @@ func TestChangefeedUpdateCli(t *testing.T) { require.NotNil(t, o.run(cmd)) } +func TestSameClusterUpdateConfigs(t *testing.T) { + replica := config.GetDefaultReplicaConfig() + replica.AllowSameCluster = new(true) + replica.Filter.Rules = []string{"src.*"} + replica.Sink.DispatchRules = []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{table}_copy"}, + } + original := v2.ToAPIReplicaConfig(replica) + + for _, tc := range []struct { + name string + config string + wantAllowSameCluster bool + wantFilterRules []string + wantDispatchRules []*v2.DispatchRule + }{ + { + name: "replace filter and routing", + config: `allow-same-cluster = true +[filter] +rules = ['new_src.*'] +[[sink.dispatchers]] +matcher = ['new_src.*'] +target-schema = 'new_dst' +target-table = '{table}_routed' +`, + wantAllowSameCluster: true, + wantFilterRules: []string{"new_src.*"}, + wantDispatchRules: []*v2.DispatchRule{ + {Matcher: []string{"new_src.*"}, TargetSchema: "new_dst", TargetTable: "{table}_routed"}, + }, + }, + { + name: "preserve omitted same-cluster configuration", + config: "memory-quota = 2097152\n", + wantAllowSameCluster: true, + wantFilterRules: original.Filter.Rules, + wantDispatchRules: original.Sink.DispatchRules, + }, + { + name: "disable same-cluster replication", + config: "allow-same-cluster = false\n", + wantAllowSameCluster: false, + wantFilterRules: original.Filter.Rules, + wantDispatchRules: original.Sink.DispatchRules, + }, + { + name: "clear routing", + config: "[sink]\ndispatchers = []\n", + wantAllowSameCluster: true, + wantFilterRules: original.Filter.Rules, + wantDispatchRules: []*v2.DispatchRule{}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + oldInfo := &v2.ChangeFeedInfo{Config: v2.ToAPIReplicaConfig(replica)} + configPath := filepath.Join(t.TempDir(), "cf.toml") + require.NoError(t, os.WriteFile(configPath, []byte(tc.config), 0o644)) + cmd := NewCmdCli() + o := newUpdateChangefeedOptions(newChangefeedCommonOptions()) + o.addFlags(cmd) + require.NoError(t, cmd.ParseFlags([]string{"--config=" + configPath})) + updated, err := o.applyChanges(oldInfo, cmd) + require.NoError(t, err) + require.Equal(t, new(tc.wantAllowSameCluster), updated.Config.AllowSameCluster) + require.Equal(t, tc.wantFilterRules, updated.Config.Filter.Rules) + require.Equal(t, tc.wantDispatchRules, updated.Config.Sink.DispatchRules) + require.Equal(t, original, oldInfo.Config) + + body, err := json.Marshal(o.getChangefeedConfig(cmd, updated)) + require.NoError(t, err) + // The API applies the serialized request to the stored configuration. + request := &v2.ChangefeedConfig{ReplicaConfig: v2.ToAPIReplicaConfig(replica)} + require.NoError(t, json.Unmarshal(body, request)) + require.Equal(t, tc.wantDispatchRules, request.ReplicaConfig.Sink.DispatchRules) + info := &config.ChangeFeedInfo{Config: request.ReplicaConfig.ToInternalReplicaConfig()} + err = check.ValidateSameClusterRouting(info.ToChangefeedConfig()) + if tc.wantAllowSameCluster && len(tc.wantDispatchRules) == 0 { + require.True(t, errors.ErrInvalidReplicaConfig.Equal(err), "%v", err) + } else { + require.NoError(t, err) + } + }) + } +} + func TestChangefeedUpdateReplicaCredentials(t *testing.T) { for _, tc := range []struct { name string diff --git a/pkg/check/cluster.go b/pkg/check/cluster.go index 534fdaab41..cced359606 100644 --- a/pkg/check/cluster.go +++ b/pkg/check/cluster.go @@ -41,6 +41,8 @@ var ( // because it can easily lead to self-replication loops. // // Compatibility and trade-offs: +// - If the changefeed config sets `allow-same-cluster = true`, the check is skipped and this +// returns false, so that creating/updating/resuming the changefeed is not blocked. // - If the sink is not TiDB, or the downstream `cluster_id` is unavailable, this returns false (keep legacy behavior). // - In TiDB Next-Gen, multiple keyspaces share the same physical `cluster_id`. When the downstream keyspace // can be determined, we treat (cluster_id, keyspace) as the cluster identity to allow cross-keyspace replication. @@ -49,11 +51,23 @@ var ( func IsSameUpstreamDownstream( ctx context.Context, upPD pd.Client, changefeedCfg *config.ChangefeedConfig, ) (bool, error) { - if upPD == nil { - return false, cerrors.New("pd client is nil") - } if changefeedCfg == nil { - return false, cerrors.New("changefeed config is nil") + return false, cerrors.ErrInternalCheckFailed.GenWithStackByArgs("changefeed config is nil") + } + // The user explicitly opted out of this verification, report "not same" so that the callers + // proceed. The flag only makes the changefeed safe when its routing rules keep every replicated + // table outside the filter, so the validation runs here, on the configuration in use. + if changefeedCfg.AllowSameCluster { + if err := ValidateSameClusterRouting(changefeedCfg); err != nil { + return false, err + } + log.Warn("skip the upstream/downstream cluster verification because allow-same-cluster is enabled", + zap.String("changefeedID", changefeedCfg.ChangefeedID.Name()), + zap.String("sinkURI", util.MaskSensitiveDataInURI(changefeedCfg.SinkURI))) + return false, nil + } + if upPD == nil { + return false, cerrors.ErrInternalCheckFailed.GenWithStackByArgs("pd client is nil") } upID := upPD.GetClusterID(ctx) @@ -175,7 +189,7 @@ func getTiDBKeyspaceName(ctx context.Context, db *sql.DB) (string, error) { continue } if value != keyspace { - return "", cerrors.New("downstream TiDB reports inconsistent keyspace-name across instances") + return "", cerrors.ErrInternalCheckFailed.GenWithStack("downstream TiDB reports inconsistent keyspace-name across instances, got %s and %s", keyspace, value) } } if err := rows.Err(); err != nil { diff --git a/pkg/check/cluster_test.go b/pkg/check/cluster_test.go index 88ee9863ac..820776504a 100644 --- a/pkg/check/cluster_test.go +++ b/pkg/check/cluster_test.go @@ -196,9 +196,14 @@ func TestIsSameUpstreamDownstream(t *testing.T) { name string upClusterID uint64 changefeedID common.ChangeFeedID - mockDownFunc func(context.Context, string, *config.ChangefeedConfig) (uint64, string, bool, error) - wantResult bool - wantErr string + // allowSameCluster mirrors the changefeed config `allow-same-cluster`. + allowSameCluster bool + // routingWithAllowSameCluster adds the routing which keeps the replicated tables outside + // the filter, which `allow-same-cluster` requires. + routingWithAllowSameCluster bool + mockDownFunc func(context.Context, string, *config.ChangefeedConfig) (uint64, string, bool, error) + wantResult bool + wantErr string }{ { name: "same cluster", @@ -227,6 +232,35 @@ func TestIsSameUpstreamDownstream(t *testing.T) { }, wantResult: false, }, + { + name: "same cluster but allow-same-cluster is enabled", + upClusterID: 123, + changefeedID: common.NewChangefeedID4Test("default", "test"), + allowSameCluster: true, + routingWithAllowSameCluster: true, + mockDownFunc: func(context.Context, string, *config.ChangefeedConfig) (uint64, string, bool, error) { + return 123, "default", true, nil + }, + wantResult: false, + }, + { + name: "allow-same-cluster skips the verification without connecting to the downstream", + upClusterID: 123, + changefeedID: common.NewChangefeedID4Test("default", "test"), + allowSameCluster: true, + routingWithAllowSameCluster: true, + mockDownFunc: func(context.Context, string, *config.ChangefeedConfig) (uint64, string, bool, error) { + return 0, "", false, errors.New("should not be called") + }, + wantResult: false, + }, + { + name: "allow-same-cluster without table routing is rejected", + upClusterID: 123, + changefeedID: common.NewChangefeedID4Test("default", "test"), + allowSameCluster: true, + wantErr: "allow-same-cluster requires table routing to be enabled", + }, { name: "not tidb", changefeedID: common.NewChangefeedID4Test("default", "test"), @@ -248,6 +282,15 @@ func TestIsSameUpstreamDownstream(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { changefeedCfg.ChangefeedID = tc.changefeedID + changefeedCfg.AllowSameCluster = tc.allowSameCluster + changefeedCfg.SinkConfig = nil + changefeedCfg.Filter = nil + if tc.routingWithAllowSameCluster { + changefeedCfg.Filter = &config.FilterConfig{Rules: []string{"src.*"}} + changefeedCfg.SinkConfig = &config.SinkConfig{DispatchRules: []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst"}, + }} + } SetGetClusterIDBySinkURIFnForTest(tc.mockDownFunc) mockPD := &mockPDClient{clusterID: tc.upClusterID} diff --git a/pkg/check/same_cluster.go b/pkg/check/same_cluster.go new file mode 100644 index 0000000000..bb0af48ce6 --- /dev/null +++ b/pkg/check/same_cluster.go @@ -0,0 +1,526 @@ +// 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 check + +import ( + "slices" + "strings" + + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" +) + +// This file validates database isolation for `allow-same-cluster`. Every replicated table must +// be routed, and every target schema must stay outside the schemas selected by the filter. +// Database DDL matches schema names even when a filter or matcher names only specific tables. +// Consequently, changing only the table name cannot isolate a changefeed from its own writes. +// +// Validation reasons about patterns to cover future databases and tables. Unsupported patterns +// are rejected. Rules overlapping on a source schema must use the same target-schema expression +// so database DDL has an unambiguous target, including rules whose table matchers are disjoint. + +const ( + schemaPlaceholder = "{schema}" + tablePlaceholder = "{table}" + // unsupportedPatternChars are characters which this decision does not parse, so a pattern which + // contains one of them is rejected as unsupported. + unsupportedPatternChars = "*?[]{}/\\`\"" +) + +// ValidateSameClusterRouting rejects a changefeed which may replicate into its own cluster unless +// its routing rules place every replicated table outside the source schema range. It is the static +// counterpart of IsSameUpstreamDownstream: the flag is only safe when this validation passes, so it is evaluated +// where the flag takes effect, on the configuration which is actually in use. +func ValidateSameClusterRouting(cfg *config.ChangefeedConfig) error { + if cfg == nil || !cfg.AllowSameCluster { + return nil + } + if !cfg.SinkConfig.TableRouteEnabled() { + return errors.ErrInvalidReplicaConfig.FastGenByArgs("allow-same-cluster requires table routing to be enabled") + } + return validateRouting(cfg.Filter, cfg.SinkConfig.DispatchRules, cfg.CaseSensitive) +} + +// validateRouting checks the routing rules against the filter rules. +func validateRouting(filter *config.FilterConfig, dispatch []*config.DispatchRule, caseSensitive bool) error { + filters, err := parseFilterRules(effectiveFilterRules(filter), caseSensitive) + if err != nil { + return err + } + routes, err := parseRouteRules(dispatch, caseSensitive) + if err != nil { + return err + } + if err := verifyFilterRulesCovered(filters, routes); err != nil { + return err + } + if err := verifySchemaTargets(filters, routes); err != nil { + return err + } + return verifySchemaRoutingConsistent(filters, routes) +} + +func normalizeName(name string, caseSensitive bool) string { + if caseSensitive { + return name + } + return strings.ToLower(name) +} + +// namePatternKind classifies the supported pattern forms. +type namePatternKind int + +const ( + // patternAny is "*". + patternAny namePatternKind = iota + // patternLiteral is a plain name. + patternLiteral + // patternPrefix is "prefix*". + patternPrefix + // patternSuffix is "*suffix". + patternSuffix +) + +// namePattern is one side (schema or table) of a filter rule or a routing matcher. +type namePattern struct { + kind namePatternKind + value string +} + +// matches reports whether a concrete name matches the pattern. +func (p namePattern) matches(name string) bool { + switch p.kind { + case patternAny: + return true + case patternLiteral: + return name == p.value + case patternPrefix: + return strings.HasPrefix(name, p.value) + case patternSuffix: + return strings.HasSuffix(name, p.value) + default: + return false + } +} + +// covers reports whether every name matching the filter pattern matches the matcher pattern. +func (p namePattern) covers(matcher namePattern) bool { + switch matcher.kind { + case patternAny: + return true + case patternLiteral: + return p.kind == patternLiteral && p.value == matcher.value + case patternPrefix: + return (p.kind == patternLiteral || p.kind == patternPrefix) && strings.HasPrefix(p.value, matcher.value) + case patternSuffix: + return (p.kind == patternLiteral || p.kind == patternSuffix) && strings.HasSuffix(p.value, matcher.value) + default: + return false + } +} + +// overlaps reports whether the patterns share a name, preserving case sensitivity. +func (p namePattern) overlaps(other namePattern) bool { + // A prefix and a suffix always share their concatenation. For all other + // supported pattern pairs, an overlap means one pattern covers the other. + return p.covers(other) || other.covers(p) || + (p.kind == patternPrefix && other.kind == patternSuffix) || + (p.kind == patternSuffix && other.kind == patternPrefix) +} + +// targetName is a parsed route target expression: literal text around one placeholder, or a literal +// name. An empty expression keeps the source name, which is an empty substitution. +type targetName struct { + literal string + prefix string + suffix string + hasVariable bool +} + +// apply returns the target name of a source name. +func (t targetName) apply(name string) string { + if t.hasVariable { + return t.prefix + name + t.suffix + } + return t.literal +} + +// tablePattern is a parsed `schema.table` pattern: a filter rule, or a matcher of a dispatch rule +// which has a target. +type tablePattern struct { + raw string + schema namePattern + table namePattern +} + +// routeRuleToCheck pairs one matcher with its dispatch rule target. +// Dispatch rules with multiple matchers are expanded during parsing. +type routeRuleToCheck struct { + rawMatchers []string + matcher tablePattern + schema targetName + schemaExpression string +} + +// effectiveFilterRules returns the filter rules which are in effect. It mirrors +// pkg/filter.VerifyTableRules, where unset rules replicate every table. +func effectiveFilterRules(cfg *config.FilterConfig) []string { + if cfg == nil || len(cfg.Rules) == 0 { + return []string{"*.*"} + } + return cfg.Rules +} + +func parseFilterRules(rules []string, caseSensitive bool) ([]tablePattern, error) { + parsed := make([]tablePattern, 0, len(rules)) + for _, rule := range rules { + pattern, err := parseRulePattern("filter rule", rule, caseSensitive) + if err != nil { + return nil, err + } + parsed = append(parsed, pattern) + } + return parsed, nil +} + +func parseRouteRules(rules []*config.DispatchRule, caseSensitive bool) ([]routeRuleToCheck, error) { + parsed := make([]routeRuleToCheck, 0, len(rules)) + for _, rule := range rules { + // Rules without a target keep the table name and are ignored by the router. + if rule == nil || (rule.TargetSchema == "" && rule.TargetTable == "") { + continue + } + route := routeRuleToCheck{rawMatchers: rule.Matcher, schemaExpression: rule.TargetSchema} + var reason string + var ok bool + if route.schema, reason, ok = parseTargetExpression(rule.TargetSchema, schemaPlaceholder); !ok { + return nil, unsupportedError("target schema of the dispatch rule matching "+strings.Join(rule.Matcher, ","), rule.TargetSchema, reason) + } + if _, reason, ok = parseTargetExpression(rule.TargetTable, tablePlaceholder); !ok { + return nil, unsupportedError("target table of the dispatch rule matching "+strings.Join(rule.Matcher, ","), rule.TargetTable, reason) + } + // Normalize literal text after parsing so placeholder names remain case sensitive. + // The runtime filter normalizes the entire substituted target before matching it. + route.schema.literal = normalizeName(route.schema.literal, caseSensitive) + route.schema.prefix = normalizeName(route.schema.prefix, caseSensitive) + route.schema.suffix = normalizeName(route.schema.suffix, caseSensitive) + for _, matcher := range rule.Matcher { + pattern, err := parseRulePattern("dispatch rule matcher", matcher, caseSensitive) + if err != nil { + return nil, err + } + route.matcher = pattern + parsed = append(parsed, route) + } + } + return parsed, nil +} + +// parseRulePattern parses a `schema.table` pattern into its two parts. It rejects, instead of +// approximating, the patterns which this decision cannot handle. +func parseRulePattern(kind, pattern string, caseSensitive bool) (tablePattern, error) { + // Match table-filter's rule preprocessing without trimming inside quoted names. + schemaPart, tablePart, ok := splitRulePattern(strings.Trim(pattern, " \t")) + if !ok { + return tablePattern{}, unsupportedError(kind, pattern, "expected a `schema.table` pattern") + } + schema, reason, ok := parseNamePattern(normalizeName(schemaPart, caseSensitive)) + if !ok { + return tablePattern{}, unsupportedError(kind, pattern, "schema pattern "+reason) + } + table, reason, ok := parseNamePattern(normalizeName(tablePart, caseSensitive)) + if !ok { + return tablePattern{}, unsupportedError(kind, pattern, "table pattern "+reason) + } + return tablePattern{raw: pattern, schema: schema, table: table}, nil +} + +// unsupportedError reports a configuration which the decision cannot handle. +func unsupportedError(what, name, reason string) error { + return errors.ErrInvalidReplicaConfig.FastGen("allow-same-cluster does not support the %s %q: %s", what, name, reason) +} + +// splitRulePattern splits a `schema.table` pattern at its single dot. A dot inside a quoted name +// does not split the pattern. +func splitRulePattern(pattern string) (string, string, bool) { + var quote byte + dot := -1 + for i := range len(pattern) { + switch c := pattern[i]; { + case quote != 0: + if c == quote { + quote = 0 + } + case c == '`' || c == '"': + quote = c + case c == '.': + if dot >= 0 { + return "", "", false + } + dot = i + } + } + if quote != 0 || dot < 0 { + return "", "", false + } + return pattern[:dot], pattern[dot+1:], true +} + +// parseNamePattern parses one part of a pattern. Supported forms are a literal name, `*`, a single +// leading `*`, a single trailing `*`, and quoted names. It returns the reason for a pattern which +// is not supported. +func parseNamePattern(part string) (namePattern, string, bool) { + if part == "" { + return namePattern{}, "is empty", false + } + switch part[0] { + case '!': + // Negated rules depend on the rule order of the table filter, which this decision does not + // reason about. + return namePattern{}, "is negated, which is not supported", false + case '`', '"': + name, ok := unquoteName(part) + if !ok { + return namePattern{}, "has an unsupported quoted name", false + } + return namePattern{kind: patternLiteral, value: name}, "", true + } + if rest, ok := strings.CutPrefix(part, "*"); ok { + if rest == "" { + return namePattern{kind: patternAny}, "", true + } + if strings.ContainsAny(rest, unsupportedPatternChars) { + return namePattern{}, "uses characters or wildcards which are not supported", false + } + return namePattern{kind: patternSuffix, value: rest}, "", true + } + if rest, ok := strings.CutSuffix(part, "*"); ok { + if strings.ContainsAny(rest, unsupportedPatternChars) { + return namePattern{}, "uses characters or wildcards which are not supported", false + } + return namePattern{kind: patternPrefix, value: rest}, "", true + } + if strings.ContainsAny(part, unsupportedPatternChars) { + return namePattern{}, "uses characters or wildcards which are not supported", false + } + return namePattern{kind: patternLiteral, value: part}, "", true +} + +// unquoteName removes a pair of backticks or double quotes around a name. +func unquoteName(part string) (string, bool) { + if len(part) < 2 || part[len(part)-1] != part[0] { + return "", false + } + quote := part[0] + name := strings.ReplaceAll(part[1:len(part)-1], strings.Repeat(string(quote), 2), string(quote)) + if strings.Contains(name, "*") { + return "", false + } + return name, true +} + +// parseTargetExpression parses a route target expression. An empty expression keeps the source name, +// which is an empty substitution. It returns the reason for an expression which is not supported. +func parseTargetExpression(expr, placeholder string) (targetName, string, bool) { + unsupported := "expected literal text with at most one " + placeholder + " placeholder" + if expr == "" { + return targetName{hasVariable: true}, "", true + } + head, tail, found := strings.Cut(expr, placeholder) + if !found { + if strings.ContainsAny(expr, "{}") { + return targetName{}, unsupported, false + } + return targetName{literal: expr}, "", true + } + if strings.ContainsAny(head+tail, "{}") { + return targetName{}, unsupported, false + } + return targetName{prefix: head, suffix: tail, hasVariable: true}, "", true +} + +// verifyFilterRulesCovered rejects filter rules which no dispatch rule with a target would route: +// such a table keeps its own name and is replicated into itself. +func verifyFilterRulesCovered(filters []tablePattern, routes []routeRuleToCheck) error { + for _, filter := range filters { + covered := slices.ContainsFunc(routes, func(route routeRuleToCheck) bool { + return filter.schema.covers(route.matcher.schema) && filter.table.covers(route.matcher.table) + }) + if !covered { + return errors.ErrInvalidReplicaConfig.FastGen("allow-same-cluster requires every filter rule to be routed to another table, but filter rule %q is not covered by any dispatch rule matcher", filter.raw) + } + } + return nil +} + +// verifySchemaTargets considers all schema matches, regardless of the table part, just like +// the runtime router and filter do for database DDL. +func verifySchemaTargets(filters []tablePattern, routes []routeRuleToCheck) error { + for _, route := range routes { + if schema, ok := route.findCapturedSchema(filters); ok { + return errors.ErrInvalidReplicaConfig.FastGen( + "allow-same-cluster requires database isolation, but the dispatch rule matching %v "+ + "routes schema %q to %q, which the filter replicates", + route.rawMatchers, schema, route.schema.apply(schema)) + } + } + return nil +} + +// findCapturedSchema checks target overlap using TiDB's case insensitive identifier lookup. +// Folding is local to this isolation check: route coverage and schema routing consistency +// must still use the configured filter semantics. +func (r routeRuleToCheck) findCapturedSchema(filters []tablePattern) (string, bool) { + matcher := r.matcher.schema + matcher.value = strings.ToLower(matcher.value) + target := r.schema + target.literal = strings.ToLower(target.literal) + target.prefix = strings.ToLower(target.prefix) + target.suffix = strings.ToLower(target.suffix) + for _, source := range filters { + // A case sensitive matcher that cannot select this source never routes its DDL. + if !source.schema.overlaps(r.matcher.schema) { + continue + } + source.schema.value = strings.ToLower(source.schema.value) + for _, capture := range filters { + capture.schema.value = strings.ToLower(capture.schema.value) + if schema, ok := findNameWitness(source.schema, matcher, capture.schema, target); ok { + return schema, true + } + } + } + return "", false +} + +// verifySchemaRoutingConsistent requires identical target-schema expressions wherever two routes +// overlap on a source schema. The runtime router compares all matching schema targets, including +// rules shadowed at table level, and compares their original spelling even in case insensitive mode. +func verifySchemaRoutingConsistent(filters []tablePattern, routes []routeRuleToCheck) error { + for i, left := range routes { + for _, right := range routes[i+1:] { + if left.schemaExpression == right.schemaExpression { + continue + } + if schema, ok := findSharedSourceSchema(filters, left.matcher.schema, right.matcher.schema); ok { + return errors.ErrInvalidReplicaConfig.FastGen( + "allow-same-cluster does not support different target-schema expressions %q and %q "+ + "for routes matching source schema %q", + left.schemaExpression, right.schemaExpression, schema) + } + } + } + return nil +} + +// findSharedSourceSchema intersects two schema matchers within the replicated source range. +func findSharedSourceSchema(filters []tablePattern, left, right namePattern) (string, bool) { + for _, source := range filters { + if schema, ok := findNameWitness(source.schema, left, right, targetName{hasVariable: true}); ok { + return schema, true + } + } + return "", false +} + +// findNameWitness finds one source name whose routed target is captured again. +func findNameWitness(source, matcher, capture namePattern, target targetName) (string, bool) { + if !target.hasVariable && !capture.matches(target.literal) { + return "", false + } + for _, name := range candidateNames(source, matcher, capture, target) { + if source.matches(name) && matcher.matches(name) && capture.matches(target.apply(name)) { + return name, true + } + } + return "", false +} + +// candidateNames lists the names which can satisfy the source rule, the matcher and the target rule +// at the same time. Every candidate is verified before use. The set contains the literal text of +// each pattern, the head or tail the pattern requires, every combination of a head with a tail, +// and the names where the substitution completes a pattern. +func candidateNames(source, matcher, capture namePattern, target targetName) []string { + atoms := slices.Concat( + atomsOf(source, "", ""), + atomsOf(matcher, "", ""), + atomsOf(capture, target.prefix, target.suffix), + ) + names := make([]string, 0, 3*len(atoms)+len(atoms)*len(atoms)+1) + names = append(names, "x") + for _, atom := range atoms { + names = append(names, atom, atom+"x", "x"+atom) + for _, other := range atoms { + names = append(names, atom+other) + } + } + return names +} + +// atomsOf returns the names which this pattern contributes to the candidates, given that `prefix` +// and `suffix` are added around the name before the pattern is matched (both empty when the pattern +// is matched directly). +func atomsOf(p namePattern, prefix, suffix string) []string { + switch p.kind { + case patternAny: + return nil + case patternLiteral: + if !strings.HasPrefix(p.value, prefix) || !strings.HasSuffix(p.value, suffix) || len(p.value) < len(prefix)+len(suffix) { + return nil + } + if name := p.value[len(prefix) : len(p.value)-len(suffix)]; name != "" { + return []string{name} + } + return nil + case patternPrefix: + if len(p.value) <= len(prefix) { + // The prefix covers the requirement on its own. + return nil + } + if !strings.HasPrefix(p.value, prefix) { + return nil + } + return prefixesOf(p.value[len(prefix):]) + case patternSuffix: + if len(p.value) <= len(suffix) { + // The suffix covers the requirement on its own. + return nil + } + if !strings.HasSuffix(p.value, suffix) { + return nil + } + return suffixesOf(p.value[:len(p.value)-len(suffix)]) + default: + return nil + } +} + +// prefixesOf returns every non-empty prefix of text, shortest first. +func prefixesOf(text string) []string { + prefixes := make([]string, 0, len(text)) + for end := range len(text) { + prefixes = append(prefixes, text[:end+1]) + } + return prefixes +} + +// suffixesOf returns every non-empty suffix of text, longest first. +func suffixesOf(text string) []string { + suffixes := make([]string, 0, len(text)) + for start := range len(text) { + suffixes = append(suffixes, text[start:]) + } + return suffixes +} diff --git a/pkg/check/same_cluster_bench_test.go b/pkg/check/same_cluster_bench_test.go new file mode 100644 index 0000000000..e2dc0be957 --- /dev/null +++ b/pkg/check/same_cluster_bench_test.go @@ -0,0 +1,66 @@ +// 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 check + +import ( + "fmt" + "strings" + "testing" + + "github.com/pingcap/ticdc/pkg/config" +) + +func BenchmarkValidateSameClusterRouting(b *testing.B) { + for _, tc := range []struct { + name string + length int + rules int + derived bool + }{ + {name: "fixedSchema16", length: 16, rules: 1}, + {name: "fixedSchema32", length: 32, rules: 1}, + {name: "fixedSchema48", length: 48, rules: 1}, + {name: "derivedSchema16", length: 16, rules: 1, derived: true}, + {name: "fourRules8", length: 8, rules: 4}, + } { + b.Run(tc.name, func(b *testing.B) { + cfg := &config.ChangefeedConfig{ + AllowSameCluster: true, + Filter: &config.FilterConfig{}, + SinkConfig: &config.SinkConfig{}, + } + for i := range tc.rules { + prefix := strings.Repeat("a", tc.length) + if tc.rules > 1 { + prefix = fmt.Sprintf("db%d%s", i, prefix) + } + pattern := prefix + "*." + prefix + "*" + rule := &config.DispatchRule{Matcher: []string{pattern}} + rule.TargetSchema = strings.Repeat("b", tc.length) + if tc.derived { + rule.TargetSchema += "{schema}" + } + cfg.Filter.Rules = append(cfg.Filter.Rules, pattern) + cfg.SinkConfig.DispatchRules = append(cfg.SinkConfig.DispatchRules, rule) + } + b.ReportAllocs() + for b.Loop() { + if err := ValidateSameClusterRouting(cfg); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/pkg/check/same_cluster_runtime_test.go b/pkg/check/same_cluster_runtime_test.go new file mode 100644 index 0000000000..b39eccfc63 --- /dev/null +++ b/pkg/check/same_cluster_runtime_test.go @@ -0,0 +1,143 @@ +// 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 check_test + +import ( + "cmp" + "fmt" + "testing" + + "github.com/pingcap/ticdc/pkg/check" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/filter" + "github.com/pingcap/ticdc/pkg/routing" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/stretchr/testify/require" +) + +func TestSameClusterRoutingRuntimeSemantics(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + filterRules []string + matcher string + targetSchema string + targetTable string + sourceSchema string + wantSchemaCaptured bool + caseInsensitiveOnly bool + }{ + { + name: "leading spaces", filterRules: []string{" src.*"}, + matcher: " src.*", targetSchema: "src", wantSchemaCaptured: true, + }, + { + name: "trailing spaces", filterRules: []string{"src.t1 "}, + matcher: "src.t1 ", targetSchema: "src", wantSchemaCaptured: true, + }, + { + name: "surrounding tabs", filterRules: []string{"\tsrc.t1\t"}, + matcher: "\tsrc.t1\t", targetSchema: "src", wantSchemaCaptured: true, + }, + { + name: "safe route with padded filter", filterRules: []string{" \tsrc.t1\t "}, + matcher: "src.t1", targetSchema: "dst", + }, + { + name: "safe route with padded matcher", filterRules: []string{"src.t1"}, + matcher: " \tsrc.t1\t ", targetSchema: "dst", + }, + { + name: "quoted whitespace is part of the name", filterRules: []string{" ` src`.`t1` "}, + matcher: "\t` src`.`t1`\t", targetSchema: "src", sourceSchema: " src", + }, + { + name: "uppercase target schema", filterRules: []string{"src.*"}, + matcher: "src.*", targetSchema: "SRC", wantSchemaCaptured: true, caseInsensitiveOnly: true, + }, + { + name: "uppercase target table", filterRules: []string{"src.t1"}, + matcher: "src.t1", targetTable: "T1", wantSchemaCaptured: true, + }, + { + name: "target schema prefix", filterRules: []string{"src.*", "copy_src.*"}, + matcher: "*.*", targetSchema: "COPY_{schema}", wantSchemaCaptured: true, caseInsensitiveOnly: true, + }, + { + name: "target schema suffix", filterRules: []string{"src.*", "src_copy.*"}, + matcher: "*.*", targetSchema: "{schema}_COPY", wantSchemaCaptured: true, caseInsensitiveOnly: true, + }, + { + name: "target table prefix", filterRules: []string{"src.t1", "src.copy_t1"}, + matcher: "src.*", targetTable: "COPY_{table}", wantSchemaCaptured: true, + }, + { + name: "target table suffix", filterRules: []string{"src.t1", "src.t1_copy"}, + matcher: "src.*", targetTable: "{table}_COPY", wantSchemaCaptured: true, + }, + { + name: "safe mixed case target", filterRules: []string{"src.*"}, + matcher: "src.*", targetSchema: "Dst_{schema}", targetTable: "{table}_Copy", + }, + } + + for _, tc := range cases { + for _, caseSensitive := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/caseSensitive=%t", tc.name, caseSensitive), func(t *testing.T) { + cfg := &config.ChangefeedConfig{ + AllowSameCluster: true, + CaseSensitive: caseSensitive, + Filter: &config.FilterConfig{Rules: tc.filterRules}, + SinkConfig: &config.SinkConfig{DispatchRules: []*config.DispatchRule{{ + Matcher: []string{tc.matcher}, TargetSchema: tc.targetSchema, TargetTable: tc.targetTable, + }}}, + } + f, err := filter.NewFilter(cfg.Filter, "UTC", caseSensitive, false) + require.NoError(t, err) + router, err := routing.NewRouter(common.NewChangefeedID4Test("default", "same-cluster"), caseSensitive, cfg.SinkConfig.DispatchRules) + require.NoError(t, err) + schema := cmp.Or(tc.sourceSchema, "src") + require.False(t, f.ShouldIgnoreTable(schema, "t1")) + routed, err := router.ApplyToTableInfo(&common.TableInfo{ + TableName: common.TableName{Schema: schema, Table: "t1"}, + }) + require.NoError(t, err) + // Table renaming cannot exclude database DDL from the source schema range. + ddl, err := router.ApplyToDDLEvent(&event.DDLEvent{ + Type: byte(model.ActionDropSchema), SchemaName: schema, + Query: "DROP DATABASE " + common.QuoteName(schema), + }) + require.NoError(t, err) + require.Equal(t, routed.GetTargetSchemaName(), ddl.GetTargetSchemaName()) + captured := !f.ShouldDiscardDDL(ddl.GetTargetSchemaName(), "", model.ActionDropSchema, nil) + require.Equal(t, tc.wantSchemaCaptured && (!caseSensitive || !tc.caseInsensitiveOnly), captured) + + err = check.ValidateSameClusterRouting(cfg) + // TiDB resolves schema identifiers case insensitively even when the + // in-memory filter does not capture the target's original spelling. + if tc.wantSchemaCaptured { + require.ErrorContains(t, err, "which the filter replicates") + require.True(t, errors.ErrInvalidReplicaConfig.Equal(err)) + } else { + require.NoError(t, err) + } + }) + } + } +} diff --git a/pkg/check/same_cluster_test.go b/pkg/check/same_cluster_test.go new file mode 100644 index 0000000000..6847be4dca --- /dev/null +++ b/pkg/check/same_cluster_test.go @@ -0,0 +1,447 @@ +// 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 check + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/config" + "github.com/stretchr/testify/require" +) + +func TestValidateSameClusterRouting(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + allowSame bool + filterRules []string + dispatch []*config.DispatchRule + wantError string + }{ + { + name: "allow-same-cluster is not set", + filterRules: []string{"src.*"}, + }, + { + name: "table routing is not enabled", + allowSame: true, + filterRules: []string{"src.*"}, + wantError: "allow-same-cluster requires table routing to be enabled", + }, + { + name: "the routing covers the filter and targets another schema", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{table}_routed"}}, + }, + { + name: "the target schema is derived from the source schema", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "{schema}_routed", TargetTable: "{table}_routed"}}, + }, + { + name: "the filter matches every table and the target schema is derived", + allowSame: true, + dispatch: []*config.DispatchRule{{Matcher: []string{"*.*"}, TargetSchema: "{schema}_routed", TargetTable: "{table}_routed"}}, + wantError: "which the filter replicates", + }, + { + name: "the filter matches every table", + allowSame: true, + dispatch: []*config.DispatchRule{{Matcher: []string{"*.*"}, TargetSchema: "dst", TargetTable: "{table}"}}, + wantError: "which the filter replicates", + }, + { + name: "the matcher is narrower than the filter rule", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.t1"}, TargetSchema: "dst", TargetTable: "{table}_routed"}}, + wantError: `filter rule "src.*" is not covered by any dispatch rule matcher`, + }, + { + name: "the target schema is replicated as well", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "src", TargetTable: "{table}_copy"}}, + wantError: "which the filter replicates", + }, + { + name: "the target table is replicated as well", + allowSame: true, + filterRules: []string{"src.*", "dst.t1"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{table}"}, + {Matcher: []string{"dst.t1"}, TargetSchema: "dst2"}, + }, + wantError: "which the filter replicates", + }, + { + name: "a different target table in the source schema is rejected", + allowSame: true, + filterRules: []string{"src.t1"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.t1"}, TargetSchema: "src", TargetTable: "t1_bak"}}, + wantError: "requires database isolation", + }, + { + name: "a derived target table in another source schema is rejected", + allowSame: true, + filterRules: []string{"src.*", "dst.t1"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{table}_routed"}, + {Matcher: []string{"dst.t1"}, TargetSchema: "dst2"}, + }, + wantError: "requires database isolation", + }, + { + name: "matching schemas with a disjoint literal target table", + allowSame: true, + filterRules: []string{"src.a*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.a*"}, TargetTable: "b"}}, + wantError: "requires database isolation", + }, + { + name: "matching schemas with a disjoint derived target table", + allowSame: true, + filterRules: []string{"src.a*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.a*"}, TargetTable: "b{table}"}}, + wantError: "requires database isolation", + }, + { + name: "both dimensions match a literal target", + allowSame: true, + filterRules: []string{"src.a*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.a*"}, TargetSchema: "src", TargetTable: "a_copy"}}, + wantError: "which the filter replicates", + }, + { + name: "the target keeps the source name", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "{schema}", TargetTable: "{table}"}}, + wantError: "which the filter replicates", + }, + { + name: "the target keeps the source schema", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetTable: "{table}_bak"}}, + wantError: "which the filter replicates", + }, + { + name: "quoted names are supported", + allowSame: true, + filterRules: []string{"`src`.`t1`"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"`src`.`t1`"}, TargetSchema: "dst", TargetTable: "{table}"}}, + }, + { + name: "case insensitive names are compared case insensitively", + allowSame: true, + filterRules: []string{"SRC.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "DST", TargetTable: "{table}"}}, + }, + { + name: "normalization does not accept an uppercase schema placeholder", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst_{SCHEMA}"}}, + wantError: "does not support the target schema", + }, + { + name: "normalization does not accept an uppercase table placeholder", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{TABLE}"}}, + wantError: "does not support the target table", + }, + { + name: "database DDL can delete another source table", + allowSame: true, + filterRules: []string{"a.t1", "b.t2"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"a.t1"}, TargetSchema: "b", TargetTable: "t1_copy"}, + {Matcher: []string{"b.t2"}, TargetSchema: "c", TargetTable: "t2_copy"}, + }, + wantError: "requires database isolation", + }, + { + name: "all schemas with only one replicated table name", + allowSame: true, + filterRules: []string{"*.orders"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"*.orders"}, TargetSchema: "{schema}_backup", TargetTable: "orders_copy"}}, + wantError: "requires database isolation", + }, + { + name: "database DDL also matches an unreplicated table rule", + allowSame: true, + filterRules: []string{"src.t1"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.t1"}, TargetSchema: "dst"}, + {Matcher: []string{"src.other"}, TargetSchema: "src"}, + }, + wantError: "requires database isolation", + }, + { + name: "different tables cannot route database DDL to different schemas", + allowSame: true, + filterRules: []string{"src.t1", "src.t2"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.t1"}, TargetSchema: "dst1"}, + {Matcher: []string{"src.t2"}, TargetSchema: "dst2"}, + }, + wantError: "different target-schema expressions", + }, + { + name: "runtime schema targets are compared without case folding", + allowSame: true, + filterRules: []string{"src.t1", "src.t2"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.t1"}, TargetSchema: "DST"}, + {Matcher: []string{"src.t2"}, TargetSchema: "dst"}, + }, + wantError: "different target-schema expressions", + }, + { + name: "different target tables may share a target schema", + allowSame: true, + filterRules: []string{"src.t1", "src.t2"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.t1"}, TargetSchema: "dst", TargetTable: "t1_copy"}, + {Matcher: []string{"src.t2"}, TargetSchema: "dst", TargetTable: "t2_copy"}, + }, + }, + { + name: "schema matchers may overlap outside the source filter", + allowSame: true, + filterRules: []string{"foo.t1", "bar.t1"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"f*.t1"}, TargetSchema: "dst1"}, + {Matcher: []string{"*r.t1"}, TargetSchema: "dst2"}, + }, + }, + + { + name: "all matchers in one route contribute to coverage", + allowSame: true, + filterRules: []string{"a.t1", "b.t2"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"a.t1", "b.t2"}, TargetSchema: "copy_{schema}"}}, + }, + { + name: "a later matcher routes back into a source schema", + allowSame: true, + filterRules: []string{"a.t1", "b.t2", "copy_b.t3"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"a.t1", "b.t2", "copy_b.t3"}, TargetSchema: "copy_{schema}"}, + }, + wantError: "requires database isolation", + }, + { + name: "a later matcher conflicts with another schema route", + allowSame: true, + filterRules: []string{"a.t1", "b.t2"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"a.t1", "b.t2"}, TargetSchema: "dst1"}, + {Matcher: []string{"other.*", "b.other"}, TargetSchema: "dst2"}, + }, + wantError: "different target-schema expressions", + }, + { + name: "negated filter rules are not supported", + allowSame: true, + filterRules: []string{"src.*", "!src.tmp"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst"}}, + wantError: "does not support the filter rule", + }, + { + name: "wildcard forms other than a single star are not supported", + allowSame: true, + filterRules: []string{"src.t?"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst"}}, + wantError: "does not support the filter rule", + }, + { + // `sr_rout*` only matches the target schema once the `{schema}_routed` suffix is appended, + // so the witness schema `sr` is shorter than the text the pattern asks for. + name: "the substitution completes the target pattern", + allowSame: true, + filterRules: []string{"*r.t1", "sr_rout*.t1"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"*r.*"}, TargetSchema: "{schema}_routed", TargetTable: "{table}"}, + {Matcher: []string{"sr_rout*.*"}, TargetSchema: "dst"}, + }, + wantError: "which the filter replicates", + }, + { + name: "the target schema must not use the table placeholder", + allowSame: true, + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst_{table}", TargetTable: "{table}"}}, + wantError: "does not support the target schema", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.ChangefeedConfig{ + AllowSameCluster: tc.allowSame, + Filter: &config.FilterConfig{Rules: tc.filterRules}, + SinkConfig: &config.SinkConfig{DispatchRules: tc.dispatch}, + } + + err := ValidateSameClusterRouting(cfg) + if tc.wantError != "" { + require.ErrorContains(t, err, tc.wantError) + return + } + require.NoError(t, err) + }) + } +} + +func TestNamePatternOverlaps(t *testing.T) { + cases := []struct { + left, right string + want bool + }{ + {"*", "*", true}, + {"*", "src", true}, + {"*", "src*", true}, + {"*", "*src", true}, + {"src", "src", true}, + {"src", "dst", false}, + {"src", "SRC", false}, + {"src", "sr*", true}, + {"src", "src_*", false}, + {"src", "*rc", true}, + {"src", "*_src", false}, + {"src*", "src*", true}, + {"src*", "src_copy*", true}, + {"src*", "dst*", false}, + {"src*", "SRC*", false}, + {"*src", "*src", true}, + {"*src", "*copy_src", true}, + {"*src", "*dst", false}, + {"*src", "*SRC", false}, + {"src*", "*dst", true}, + {"src*", "*SRC", true}, + } + for _, tc := range cases { + t.Run(tc.left+"/"+tc.right, func(t *testing.T) { + left, reason, ok := parseNamePattern(tc.left) + require.True(t, ok, reason) + right, reason, ok := parseNamePattern(tc.right) + require.True(t, ok, reason) + require.Equal(t, tc.want, left.overlaps(right)) + require.Equal(t, tc.want, right.overlaps(left)) + }) + } +} + +func TestSameClusterSchemaIsolationCaseSensitive(t *testing.T) { + cases := []struct { + name string + filterRules []string + dispatch []*config.DispatchRule + wantError string + }{ + { + name: "literal target aliases source", + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "SRC"}}, + wantError: "requires database isolation", + }, + { + name: "mixed case source aliases target", + filterRules: []string{"Src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"Src.*"}, TargetSchema: "src"}}, + wantError: "requires database isolation", + }, + { + name: "literal target overlaps prefix filter", + filterRules: []string{"src*.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src*.*"}, TargetSchema: "SRC_COPY"}}, + wantError: "requires database isolation", + }, + { + name: "literal target overlaps suffix filter", + filterRules: []string{"*src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"*src.*"}, TargetSchema: "COPY_SRC"}}, + wantError: "requires database isolation", + }, + { + name: "derived prefix overlaps source range", + filterRules: []string{"src.*", "copy_*.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"*.*"}, TargetSchema: "COPY_{schema}"}}, + wantError: "requires database isolation", + }, + { + name: "derived suffix overlaps source range", + filterRules: []string{"src.*", "*_copy.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"*.*"}, TargetSchema: "{schema}_COPY"}}, + wantError: "requires database isolation", + }, + { + name: "safe mixed case derived target", + filterRules: []string{"Src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"Src.*"}, TargetSchema: "Copy_{schema}"}}, + }, + { + name: "schema coverage remains case sensitive", + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"SRC.*"}, TargetSchema: "dst"}}, + wantError: "is not covered by any dispatch rule matcher", + }, + { + name: "table coverage remains case sensitive", + filterRules: []string{"src.t1"}, + dispatch: []*config.DispatchRule{{Matcher: []string{"src.T1"}, TargetSchema: "dst"}}, + wantError: "is not covered by any dispatch rule matcher", + }, + { + name: "unmatched schema route remains inactive", + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst"}, + {Matcher: []string{"SRC.*"}, TargetSchema: "src"}, + }, + }, + { + name: "schema target consistency preserves original spelling", + filterRules: []string{"src.*"}, + dispatch: []*config.DispatchRule{ + {Matcher: []string{"src.*"}, TargetSchema: "dst"}, + {Matcher: []string{"src.t1"}, TargetSchema: "DST"}, + }, + wantError: "different target-schema expressions", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.ChangefeedConfig{ + AllowSameCluster: true, + CaseSensitive: true, + Filter: &config.FilterConfig{Rules: tc.filterRules}, + SinkConfig: &config.SinkConfig{DispatchRules: tc.dispatch}, + } + err := ValidateSameClusterRouting(cfg) + if tc.wantError != "" { + require.ErrorContains(t, err, tc.wantError) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/pkg/config/changefeed.go b/pkg/config/changefeed.go index 281e8a2922..4faedeffbd 100644 --- a/pkg/config/changefeed.go +++ b/pkg/config/changefeed.go @@ -213,6 +213,7 @@ type ChangefeedConfig struct { // Epoch is the epoch of a changefeed, changes on every restart. Epoch uint64 `json:"epoch"` BDRMode bool `json:"bdr_mode" default:"false"` + AllowSameCluster bool `json:"allow_same_cluster" default:"false"` EnableActiveActive bool `json:"enable_active_active" default:"false"` ActiveActiveProgressInterval time.Duration `json:"active_active_progress_interval" default:"30m"` ActiveActiveSyncStatsInterval time.Duration `json:"active_active_sync_stats_interval" default:"1m"` @@ -316,6 +317,7 @@ func (info *ChangeFeedInfo) ToChangefeedConfig() *ChangefeedConfig { EventCollectorBatchBytes: info.Config.EventCollectorBatchBytes, Epoch: info.Epoch, BDRMode: util.GetOrZero(info.Config.BDRMode), + AllowSameCluster: util.GetOrZero(info.Config.AllowSameCluster), EnableActiveActive: util.GetOrZero(info.Config.EnableActiveActive), ActiveActiveProgressInterval: util.GetOrZero(info.Config.ActiveActiveProgressInterval), ActiveActiveSyncStatsInterval: util.GetOrZero(info.Config.ActiveActiveSyncStatsInterval), diff --git a/pkg/config/replica_config.go b/pkg/config/replica_config.go index 556e10cd94..37f96d527e 100644 --- a/pkg/config/replica_config.go +++ b/pkg/config/replica_config.go @@ -158,6 +158,11 @@ type replicaConfig struct { CaseSensitive *bool `toml:"case-sensitive" json:"case-sensitive,omitempty"` ForceReplicate *bool `toml:"force-replicate" json:"force-replicate,omitempty"` CheckGCSafePoint *bool `toml:"check-gc-safe-point" json:"check-gc-safe-point,omitempty"` + // AllowSameCluster allows the downstream to be the same TiDB logical cluster as the upstream. + // By default TiCDC rejects such a changefeed to avoid self-replication loops. Set it to true + // only when the changefeed cannot capture its own writes, for example when the downstream + // tables are not matched by the changefeed's filter. + AllowSameCluster *bool `toml:"allow-same-cluster" json:"allow-same-cluster,omitempty"` // EnableRedoIOCheck controls whether consistency storage validation should // perform an I/O accessibility check. This field is internal only. EnableRedoIOCheck *bool `toml:"-" json:"-"` diff --git a/pkg/config/replica_config_test.go b/pkg/config/replica_config_test.go index 7b8150f1e3..b66ae1c52a 100644 --- a/pkg/config/replica_config_test.go +++ b/pkg/config/replica_config_test.go @@ -18,6 +18,7 @@ import ( "testing" "time" + "github.com/BurntSushi/toml" "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/redo" "github.com/pingcap/ticdc/pkg/util" @@ -316,3 +317,24 @@ func TestReplicaConfig_EnableRedoIOCheck_CanDisableForCLI(t *testing.T) { require.NoError(t, err) require.NoError(t, config.ValidateAndAdjust(sinkURI)) } + +func TestReplicaConfig_AllowSameCluster(t *testing.T) { + t.Parallel() + + cfg := GetDefaultReplicaConfig() + require.Nil(t, cfg.AllowSameCluster) + + // `allow-same-cluster` is a top-level option of the changefeed config file. + metaData, err := toml.Decode("allow-same-cluster = true\n", cfg) + require.NoError(t, err) + require.Empty(t, metaData.Undecoded()) + require.True(t, util.GetOrZero(cfg.AllowSameCluster)) + + // Clone must keep the option, the config is cloned when it is converted to the API model. + require.True(t, util.GetOrZero(cfg.Clone().AllowSameCluster)) + + // The same upstream/downstream check runs on the ChangefeedConfig derived from the persisted + // replica config, so the option must survive the conversion to skip the check. + info := &ChangeFeedInfo{Config: cfg} + require.True(t, info.ToChangefeedConfig().AllowSameCluster) +} diff --git a/pkg/config/sink.go b/pkg/config/sink.go index 0c57d01a2f..6e396cc934 100644 --- a/pkg/config/sink.go +++ b/pkg/config/sink.go @@ -17,6 +17,7 @@ import ( "fmt" "net/url" "regexp" + "slices" "strconv" "strings" "time" @@ -809,6 +810,10 @@ func CheckUseTableIDAsPathCompatibility( } func (s *SinkConfig) validateAndAdjust(sinkURI *url.URL) error { + s.DispatchRules = slices.DeleteFunc(s.DispatchRules, func(rule *DispatchRule) bool { + return rule == nil + }) + if err := s.validateAndAdjustSinkURI(sinkURI); err != nil { return err } diff --git a/pkg/config/sink_test.go b/pkg/config/sink_test.go index dbb49cc0a2..b5a69f20ae 100644 --- a/pkg/config/sink_test.go +++ b/pkg/config/sink_test.go @@ -129,12 +129,22 @@ func TestValidateTxnAtomicity(t *testing.T) { } for _, tc := range testCases { - cfg := SinkConfig{} + cfg := SinkConfig{ + DispatchRules: []*DispatchRule{ + nil, + {Matcher: []string{"src.orders"}, DispatcherRule: "table"}, + nil, + {Matcher: []string{"src.customers"}, DispatcherRule: "table"}, + }, + } parsedSinkURI, err := url.Parse(tc.sinkURI) require.Nil(t, err) if tc.expectedErr == "" { require.Nil(t, cfg.validateAndAdjust(parsedSinkURI)) require.Equal(t, tc.shouldSplitTxn, util.GetOrZero(cfg.TxnAtomicity).ShouldSplitTxn()) + require.Len(t, cfg.DispatchRules, 2) + require.Equal(t, []string{"src.orders"}, cfg.DispatchRules[0].Matcher) + require.Equal(t, []string{"src.customers"}, cfg.DispatchRules[1].Matcher) } else { require.Regexp(t, tc.expectedErr, cfg.validateAndAdjust(parsedSinkURI)) } @@ -570,9 +580,16 @@ func TestValidateAndAdjustStorageConfig(t *testing.T) { sinkURI, err := url.Parse("s3://bucket?protocol=csv") require.NoError(t, err) s := GetDefaultReplicaConfig() + s.Sink.DispatchRules = []*DispatchRule{ + nil, + {Matcher: []string{"src.*"}, DispatcherRule: "table"}, + nil, + } err = s.ValidateAndAdjust(sinkURI) require.NoError(t, err) require.Equal(t, DefaultFileIndexWidth, util.GetOrZero(s.Sink.FileIndexWidth)) + require.Len(t, s.Sink.DispatchRules, 1) + require.Equal(t, "table", s.Sink.DispatchRules[0].PartitionRule) err = s.ValidateAndAdjust(sinkURI) require.NoError(t, err) diff --git a/pkg/routing/router.go b/pkg/routing/router.go index 175c431f79..f5470ab4f7 100644 --- a/pkg/routing/router.go +++ b/pkg/routing/router.go @@ -118,7 +118,7 @@ func NewRouter( ) (Router, error) { routingRules := make([]rule, 0, len(rules)) for _, r := range rules { - if r.TargetSchema == "" && r.TargetTable == "" { + if r == nil || (r.TargetSchema == "" && r.TargetTable == "") { continue } diff --git a/pkg/routing/router_test.go b/pkg/routing/router_test.go index 2bc7b029bd..a17510beb2 100644 --- a/pkg/routing/router_test.go +++ b/pkg/routing/router_test.go @@ -136,6 +136,21 @@ func TestNewRouter(t *testing.T) { require.Empty(t, router.rules) }) + t.Run("nil rules are skipped", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + nil, + { + Matcher: []string{"db1.*"}, + TargetSchema: "archive", + TargetTable: TablePlaceholder, + }, + }) + require.NoError(t, err) + require.Len(t, router.rules, 1) + }) + t.Run("invalid matcher returns error", func(t *testing.T) { t.Parallel() diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster.toml new file mode 100644 index 0000000000..fd6ef75786 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster.toml @@ -0,0 +1,22 @@ +# This changefeed writes to the upstream cluster itself, which is only allowed because +# `allow-same-cluster` is set. +# +# Both source ranges route to databases outside the filter, including future schemas. +allow-same-cluster = true +case-sensitive = false + +[filter] +# Rule padding must be ignored; target names must be compared case insensitively. +rules = [" \tallow_same_cluster_src.*\t ", "isolation_src*.*"] + +[sink] +[[sink.dispatchers]] +matcher = ["\tallow_same_cluster_src.* "] +target-schema = 'ALLOW_SAME_CLUSTER_DST' +target-table = '{table}_ROUTED' + +# Cover derived names and database DDL for schemas created after the changefeed. +[[sink.dispatchers]] +matcher = ['isolation_src*.*'] +target-schema = 'copy_{schema}' +target-table = '{table}_routed' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_all_schemas.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_all_schemas.toml new file mode 100644 index 0000000000..4bfdd6e3bd --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_all_schemas.toml @@ -0,0 +1,9 @@ +allow-same-cluster = true + +[filter] +rules = ['*.t1'] + +[[sink.dispatchers]] +matcher = ['*.t1'] +target-schema = '{schema}_backup' +target-table = 't1_copy' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_case_sensitive.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_case_sensitive.toml new file mode 100644 index 0000000000..bd886eea97 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_case_sensitive.toml @@ -0,0 +1,9 @@ +allow-same-cluster = true +case-sensitive = true + +[filter] +rules = ['allow_same_cluster_src.*'] + +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.*'] +target-schema = 'ALLOW_SAME_CLUSTER_SRC' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_narrow_route.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_narrow_route.toml new file mode 100644 index 0000000000..f6af1604b4 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_narrow_route.toml @@ -0,0 +1,11 @@ +# The matcher is narrower than the filter rule, so tables of `allow_same_cluster_src` other than +# `t1` would keep their own name. This changefeed must be rejected. +allow-same-cluster = true + +[filter] +rules = ['allow_same_cluster_src.*'] + +[sink] +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.t1'] +target-schema = 'allow_same_cluster_dst' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_no_route.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_no_route.toml new file mode 100644 index 0000000000..a10419d686 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_no_route.toml @@ -0,0 +1,10 @@ +# `allow-same-cluster` is only allowed together with table routing, so this changefeed must be +# rejected before it is created. +allow-same-cluster = true + +[filter] +rules = ['allow_same_cluster_src.*'] + +# Updates merge into the existing config; explicitly remove the previous routes. +[sink] +dispatchers = [] diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_same_schema.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_same_schema.toml new file mode 100644 index 0000000000..1fe44c4393 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_same_schema.toml @@ -0,0 +1,11 @@ +allow-same-cluster = true +case-sensitive = false + +# Rule padding must not hide a target database inside the source range. +[filter] +rules = [" \tallow_same_cluster_src.t1\t "] + +[[sink.dispatchers]] +matcher = [" \tallow_same_cluster_src.t1\t "] +target-schema = 'ALLOW_SAME_CLUSTER_SRC' +target-table = 'T1_COPY' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_schema_ambiguity.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_schema_ambiguity.toml new file mode 100644 index 0000000000..fbce36cbce --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_schema_ambiguity.toml @@ -0,0 +1,14 @@ +allow-same-cluster = true + +[filter] +rules = ['allow_same_cluster_src.t1', 'allow_same_cluster_src.t2'] + +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.t1'] +target-schema = 'allow_same_cluster_dst' +target-table = 't1' + +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.t2'] +target-schema = 'allow_same_cluster_dst2' +target-table = 't2' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_source_schema_chain.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_source_schema_chain.toml new file mode 100644 index 0000000000..3b20215867 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_source_schema_chain.toml @@ -0,0 +1,15 @@ +allow-same-cluster = true +case-sensitive = false + +[filter] +rules = ['allow_same_cluster_src.t1', 'allow_same_cluster_src_copy.t2'] + +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.t1'] +target-schema = '{schema}_COPY' +target-table = 't1_copy' + +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src_copy.t2'] +target-schema = 'allow_same_cluster_third' +target-table = 't2_copy' diff --git a/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_unsupported.toml b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_unsupported.toml new file mode 100644 index 0000000000..73184114b4 --- /dev/null +++ b/tests/integration_tests/same_upstream_downstream/conf/allow_same_cluster_unsupported.toml @@ -0,0 +1,11 @@ +# Negated filter rules are not supported together with `allow-same-cluster`, so this configuration +# must be rejected instead of being approximated. +allow-same-cluster = true + +[filter] +rules = ['allow_same_cluster_src.*', '!allow_same_cluster_src.t1'] + +[sink] +[[sink.dispatchers]] +matcher = ['allow_same_cluster_src.*'] +target-schema = 'allow_same_cluster_dst' diff --git a/tests/integration_tests/same_upstream_downstream/run.sh b/tests/integration_tests/same_upstream_downstream/run.sh index e8d126e45f..02c77968cc 100644 --- a/tests/integration_tests/same_upstream_downstream/run.sh +++ b/tests/integration_tests/same_upstream_downstream/run.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Verify TiCDC rejects using the same TiDB cluster as both upstream and downstream. +# Verify same-cluster replication requires database isolation. set -eu @@ -22,11 +22,14 @@ function run() { run_cdc_server --workdir $WORK_DIR --binary $CDC_BINARY UP_SINK_URI="mysql://root@${UP_TIDB_HOST}:${UP_TIDB_PORT}/" + UP_PD_ENDPOINT="http://${UP_PD_HOST_1}:${UP_PD_PORT_1}" DOWN_SINK_URI="mysql://root@${DOWN_TIDB_HOST}:${DOWN_TIDB_PORT}/" - UP_PD_ENDPOINTS="${UP_PD_HOST_1}:${UP_PD_PORT_1}" # 1) Create should be rejected when sink points to upstream cluster. - result=$(cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" -c "same-up-down-create" 2>&1 || true) + if result=$(cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" -c "same-up-down-create" 2>&1); then + echo "Expected changefeed operation to be rejected, got: $result" + exit 1 + fi if [[ "$result" != *"CDC:ErrSameUpstreamDownstream"* ]] || [[ "$result" != *"creating a changefeed"* ]]; then echo "Expected create to fail with ErrSameUpstreamDownstream, got:" echo "$result" @@ -37,27 +40,157 @@ function run() { changefeed_id="same-up-down" cdc_cli_changefeed create --sink-uri="$DOWN_SINK_URI" -c "$changefeed_id" cdc_cli_changefeed pause -c "$changefeed_id" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$changefeed_id" "stopped" "null" "" - result=$(cdc_cli_changefeed update -c "$changefeed_id" --sink-uri="$UP_SINK_URI" --no-confirm 2>&1 || true) + if result=$(cdc_cli_changefeed update -c "$changefeed_id" --sink-uri="$UP_SINK_URI" --no-confirm 2>&1); then + echo "Expected changefeed operation to be rejected, got: $result" + exit 1 + fi if [[ "$result" != *"CDC:ErrSameUpstreamDownstream"* ]] || [[ "$result" != *"updating a changefeed"* ]]; then echo "Expected update to fail with ErrSameUpstreamDownstream, got:" echo "$result" exit 1 fi - # 3) Resume should be rejected even if the sink URI is modified via etcd directly (e.g. legacy metadata). - info_key="/tidb/cdc/default/$KEYSPACE_NAME/changefeed/info/$changefeed_id" - info_value=$(ETCDCTL_API=3 etcdctl --endpoints="$UP_PD_ENDPOINTS" get "$info_key" --print-value-only) - new_info_value=$(echo "$info_value" | jq -c --arg uri "$UP_SINK_URI" '.["sink-uri"]=$uri') - ETCDCTL_API=3 etcdctl --endpoints="$UP_PD_ENDPOINTS" put "$info_key" "$new_info_value" + cdc_cli_changefeed remove -c "$changefeed_id" + + wait_for_rows() { + local expected=$1 table=$2 count=0 + for _ in $(seq 1 60); do + count=$(mysql -h"$UP_TIDB_HOST" -P"$UP_TIDB_PORT" -uroot -N \ + -e "select count(*) from $table" 2>/dev/null || echo 0) + if [ "$count" == "$expected" ]; then + return 0 + fi + sleep 2 + done + echo "Expected $expected rows in $table of the upstream cluster, got: $count" + return 1 + } + + # 3) Create is allowed when the changefeed config sets `allow-same-cluster`, as long as the + # changefeed cannot capture its own writes. The sink writes into the upstream cluster, but + # table routing maps the source table into another schema, which is not matched by the filter. + allow_same_cluster_id="allow-same-cluster" + src_db="allow_same_cluster_src" + dst_db="allow_same_cluster_dst" + dst_table="t1_routed" + run_sql "create database $src_db;" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + run_sql "create database $dst_db;" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + run_sql "create table $src_db.t1 (id int primary key, v varchar(16));" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + run_sql "create table $dst_db.$dst_table (id int primary key, v varchar(16));" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + + # Exercise TiDB identifier lookup: an uppercase target writes into the lowercase + # source database even when the TiCDC filter is case sensitive. + lower_case_table_names=$(mysql -h"$UP_TIDB_HOST" -P"$UP_TIDB_PORT" -uroot -N \ + -e "select @@lower_case_table_names") + if [ "$lower_case_table_names" != "2" ]; then + echo "Expected TiDB lower_case_table_names=2, got: $lower_case_table_names" + exit 1 + fi + run_sql "insert into ALLOW_SAME_CLUSTER_SRC.t1 values (0, 'case_alias');" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_rows 1 "$src_db.t1" + run_sql "delete from $src_db.t1 where id = 0;" "$UP_TIDB_HOST" "$UP_TIDB_PORT" - result=$(cdc_cli_changefeed resume -c "$changefeed_id" 2>&1 || true) - if [[ "$result" != *"CDC:ErrSameUpstreamDownstream"* ]] || [[ "$result" != *"resuming a changefeed"* ]]; then - echo "Expected resume to fail with ErrSameUpstreamDownstream, got:" + result=$(cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" \ + --config="$CUR/conf/allow_same_cluster.toml" -c "$allow_same_cluster_id" 2>&1) + if [[ "$result" != *"Create changefeed successfully"* ]]; then + echo "Expected create to be allowed with allow-same-cluster, got:" echo "$result" exit 1 fi + run_sql "insert into $src_db.t1 values (1, 'a'), (2, 'b');" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + + wait_for_rows 2 "$dst_db.$dst_table" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "normal" "null" "" + + # Keep data in another source database while rejecting routes that would endanger it. + run_sql "create database allow_same_cluster_src_copy; create table allow_same_cluster_src_copy.t2 (id int primary key); insert into allow_same_cluster_src_copy.t2 values (1);" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + # Create and update must reject database overlap and ambiguous schema routing. + cdc_cli_changefeed pause -c "$allow_same_cluster_id" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "stopped" "null" "" + for unsafe_case in same_schema case_sensitive source_schema_chain all_schemas schema_ambiguity no_route narrow_route unsupported; do + expected_error="which the filter replicates" + case "$unsafe_case" in + schema_ambiguity) expected_error="different target-schema expressions" ;; + no_route) expected_error="requires table routing to be enabled" ;; + narrow_route) expected_error="is not covered by any dispatch rule matcher" ;; + unsupported) expected_error="does not support the filter rule" ;; + esac + unsafe_config="$CUR/conf/allow_same_cluster_${unsafe_case}.toml" + if result=$(cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" \ + --config="$unsafe_config" -c "reject-${unsafe_case//_/-}" 2>&1); then + echo "Unexpected create success for $unsafe_case: $result" + exit 1 + fi + if [[ "$result" != *"CDC:ErrInvalidReplicaConfig"* ]] || [[ "$result" != *"$expected_error"* ]]; then + echo "Expected create to reject $unsafe_case, got: $result" + exit 1 + fi + # Each update case starts from the same valid config on its own changefeed. + update_case_id="update-reject-${unsafe_case//_/-}" + cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" \ + --config="$CUR/conf/allow_same_cluster.toml" -c "$update_case_id" + cdc_cli_changefeed pause -c "$update_case_id" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$update_case_id" "stopped" "null" "" + if result=$(cdc_cli_changefeed update -c "$update_case_id" \ + --config="$unsafe_config" --no-confirm 2>&1); then + echo "Unexpected update success for $unsafe_case: $result" + exit 1 + fi + if [[ "$result" != *"CDC:ErrInvalidReplicaConfig"* ]] || [[ "$result" != *"$expected_error"* ]]; then + echo "Expected update to reject $unsafe_case, got: $result" + exit 1 + fi + cdc_cli_changefeed remove -c "$update_case_id" + done + wait_for_rows 1 "allow_same_cluster_src_copy.t2" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "stopped" "null" "" + # Resume the original changefeed, whose configuration was not updated by the rejection cases. + cdc_cli_changefeed resume -c "$allow_same_cluster_id" + run_sql "insert into $src_db.t1 values (3, 'c');" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_rows 3 "$dst_db.$dst_table" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "normal" "null" "" + + # 4) The same configuration also routes future databases and derived table names. + run_sql "create database isolation_src_future character set utf8mb4 collate utf8mb4_general_ci; create table isolation_src_future.t1 (id int primary key);" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + check_table_exists "copy_isolation_src_future.t1_routed" "$UP_TIDB_HOST" "$UP_TIDB_PORT" 90 + run_sql "insert into isolation_src_future.t1 values (1);" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_rows 1 "copy_isolation_src_future.t1_routed" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "normal" "null" "" + run_sql "alter database isolation_src_future collate utf8mb4_bin;" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_schema_count() { + local expected=$1 predicate=$2 count=0 + for _ in $(seq 1 60); do + count=$(mysql -h"$UP_TIDB_HOST" -P"$UP_TIDB_PORT" -uroot -N \ + -e "select count(*) from information_schema.schemata where schema_name='copy_isolation_src_future' $predicate") + if [ "$count" == "$expected" ]; then + return 0 + fi + sleep 2 + done + echo "Expected schema count $expected ($predicate), got: $count" + return 1 + } + wait_for_schema_count 1 "and default_collation_name='utf8mb4_bin'" + run_sql "drop database isolation_src_future;" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_schema_count 0 "" + wait_for_rows 3 "$src_db.t1" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$allow_same_cluster_id" "normal" "null" "" + wait_for_rows 1 "allow_same_cluster_src_copy.t2" + cdc_cli_changefeed remove -c "$allow_same_cluster_id" + + # Case sensitive filtering still permits routes into a separate schema. + case_sensitive_id="allow-same-cluster-case-sensitive" + sed 's/case-sensitive = false/case-sensitive = true/' "$CUR/conf/allow_same_cluster.toml" >"$WORK_DIR/case_sensitive_safe.toml" + cdc_cli_changefeed create --sink-uri="$UP_SINK_URI" \ + --config="$WORK_DIR/case_sensitive_safe.toml" -c "$case_sensitive_id" + run_sql "insert into $src_db.t1 values (4, 'd');" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + wait_for_rows 4 "$dst_db.$dst_table" + ensure 30 check_changefeed_state "$UP_PD_ENDPOINT" "$case_sensitive_id" "normal" "null" "" + cdc_cli_changefeed remove -c "$case_sensitive_id" + cleanup_process $CDC_BINARY }