github.com/polarismesh/polaris@v1.17.8/plugin/ratelimit.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package plugin
    19  
    20  import (
    21  	"os"
    22  	"sync"
    23  )
    24  
    25  // RatelimitType rate limit type
    26  type RatelimitType int
    27  
    28  const (
    29  	// IPRatelimit Based on IP flow control
    30  	IPRatelimit RatelimitType = iota + 1
    31  
    32  	// APIRatelimit Based on interface-level flow control
    33  	APIRatelimit
    34  
    35  	// ServiceRatelimit Based on Service flow control
    36  	ServiceRatelimit
    37  
    38  	// InstanceRatelimit Based on Instance flow control
    39  	InstanceRatelimit
    40  )
    41  
    42  // RatelimitStr rate limit string map
    43  var RatelimitStr = map[RatelimitType]string{
    44  	IPRatelimit:       "ip-limit",
    45  	APIRatelimit:      "api-limit",
    46  	ServiceRatelimit:  "service-limit",
    47  	InstanceRatelimit: "instance-limit",
    48  }
    49  
    50  var (
    51  	rateLimitOnce sync.Once
    52  )
    53  
    54  // Ratelimit Ratelimit plugin interface
    55  type Ratelimit interface {
    56  	Plugin
    57  
    58  	// Allow Whether to allow access, true: allow, FALSE: not allowing Todo
    59  	// - Parameter ratingype is the type of current limits, and the ID is the key that limits the current
    60  	// - If RateType is Ratelimitip, the ID is IP, RateType is Ratelimitservice, and the ID is
    61  	//  IP_NAMESPACE_SERVICE or IP_SERVICEID
    62  	Allow(typ RatelimitType, key string) bool
    63  }
    64  
    65  // GetRatelimit Get the Ratelimit plugin
    66  func GetRatelimit() Ratelimit {
    67  	c := &config.RateLimit
    68  
    69  	plugin, exist := pluginSet[c.Name]
    70  	if !exist {
    71  		return nil
    72  	}
    73  
    74  	rateLimitOnce.Do(func() {
    75  		if err := plugin.Initialize(c); err != nil {
    76  			log.Errorf("Ratelimit plugin init err: %s", err.Error())
    77  			os.Exit(-1)
    78  		}
    79  	})
    80  	return plugin.(Ratelimit)
    81  }