vitess.io/vitess@v0.16.2/go/vt/throttler/max_rate_module.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package throttler
    18  
    19  import (
    20  	"vitess.io/vitess/go/sync2"
    21  )
    22  
    23  // MaxRateModule allows to set and retrieve a maximum rate limit.
    24  // It implements the Module interface.
    25  type MaxRateModule struct {
    26  	maxRate        sync2.AtomicInt64
    27  	rateUpdateChan chan<- struct{}
    28  }
    29  
    30  // NewMaxRateModule will create a new module instance and set the initial
    31  // rate limit to maxRate.
    32  func NewMaxRateModule(maxRate int64) *MaxRateModule {
    33  	return &MaxRateModule{
    34  		maxRate: sync2.NewAtomicInt64(maxRate),
    35  	}
    36  }
    37  
    38  // Start currently does nothing. It implements the Module interface.
    39  func (m *MaxRateModule) Start(rateUpdateChan chan<- struct{}) {
    40  	m.rateUpdateChan = rateUpdateChan
    41  }
    42  
    43  // Stop currently does nothing. It implements the Module interface.
    44  func (m *MaxRateModule) Stop() {}
    45  
    46  // MaxRate returns the current maximum allowed rate.
    47  func (m *MaxRateModule) MaxRate() int64 {
    48  	return m.maxRate.Get()
    49  }
    50  
    51  // SetMaxRate sets the current max rate and notifies the throttler about the
    52  // rate update.
    53  func (m *MaxRateModule) SetMaxRate(rate int64) {
    54  	m.maxRate.Set(rate)
    55  	m.rateUpdateChan <- struct{}{}
    56  }