Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ public final class RuleConstant {
public static final int CONTROL_BEHAVIOR_WARM_UP = 1;
public static final int CONTROL_BEHAVIOR_RATE_LIMITER = 2;
public static final int CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER = 3;
/**
* User-defined control behavior values MUST be >= 256 (0x100)
*/
public static final int CONTROL_BEHAVIOR_USER_DEFINED_MIN = 0x100; // 256

public static final int DEFAULT_BLOCK_STRATEGY = 0;
public static final int TRY_AGAIN_BLOCK_STRATEGY = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,18 @@
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.RuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController;
import com.alibaba.csp.sentinel.slots.block.flow.controller.ThrottlingController;
import com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController;
import com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpRateLimiterController;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.csp.sentinel.util.function.Function;
import com.alibaba.csp.sentinel.util.function.Predicate;

import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
Expand Down Expand Up @@ -132,18 +135,9 @@ public static <K> Map<K, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, F

private static TrafficShapingController generateRater(/*@Valid*/ FlowRule rule) {
if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS) {
switch (rule.getControlBehavior()) {
case RuleConstant.CONTROL_BEHAVIOR_WARM_UP:
return new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(),
ColdFactorProperty.coldFactor);
case RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER:
return new ThrottlingController(rule.getMaxQueueingTimeMs(), rule.getCount());
case RuleConstant.CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER:
return new WarmUpRateLimiterController(rule.getCount(), rule.getWarmUpPeriodSec(),
rule.getMaxQueueingTimeMs(), ColdFactorProperty.coldFactor);
case RuleConstant.CONTROL_BEHAVIOR_DEFAULT:
default:
// Default mode or unknown mode: default traffic shaping controller (fast-reject).
TrafficShapingControllerFactory trafficShapingControllerFactory = TrafficShapingControllerFactories.get(rule.getControlBehavior());
if (trafficShapingControllerFactory != null) {
return trafficShapingControllerFactory.create(rule);
}
}
return new DefaultController(rule.getCount(), rule.getGrade());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow;

import com.alibaba.csp.sentinel.log.RecordLog;

import java.util.Objects;

public class LoggingTrafficShapingControllerFactory implements TrafficShapingControllerFactory {

private final TrafficShapingControllerFactory delegate;

public LoggingTrafficShapingControllerFactory(TrafficShapingControllerFactory delegate) {
this.delegate = Objects.requireNonNull(delegate, "delegate must be not null.");
}

@Override
public TrafficShapingController create(FlowRule rule) {
RecordLog.debug("Creating traffic shaping controller '" + delegate.getClass().getName() + "' for rule: " + rule);
return delegate.create(rule);
}

@Override
public int getControlBehavior() {
return delegate.getControlBehavior();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow;

import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.spi.SpiLoader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class TrafficShapingControllerFactories {

private static final Map<Integer, TrafficShapingControllerFactory> FACTORIES;

static {
FACTORIES = initFactories();
}

/**
* Using existing factory if the factory with the same control behavior already exists, because the existing factory has higher priority
*/
private static BinaryOperator<TrafficShapingControllerFactory> usingExisting() {
return (existing, replacement) -> {
RecordLog.warn("[TrafficShapingControllerFactories] Duplicate control behavior [{}], " +
"using existing factory [{}], ignoring [{}]",
existing.getControlBehavior(),
existing.getClass().getName(),
replacement.getClass().getName());
return existing;
};
}

private static TrafficShapingControllerFactory logging(TrafficShapingControllerFactory factory) {
return new LoggingTrafficShapingControllerFactory(factory);
}

/**
* Validates the control behavior namespace of a factory.
*/
private static void validateControlBehavior(TrafficShapingControllerFactory factory) {
int controlBehavior = factory.getControlBehavior();

// User-defined factories must not use reserved range [0, 255]
if (!factory.isBuiltIn() && isReservedControlBehavior(controlBehavior)) {
throw new IllegalArgumentException(String.format(
"Invalid control behavior [%d] for factory [%s]. " +
"Control behavior values in range [0, %d] are reserved for Sentinel built-in implementations. " +
"User-defined factories must use values >= %d to ensure compatibility with future Sentinel upgrades.",
controlBehavior,
factory.getClass().getName(),
RuleConstant.CONTROL_BEHAVIOR_USER_DEFINED_MIN - 1,
RuleConstant.CONTROL_BEHAVIOR_USER_DEFINED_MIN));
}

RecordLog.info("[TrafficShapingControllerFactories] Registered factory [{}] for control behavior [{}]",
factory.getClass().getName(), controlBehavior);
}

private static Map<Integer, TrafficShapingControllerFactory> initFactories() {
List<TrafficShapingControllerFactory> factories = SpiLoader.of(TrafficShapingControllerFactory.class)
.loadInstanceListSorted();
// Validate all factories
for (TrafficShapingControllerFactory factory : factories) {
validateControlBehavior(factory);
}
return factories.stream()
.collect(Collectors.toMap(
TrafficShapingControllerFactory::getControlBehavior,
TrafficShapingControllerFactories::logging,
usingExisting(),
HashMap::new));
}

public static TrafficShapingControllerFactory get(int controlBehavior) {
return FACTORIES.get(controlBehavior);
}

private TrafficShapingControllerFactories() {
}

public static boolean isReservedControlBehavior(int controlBehavior) {
return controlBehavior < RuleConstant.CONTROL_BEHAVIOR_USER_DEFINED_MIN;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow;

/**
* a factory interface to create TrafficShapingController instance
*/
public interface TrafficShapingControllerFactory {

/**
* create a TrafficShapingController instance
* @param rule flow rule
* @return a new TrafficShapingController instance
*/
TrafficShapingController create(FlowRule rule);

/**
* get the factory control behavior
* @return the control behavior
*/
int getControlBehavior();

/**
* Indicates whether this factory is a built-in Sentinel implementation.
* Built-in factories are allowed to use control behavior values in the reserved range [0, 255].
* User-defined factories should return {@code false} (default) and use values >= 256.
*
* This method is used internally for validation during factory registration to ensure
* proper namespace separation and prevent conflicts.
*
* @return {@code true} if this is a Sentinel built-in factory, {@code false} for user-defined implementations
*/
default boolean isBuiltIn() {
return false;
}
Comment on lines +36 to +48
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think built in impl could be override and improve by user, it seems no need to limit

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think built in impl could be override and improve by user, it seems no need to limit

The main point here is to give a light warning—keeping it flexible while still notifying the user.

For instance, the default is false (not built-in). If a user forces the override, it means they are aware of the warning and its consequences.

Thought process:
I spent a lot of time thinking about this. As a beginner, without any restrictions or warnings, maintaining and ensuring compatibility down the line could be a real challenge. I considered three options:

  1. Fully open: great flexibility, but tough to maintain and keep compatible.

  2. Light restriction (this one): default false, can still be overridden. ☑️

  3. Fully restricted: only custom interfaces with strict enforcement, but might limit third-party flexibility and design.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow.controller;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingControllerFactory;

public class DefaultControllerFactory implements TrafficShapingControllerFactory {

@Override
public TrafficShapingController create(FlowRule rule) {
return new DefaultController(rule.getCount(), rule.getGrade());
}

@Override
public int getControlBehavior() {
return RuleConstant.CONTROL_BEHAVIOR_DEFAULT;
}

@Override
public boolean isBuiltIn() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow.controller;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingControllerFactory;

public class ThrottlingControllerFactory implements TrafficShapingControllerFactory {

@Override
public TrafficShapingController create(FlowRule rule) {
return new ThrottlingController(rule.getMaxQueueingTimeMs(), rule.getCount());
}

@Override
public int getControlBehavior() {
return RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER;
}

@Override
public boolean isBuiltIn() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.slots.block.flow.controller;

import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController;
import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingControllerFactory;

public class WarmUpControllerFactory implements TrafficShapingControllerFactory {

static volatile int coldFactor = SentinelConfig.coldFactor();

@Override
public TrafficShapingController create(FlowRule rule) {
return new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(), coldFactor);
}

@Override
public int getControlBehavior() {
return RuleConstant.CONTROL_BEHAVIOR_WARM_UP;
}

@Override
public boolean isBuiltIn() {
return true;
}
}
Loading
Loading