Skip to content

Commit a515240

Browse files
committed
ci: Run the Flagsmith SDK behavioural spec
1 parent 6df032a commit a515240

4 files changed

Lines changed: 205 additions & 0 deletions

File tree

‎.github/workflows/sdk-spec.yml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
name: SDK spec
2+
3+
on:
4+
pull_request:
5+
push:
6+
branches: [main]
7+
8+
permissions:
9+
contents: read
10+
11+
jobs:
12+
sdk-spec:
13+
# Keep the ref in `uses:` and `spec-ref` in sync.
14+
uses: Flagsmith/sdk-spec/.github/workflows/run-spec.yml@v0.1.1
15+
with:
16+
spec-ref: v0.1.1

‎renovate.json‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@
44
"ignorePresets": [":semanticPrefixFixDepsChoreOthers"],
55
"semanticCommitType": "deps",
66
"git-submodules": { "enabled": true },
7+
"customManagers": [
8+
{
9+
"customType": "regex",
10+
"managerFilePatterns": ["/^\\.github/workflows/sdk-spec\\.yml$/"],
11+
"matchStrings": ["spec-ref: (?<currentValue>v[\\d.]+)"],
12+
"depNameTemplate": "Flagsmith/sdk-spec",
13+
"datasourceTemplate": "github-tags"
14+
}
15+
],
716
"packageRules": [
817
{
918
"matchUpdateTypes": [
@@ -23,6 +32,11 @@
2332
"matchManagers": ["git-submodules"],
2433
"versioning": "semver-coerced",
2534
"enabled": true
35+
},
36+
{
37+
"matchPackageNames": ["Flagsmith/sdk-spec"],
38+
"groupName": "SDK spec",
39+
"enabled": true
2640
}
2741
]
2842
}

‎spec-adapter/Adapter.java‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import com.fasterxml.jackson.core.type.TypeReference;
2+
import com.fasterxml.jackson.databind.ObjectMapper;
3+
import com.flagsmith.FlagsmithClient;
4+
import com.flagsmith.Versions;
5+
import com.flagsmith.models.BaseFlag;
6+
import com.flagsmith.models.Flags;
7+
import com.sun.net.httpserver.HttpExchange;
8+
import com.sun.net.httpserver.HttpServer;
9+
import java.io.IOException;
10+
import java.io.OutputStream;
11+
import java.net.InetSocketAddress;
12+
import java.util.ArrayList;
13+
import java.util.HashMap;
14+
import java.util.LinkedHashMap;
15+
import java.util.List;
16+
import java.util.Map;
17+
import java.util.concurrent.ConcurrentHashMap;
18+
import java.util.concurrent.Executors;
19+
import java.util.concurrent.atomic.AtomicLong;
20+
import java.util.regex.Matcher;
21+
import java.util.regex.Pattern;
22+
23+
/**
24+
* Adapter that lets the Flagsmith SDK behavioural spec drive this SDK.
25+
*
26+
* <p>Protocol: https://github.com/Flagsmith/sdk-spec/blob/main/ADAPTER.md
27+
*/
28+
public class Adapter {
29+
30+
private static final ObjectMapper MAPPER = new ObjectMapper();
31+
private static final TypeReference<Map<String, Object>> JSON_OBJECT =
32+
new TypeReference<Map<String, Object>>() {};
33+
private static final Pattern CLIENT_ROUTE =
34+
Pattern.compile("^/clients/(?<clientId>[^/]+)(?<action>/[a-z-]+)?$");
35+
36+
private static final Map<String, FlagsmithClient> clients = new ConcurrentHashMap<>();
37+
private static final AtomicLong clientIds = new AtomicLong();
38+
39+
public static void main(String[] args) throws IOException {
40+
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
41+
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
42+
server.createContext("/", Adapter::dispatch);
43+
server.setExecutor(Executors.newCachedThreadPool());
44+
server.start();
45+
System.out.println("adapter: listening on :" + port);
46+
}
47+
48+
private static void dispatch(HttpExchange exchange) throws IOException {
49+
try {
50+
route(exchange);
51+
} catch (Exception e) {
52+
// Report SDK errors to the runner.
53+
e.printStackTrace();
54+
send(exchange, 500, error(e.getClass().getSimpleName() + ": " + e.getMessage()));
55+
} finally {
56+
System.out.println("adapter: " + exchange.getRequestMethod() + " "
57+
+ exchange.getRequestURI() + " " + exchange.getResponseCode());
58+
exchange.close();
59+
}
60+
}
61+
62+
private static void route(HttpExchange exchange) throws Exception {
63+
String method = exchange.getRequestMethod();
64+
String path = exchange.getRequestURI().getPath();
65+
66+
if (method.equals("GET") && path.equals("/health")) {
67+
Map<String, Object> health = new LinkedHashMap<>();
68+
health.put("sdk", "flagsmith-java-client");
69+
health.put("version", Versions.getVersion());
70+
send(exchange, 200, health);
71+
return;
72+
}
73+
74+
if (method.equals("POST") && path.equals("/clients")) {
75+
Map<String, Object> body = body(exchange);
76+
String clientId = String.valueOf(clientIds.incrementAndGet());
77+
clients.put(clientId, FlagsmithClient.newBuilder()
78+
.setApiKey((String) body.get("environmentKey"))
79+
.withApiUrl((String) body.get("apiUrl"))
80+
.build());
81+
send(exchange, 201, Map.of("clientId", clientId));
82+
return;
83+
}
84+
85+
Matcher match = CLIENT_ROUTE.matcher(path);
86+
FlagsmithClient client = match.matches() ? clients.get(match.group("clientId")) : null;
87+
if (client == null) {
88+
send(exchange, 404, error("No route for " + method + " " + path));
89+
return;
90+
}
91+
String action = match.group("action");
92+
93+
if (method.equals("DELETE") && action == null) {
94+
clients.remove(match.group("clientId")).close();
95+
send(exchange, 204, null);
96+
return;
97+
}
98+
99+
if (method.equals("POST") && "/environment-flags".equals(action)) {
100+
send(exchange, 200, serialiseFlags(client.getEnvironmentFlags()));
101+
return;
102+
}
103+
104+
if (method.equals("POST") && "/identity-flags".equals(action)) {
105+
Map<String, Object> body = body(exchange);
106+
@SuppressWarnings("unchecked")
107+
Map<String, Object> traits = (Map<String, Object>) body.get("traits");
108+
Flags flags = client.getIdentityFlags(
109+
(String) body.get("identifier"), traits != null ? traits : new HashMap<>());
110+
send(exchange, 200, serialiseFlags(flags));
111+
return;
112+
}
113+
114+
send(exchange, 404, error("No route for " + method + " " + path));
115+
}
116+
117+
private static Map<String, Object> serialiseFlags(Flags flags) {
118+
List<Map<String, Object>> serialised = new ArrayList<>();
119+
for (BaseFlag flag : flags.getAllFlags()) {
120+
Map<String, Object> entry = new LinkedHashMap<>();
121+
entry.put("featureName", flag.getFeatureName());
122+
entry.put("enabled", flag.getEnabled());
123+
// The SDK keeps API values as Jackson nodes, which serialise with their JSON type intact.
124+
entry.put("value", flag.getValue());
125+
serialised.add(entry);
126+
}
127+
return Map.of("flags", serialised);
128+
}
129+
130+
private static Map<String, Object> error(String message) {
131+
return Map.of("error", String.valueOf(message));
132+
}
133+
134+
private static Map<String, Object> body(HttpExchange exchange) throws IOException {
135+
byte[] bytes = exchange.getRequestBody().readAllBytes();
136+
return bytes.length > 0 ? MAPPER.readValue(bytes, JSON_OBJECT) : new HashMap<>();
137+
}
138+
139+
private static void send(HttpExchange exchange, int status, Object body) throws IOException {
140+
if (body == null) {
141+
exchange.sendResponseHeaders(status, -1);
142+
return;
143+
}
144+
byte[] payload = MAPPER.writeValueAsBytes(body);
145+
exchange.getResponseHeaders().set("Content-Type", "application/json");
146+
exchange.sendResponseHeaders(status, payload.length);
147+
try (OutputStream out = exchange.getResponseBody()) {
148+
out.write(payload);
149+
}
150+
}
151+
}

‎spec-adapter/Dockerfile‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Builds the SDK from source with the adapter for the Flagsmith SDK behavioural spec.
2+
# Build from the repository root: docker build -f spec-adapter/Dockerfile .
3+
FROM docker.io/library/maven:3.9-eclipse-temurin-11 AS build
4+
5+
WORKDIR /sdk
6+
COPY pom.xml lombok.config ./
7+
COPY src/main ./src/main
8+
RUN mvn --batch-mode --no-transfer-progress \
9+
-Dmaven.test.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true -Dmaven.source.skip=true \
10+
package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/lib \
11+
&& cp target/flagsmith-java-client-*.jar target/lib/
12+
13+
COPY spec-adapter/Adapter.java ./spec-adapter/
14+
RUN javac -cp "target/lib/*" -d target/adapter spec-adapter/Adapter.java
15+
16+
FROM docker.io/library/eclipse-temurin:11-jre
17+
18+
WORKDIR /adapter
19+
COPY --from=build /sdk/target/lib ./lib
20+
COPY --from=build /sdk/target/adapter ./classes
21+
22+
ENV PORT=8080
23+
EXPOSE 8080
24+
CMD ["java", "-cp", "classes:lib/*", "Adapter"]

0 commit comments

Comments
 (0)