-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathFlagsmithApiWrapper.java
More file actions
353 lines (301 loc) · 10.4 KB
/
FlagsmithApiWrapper.java
File metadata and controls
353 lines (301 loc) · 10.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package com.flagsmith;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.flagsmith.config.FlagsmithConfig;
import com.flagsmith.exceptions.FlagsmithRuntimeError;
import com.flagsmith.flagengine.EvaluationContext;
import com.flagsmith.interfaces.FlagsmithCache;
import com.flagsmith.interfaces.FlagsmithSdk;
import com.flagsmith.mappers.EngineMappers;
import com.flagsmith.models.Flags;
import com.flagsmith.models.TraitModel;
import com.flagsmith.models.environments.EnvironmentModel;
import com.flagsmith.models.features.FeatureStateModel;
import com.flagsmith.responses.FlagsAndTraitsResponse;
import com.flagsmith.threads.AnalyticsProcessor;
import com.flagsmith.threads.RequestProcessor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.Getter;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
@Getter
public class FlagsmithApiWrapper implements FlagsmithSdk {
private static final String AUTH_HEADER = "X-Environment-Key";
private static final String USER_AGENT_HEADER = "User-Agent";
private static final String ACCEPT_HEADER = "Accept";
private static final Integer TIMEOUT = 15000;
private final FlagsmithLogger logger;
private final FlagsmithConfig defaultConfig;
private final HashMap<String, String> customHeaders;
// an api key per environment
private final String apiKey;
private RequestProcessor requestor;
private FlagsmithCache cache = null;
/**
* Instantiate with cache.
*
* @param cache cache object
* @param defaultConfig config object
* @param customHeaders custom headers list
* @param logger logger object
* @param apiKey api key
*/
public FlagsmithApiWrapper(
final FlagsmithCache cache,
final FlagsmithConfig defaultConfig,
final HashMap<String, String> customHeaders,
final FlagsmithLogger logger,
final String apiKey
) {
this(defaultConfig, customHeaders, logger, apiKey);
this.cache = cache;
}
/**
* Instantiate with config, custom headers, logger and apikey.
*
* @param defaultConfig config object
* @param customHeaders custom headers list
* @param logger logger instance
* @param apiKey api key
*/
public FlagsmithApiWrapper(
final FlagsmithConfig defaultConfig,
final HashMap<String, String> customHeaders,
final FlagsmithLogger logger,
final String apiKey
) {
this.defaultConfig = defaultConfig;
this.customHeaders = customHeaders;
this.logger = logger;
this.apiKey = apiKey;
requestor = new RequestProcessor(
defaultConfig.getHttpClient(),
logger,
defaultConfig.getRetries()
);
}
/**
* Instantiate with config, custom headers, logger, apikey and request processor.
*
* @param defaultConfig config object
* @param customHeaders custom headers list
* @param logger logger instance
* @param apiKey api key
* @param requestProcessor request processor
*/
public FlagsmithApiWrapper(
final FlagsmithConfig defaultConfig,
final HashMap<String, String> customHeaders,
final FlagsmithLogger logger,
final String apiKey,
final RequestProcessor requestProcessor
) {
this.defaultConfig = defaultConfig;
this.customHeaders = customHeaders;
this.logger = logger;
this.apiKey = apiKey;
this.requestor = requestProcessor;
}
/**
* Get Feature Flags from API.
*
* @param doThrow - whether throw exception or not
*/
public Flags getFeatureFlags(boolean doThrow) {
Flags featureFlags = new Flags();
if (getCache() != null && getCache().getEnvFlagsCacheKey() != null) {
featureFlags = getCache().getIfPresent(getCache().getEnvFlagsCacheKey());
if (featureFlags != null) {
return featureFlags;
}
}
HttpUrl urlBuilder = defaultConfig.getFlagsUri();
Request request = this.newGetRequest(urlBuilder);
Future<List<FeatureStateModel>> featureFlagsFuture = requestor.executeAsync(
request,
new TypeReference<List<FeatureStateModel>>() {},
doThrow
);
try {
List<FeatureStateModel> featureFlagsResponse = featureFlagsFuture.get(
TIMEOUT, TimeUnit.MILLISECONDS
);
if (featureFlagsResponse == null) {
featureFlagsResponse = new ArrayList<>();
}
featureFlags = Flags.fromApiFlags(
featureFlagsResponse,
getConfig().getAnalyticsProcessor(),
getConfig().getFlagsmithFlagDefaults()
);
if (getCache() != null && getCache().getEnvFlagsCacheKey() != null) {
getCache().getCache().put(getCache().getEnvFlagsCacheKey(), featureFlags);
logger.info("Got feature flags for flags = {} and cached.", featureFlags);
}
} catch (TimeoutException te) {
logger.error("Timed out on fetching Feature flags.", te);
} catch (InterruptedException ie) {
logger.error("Interrupted on fetching Feature flags.", ie);
} catch (ExecutionException ee) {
logger.error("Execution failed on fetching Feature flags.", ee);
if (doThrow) {
throw new FlagsmithRuntimeError(ee);
}
}
logger.info("Got feature flags for flags = {}", featureFlags);
return featureFlags;
}
@Override
public Flags identifyUserWithTraits(
String identifier, List<? extends TraitModel> traits, boolean isTransient, boolean doThrow
) {
assertValidUser(identifier);
Flags flags = null;
String cacheKey = null;
if (getCache() != null) {
cacheKey = getCache().getIdentityFlagsCacheKey(identifier, isTransient);
flags = getCache().getIfPresent(cacheKey);
if (flags != null) {
return flags;
}
}
ObjectNode node = MapperFactory.getMapper().createObjectNode();
node.put("identifier", identifier);
if (isTransient) {
node.put("transient", true);
}
if (traits != null) {
node.putPOJO("traits", traits);
}
MediaType json = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(node.toString(), json);
HttpUrl url = defaultConfig.getIdentitiesUri();
final Request request = this.newPostRequest(url, body);
Future<FlagsAndTraitsResponse> featureFlagsFuture = requestor.executeAsync(
request,
new TypeReference<FlagsAndTraitsResponse>() {},
doThrow
);
try {
FlagsAndTraitsResponse flagsAndTraitsResponse = featureFlagsFuture.get(
TIMEOUT, TimeUnit.MILLISECONDS
);
List<FeatureStateModel> flagsArray = flagsAndTraitsResponse != null
&& flagsAndTraitsResponse.getFlags() != null
? flagsAndTraitsResponse.getFlags() : new ArrayList<>();
flags = Flags.fromApiFlags(
flagsArray,
getConfig().getAnalyticsProcessor(),
getConfig().getFlagsmithFlagDefaults()
);
if (cacheKey != null) {
getCache().getCache().put(cacheKey, flags);
logger.info("Cached flags for identity {}.", identifier);
}
} catch (TimeoutException ie) {
logger.error("Timed out on fetching Feature flags.", ie);
} catch (InterruptedException ie) {
logger.error("Interrupted on fetching Feature flags.", ie);
} catch (ExecutionException ee) {
logger.error("Execution failed on fetching Feature flags.", ee);
if (doThrow) {
throw new FlagsmithRuntimeError(ee);
}
}
logger.info("Got flags based on identify for identifier = {}, flags = {}",
identifier, flags);
return flags;
}
@Override
public EvaluationContext getEvaluationContext() {
final Request request = newGetRequest(defaultConfig.getEnvironmentUri());
Future<EnvironmentModel> environmentFuture = requestor.executeAsync(request,
new TypeReference<EnvironmentModel>() {},
Boolean.TRUE);
try {
EnvironmentModel environment = environmentFuture.get(TIMEOUT, TimeUnit.MILLISECONDS);
return EngineMappers.mapEnvironmentToContext(environment);
} catch (TimeoutException ie) {
logger.error("Timed out on fetching Feature flags.", ie);
} catch (InterruptedException ie) {
logger.error("Environment loading interrupted.", ie);
} catch (IllegalArgumentException iae) {
logger.error("Environment loading failed.", iae);
} catch (ExecutionException ee) {
logger.error("Execution failed on Environment loading.", ee);
throw new FlagsmithRuntimeError(ee);
}
return null;
}
@Override
public RequestProcessor getRequestor() {
return this.requestor;
}
public void setRequestor(RequestProcessor requestor) {
this.requestor = requestor;
}
@Override
public FlagsmithConfig getConfig() {
return this.defaultConfig;
}
@Override
public FlagsmithCache getCache() {
return cache;
}
public FlagsmithLogger getLogger() {
return logger;
}
private Request.Builder newRequestBuilder() {
final Request.Builder builder = new Request.Builder()
.header(AUTH_HEADER, apiKey)
.header(USER_AGENT_HEADER, "flagsmith-java-sdk/" + Versions.getVersion())
.addHeader(ACCEPT_HEADER, "application/json");
if (this.customHeaders != null && !this.customHeaders.isEmpty()) {
this.customHeaders.forEach((k, v) -> builder.addHeader(k, v));
}
return builder;
}
/**
* Returns a build request with GET.
*
* @param url - URL to invoke
*/
@Override
public Request newGetRequest(HttpUrl url) {
final Request.Builder builder = newRequestBuilder();
builder.url(url);
return builder.build();
}
/**
* Returns a build request with GET.
*
* @param url - URL to invoke
* @param body - body to post
*/
@Override
public Request newPostRequest(HttpUrl url, RequestBody body) {
final Request.Builder builder = newRequestBuilder();
builder.url(url).post(body);
return builder.build();
}
/**
* Close the FlagsmithAPIWrapper instance, cleaning up any dependent threads or services
* which need cleaning up before the instance can be fully destroyed.
*/
public void close() {
this.requestor.close();
AnalyticsProcessor analyticsProcessor = this.getConfig().getAnalyticsProcessor();
if (analyticsProcessor != null) {
analyticsProcessor.close();
}
}
}