-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventQueueManager.java
More file actions
186 lines (154 loc) · 6.98 KB
/
EventQueueManager.java
File metadata and controls
186 lines (154 loc) · 6.98 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
package com.devcycle.sdk.server.local.managers;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.devcycle.sdk.server.common.api.IDevCycleApi;
import com.devcycle.sdk.server.common.logging.DevCycleLogger;
import com.devcycle.sdk.server.common.model.DevCycleEvent;
import com.devcycle.sdk.server.common.model.DevCycleResponse;
import com.devcycle.sdk.server.common.model.DevCycleUser;
import com.devcycle.sdk.server.local.api.DevCycleLocalEventsApiClient;
import com.devcycle.sdk.server.local.bucketing.LocalBucketing;
import com.devcycle.sdk.server.local.model.BucketedUserConfig;
import com.devcycle.sdk.server.local.model.DevCycleLocalOptions;
import com.devcycle.sdk.server.local.model.EventsBatch;
import com.devcycle.sdk.server.local.model.FlushPayload;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import retrofit2.Call;
import retrofit2.Response;
public class EventQueueManager {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final String sdkKey;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new DaemonThreadFactory());
private final LocalBucketing localBucketing;
private final IDevCycleApi eventsApiClient;
private final int eventFlushIntervalMS;
private boolean isFlushingEvents = false;
private final int flushEventQueueSize;
private final int maxEventQueueSize;
public EventQueueManager(String sdkKey, LocalBucketing localBucketing, String clientUUID, DevCycleLocalOptions options) throws Exception {
this.localBucketing = localBucketing;
this.sdkKey = sdkKey;
eventFlushIntervalMS = options.getEventFlushIntervalMS();
flushEventQueueSize = options.getFlushEventQueueSize();
maxEventQueueSize = options.getMaxEventQueueSize();
eventsApiClient = new DevCycleLocalEventsApiClient(sdkKey, options).initialize();
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.localBucketing.initEventQueue(sdkKey, clientUUID, OBJECT_MAPPER.writeValueAsString(options));
setupScheduler();
}
private void setupScheduler() {
Runnable flushEventsRunnable = () -> {
try {
flushEvents();
} catch (Exception e) {
DevCycleLogger.error("DevCycle Error flushing events: " + e.getMessage(), e);
}
};
scheduler.scheduleAtFixedRate(flushEventsRunnable, 0, this.eventFlushIntervalMS, TimeUnit.MILLISECONDS);
}
/**
* Flush events in queue to DevCycle Events API. Requeue events if flush fails
*/
public synchronized void flushEvents() throws Exception {
if (isFlushingEvents) return;
if (sdkKey == null || sdkKey.equals("")) {
throw new Exception("DevCycle is not yet initialized to publish events.");
}
FlushPayload[] flushPayloads = new FlushPayload[0];
try {
flushPayloads = this.localBucketing.flushEventQueue(this.sdkKey);
} catch (Exception e) {
DevCycleLogger.error("DevCycle Error flushing event payloads: " + e.getMessage(), e);
}
if (flushPayloads.length == 0) return;
DevCycleLogger.debug("DevCycle Flush Payloads: " + Arrays.toString(flushPayloads));
int eventCount = 0;
isFlushingEvents = true;
try {
for (FlushPayload payload : flushPayloads) {
eventCount += payload.eventCount;
publishEvents(this.sdkKey, payload);
}
} finally {
isFlushingEvents = false;
}
DevCycleLogger.debug(String.format("DevCycle Flush %d AS Events, for %d Users", eventCount, flushPayloads.length));
}
/**
* Queue DevCycleAPIEvent for publishing to DevCycle Events API.
*/
public void queueEvent(DevCycleUser user, DevCycleEvent event) throws Exception {
if (checkEventQueueSize()) {
DevCycleLogger.warning("Max event queue size reached, dropping event: " + event);
return;
}
this.localBucketing.queueEvent(this.sdkKey, OBJECT_MAPPER.writeValueAsString(user), OBJECT_MAPPER.writeValueAsString(event));
}
/**
* Queue DevCycleEvent that can be aggregated together, where multiple calls are aggregated
* by incrementing the 'value' field.
*/
public void queueAggregateEvent(DevCycleEvent event, BucketedUserConfig bucketedConfig) throws Exception {
if (checkEventQueueSize()) {
DevCycleLogger.warning("Max event queue size reached, dropping aggregate event: " + event);
return;
}
String eventString = OBJECT_MAPPER.writeValueAsString(event);
if (bucketedConfig != null) {
String variableVariationMapString = OBJECT_MAPPER.writeValueAsString(bucketedConfig.variableVariationMap);
this.localBucketing.queueAggregateEvent(this.sdkKey, eventString, variableVariationMapString);
} else {
this.localBucketing.queueAggregateEvent(this.sdkKey, eventString, "{}");
}
}
private void publishEvents(String sdkKey, FlushPayload flushPayload) throws InterruptedException {
Call<DevCycleResponse> response = eventsApiClient.publishEvents(EventsBatch.builder().batch(flushPayload.records).build());
int responseCode = getResponse(response);
if (responseCode == 201) {
localBucketing.onPayloadSuccess(sdkKey, flushPayload.payloadId);
} else {
DevCycleLogger.warning("DevCycle Error Publishing Events: " + responseCode);
localBucketing.onPayloadFailure(sdkKey, flushPayload.payloadId, responseCode >= 500);
}
}
private int getResponse(Call call) {
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
DevCycleLogger.error("DevCycle Events error: " + e.getMessage(), e);
}
if (response == null) {
return 500;
} else {
return response.code();
}
}
/**
* Returns true if event queue size is greater or equal to flushEventQueueSize or maxEventQueueSize
* Flushes events if event queue size is equal or greater to flushEventQueueSize
*/
private boolean checkEventQueueSize() throws Exception {
int queueSize = localBucketing.getEventQueueSize(sdkKey);
if (queueSize >= flushEventQueueSize) {
if (!isFlushingEvents) {
flushEvents();
}
return queueSize >= maxEventQueueSize;
}
return false;
}
public void cleanup() {
// Flush any remaining events
try {
flushEvents();
} catch (Exception e) {
DevCycleLogger.error("DevCycle Cleanup error: " + e.getMessage(), e);
}
scheduler.shutdown();
}
}