github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/cdc/kv/regionlock/utils.go (about) 1 // Copyright 2020 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package regionlock 15 16 import ( 17 "sort" 18 19 "github.com/pingcap/kvproto/pkg/metapb" 20 "github.com/pingcap/tiflow/cdc/processor/tablepb" 21 "github.com/pingcap/tiflow/pkg/spanz" 22 ) 23 24 // CheckRegionsLeftCover checks whether the regions cover the left part of given span 25 func CheckRegionsLeftCover(regions []*metapb.Region, span tablepb.Span) bool { 26 subRegions := CutRegionsLeftCoverSpan(regions, span) 27 return len(regions) > 0 && len(subRegions) == len(regions) 28 } 29 30 // CutRegionsLeftCoverSpan processes a list of regions to remove those that 31 // do not cover the specified span or are discontinuous with the previous region. 32 // It returns a new slice containing only the continuous regions that cover the span. 33 func CutRegionsLeftCoverSpan(regions []*metapb.Region, spanToCover tablepb.Span) []*metapb.Region { 34 if len(regions) == 0 { 35 return nil 36 } 37 38 sort.Slice(regions, func(i, j int) bool { 39 return spanz.StartCompare(regions[i].StartKey, regions[j].StartKey) == -1 40 }) 41 42 // If the start key of the first region is after the span's start key, 43 // no regions cover the span, return nil. 44 if spanz.StartCompare(regions[0].StartKey, spanToCover.StartKey) == 1 { 45 return nil 46 } 47 48 nextStartKey := regions[0].StartKey 49 for i, region := range regions { 50 // If find discontinuous, return the regions up to the current index. 51 if spanz.StartCompare(nextStartKey, region.StartKey) != 0 { 52 return regions[:i] 53 } 54 nextStartKey = region.EndKey 55 } 56 return regions 57 }