-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPricingContext.java
More file actions
292 lines (249 loc) · 11.4 KB
/
PricingContext.java
File metadata and controls
292 lines (249 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package io.github.isagroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.error.YAMLException;
import io.github.isagroup.exceptions.PricingPlanEvaluationException;
import io.github.isagroup.models.PricingManager;
import io.github.isagroup.models.UsageLimit;
import io.github.isagroup.services.yaml.YamlUtils;
import io.github.isagroup.models.AddOn;
import io.github.isagroup.models.Feature;
import io.github.isagroup.models.Plan;
/**
* An abstract class from which create a component that adapt the pricing
* configuration to the application domain
*/
@Component
public abstract class PricingContext {
private static final Logger logger = LoggerFactory.getLogger(PricingContext.class);
/**
* Returns the path to the Pricing2Yaml configuration file. The {@link String}
* path given to the implementation of this method should point to a
* Pricing2Yaml file under {@code resources} folder.
*
* @return a path as {@link String} to a Pricing2Yaml configuration file
* relative to the {@code resources} folder
*/
public abstract String getConfigFilePath();
/**
* Returns the secret used to sign the pricing JWT. The secret key needs to be
* encoded in {@code base64}. Internally JWT library will choose the best
* algorithm to sign the JWT ({@code HS256}, {@code HS384} or {@code HS512}), if
* the secret key bit length does not conform to the minimun stated by these
* algorithms will throw a {@link io.jsonwebtoken.security.WeakKeyException}
*
* @return a pricing secret encoded in {@code base64}
* @see <a href=
* "https://github.com/jwtk/jjwt#signature-algorithms-keys">Signature
* Algorithm Keys</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc7518#section-3.2">HMAC
* with SHA-2 Functions</a>
*/
public abstract String getJwtSecret();
/**
* Returns the secret used to sign the authorization JWT. The secret key needs
* to be encoded in {@code base64}. Internally JWT library will choose the best
* algorithm to sign the JWT ({@code HS256}, {@code HS384} or {@code HS512}), if
* the secret key bit length does not conform to the minimun stated by these
* algorithms will throw a {@link io.jsonwebtoken.security.WeakKeyException}
*
* @return a pricing secret encoded in {@code base64}
* @see <a href=
* "https://github.com/jwtk/jjwt#signature-algorithms-keys">Signature
* Algorithm Keys</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc7518#section-3.2">HMAC
* with SHA-2 Functions</a>
*/
public String getAuthJwtSecret() {
return this.getJwtSecret();
}
/**
* Returns the expiration time of the JWT in milliseconds
*
* @return JWT expiration time in milliseconds
*/
public int getJwtExpiration() {
return 86400000;
}
/**
* This method can be used to determine which users are affected
* by the pricing, so a pricing-driven JWT will be only generated
* for them.
*
* @return A {@link Boolean} indicating the condition to include, or not,
* the pricing evaluation context in the JWT. Set to {@code true} by
* default
*
* @see PricingEvaluatorUtil#generateUserToken
*
*/
public Boolean userAffectedByPricing() {
return true;
}
/**
* This method should return the user context that will be used to evaluate the
* pricing plan. It should be considered which users has accessed the service
* and what information is available.
*
* @return Map with the user context
*/
public abstract Map<String, Object> getUserContext();
/**
* This method should return the plan name of the current user.
* With this information, the library will be able to build the {@link Plan}
* object of the user from the configuration.
*
* @return a {@link String} with the current user's plan name
*/
public abstract String getUserPlan();
/**
* This method should return a list with the name of the add-ons contracted by
* the current user. If the pricing does not include add-ons, then just return
* an empty {@link List}. With this information, the library will be able to
* build the subscription of the user from the configuration.
*
* @return a list with the current user's contracted add-ons.
* Add-on names should be the same as in the pricing configuration file.
*
*/
public abstract List<String> getUserAddOns();
/**
* Returns a list with the full subscription contracted by the current user
* (including plans and add-ons).
* <p>
* There are two keys inside this {@link Map}:
* <ul>
* <li>Key {@code plans} contains the plan name of the user
* <li>Key {@code addOns} contains a list with the add-ons contracted by the
* user
* </ul>
*
* @return {@code Map<String, Object>} with the current user's contracted
* subscription.
*/
public final Map<String, Object> getUserSubscription() {
Map<String, Object> userSubscription = new HashMap<>();
userSubscription.put("plan", this.getUserPlan());
userSubscription.put("addOns", this.getUserAddOns());
return userSubscription;
}
/**
* This method returns the plan context of the current user, represented by a
* {@link Map}. It's used to evaluate the pricing plan.
*
* @return current user's plan context
*/
public final Map<String, Object> getPlanContext() {
Plan plan = this.getPricingManager().getPlans().get(this.getUserPlan());
Map<String, AddOn> addOnsMap = this.getPricingManager().getAddOns();
List<AddOn> addOns = new ArrayList<>();
for (String addOnName : this.getUserAddOns()) {
AddOn addOn = addOnsMap.get(addOnName);
if (addOn != null) {
addOns.add(addOn);
} else {
logger.warn(
"[WARNING] User add-on {} not found in the pricing configuration. It hasn't been considered in feature evaluation.",
addOnName);
}
}
Map<String, Object> planContext = new HashMap<>();
Map<String, Object> planFeaturesContext = computeFeatureValueMap(plan, addOns);
planContext.put("features", planFeaturesContext);
Map<String, Object> planUsageLimitMap = computeUsageLimitValueMap(plan, addOns);
planContext.put("usageLimits", planUsageLimitMap);
return planContext;
}
/**
* This method returns the {@link PricingManager} object that is being used to
* evaluate the pricing plan.
*
* @return {@link PricingManager} object
*/
public final PricingManager getPricingManager() {
try {
return YamlUtils.retrieveManagerFromYaml(this.getConfigFilePath());
} catch (YAMLException e) {
throw new PricingPlanEvaluationException("Error while parsing YAML file");
}
}
private final Map<String, Object> computeFeatureValueMap(Plan plan, List<AddOn> addOns) {
Map<String, Object> featureValueMap = new HashMap<>();
// Add plan features
featureValueMap.putAll(plan.getFeatures().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().getValue() != null ? e.getValue().getValue()
: e.getValue().getDefaultValue())));
// Replace by add-ons features
for (AddOn addOn : addOns) {
try {
Map<String, Feature> addOnFeatures = addOn.getFeatures();
if (addOnFeatures == null) {
continue;
}
featureValueMap.putAll(addOnFeatures.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().getValue())));
} catch (NullPointerException e) {
throw new PricingPlanEvaluationException("Error while creating evaluation context. Add-on "
+ addOn.getName() + " do not have a value for all its features.");
}
}
return featureValueMap;
}
private final Map<String, Object> computeUsageLimitValueMap(Plan plan, List<AddOn> addOns) {
Map<String, Object> usageLimitMap = new HashMap<>();
// Add plan usage limits
usageLimitMap.putAll(plan.getUsageLimits().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().getValue() != null ? e.getValue().getValue()
: e.getValue().getDefaultValue())));
// Replace by add-ons usage limits
for (AddOn addOn : addOns) {
try {
Map<String, UsageLimit> addOnUsageLimits = addOn.getUsageLimits();
if (addOnUsageLimits == null) {
continue;
}
usageLimitMap.putAll(addOnUsageLimits.entrySet().stream()
.collect(Collectors.toMap(e -> e.getValue().getName(),
e -> e.getValue().getValue())));
} catch (NullPointerException e) {
throw new PricingPlanEvaluationException("Error while creating evaluation context. Add-on "
+ addOn.getName() + " do not have a value for all its features.");
}
}
// Extend with Add add-ons usage limits extensions
for (AddOn addOn : addOns) {
try {
Map<String, UsageLimit> addOnUsageLimitsExtensions = addOn.getUsageLimitsExtensions();
if (addOnUsageLimitsExtensions == null) {
continue;
}
usageLimitMap.putAll(addOnUsageLimitsExtensions.entrySet().stream()
.collect(Collectors.toMap(e -> e.getValue().getName(),
e -> {
Number existingValue = (Number) usageLimitMap.get(e.getValue().getName());
Number extensionValue = (Number) e.getValue().getValue();
if (existingValue == null || extensionValue == null) {
throw new PricingPlanEvaluationException(
"Error while creating evaluation context. Usage limit extension values must be numeric and not null.");
}
return existingValue.doubleValue() + extensionValue.doubleValue();
})));
} catch (NullPointerException e) {
throw new PricingPlanEvaluationException(
"Error while creating evaluation context. It wasn't possible to extend the add-on "
+ addOn.getName()
+ ". Please check that the usage limit that youre trying to extend actually exists in the configuration and that it's NUMERIC.");
}
}
return usageLimitMap;
}
}