1 package io.getunleash.strategy;
2
3 import io.getunleash.UnleashContext;
4 import java.util.Map;
5 import java.util.Optional;
6
7 /**
8  * Implements a gradual roll-out strategy based on userId.
9  *
10  * <p>Using this strategy you can target only logged in users and gradually expose your feature to
11  * higher percentage of the logged in user.
12  *
13  * <p>This strategy takes two parameters: - percentage : a number between 0 and 100. The percentage
14  * you want to enable the feature for. - groupId : a groupId used for rolling out the feature. By
15  * using the same groupId for different toggles you can correlate the user experience across
16  * toggles.
17  */

18 public final class GradualRolloutUserIdStrategy implements Strategy {
19     protected static final String PERCENTAGE = "percentage";
20     protected static final String GROUP_ID = "groupId";
21
22     private static final String NAME = "gradualRolloutUserId";
23
24     @Override
25     public String getName() {
26         return NAME;
27     }
28
29     @Override
30     public boolean isEnabled(Map<String, String> parameters) {
31         return false;
32     }
33
34     @Override
35     public boolean isEnabled(final Map<String, String> parameters, UnleashContext unleashContext) {
36         Optional<String> userId = unleashContext.getUserId();
37
38         if (!userId.isPresent()) {
39             return false;
40         }
41
42         final int percentage = StrategyUtils.getPercentage(parameters.get(PERCENTAGE));
43         final String groupId = parameters.getOrDefault(GROUP_ID, "");
44
45         final int normalizedUserId = StrategyUtils.getNormalizedNumber(userId.get(), groupId, 0);
46
47         return percentage > 0 && normalizedUserId <= percentage;
48     }
49 }
50