Repository navigation
Expand file tree
/
Copy pathSimpleFeatureFlagService.java
More file actions
255 lines (214 loc) · 9.96 KB
/
Copy pathSimpleFeatureFlagService.java
File metadata and controls
255 lines (214 loc) · 9.96 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
package dev.faststats;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.jspecify.annotations.Nullable;
import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
final class SimpleFeatureFlagService extends SubmissionService implements FeatureFlagService {
private static final Duration DEFAULT_TTL = Duration.ofMinutes(5);
private static final String CHECK_PATH = "/v1/check";
private static final String OPT_IN_PATH = "/v1/opt-in";
private static final String OPT_OUT_PATH = "/v1/opt-out";
private final URI url = getServerUrl("faststats.flags-server", "https://flags.faststats.dev");
private final SimpleContext context;
private final Attributes attributes;
private final Duration ttl;
private final Map<String, CompletableFuture<?>> fetchesInProgress = new ConcurrentHashMap<>();
SimpleFeatureFlagService(
final SimpleContext context,
final Attributes attributes,
final Duration ttl
) throws IllegalArgumentException {
super(context);
if (ttl.isNegative()) throw new IllegalArgumentException("TTL cannot be negative");
this.attributes = attributes;
this.context = context;
this.ttl = ttl;
}
@SuppressWarnings("unchecked")
<T> CompletableFuture<T> fetch(final SimpleFeatureFlag<T> flag) {
final var future = new CompletableFuture<T>();
final var existing = fetchesInProgress.putIfAbsent(flag.getId(), future);
if (existing != null) return (CompletableFuture<T>) existing;
createFetch(flag).whenComplete((value, throwable) -> {
fetchesInProgress.remove(flag.getId(), future);
if (throwable != null) future.completeExceptionally(throwable);
else future.complete(value);
});
return future;
}
<T> CompletableFuture<T> optIn(final SimpleFeatureFlag<T> flag) {
return sendOptRequest(flag, OPT_IN_PATH);
}
<T> CompletableFuture<T> optOut(final SimpleFeatureFlag<T> flag) {
return sendOptRequest(flag, OPT_OUT_PATH);
}
private <T> CompletableFuture<T> sendOptRequest(final SimpleFeatureFlag<T> flag, final String path) {
final var requestBody = createRequestBody(flag);
return send(path, requestBody).thenCompose(response -> {
if (isSuccessful(response)) return fetch(flag);
logUnsuccessfulResponse(response);
return CompletableFuture.failedFuture(new IllegalStateException(
"Feature flag opt request failed with status %s (%s)".formatted(response.statusCode(), response.body())
));
});
}
private <T> CompletableFuture<T> createFetch(final SimpleFeatureFlag<T> flag) {
final var requestBody = createRequestBody(flag);
final var request = createRequest(CHECK_PATH, requestBody);
logger.info("Fetching %s: %s", request.uri(), requestBody.toString());
return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> handleFetchResponse(flag, response));
}
private JsonObject createRequestBody(final SimpleFeatureFlag<?> flag) {
final var requestBody = new JsonObject();
final var attributes = new JsonObject();
requestBody.addProperty("identifier", context.getConfig().serverId().toString());
requestBody.addProperty("key", flag.getId());
this.attributes.forEachPrimitive(attributes::add);
if (flag.attributes() != null) flag.attributes().forEachPrimitive(attributes::add);
if (!attributes.isEmpty()) requestBody.add("attributes", attributes);
return requestBody;
}
private CompletableFuture<HttpResponse<String>> send(final String path, final JsonObject requestBody) {
return HTTP_CLIENT.sendAsync(createRequest(path, requestBody), HttpResponse.BodyHandlers.ofString());
}
private HttpRequest createRequest(final String path, final JsonObject requestBody) {
return HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + context.getToken())
.timeout(TIMEOUT)
.uri(url.resolve(path))
.build();
}
private <T> T handleFetchResponse(final SimpleFeatureFlag<T> flag, final HttpResponse<String> response) {
try {
if (!isSuccessful(response)) {
logUnsuccessfulResponse(response);
throw new IllegalStateException("Unexpected response status: %s (%s)".formatted(response.statusCode(), response.body()));
}
final var body = JsonParser.parseString(response.body());
final var value = getValue(flag, body);
logger.info("Fetch returned body: %s (value: %s)", body, value);
flag.setLastFetch(System.currentTimeMillis());
flag.setValue(value);
return value;
} catch (final JsonParseException e) {
logger.error("Unexpected response body: %s (%s)", e, response.body(), response.statusCode());
throw new IllegalStateException("Unexpected response body: %s (%s)".formatted(response.body(), response.statusCode()), e);
}
}
@SuppressWarnings("unchecked")
private <T> T getValue(final SimpleFeatureFlag<T> flag, final JsonElement body) {
if (!(body instanceof final JsonObject object)) {
logger.warn("Unexpected JSON response: %s", body);
throw new IllegalStateException("Unexpected JSON response: " + body);
}
if (!(object.get("value") instanceof final JsonPrimitive primitive)) {
logger.warn("Missing or invalid 'value' in JSON response: %s", body);
throw new IllegalStateException("Missing or invalid 'value' in JSON response: " + body);
}
return (T) switch (flag.getType()) {
case STRING -> primitive.getAsString();
case NUMBER -> getAsNumber(primitive);
case BOOLEAN -> getAsBoolean(primitive);
};
}
private Number getAsNumber(final JsonPrimitive primitive) {
try {
if (primitive.isNumber()) return primitive.getAsNumber();
return new BigDecimal(primitive.getAsString());
} catch (final NumberFormatException e) {
logger.warn("Expected a number but got: %s", primitive.getAsString());
throw new IllegalStateException("Expected a number but got: " + primitive.getAsString(), e);
}
}
private boolean getAsBoolean(final JsonPrimitive primitive) {
if (primitive.isBoolean()) return primitive.getAsBoolean();
return switch (primitive.getAsString()) {
case "true" -> true;
case "false" -> false;
default -> {
logger.warn("Expected a boolean but got: %s", primitive.getAsString());
throw new IllegalStateException("Expected a boolean but got: " + primitive.getAsString());
}
};
}
@Override
public FeatureFlag<Boolean> define(final String id, final boolean defaultValue) {
return defineFlag(id, defaultValue, null);
}
@Override
public FeatureFlag<Boolean> define(final String id, final boolean defaultValue, final Attributes attributes) {
return defineFlag(id, defaultValue, attributes);
}
@Override
public FeatureFlag<String> define(final String id, final String defaultValue) {
return defineFlag(id, defaultValue, null);
}
@Override
public FeatureFlag<String> define(final String id, final String defaultValue, final Attributes attributes) {
return defineFlag(id, defaultValue, attributes);
}
@Override
public FeatureFlag<Number> define(final String id, final Number defaultValue) {
return defineFlag(id, defaultValue, null);
}
@Override
public FeatureFlag<Number> define(final String id, final Number defaultValue, final Attributes attributes) {
return defineFlag(id, defaultValue, attributes);
}
private <T> FeatureFlag<T> defineFlag(final String id, final T defaultValue, @Nullable final Attributes attributes) {
return new SimpleFeatureFlag<>(id, defaultValue, attributes, this);
}
@Override
public Attributes getAttributes() {
return attributes;
}
@Override
public Duration getTTL() {
return ttl;
}
public void shutdown() {
fetchesInProgress.values().forEach(fetch -> fetch.cancel(true));
fetchesInProgress.clear();
}
@Override
protected String serverType() {
return "feature flag";
}
static final class Factory implements FeatureFlagService.Factory {
private final SimpleContext context;
private @Nullable Attributes attributes;
private Duration ttl = DEFAULT_TTL;
Factory(final SimpleContext context) {
this.context = context;
}
@Override
public FeatureFlagService.Factory attributes(final Attributes attributes) {
this.attributes = attributes;
return this;
}
@Override
public FeatureFlagService.Factory ttl(final Duration ttl) throws IllegalArgumentException {
if (ttl.isNegative()) throw new IllegalArgumentException("TTL cannot be negative");
this.ttl = ttl;
return this;
}
@Override
public FeatureFlagService create() throws IllegalArgumentException {
final var attributes = this.attributes != null ? this.attributes : Attributes.empty();
return new SimpleFeatureFlagService(context, attributes, ttl);
}
}
}