github.com/kubevela/workflow@v0.6.0/pkg/providers/http/ratelimiter/ratelimiter.go (about)

     1  /*
     2  Copyright 2022 The KubeVela 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 ratelimiter
    18  
    19  import (
    20  	"time"
    21  
    22  	"github.com/golang/groupcache/lru"
    23  	"golang.org/x/time/rate"
    24  )
    25  
    26  // RateLimiter is the rate limiter.
    27  type RateLimiter struct {
    28  	store *lru.Cache
    29  }
    30  
    31  // NewRateLimiter returns a new rate limiter.
    32  func NewRateLimiter(len int) *RateLimiter {
    33  	store := lru.New(len)
    34  	store.Clear()
    35  	return &RateLimiter{store: store}
    36  }
    37  
    38  // Allow returns true if the operation is allowed.
    39  func (rl *RateLimiter) Allow(id string, limit int, duration time.Duration) bool {
    40  	if l, ok := rl.store.Get(id); ok {
    41  		limiter := l.(*rate.Limiter)
    42  		if limiter.Limit() == rate.Every(duration) && limiter.Burst() == limit {
    43  			return limiter.Allow()
    44  		}
    45  	}
    46  	limiter := rate.NewLimiter(rate.Every(duration), limit)
    47  	rl.store.Add(id, limiter)
    48  	return limiter.Allow()
    49  }