Add openfeature module: OpenFeature Java SDK 1.23.0 and flagd 0.19.0 on Spring Boot 4.2.0, targeting, 10% rollout, live reload, flagd-down behaviour, InMemoryProvider tests, with real transcripts
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6ZEVHGaYy15HAxRzy
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
658bc52e2b
commit
24dc4ba3ff
@@ -9,6 +9,7 @@ files.
|
||||
|
||||
| Directory | Article | What it demonstrates |
|
||||
|---|---|---|
|
||||
| [`openfeature/`](openfeature) | [Feature Flags in Spring Boot with OpenFeature and flagd: Targeting, Gradual Rollout and Failure Modes](https://ankurm.com/spring-boot-feature-flags-openfeature-flagd/) | the OpenFeature Java SDK 1.23.0 and flagd 0.19.0 behind Spring Boot 4.2.0: five flag types and their reasons, targeting by tier and e-mail domain, a 10% rollout measured on 1000 users (100 on, and 0 flipped off when widened to 50%), a flag file edited under a connected client, flagd absent at start (`PROVIDER_NOT_READY`) and killed mid-run (targeted flags fall back to the code default while a static flag keeps answering `CACHED`), unknown keys and type mismatches, `InMemoryProvider` tests of both states and the in-process `FILE` resolver giving the same 100 of 1000 |
|
||||
| [`resttemplate-to-restclient/`](resttemplate-to-restclient) | [RestTemplate Is Deprecated in Spring Framework 7.1: Migrate to RestClient (and TestRestTemplate to RestTestClient)](https://ankurm.com/resttemplate-to-restclient-migration-guide/) | the `[removal]` warnings on 4.2.0 vs none on 4.1.3, every `RestTemplate` method next to its `RestClient` call on one real server, `exchange()` that stops throwing, the `RestClient.create(restTemplate)` bridge that changes URI encoding, PATCH and `User-Agent` of each default stack, an interceptor that eats the body, `TestRestTemplate` vs `RestTestClient`, and the OpenRewrite recipe's output run for real |
|
||||
| [`email/`](email) | [Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing](https://ankurm.com/sending-emails-in-spring-boot-3-a-complete-guide/) | the MIME tree of six message shapes (`multipart/mixed` > `related` > `alternative`, and `addInline` before `setText` putting the image first), Thymeleaf HTML and TEXT templates (`[[...]]` still HTML-escapes in TEXT mode), Devanagari subjects as encoded-words and a wrong `defaultEncoding` turning them into `?`, one `send` per message (5 connections) vs the varargs `send` (1), `@Async` returning in milliseconds and a `void @Async` failure that never reaches the caller, a server that never greets blocking forever until `mail.smtp.timeout` is set (`connectiontimeout` does not help), `starttls.enable` authenticating in plain text while `starttls.required` refuses, an email still sent when the transaction rolls back unless it waits for `AFTER_COMMIT`, all against GreenMail on Spring Boot 4.1.2 |
|
||||
| [`log4j2-levels/`](log4j2-levels) | [Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime](https://ankurm.com/log4j2-logging-levels-complete-guide/) | the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom `DIAG`/`PERF` levels between the standard ones, `/actuator/loggers` rejecting a custom level and a `null` reset landing on the root's level instead of the XML's, `logging.level.*` beating the XML and a custom level in that property stopping the app at startup, argument `toString()` counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback |
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# openfeature
|
||||
|
||||
Companion code for **Feature Flags in Spring Boot with OpenFeature and flagd** on
|
||||
[ankurm.com](https://ankurm.com/spring-boot-feature-flags-openfeature-flagd/).
|
||||
|
||||
A Spring Boot 4.2 app evaluates feature flags through the vendor-neutral OpenFeature client, with flagd (a
|
||||
small flag daemon that watches a JSON file) behind it. One flag file, one `/checkout` endpoint, and a test
|
||||
suite that writes what it saw to `output/`.
|
||||
|
||||
| Piece | Version | Checked against |
|
||||
|---|---|---|
|
||||
| Spring Boot | 4.2.0 | `maven-metadata.xml` for `spring-boot-starter-parent` (GA, jar published 19 Nov 2026) |
|
||||
| JDK | 25 | Temurin 25.0.5 |
|
||||
| OpenFeature Java SDK `dev.openfeature:sdk` | 1.23.0 | `maven-metadata.xml` (`<release>`) |
|
||||
| flagd provider `dev.openfeature.contrib.providers:flagd` | 0.15.0 | `maven-metadata.xml` (`<release>`) |
|
||||
| flagd daemon | 0.19.0 | built with `go install github.com/open-feature/flagd/[email protected]` (the Go module proxy lists it as tagged 17 Nov 2026) |
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
export FLAGD_BIN=/path/to/flagd # or have flagd on the PATH
|
||||
mvn -B test # 11 tests; transcripts 01-08 are written to output/
|
||||
./scripts/run-all.sh # the above plus the HTTP demo (output/09)
|
||||
```
|
||||
|
||||
The 6 tests in `LiveFlagdTest` start a real flagd process on free ports and are **skipped** if no flagd binary
|
||||
is found; the other 5 need nothing but the JDK. To run the application by hand:
|
||||
|
||||
```bash
|
||||
./scripts/run-flagd.sh & # flagd on :8013, watching flags/flags.json
|
||||
mvn spring-boot:run # app on :8080
|
||||
curl -H 'X-User-Id: u3' -H 'X-Tier: premium' localhost:8080/checkout
|
||||
```
|
||||
|
||||
Set `flags.mode=file` (for example `--flags.mode=file`) to evaluate `flags/flags.json` inside the JVM and skip
|
||||
the daemon.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| [`flags/flags.json`](flags/flags.json) | the flag definitions (boolean, string, int, object, targeting, fractional, disabled) |
|
||||
| [`FlagConfig.java`](src/main/java/com/ankurm/openfeature/FlagConfig.java) | registers the provider, hook and event handlers once |
|
||||
| [`CheckoutFlags.java`](src/main/java/com/ankurm/openfeature/CheckoutFlags.java) | the only class that knows flag keys and defaults |
|
||||
| [`CheckoutController.java`](src/main/java/com/ankurm/openfeature/CheckoutController.java) | `GET /checkout`, returns every decision with its variant and reason |
|
||||
| [`LoggingHook.java`](src/main/java/com/ankurm/openfeature/LoggingHook.java) | one log line per evaluation |
|
||||
| [`LiveFlagdTest.java`](src/test/java/com/ankurm/openfeature/LiveFlagdTest.java) | transcripts 01-06 against a real daemon |
|
||||
| [`FileResolverTest.java`](src/test/java/com/ankurm/openfeature/FileResolverTest.java) | transcript 07, no daemon |
|
||||
| [`BothStatesTest.java`](src/test/java/com/ankurm/openfeature/BothStatesTest.java) | transcript 08, `InMemoryProvider` |
|
||||
| [`scripts/http-demo.sh`](scripts/http-demo.sh) | transcript 09: flagd + the app + curl + a live flag edit + flagd killed |
|
||||
|
||||
## Captured output
|
||||
|
||||
| File | What it shows |
|
||||
|---|---|
|
||||
| [`output/01-typed-evaluation.txt`](output/01-typed-evaluation.txt) | five flag types and their reasons |
|
||||
| [`output/02-targeting.txt`](output/02-targeting.txt) | targeting by tier and e-mail domain |
|
||||
| [`output/03-gradual-rollout.txt`](output/03-gradual-rollout.txt) | 1000 users at 10% and 50%, stickiness |
|
||||
| [`output/04-live-reload.txt`](output/04-live-reload.txt) | editing the flag file while connected |
|
||||
| [`output/05-flagd-down.txt`](output/05-flagd-down.txt) | flagd absent at start, and killed mid-run |
|
||||
| [`output/06-errors.txt`](output/06-errors.txt) | unknown flag, typo, wrong type |
|
||||
| [`output/07-file-resolver.txt`](output/07-file-resolver.txt) | the same file evaluated with no daemon |
|
||||
| [`output/08-test-both-states.txt`](output/08-test-both-states.txt) | testing code behind a flag |
|
||||
| [`output/09-http-demo.txt`](output/09-http-demo.txt) | the whole thing over HTTP |
|
||||
|
||||
Timings and gRPC error text drift between runs; the transcripts keep only the first 50 characters of an error.
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"$schema": "https://flagd.dev/schema/v0/flags.json",
|
||||
"flags": {
|
||||
"new-checkout": {
|
||||
"state": "ENABLED",
|
||||
"variants": { "on": true, "off": false },
|
||||
"defaultVariant": "off",
|
||||
"targeting": {
|
||||
"if": [
|
||||
{ "or": [
|
||||
{ "==": [ { "var": "tier" }, "premium" ] },
|
||||
{ "ends_with": [ { "var": "email" }, "@ankurm.com" ] }
|
||||
] },
|
||||
"on",
|
||||
null
|
||||
]
|
||||
}
|
||||
},
|
||||
"payment-flow-v2": {
|
||||
"state": "ENABLED",
|
||||
"variants": { "on": true, "off": false },
|
||||
"defaultVariant": "off",
|
||||
"targeting": {
|
||||
"fractional": [
|
||||
[ "on", 10 ],
|
||||
[ "off", 90 ]
|
||||
]
|
||||
}
|
||||
},
|
||||
"discount-percent": {
|
||||
"state": "ENABLED",
|
||||
"variants": { "none": 0, "small": 5, "big": 20 },
|
||||
"defaultVariant": "none",
|
||||
"targeting": {
|
||||
"if": [
|
||||
{ "==": [ { "var": "tier" }, "premium" ] }, "big",
|
||||
{ "==": [ { "var": "tier" }, "standard" ] }, "small",
|
||||
null
|
||||
]
|
||||
}
|
||||
},
|
||||
"banner-text": {
|
||||
"state": "ENABLED",
|
||||
"variants": { "plain": "Free shipping over 999", "sale": "Year-end sale: extra 5% off" },
|
||||
"defaultVariant": "plain"
|
||||
},
|
||||
"theme": {
|
||||
"state": "ENABLED",
|
||||
"variants": {
|
||||
"calm": { "color": "teal", "density": "comfortable" },
|
||||
"dense": { "color": "slate", "density": "compact" }
|
||||
},
|
||||
"defaultVariant": "calm"
|
||||
},
|
||||
"legacy-export": {
|
||||
"state": "DISABLED",
|
||||
"variants": { "on": true, "off": false },
|
||||
"defaultVariant": "on"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# One flag file, five types, as seen through the OpenFeature client
|
||||
|
||||
evaluation context: targetingKey=anon-1, no attributes
|
||||
boolean flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
string flag=banner-text value=Free shipping over 999 variant=plain reason=STATIC
|
||||
integer flag=discount-percent value=0 variant=none reason=DEFAULT
|
||||
object flag=theme value=[color, density] variant=calm reason=STATIC
|
||||
disabled flag flag=legacy-export value=false variant=null reason=DISABLED
|
||||
@@ -0,0 +1,12 @@
|
||||
# Targeting rules: who sees what
|
||||
|
||||
rule new-checkout : on if tier == premium OR email ends with @ankurm.com, else default (off)
|
||||
anonymous flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
standard flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
premium flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
staff email flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
|
||||
rule discount-percent : premium -> 20, standard -> 5, otherwise default (0)
|
||||
anonymous flag=discount-percent value=0 variant=none reason=DEFAULT
|
||||
standard flag=discount-percent value=5 variant=small reason=TARGETING_MATCH
|
||||
premium flag=discount-percent value=20 variant=big reason=TARGETING_MATCH
|
||||
@@ -0,0 +1,9 @@
|
||||
# Percentage rollout: 1000 users hashed on targetingKey
|
||||
|
||||
split 10/90: users with the flag on = 100 of 1000
|
||||
split 50/50: users with the flag on = 486 of 1000
|
||||
users on at 10% but off at 50% = 0 (growing the share never takes a user back)
|
||||
same user asked twice, same answer = 1000 of 1000
|
||||
|
||||
no targetingKey at all:
|
||||
anonymous flag=payment-flow-v2 value=false variant=off reason=DEFAULT
|
||||
@@ -0,0 +1,8 @@
|
||||
# Edit flags.json while the app is running
|
||||
|
||||
before the edit flag=banner-text value=Free shipping over 999 variant=plain reason=STATIC
|
||||
asked again flag=banner-text value=Free shipping over 999 variant=plain reason=CACHED
|
||||
edit: banner-text defaultVariant plain -> sale
|
||||
provider event: CONFIGURATION_CHANGED, flagsChanged=[banner-text]
|
||||
after the edit flag=banner-text value=Year-end sale: extra 5% off variant=sale reason=STATIC
|
||||
event arrived within 10 s: true (indicative latency: about 923 ms)
|
||||
@@ -0,0 +1,17 @@
|
||||
# flagd is not there
|
||||
|
||||
(a) setProvider() against a closed port, asked immediately
|
||||
provider state: NOT_READY
|
||||
premium user flag=new-checkout value=false variant=null reason=ERROR errorCode=PROVIDER_NOT_READY (Provider not yet initialized)
|
||||
|
||||
(b) setProviderAndWait() against a closed port
|
||||
threw: GeneralError
|
||||
message: Initialization timeout exceeded; did not complete within the 1000 ms deadline.
|
||||
state afterwards: ERROR
|
||||
|
||||
(c) flagd is killed while the app is running
|
||||
before the kill flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
asked again flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
provider state 1.5 s after the kill: STALE
|
||||
same flag, after flag=new-checkout value=false variant=null reason=ERROR errorCode=GENERAL (DEADLINE_EXCEEDED: CallOptions deadline exceeded a...)
|
||||
never-asked flag, after flag=discount-percent value=0 variant=null reason=ERROR errorCode=GENERAL (DEADLINE_EXCEEDED: CallOptions deadline exceeded a...)
|
||||
@@ -0,0 +1,6 @@
|
||||
# Mistakes the client absorbs: the in-code default is returned, with a reason
|
||||
|
||||
unknown flag flag=no-such-flag value=true variant=null reason=ERROR errorCode=FLAG_NOT_FOUND (NOT_FOUND: Flag not found)
|
||||
typo in the key flag=new-chekout value=false variant=null reason=ERROR errorCode=FLAG_NOT_FOUND (NOT_FOUND: Flag not found)
|
||||
boolean asked of a string flag=banner-text value=true variant=null reason=ERROR errorCode=TYPE_MISMATCH (INVALID_ARGUMENT: Type mismatch error)
|
||||
string asked of an int flag=discount-percent value=n/a variant=null reason=ERROR errorCode=TYPE_MISMATCH (INVALID_ARGUMENT: Type mismatch error)
|
||||
@@ -0,0 +1,7 @@
|
||||
# FILE resolver: the same flags.json evaluated inside the JVM
|
||||
|
||||
premium flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
staff email flag=new-checkout value=true variant=on reason=TARGETING_MATCH
|
||||
anonymous flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
banner flag=banner-text value=Free shipping over 999 variant=plain reason=STATIC
|
||||
payment-flow-v2 on for 100 of 1000 users (the flagd daemon said 100 in transcript 03)
|
||||
@@ -0,0 +1,5 @@
|
||||
# Testing behind a flag with InMemoryProvider (no flagd, no network)
|
||||
|
||||
new-checkout, defaultVariant=off anonymous -> false
|
||||
same flag, now with a context evaluator anonymous -> false, premium -> true
|
||||
tests in this class: flagOff, flagOn, flipTheStateInsideOneTestAndTargetByContext
|
||||
@@ -0,0 +1,56 @@
|
||||
# 1. Three callers, one flag file
|
||||
$ curl -H 'X-User-Id: anon-1' localhost:8080/checkout # anonymous
|
||||
page: legacy-checkout
|
||||
newCheckout: {"value": false, "variant": "off", "reason": "DEFAULT"}
|
||||
paymentFlowV2: {"value": false, "variant": "off", "reason": "TARGETING_MATCH"}
|
||||
discountPercent: {"value": 0, "variant": "none", "reason": "DEFAULT"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
$ curl -H 'X-User-Id: u2' -H 'X-Tier: standard' localhost:8080/checkout # standard
|
||||
page: legacy-checkout
|
||||
newCheckout: {"value": false, "variant": "off", "reason": "DEFAULT"}
|
||||
paymentFlowV2: {"value": false, "variant": "off", "reason": "TARGETING_MATCH"}
|
||||
discountPercent: {"value": 5, "variant": "small", "reason": "TARGETING_MATCH"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
$ curl -H 'X-User-Id: u3' -H 'X-Tier: premium' localhost:8080/checkout # premium
|
||||
page: new-checkout
|
||||
newCheckout: {"value": true, "variant": "on", "reason": "TARGETING_MATCH"}
|
||||
paymentFlowV2: {"value": false, "variant": "off", "reason": "TARGETING_MATCH"}
|
||||
discountPercent: {"value": 20, "variant": "big", "reason": "TARGETING_MATCH"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
$ curl -H 'X-User-Id: u4' -H 'X-Tier: standard' -H 'X-Email: [email protected]' localhost:8080/checkout # staff
|
||||
page: new-checkout
|
||||
newCheckout: {"value": true, "variant": "on", "reason": "TARGETING_MATCH"}
|
||||
paymentFlowV2: {"value": false, "variant": "off", "reason": "TARGETING_MATCH"}
|
||||
discountPercent: {"value": 5, "variant": "small", "reason": "TARGETING_MATCH"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
# 2. Edit the flag file: new-checkout defaultVariant off -> on (no restart, no deploy)
|
||||
$ curl -H 'X-User-Id: anon-1' localhost:8080/checkout # anonymous, after the edit
|
||||
page: new-checkout
|
||||
newCheckout: {"value": true, "variant": "on", "reason": "DEFAULT"}
|
||||
paymentFlowV2: {"value": false, "variant": "off", "reason": "TARGETING_MATCH"}
|
||||
discountPercent: {"value": 0, "variant": "none", "reason": "DEFAULT"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
# 3. Kill flagd
|
||||
$ curl -H 'X-User-Id: u3' -H 'X-Tier: premium' localhost:8080/checkout # premium, flagd gone
|
||||
page: legacy-checkout
|
||||
newCheckout: {"value": false, "variant": null, "reason": "ERROR", "errorCode": "GENERAL"}
|
||||
paymentFlowV2: {"value": false, "variant": null, "reason": "ERROR", "errorCode": "GENERAL"}
|
||||
discountPercent: {"value": 0, "variant": null, "reason": "ERROR", "errorCode": "GENERAL"}
|
||||
banner: {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
|
||||
|
||||
|
||||
# Application log: provider events, then the first hook lines
|
||||
INFO com.ankurm.openfeature.FlagConfig : flag provider READY (flagd)
|
||||
INFO com.ankurm.openfeature.FlagConfig : flag provider READY (flagd)
|
||||
INFO com.ankurm.openfeature.FlagConfig : flag configuration changed: [new-checkout]
|
||||
WARN com.ankurm.openfeature.FlagConfig : flag provider STALE: there has been an error
|
||||
...
|
||||
INFO flags : flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
INFO flags : flag=new-checkout value=false variant=off reason=DEFAULT
|
||||
INFO flags : flag=payment-flow-v2 value=false variant=off reason=DEFAULT
|
||||
INFO flags : flag=discount-percent value=0 variant=none reason=DEFAULT
|
||||
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>openfeature</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>openfeature</name>
|
||||
<description>Feature flags in Spring Boot 4.2 with the OpenFeature Java SDK and flagd: typed evaluation, targeting rules, gradual rollout, live reload, failure modes and testing both states</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<openfeature.sdk.version>1.23.0</openfeature.sdk.version>
|
||||
<flagd.provider.version>0.15.0</flagd.provider.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dev.openfeature</groupId>
|
||||
<artifactId>sdk</artifactId>
|
||||
<version>${openfeature.sdk.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dev.openfeature.contrib.providers</groupId>
|
||||
<artifactId>flagd</artifactId>
|
||||
<version>${flagd.provider.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# End-to-end: a real flagd daemon, the Spring Boot app, curl, a live flag edit, then flagd killed.
|
||||
# Writes output/09-http-demo.txt. Needs FLAGD_BIN (or flagd on PATH), JAVA_HOME on JDK 25, mvn.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
FLAGD="${FLAGD_BIN:-flagd}"
|
||||
OUT=output/09-http-demo.txt
|
||||
WORK="$(mktemp -d)"
|
||||
cp flags/flags.json "$WORK/flags.json"
|
||||
mkdir -p output
|
||||
|
||||
mvn -B -q -DskipTests package
|
||||
"$FLAGD" start -f "file:$WORK/flags.json" > "$WORK/flagd.log" 2>&1 &
|
||||
FLAGD_PID=$!
|
||||
for i in $(seq 1 30); do (echo > /dev/tcp/localhost/8013) 2>/dev/null && break; sleep 1; done
|
||||
java -jar target/openfeature-1.0.0.jar > "$WORK/app.log" 2>&1 &
|
||||
APP_PID=$!
|
||||
trap 'kill $APP_PID $FLAGD_PID 2>/dev/null || true' EXIT
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
curl -s -o /dev/null localhost:8080/checkout && break
|
||||
sleep 1
|
||||
done
|
||||
sleep 2 # let the provider finish connecting
|
||||
|
||||
call() { # call <label> <header>...
|
||||
local label="$1"; shift
|
||||
local args=() shown=""
|
||||
for h in "$@"; do args+=(-H "$h"); shown+="-H '$h' "; done
|
||||
echo "\$ curl ${shown}localhost:8080/checkout # $label"
|
||||
curl -s "${args[@]}" localhost:8080/checkout | python3 -c '
|
||||
import json, sys
|
||||
d = json.load(sys.stdin)
|
||||
print(" page:", d["page"])
|
||||
for k in ("newCheckout", "paymentFlowV2", "discountPercent", "banner"):
|
||||
print(" %-16s %s" % (k + ":", json.dumps(d[k])))'
|
||||
echo
|
||||
}
|
||||
|
||||
{
|
||||
echo "# 1. Three callers, one flag file"
|
||||
call "anonymous" "X-User-Id: anon-1"
|
||||
call "standard" "X-User-Id: u2" "X-Tier: standard"
|
||||
call "premium" "X-User-Id: u3" "X-Tier: premium"
|
||||
call "staff" "X-User-Id: u4" "X-Tier: standard" "X-Email: [email protected]"
|
||||
|
||||
echo "# 2. Edit the flag file: new-checkout defaultVariant off -> on (no restart, no deploy)"
|
||||
sed -i '/"new-checkout"/,/"defaultVariant"/ s/"defaultVariant": "off"/"defaultVariant": "on"/' "$WORK/flags.json"
|
||||
sleep 2
|
||||
call "anonymous, after the edit" "X-User-Id: anon-1"
|
||||
|
||||
echo "# 3. Kill flagd"
|
||||
kill "$FLAGD_PID"; wait "$FLAGD_PID" 2>/dev/null || true
|
||||
sleep 2
|
||||
call "premium, flagd gone" "X-User-Id: u3" "X-Tier: premium"
|
||||
} > "$OUT" 2>&1
|
||||
|
||||
{
|
||||
echo
|
||||
echo "# Application log: provider events, then the first hook lines"
|
||||
strip() { sed -E 's/^[^ ]+ +([A-Z]+) [0-9]+ --- \[[^]]*\] +/\1 /' | cut -c1-150; }
|
||||
grep -E 'flag provider|flag configuration' "$WORK/app.log" | strip | head -8
|
||||
echo "..."
|
||||
grep -E ': flag=' "$WORK/app.log" | strip | head -4
|
||||
} >> "$OUT"
|
||||
echo "wrote $OUT"
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerate every transcript in output/. Needs JDK 25, Maven 3.9, and a flagd binary (FLAGD_BIN).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -f output/*.txt
|
||||
mvn -B test # writes output/01..08 (the live tests are skipped if flagd is missing)
|
||||
./scripts/http-demo.sh # writes output/09
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start a flagd daemon on flags/flags.json (gRPC evaluation on 8013). flagd watches the file,
|
||||
# so editing it while this runs is the "change a flag without a deploy" demo.
|
||||
# FLAGD_BIN=/path/to/flagd ./scripts/run-flagd.sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec "${FLAGD_BIN:-flagd}" start -f "file:$(pwd)/flags/flags.json"
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.EvaluationContext;
|
||||
import dev.openfeature.sdk.FlagEvaluationDetails;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class CheckoutController {
|
||||
|
||||
private final CheckoutFlags flags;
|
||||
|
||||
public CheckoutController(CheckoutFlags flags) {
|
||||
this.flags = flags;
|
||||
}
|
||||
|
||||
/** Shows every flag decision for the caller, including the variant and the reason. */
|
||||
@GetMapping("/checkout")
|
||||
Map<String, Object> checkout(@RequestHeader(value = "X-User-Id", required = false) String userId,
|
||||
@RequestHeader(value = "X-Tier", required = false) String tier,
|
||||
@RequestHeader(value = "X-Email", required = false) String email) {
|
||||
EvaluationContext ctx = CheckoutFlags.userContext(userId, tier, email);
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("user", userId);
|
||||
body.put("tier", tier);
|
||||
body.put("page", flags.newCheckout(ctx) ? "new-checkout" : "legacy-checkout");
|
||||
body.put("newCheckout", describe(flags.newCheckoutDetails(ctx)));
|
||||
body.put("paymentFlowV2", describe(flags.paymentFlowV2(ctx)));
|
||||
body.put("discountPercent", describe(flags.discountPercent(ctx)));
|
||||
body.put("banner", describe(flags.banner(ctx)));
|
||||
return body;
|
||||
}
|
||||
|
||||
private static Map<String, Object> describe(FlagEvaluationDetails<?> d) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("value", d.getValue());
|
||||
m.put("variant", d.getVariant());
|
||||
m.put("reason", d.getReason());
|
||||
if (d.getErrorCode() != null) m.put("errorCode", d.getErrorCode().name());
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.EvaluationContext;
|
||||
import dev.openfeature.sdk.FlagEvaluationDetails;
|
||||
import dev.openfeature.sdk.ImmutableContext;
|
||||
import dev.openfeature.sdk.ImmutableStructure;
|
||||
import dev.openfeature.sdk.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The only class that knows flag keys. Business code asks a question ("is the new checkout on
|
||||
* for this user?"); the flag key, the default and the context shape live here, in one place.
|
||||
*/
|
||||
@Service
|
||||
public class CheckoutFlags {
|
||||
|
||||
public static final String NEW_CHECKOUT = "new-checkout";
|
||||
public static final String PAYMENT_FLOW_V2 = "payment-flow-v2";
|
||||
public static final String DISCOUNT_PERCENT = "discount-percent";
|
||||
public static final String BANNER_TEXT = "banner-text";
|
||||
public static final String THEME = "theme";
|
||||
|
||||
private final Client client;
|
||||
|
||||
public CheckoutFlags(Client client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
/** Who is asking. The targeting key is what percentage rollouts hash on. */
|
||||
public static EvaluationContext userContext(String userId, String tier, String email) {
|
||||
Map<String, Value> attrs = new HashMap<>();
|
||||
if (tier != null) attrs.put("tier", new Value(tier));
|
||||
if (email != null) attrs.put("email", new Value(email));
|
||||
return new ImmutableContext(userId, attrs);
|
||||
}
|
||||
|
||||
public boolean newCheckout(EvaluationContext ctx) {
|
||||
return client.getBooleanValue(NEW_CHECKOUT, false, ctx);
|
||||
}
|
||||
|
||||
public FlagEvaluationDetails<Boolean> newCheckoutDetails(EvaluationContext ctx) {
|
||||
return client.getBooleanDetails(NEW_CHECKOUT, false, ctx);
|
||||
}
|
||||
|
||||
public FlagEvaluationDetails<Boolean> paymentFlowV2(EvaluationContext ctx) {
|
||||
return client.getBooleanDetails(PAYMENT_FLOW_V2, false, ctx);
|
||||
}
|
||||
|
||||
public FlagEvaluationDetails<Integer> discountPercent(EvaluationContext ctx) {
|
||||
return client.getIntegerDetails(DISCOUNT_PERCENT, 0, ctx);
|
||||
}
|
||||
|
||||
public FlagEvaluationDetails<String> banner(EvaluationContext ctx) {
|
||||
return client.getStringDetails(BANNER_TEXT, "Welcome", ctx);
|
||||
}
|
||||
|
||||
public FlagEvaluationDetails<Value> theme(EvaluationContext ctx) {
|
||||
return client.getObjectDetails(THEME, new Value(new ImmutableStructure(Map.of("color", new Value("grey")))), ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.contrib.providers.flagd.Config;
|
||||
import dev.openfeature.contrib.providers.flagd.FlagdOptions;
|
||||
import dev.openfeature.contrib.providers.flagd.FlagdProvider;
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.OpenFeatureAPI;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires OpenFeature once per JVM: choose a provider, register a logging hook, hand out a Client.
|
||||
*
|
||||
* <p>{@code setProvider} (not {@code setProviderAndWait}) is deliberate: the application starts even
|
||||
* when flagd is down, and every evaluation returns the in-code default until the provider is READY.
|
||||
*/
|
||||
@Configuration
|
||||
public class FlagConfig {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FlagConfig.class);
|
||||
|
||||
@Bean
|
||||
Client featureClient(FlagProperties props) {
|
||||
FlagdOptions options = "file".equals(props.mode())
|
||||
? FlagdOptions.builder()
|
||||
.resolverType(Config.Resolver.FILE)
|
||||
.offlineFlagSourcePath(props.file())
|
||||
.build()
|
||||
: FlagdOptions.builder()
|
||||
.resolverType(Config.Resolver.RPC)
|
||||
.host(props.host())
|
||||
.port(props.port())
|
||||
.build();
|
||||
|
||||
OpenFeatureAPI api = OpenFeatureAPI.getInstance();
|
||||
api.onProviderReady(e -> log.info("flag provider READY ({})", e.getProviderName()));
|
||||
api.onProviderConfigurationChanged(e -> log.info("flag configuration changed: {}", e.getFlagsChanged()));
|
||||
api.onProviderError(e -> log.warn("flag provider ERROR: {}", e.getMessage()));
|
||||
api.onProviderStale(e -> log.warn("flag provider STALE: {}", e.getMessage()));
|
||||
api.addHooks(new LoggingHook());
|
||||
api.setProvider(new FlagdProvider(options));
|
||||
return api.getClient("checkout");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Where the flag values come from.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code rpc} - talk to a flagd daemon over gRPC (host/port); flagd owns the flag file.</li>
|
||||
* <li>{@code file} - evaluate the same JSON file inside the JVM, no daemon at all.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "flags")
|
||||
public record FlagProperties(String mode, String host, int port, String file) {
|
||||
public FlagProperties {
|
||||
if (mode == null) mode = "rpc";
|
||||
if (host == null) host = "localhost";
|
||||
if (port == 0) port = 8013;
|
||||
if (file == null) file = "flags/flags.json";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.FlagEvaluationDetails;
|
||||
import dev.openfeature.sdk.Hook;
|
||||
import dev.openfeature.sdk.HookContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** One log line per evaluation: which flag, what came back, and why. */
|
||||
public class LoggingHook implements Hook<Object> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger("flags");
|
||||
|
||||
@Override
|
||||
public void after(HookContext<Object> ctx, FlagEvaluationDetails<Object> details, Map<String, Object> hints) {
|
||||
log.info("flag={} value={} variant={} reason={}",
|
||||
details.getFlagKey(), details.getValue(), details.getVariant(), details.getReason());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(HookContext<Object> ctx, Exception error, Map<String, Object> hints) {
|
||||
log.warn("flag={} error={}", ctx.getFlagKey(), error.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties(FlagProperties.class)
|
||||
public class OpenFeatureApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OpenFeatureApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
# flags.mode=rpc -> flagd daemon at flags.host:flags.port (gRPC, port 8013)
|
||||
# flags.mode=file -> evaluate flags/flags.json inside the JVM, no daemon
|
||||
flags:
|
||||
mode: rpc
|
||||
host: localhost
|
||||
port: 8013
|
||||
file: flags/flags.json
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.EvaluationContext;
|
||||
import dev.openfeature.sdk.OpenFeatureAPI;
|
||||
import dev.openfeature.sdk.providers.memory.Flag;
|
||||
import dev.openfeature.sdk.providers.memory.InMemoryProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* How to test code that sits behind a flag: an isolated API and an InMemoryProvider.
|
||||
* No flagd, no network, and every test chooses its own flag state.
|
||||
*/
|
||||
class BothStatesTest {
|
||||
|
||||
private static Map<String, Flag<?>> flags(boolean newCheckoutOn) {
|
||||
Map<String, Flag<?>> m = new HashMap<>();
|
||||
m.put(CheckoutFlags.NEW_CHECKOUT, Flag.<Boolean>builder()
|
||||
.variant("on", true).variant("off", false)
|
||||
.defaultVariant(newCheckoutOn ? "on" : "off")
|
||||
.build());
|
||||
return m;
|
||||
}
|
||||
|
||||
private static CheckoutFlags service(OpenFeatureAPI api, InMemoryProvider provider) throws Exception {
|
||||
api.setProviderAndWait(provider);
|
||||
Client client = api.getClient();
|
||||
return new CheckoutFlags(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void flagOff() throws Exception {
|
||||
CheckoutFlags f = service(OpenFeatureAPI.createIsolated(), new InMemoryProvider(flags(false)));
|
||||
assertFalse(f.newCheckout(CheckoutFlags.userContext("u1", null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flagOn() throws Exception {
|
||||
CheckoutFlags f = service(OpenFeatureAPI.createIsolated(), new InMemoryProvider(flags(true)));
|
||||
assertTrue(f.newCheckout(CheckoutFlags.userContext("u1", null, null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void flipTheStateInsideOneTestAndTargetByContext() throws Exception {
|
||||
InMemoryProvider provider = new InMemoryProvider(flags(false));
|
||||
CheckoutFlags f = service(OpenFeatureAPI.createIsolated(), provider);
|
||||
EvaluationContext anon = CheckoutFlags.userContext("u1", null, null);
|
||||
EvaluationContext premium = CheckoutFlags.userContext("u2", "premium", null);
|
||||
|
||||
boolean before = f.newCheckout(anon);
|
||||
provider.updateFlag(CheckoutFlags.NEW_CHECKOUT, Flag.<Boolean>builder()
|
||||
.variant("on", true).variant("off", false).defaultVariant("off")
|
||||
.contextEvaluator((flag, ctx) -> ctx.getValue("tier") != null
|
||||
&& "premium".equals(ctx.getValue("tier").asString()))
|
||||
.build());
|
||||
boolean anonAfter = f.newCheckout(anon);
|
||||
boolean premiumAfter = f.newCheckout(premium);
|
||||
|
||||
new Transcript("08-test-both-states.txt", "Testing behind a flag with InMemoryProvider (no flagd, no network)")
|
||||
.line("new-checkout, defaultVariant=off anonymous -> %s", before)
|
||||
.line("same flag, now with a context evaluator anonymous -> %s, premium -> %s", anonAfter, premiumAfter)
|
||||
.line("tests in this class: flagOff, flagOn, flipTheStateInsideOneTestAndTargetByContext")
|
||||
.write();
|
||||
|
||||
assertFalse(before);
|
||||
assertFalse(anonAfter);
|
||||
assertTrue(premiumAfter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingFlagFallsBackToTheCodeDefault() throws Exception {
|
||||
CheckoutFlags f = service(OpenFeatureAPI.createIsolated(), new InMemoryProvider(Map.of()));
|
||||
assertFalse(f.newCheckout(CheckoutFlags.userContext("u1", "premium", null)),
|
||||
"an unknown flag must give the default (false), not an exception");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.OpenFeatureAPI;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static com.ankurm.openfeature.CheckoutFlags.userContext;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** No daemon: the provider reads flags/flags.json itself. Same file, same rules, same hashing. */
|
||||
class FileResolverTest {
|
||||
|
||||
@Test
|
||||
void sameFileSameAnswersWithoutADaemon() throws Exception {
|
||||
Client c = Providers.file(OpenFeatureAPI.createIsolated(), Path.of("flags/flags.json"));
|
||||
|
||||
var premium = c.getBooleanDetails("new-checkout", false, userContext("u3", "premium", null));
|
||||
var staff = c.getBooleanDetails("new-checkout", false, userContext("u4", "standard", "[email protected]"));
|
||||
var anon = c.getBooleanDetails("new-checkout", false, userContext("u1", null, null));
|
||||
var banner = c.getStringDetails("banner-text", "Welcome", userContext("u1", null, null));
|
||||
|
||||
int on = 0;
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
if (c.getBooleanValue("payment-flow-v2", false, userContext("user-%04d".formatted(i), null, null))) on++;
|
||||
}
|
||||
|
||||
new Transcript("07-file-resolver.txt", "FILE resolver: the same flags.json evaluated inside the JVM")
|
||||
.eval("premium", premium).eval("staff email", staff).eval("anonymous", anon).eval("banner", banner)
|
||||
.line("payment-flow-v2 on for %d of 1000 users (the flagd daemon said 100 in transcript 03)", on)
|
||||
.write();
|
||||
|
||||
assertTrue(premium.getValue());
|
||||
assertTrue(staff.getValue());
|
||||
assertFalse(anon.getValue());
|
||||
assertEquals(100, on, "in-process bucketing must match the daemon's");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Starts a real flagd process on free ports, pointed at a flag file. The binary comes from the
|
||||
* FLAGD_BIN environment variable, or "flagd" on the PATH. Tests that need it skip when it is missing.
|
||||
*/
|
||||
final class FlagdDaemon implements AutoCloseable {
|
||||
|
||||
final int rpcPort = freePort();
|
||||
final Path flagFile;
|
||||
private final Process process;
|
||||
|
||||
static boolean available() {
|
||||
try {
|
||||
Process p = new ProcessBuilder(binary(), "version").redirectErrorStream(true).start();
|
||||
p.getInputStream().readAllBytes();
|
||||
return p.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static String binary() {
|
||||
String env = System.getenv("FLAGD_BIN");
|
||||
return env != null ? env : "flagd";
|
||||
}
|
||||
|
||||
/** Copies the flag file into a temp directory first, so tests can edit it without touching the repo copy. */
|
||||
FlagdDaemon(Path source) throws IOException {
|
||||
this.flagFile = Files.createTempFile("flags-", ".json");
|
||||
Files.copy(source, flagFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
this.process = new ProcessBuilder(binary(), "start",
|
||||
"-f", "file:" + flagFile.toAbsolutePath(),
|
||||
"-p", String.valueOf(rpcPort),
|
||||
"-m", String.valueOf(freePort()),
|
||||
"-g", String.valueOf(freePort()),
|
||||
"-r", String.valueOf(freePort()))
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
waitForPort();
|
||||
}
|
||||
|
||||
private void waitForPort() throws IOException {
|
||||
long deadline = System.currentTimeMillis() + 15_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
try (Socket s = new Socket()) {
|
||||
s.connect(new InetSocketAddress("localhost", rpcPort), 200);
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }
|
||||
}
|
||||
}
|
||||
throw new IOException("flagd did not open port " + rpcPort);
|
||||
}
|
||||
|
||||
/** Stops the daemon, as a crash or a deploy would. */
|
||||
void kill() {
|
||||
process.destroyForcibly();
|
||||
try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
kill();
|
||||
}
|
||||
|
||||
static int freePort() {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
return s.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.ErrorCode;
|
||||
import dev.openfeature.sdk.FlagEvaluationDetails;
|
||||
import dev.openfeature.sdk.OpenFeatureAPI;
|
||||
import dev.openfeature.sdk.Value;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.ankurm.openfeature.CheckoutFlags.userContext;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/** Everything here talks to a real flagd process over gRPC. Skipped when no flagd binary is found. */
|
||||
class LiveFlagdTest {
|
||||
|
||||
static final Path FLAGS = Path.of("flags/flags.json");
|
||||
|
||||
@BeforeAll
|
||||
static void needFlagd() {
|
||||
assumeTrue(FlagdDaemon.available(), "flagd binary not found (set FLAGD_BIN)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void typedEvaluationWithReasons() throws Exception {
|
||||
try (var flagd = new FlagdDaemon(FLAGS)) {
|
||||
OpenFeatureAPI api = OpenFeatureAPI.createIsolated();
|
||||
Client c = Providers.rpc(api, flagd.rpcPort);
|
||||
var anon = userContext("anon-1", null, null);
|
||||
|
||||
var bool = c.getBooleanDetails("new-checkout", false, anon);
|
||||
var str = c.getStringDetails("banner-text", "Welcome", anon);
|
||||
var num = c.getIntegerDetails("discount-percent", 0, anon);
|
||||
var obj = c.getObjectDetails("theme", new Value("fallback"), anon);
|
||||
var off = c.getBooleanDetails("legacy-export", false, anon);
|
||||
|
||||
new Transcript("01-typed-evaluation.txt", "One flag file, five types, as seen through the OpenFeature client")
|
||||
.line("evaluation context: targetingKey=anon-1, no attributes")
|
||||
.eval("boolean", bool).eval("string", str).eval("integer", num)
|
||||
.line("%-22s flag=theme value=%s variant=%s reason=%s", "object", obj.getValue().asStructure().asMap().keySet().stream().sorted().toList(), obj.getVariant(), obj.getReason())
|
||||
.eval("disabled flag", off)
|
||||
.write();
|
||||
|
||||
assertFalse(bool.getValue());
|
||||
assertEquals("DEFAULT", bool.getReason());
|
||||
assertEquals("STATIC", str.getReason());
|
||||
assertEquals(0, num.getValue());
|
||||
assertEquals("DISABLED", off.getReason());
|
||||
assertFalse(off.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetingRules() throws Exception {
|
||||
try (var flagd = new FlagdDaemon(FLAGS)) {
|
||||
Client c = Providers.rpc(OpenFeatureAPI.createIsolated(), flagd.rpcPort);
|
||||
|
||||
var anon = c.getBooleanDetails("new-checkout", false, userContext("u1", null, null));
|
||||
var standard = c.getBooleanDetails("new-checkout", false, userContext("u2", "standard", "[email protected]"));
|
||||
var premium = c.getBooleanDetails("new-checkout", false, userContext("u3", "premium", "[email protected]"));
|
||||
var staff = c.getBooleanDetails("new-checkout", false, userContext("u4", "standard", "[email protected]"));
|
||||
|
||||
var dAnon = c.getIntegerDetails("discount-percent", 0, userContext("u1", null, null));
|
||||
var dStd = c.getIntegerDetails("discount-percent", 0, userContext("u2", "standard", null));
|
||||
var dPrem = c.getIntegerDetails("discount-percent", 0, userContext("u3", "premium", null));
|
||||
|
||||
new Transcript("02-targeting.txt", "Targeting rules: who sees what")
|
||||
.line("rule new-checkout : on if tier == premium OR email ends with @ankurm.com, else default (off)")
|
||||
.eval("anonymous", anon).eval("standard", standard).eval("premium", premium).eval("staff email", staff)
|
||||
.line("")
|
||||
.line("rule discount-percent : premium -> 20, standard -> 5, otherwise default (0)")
|
||||
.eval("anonymous", dAnon).eval("standard", dStd).eval("premium", dPrem)
|
||||
.write();
|
||||
|
||||
assertFalse(anon.getValue());
|
||||
assertEquals("DEFAULT", anon.getReason());
|
||||
assertFalse(standard.getValue());
|
||||
assertTrue(premium.getValue());
|
||||
assertEquals("TARGETING_MATCH", premium.getReason());
|
||||
assertTrue(staff.getValue());
|
||||
assertEquals(0, dAnon.getValue());
|
||||
assertEquals(5, dStd.getValue());
|
||||
assertEquals(20, dPrem.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void gradualRolloutIsStickyWhenTheShareGrows() throws Exception {
|
||||
Path widened = Files.createTempFile("flags-50-", ".json");
|
||||
Files.writeString(widened, Files.readString(FLAGS)
|
||||
.replace("[ \"on\", 10 ]", "[ \"on\", 50 ]").replace("[ \"off\", 90 ]", "[ \"off\", 50 ]"));
|
||||
assertNotEquals(Files.readString(FLAGS), Files.readString(widened), "the 10/90 split must have been rewritten");
|
||||
|
||||
int users = 1000;
|
||||
boolean[] at10 = new boolean[users];
|
||||
boolean[] at50 = new boolean[users];
|
||||
boolean[] repeat = new boolean[users];
|
||||
|
||||
try (var d10 = new FlagdDaemon(FLAGS); var d50 = new FlagdDaemon(widened)) {
|
||||
Client c10 = Providers.rpc(OpenFeatureAPI.createIsolated(), d10.rpcPort);
|
||||
Client c50 = Providers.rpc(OpenFeatureAPI.createIsolated(), d50.rpcPort);
|
||||
for (int i = 0; i < users; i++) {
|
||||
var ctx = userContext("user-%04d".formatted(i), null, null);
|
||||
at10[i] = c10.getBooleanValue("payment-flow-v2", false, ctx);
|
||||
repeat[i] = c10.getBooleanValue("payment-flow-v2", false, ctx);
|
||||
at50[i] = c50.getBooleanValue("payment-flow-v2", false, ctx);
|
||||
}
|
||||
var noKey = c10.getBooleanDetails("payment-flow-v2", false, userContext(null, null, null));
|
||||
|
||||
int on10 = 0, on50 = 0, flippedOff = 0, same = 0;
|
||||
for (int i = 0; i < users; i++) {
|
||||
if (at10[i]) on10++;
|
||||
if (at50[i]) on50++;
|
||||
if (at10[i] && !at50[i]) flippedOff++;
|
||||
if (at10[i] == repeat[i]) same++;
|
||||
}
|
||||
new Transcript("03-gradual-rollout.txt", "Percentage rollout: 1000 users hashed on targetingKey")
|
||||
.line("split 10/90: users with the flag on = %d of %d", on10, users)
|
||||
.line("split 50/50: users with the flag on = %d of %d", on50, users)
|
||||
.line("users on at 10%% but off at 50%% = %d (growing the share never takes a user back)", flippedOff)
|
||||
.line("same user asked twice, same answer = %d of %d", same, users)
|
||||
.line("")
|
||||
.line("no targetingKey at all:")
|
||||
.eval("anonymous", noKey)
|
||||
.write();
|
||||
|
||||
assertEquals(users, same);
|
||||
assertEquals(0, flippedOff);
|
||||
assertTrue(on10 > 60 && on10 < 140, "about 10%: " + on10);
|
||||
assertTrue(on50 > 440 && on50 < 560, "about 50%: " + on50);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingTheFlagFileChangesTheAnswerWithoutARestart() throws Exception {
|
||||
try (var flagd = new FlagdDaemon(FLAGS)) {
|
||||
OpenFeatureAPI api = OpenFeatureAPI.createIsolated();
|
||||
CountDownLatch changed = new CountDownLatch(1);
|
||||
java.util.concurrent.atomic.AtomicReference<java.util.List<String>> flagsChanged = new java.util.concurrent.atomic.AtomicReference<>();
|
||||
api.onProviderConfigurationChanged(e -> { flagsChanged.set(e.getFlagsChanged()); changed.countDown(); });
|
||||
Client c = Providers.rpc(api, flagd.rpcPort);
|
||||
var ctx = userContext("anon-1", null, null);
|
||||
|
||||
var before = c.getStringDetails("banner-text", "Welcome", ctx);
|
||||
var beforeAgain = c.getStringDetails("banner-text", "Welcome", ctx);
|
||||
|
||||
long t0 = System.nanoTime();
|
||||
Files.writeString(flagd.flagFile, Files.readString(flagd.flagFile)
|
||||
.replace("\"defaultVariant\": \"plain\"", "\"defaultVariant\": \"sale\""));
|
||||
boolean gotEvent = changed.await(10, TimeUnit.SECONDS);
|
||||
long ms = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0);
|
||||
var after = c.getStringDetails("banner-text", "Welcome", ctx);
|
||||
|
||||
new Transcript("04-live-reload.txt", "Edit flags.json while the app is running")
|
||||
.eval("before the edit", before)
|
||||
.eval("asked again", beforeAgain)
|
||||
.line("edit: banner-text defaultVariant plain -> sale")
|
||||
.line("provider event: CONFIGURATION_CHANGED, flagsChanged=%s", flagsChanged.get())
|
||||
.eval("after the edit", after)
|
||||
.line("event arrived within 10 s: %s (indicative latency: about %d ms)", gotEvent, ms)
|
||||
.write();
|
||||
System.out.println("live-reload event latency ms=" + ms);
|
||||
|
||||
assertTrue(gotEvent, "CONFIGURATION_CHANGED must arrive");
|
||||
assertEquals("Free shipping over 999", before.getValue());
|
||||
assertEquals("Year-end sale: extra 5% off", after.getValue());
|
||||
assertEquals("banner-text", flagsChanged.get().getFirst());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFlagdIsUnreachableTheDefaultWins() throws Exception {
|
||||
int deadPort = FlagdDaemon.freePort();
|
||||
Transcript t = new Transcript("05-flagd-down.txt", "flagd is not there");
|
||||
|
||||
// (a) async registration: the app starts, evaluations fall back to the in-code default
|
||||
OpenFeatureAPI api = OpenFeatureAPI.createIsolated();
|
||||
api.setProvider(new dev.openfeature.contrib.providers.flagd.FlagdProvider(
|
||||
dev.openfeature.contrib.providers.flagd.FlagdOptions.builder()
|
||||
.resolverType(dev.openfeature.contrib.providers.flagd.Config.Resolver.RPC)
|
||||
.host("localhost").port(deadPort).deadline(500).build()));
|
||||
Client c = api.getClient();
|
||||
var ctx = userContext("u3", "premium", null);
|
||||
var d = c.getBooleanDetails("new-checkout", false, ctx);
|
||||
t.line("(a) setProvider() against a closed port, asked immediately")
|
||||
.line(" provider state: %s", c.getProviderState())
|
||||
.eval(" premium user", d);
|
||||
assertFalse(d.getValue());
|
||||
assertEquals(ErrorCode.PROVIDER_NOT_READY, d.getErrorCode());
|
||||
assertEquals("ERROR", d.getReason());
|
||||
|
||||
// (b) blocking registration: the failure is loud
|
||||
OpenFeatureAPI strict = OpenFeatureAPI.createIsolated();
|
||||
long t0 = System.nanoTime();
|
||||
Throwable failure = null;
|
||||
try {
|
||||
strict.setProviderAndWait(new dev.openfeature.contrib.providers.flagd.FlagdProvider(
|
||||
dev.openfeature.contrib.providers.flagd.FlagdOptions.builder()
|
||||
.resolverType(dev.openfeature.contrib.providers.flagd.Config.Resolver.RPC)
|
||||
.host("localhost").port(deadPort).deadline(500).build()));
|
||||
} catch (Throwable e) {
|
||||
failure = e;
|
||||
}
|
||||
long ms = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0);
|
||||
t.line("")
|
||||
.line("(b) setProviderAndWait() against a closed port")
|
||||
.line(" threw: %s", failure == null ? "nothing" : failure.getClass().getSimpleName())
|
||||
.line(" message: %s", failure == null ? "" : failure.getMessage().lines().findFirst().orElse(""))
|
||||
.line(" state afterwards: %s", strict.getClient().getProviderState());
|
||||
System.out.println("setProviderAndWait failure ms=" + ms + " msg=" + (failure == null ? null : failure.getMessage()));
|
||||
assertNotNull(failure);
|
||||
|
||||
// (c) flagd dies after the app has been running
|
||||
try (var flagd = new FlagdDaemon(FLAGS)) {
|
||||
OpenFeatureAPI live = OpenFeatureAPI.createIsolated();
|
||||
Client lc = Providers.rpc(live, flagd.rpcPort);
|
||||
var before = lc.getBooleanDetails("new-checkout", false, ctx);
|
||||
var cached = lc.getBooleanDetails("new-checkout", false, ctx);
|
||||
flagd.kill();
|
||||
Thread.sleep(1500);
|
||||
var after = lc.getBooleanDetails("new-checkout", false, ctx);
|
||||
var other = lc.getIntegerDetails("discount-percent", 0, ctx);
|
||||
t.line("")
|
||||
.line("(c) flagd is killed while the app is running")
|
||||
.eval(" before the kill", before)
|
||||
.eval(" asked again", cached)
|
||||
.line(" provider state 1.5 s after the kill: %s", lc.getProviderState())
|
||||
.eval(" same flag, after", after)
|
||||
.eval(" never-asked flag, after", other);
|
||||
assertTrue(before.getValue());
|
||||
assertEquals(dev.openfeature.sdk.ProviderState.STALE, lc.getProviderState());
|
||||
// the premium user was on the new checkout a moment ago; now the in-code default (false) decides
|
||||
assertFalse(after.getValue());
|
||||
assertEquals(ErrorCode.GENERAL, after.getErrorCode());
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownFlagAndWrongTypeFallBackToTheDefault() throws Exception {
|
||||
try (var flagd = new FlagdDaemon(FLAGS)) {
|
||||
Client c = Providers.rpc(OpenFeatureAPI.createIsolated(), flagd.rpcPort);
|
||||
var ctx = userContext("u1", "premium", null);
|
||||
var missing = c.getBooleanDetails("no-such-flag", true, ctx);
|
||||
var wrongType = c.getBooleanDetails("banner-text", true, ctx);
|
||||
var numberAsString = c.getStringDetails("discount-percent", "n/a", ctx);
|
||||
var typo = c.getBooleanDetails("new-chekout", false, ctx);
|
||||
|
||||
new Transcript("06-errors.txt", "Mistakes the client absorbs: the in-code default is returned, with a reason")
|
||||
.eval("unknown flag", missing)
|
||||
.eval("typo in the key", typo)
|
||||
.eval("boolean asked of a string", wrongType)
|
||||
.eval("string asked of an int", numberAsString)
|
||||
.write();
|
||||
|
||||
assertTrue(missing.getValue());
|
||||
assertEquals(ErrorCode.FLAG_NOT_FOUND, missing.getErrorCode());
|
||||
assertEquals(ErrorCode.TYPE_MISMATCH, wrongType.getErrorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.contrib.providers.flagd.Config;
|
||||
import dev.openfeature.contrib.providers.flagd.FlagdOptions;
|
||||
import dev.openfeature.contrib.providers.flagd.FlagdProvider;
|
||||
import dev.openfeature.sdk.Client;
|
||||
import dev.openfeature.sdk.OpenFeatureAPI;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Builds isolated OpenFeature APIs so tests never share the global singleton. */
|
||||
final class Providers {
|
||||
|
||||
static Client rpc(OpenFeatureAPI api, int port) throws Exception {
|
||||
api.setProviderAndWait(new FlagdProvider(FlagdOptions.builder()
|
||||
.resolverType(Config.Resolver.RPC)
|
||||
.host("localhost").port(port)
|
||||
.deadline(3000) // the default is 500 ms; a just-started daemon can miss that on the first call
|
||||
.build()));
|
||||
return api.getClient();
|
||||
}
|
||||
|
||||
static Client file(OpenFeatureAPI api, Path flagFile) throws Exception {
|
||||
api.setProviderAndWait(new FlagdProvider(FlagdOptions.builder()
|
||||
.resolverType(Config.Resolver.FILE)
|
||||
.offlineFlagSourcePath(flagFile.toAbsolutePath().toString())
|
||||
.build()));
|
||||
return api.getClient();
|
||||
}
|
||||
|
||||
private Providers() {}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.openfeature;
|
||||
|
||||
import dev.openfeature.sdk.FlagEvaluationDetails;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Collects lines and writes them to output/NN-name.txt, so every figure in the post is a test result. */
|
||||
final class Transcript {
|
||||
|
||||
private final String file;
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
|
||||
Transcript(String file, String title) {
|
||||
this.file = file;
|
||||
lines.add("# " + title);
|
||||
lines.add("");
|
||||
}
|
||||
|
||||
Transcript line(String format, Object... args) {
|
||||
lines.add(args.length == 0 ? format : String.format(format, args));
|
||||
return this;
|
||||
}
|
||||
|
||||
static String show(FlagEvaluationDetails<?> d) {
|
||||
return "flag=%s value=%s variant=%s reason=%s%s".formatted(
|
||||
d.getFlagKey(), d.getValue(), d.getVariant(), d.getReason(),
|
||||
d.getErrorCode() == null ? "" : " errorCode=" + d.getErrorCode() + " (" + firstLine(d.getErrorMessage()) + ")");
|
||||
}
|
||||
|
||||
/** gRPC error messages carry whole stack traces; keep the first line, capped. */
|
||||
static String firstLine(String message) {
|
||||
if (message == null) return "";
|
||||
String line = message.lines().findFirst().orElse("");
|
||||
return line.length() > 50 ? line.substring(0, 50) + "..." : line;
|
||||
}
|
||||
|
||||
Transcript eval(String who, FlagEvaluationDetails<?> d) {
|
||||
return line("%-22s %s", who, show(d));
|
||||
}
|
||||
|
||||
void write() {
|
||||
try {
|
||||
Path dir = Path.of("output");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve(file), String.join("\n", lines) + "\n");
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user