github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/lightning/backend/kv/allocator.go (about)

     1  // Copyright 2019 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  // TODO combine with the pkg/kv package outside.
    15  
    16  package kv
    17  
    18  import (
    19  	"sync/atomic"
    20  
    21  	"github.com/pingcap/tidb/meta/autoid"
    22  )
    23  
    24  // panickingAllocator is an ID allocator which panics on all operations except Rebase
    25  type panickingAllocator struct {
    26  	autoid.Allocator
    27  	base *int64
    28  	ty   autoid.AllocatorType
    29  }
    30  
    31  // NewPanickingAllocator creates a PanickingAllocator shared by all allocation types.
    32  func NewPanickingAllocators(base int64) autoid.Allocators {
    33  	sharedBase := &base
    34  	return autoid.NewAllocators(
    35  		&panickingAllocator{base: sharedBase, ty: autoid.RowIDAllocType},
    36  		&panickingAllocator{base: sharedBase, ty: autoid.AutoIncrementType},
    37  		&panickingAllocator{base: sharedBase, ty: autoid.AutoRandomType},
    38  	)
    39  }
    40  
    41  // Rebase implements the autoid.Allocator interface
    42  func (alloc *panickingAllocator) Rebase(tableID, newBase int64, allocIDs bool) error {
    43  	// CAS
    44  	for {
    45  		oldBase := atomic.LoadInt64(alloc.base)
    46  		if newBase <= oldBase {
    47  			break
    48  		}
    49  		if atomic.CompareAndSwapInt64(alloc.base, oldBase, newBase) {
    50  			break
    51  		}
    52  	}
    53  	return nil
    54  }
    55  
    56  // Base implements the autoid.Allocator interface
    57  func (alloc *panickingAllocator) Base() int64 {
    58  	return atomic.LoadInt64(alloc.base)
    59  }
    60  
    61  func (alloc *panickingAllocator) GetType() autoid.AllocatorType {
    62  	return alloc.ty
    63  }