forked from harness/ff-java-server-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInnerClient.java
More file actions
384 lines (319 loc) · 11 KB
/
InnerClient.java
File metadata and controls
384 lines (319 loc) · 11 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package io.harness.cf.client.api;
import com.google.gson.JsonObject;
import io.harness.cf.client.common.SdkCodes;
import io.harness.cf.client.connector.*;
import io.harness.cf.client.dto.Message;
import io.harness.cf.client.dto.Target;
import io.harness.cf.model.FeatureConfig;
import io.harness.cf.model.Variation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@Slf4j
class InnerClient
implements AutoCloseable,
FlagEvaluateCallback,
AuthCallback,
PollerCallback,
RepositoryCallback,
MetricsCallback,
Updater {
enum Processor {
POLL,
STREAM,
METRICS,
}
private Connector connector;
private Evaluation evaluator;
private Repository repository;
private BaseConfig options;
private AuthService authService;
private PollingProcessor pollProcessor;
private MetricsProcessor metricsProcessor;
private UpdateProcessor updateProcessor;
private boolean initialized = false;
private boolean closing = false;
private boolean failure = false;
private boolean pollerReady = false;
private boolean streamReady = false;
private boolean metricReady = false;
private final ConcurrentHashMap<Event, CopyOnWriteArrayList<Consumer<String>>> events =
new ConcurrentHashMap<>();
public InnerClient(@NonNull final String sdkKey) {
this(sdkKey, BaseConfig.builder().build());
}
@Deprecated
public InnerClient(@NonNull final String sdkKey, @NonNull final Config options) {
HarnessConfig config =
HarnessConfig.builder()
.configUrl(options.getConfigUrl())
.eventUrl(options.getEventUrl())
.connectionTimeout(options.getConnectionTimeout())
.readTimeout(options.readTimeout)
.writeTimeout(options.getWriteTimeout())
.build();
HarnessConnector harnessConnector = new HarnessConnector(sdkKey, config);
setUp(harnessConnector, options);
}
public InnerClient(@NonNull final String sdkKey, @NonNull final BaseConfig options) {
HarnessConfig config = HarnessConfig.builder().build();
HarnessConnector harnessConnector = new HarnessConnector(sdkKey, config);
setUp(harnessConnector, options);
}
public InnerClient(@NonNull final Connector connector) {
this(connector, BaseConfig.builder().build());
}
public InnerClient(@NonNull Connector connector, @NonNull final BaseConfig options) {
setUp(connector, options);
}
protected void setUp(@NonNull final Connector connector, @NonNull final BaseConfig options) {
this.options = options;
if (log.isInfoEnabled()) {
log.info("Starting SDK client with configuration: {}", this.options);
}
this.connector = connector;
this.connector.setOnUnauthorized(this::onUnauthorized);
// initialization
repository = new StorageRepository(options.getCache(), options.getStore(), this);
evaluator = new Evaluator(repository);
authService = new AuthService(this.connector, options.getPollIntervalInSeconds(), this);
pollProcessor =
new PollingProcessor(this.connector, repository, options.getPollIntervalInSeconds(), this);
metricsProcessor = new MetricsProcessor(this.connector, this.options, this);
updateProcessor = new UpdateProcessor(this.connector, this.repository, this);
// start with authentication
authService.start();
}
protected void onUnauthorized() {
if (closing) {
return;
}
log.info("Unauthorized event received. Stopping all processors and run auth service");
pollProcessor.stop();
if (options.isStreamEnabled()) {
updateProcessor.stop();
}
if (options.isAnalyticsEnabled()) {
metricsProcessor.stop();
}
authService.start();
log.info("re-auth started");
}
@Override
public void onAuthSuccess() {
log.debug("SDK successfully logged in");
if (closing) {
return;
}
log.debug("start poller processor");
pollProcessor.start();
if (options.isStreamEnabled()) {
log.debug("Stream enabled, start update processor");
updateProcessor.start();
}
if (options.isAnalyticsEnabled()) {
log.debug("Analytics enabled, start metrics processor");
metricsProcessor.start();
}
}
@Override
public void onPollerReady() {
initialize(Processor.POLL);
}
@Override
public void onPollerError(@NonNull final Exception exc) {
log.error("PollerProcessor exception", exc);
}
@Override
public void onPollerFailed(@NonNull final Exception exc) {
log.error("PollerProcessor failed while initializing, exception: ", exc);
}
@Override
public void onFlagStored(@NonNull final String identifier) {
notifyConsumers(Event.CHANGED, identifier);
}
@Override
public void onFlagDeleted(@NonNull final String identifier) {
notifyConsumers(Event.CHANGED, identifier);
}
@Override
public void onSegmentStored(@NonNull final String identifier) {
repository.findFlagsBySegment(identifier).forEach(s -> notifyConsumers(Event.CHANGED, s));
}
@Override
public void onSegmentDeleted(@NonNull final String identifier) {
repository.findFlagsBySegment(identifier).forEach(s -> notifyConsumers(Event.CHANGED, s));
}
@Override
public void onMetricsReady() {
initialize(Processor.METRICS);
}
@Override
public void onMetricsError(@NonNull final String error) {
log.error("Metrics error: {}", error);
}
@Override
public synchronized void onMetricsFailure() {
failure = true;
notifyAll();
}
@Override
public void onConnected() {
SdkCodes.infoStreamConnected();
if (pollProcessor.isRunning()) {
// refresh any flags that may have gotten out of sync if the SSE connection was down
pollProcessor.retrieveAll();
pollProcessor.stop();
}
}
@Override
public void onDisconnected(String reason) {
SdkCodes.warnStreamDisconnected(reason);
if (!closing && !pollProcessor.isRunning()) {
log.debug("onDisconnected triggered, starting poller to get latest flags");
pollProcessor.close();
pollProcessor =
new PollingProcessor(connector, repository, options.getPollIntervalInSeconds(), this);
pollProcessor.start();
if (updateProcessor != null && options.isStreamEnabled()) {
updateProcessor.restart();
}
} else {
log.debug(
"Poller already running [closing={} interval={}]",
closing,
options.getPollIntervalInSeconds());
log.debug("SSE disconnect detected - asking poller to refresh flags");
pollProcessor.retrieveAll();
}
}
@Override
public void onReady() {
log.debug("onReady triggered");
initialize(Processor.STREAM);
}
public synchronized void onFailure(@NonNull final String error) {
SdkCodes.warnAuthFailedSrvDefaults(error);
failure = true;
notifyAll();
}
@Override
public void update(@NonNull final Message message) {
log.debug("update triggered [event={}] ", message.getEvent());
updateProcessor.update(message);
}
public void update(@NonNull final Message message, final boolean manual) {
log.debug("update triggered [event={} manual={}] ", message.getEvent(), manual);
if (options.isStreamEnabled() && manual) {
log.warn(
"You have run update method manually with the stream enabled. Please turn off the stream in this case.");
}
update(message);
}
private synchronized void initialize(@NonNull final Processor processor) {
if (initialized || closing) {
log.debug("client is already initialized {} or closing {}", initialized, closing);
return;
}
switch (processor) {
case POLL:
pollerReady = true;
log.debug("PollingProcessor ready");
break;
case STREAM:
streamReady = true;
log.debug("Updater ready");
break;
case METRICS:
metricReady = true;
log.debug("MetricsProcessor ready");
break;
}
if ((options.isStreamEnabled() && !streamReady)
|| (options.isAnalyticsEnabled() && !this.metricReady)
|| (!this.pollerReady)) {
return;
}
initialized = true;
notifyAll();
notifyConsumers(Event.READY, null);
SdkCodes.infoSdkInitOk();
}
protected void notifyConsumers(@NonNull final Event event, final String value) {
CopyOnWriteArrayList<Consumer<String>> consumers = events.get(event);
if (consumers != null && !consumers.isEmpty()) {
consumers.forEach(c -> c.accept(value));
}
}
/** if waitForInitialization is used then on(READY) will never be triggered */
public synchronized void waitForInitialization()
throws InterruptedException, FeatureFlagInitializeException {
while (!initialized) {
log.info("Wait for initialization to finish");
wait(5000);
if (failure) {
log.error("Failure while initializing SDK!");
throw new FeatureFlagInitializeException();
}
}
}
public void on(@NonNull final Event event, @NonNull final Consumer<String> consumer) {
final CopyOnWriteArrayList<Consumer<String>> consumers =
events.getOrDefault(event, new CopyOnWriteArrayList<>());
consumers.add(consumer);
events.put(event, consumers);
}
public void off() {
events.clear();
}
public void off(@NonNull final Event event) {
events.get(event).clear();
}
public void off(@NonNull final Event event, @NonNull final Consumer<String> consumer) {
events.get(event).removeIf(next -> next == consumer);
}
public boolean boolVariation(
@NonNull final String identifier, final Target target, final boolean defaultValue) {
return evaluator.boolVariation(identifier, target, defaultValue, this);
}
public String stringVariation(
@NonNull final String identifier, final Target target, @NonNull final String defaultValue) {
return evaluator.stringVariation(identifier, target, defaultValue, this);
}
public double numberVariation(
@NonNull final String identifier, final Target target, final double defaultValue) {
return evaluator.numberVariation(identifier, target, defaultValue, this);
}
public JsonObject jsonVariation(
@NonNull String identifier, Target target, @NonNull JsonObject defaultValue) {
return evaluator.jsonVariation(identifier, target, defaultValue, this);
}
@Override
public void processEvaluation(
@NonNull FeatureConfig featureConfig, Target target, @NonNull Variation variation) {
if (this.options.isAnalyticsEnabled()) {
metricsProcessor.registerEvaluation(target, featureConfig.getFeature(), variation);
}
}
public void close() {
log.info("Closing the client");
closing = true;
off();
authService.close();
repository.close();
pollProcessor.close();
updateProcessor.close();
metricsProcessor.close();
connector.close();
log.info("All resources released and client closed");
}
/* Package private */
BaseConfig getOptions() {
return options;
}
PollingProcessor getPollProcessor() {
return pollProcessor;
}
}