diff --git a/README.md b/README.md index 3eb66d9..48f350c 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/openfeature/README.md b/openfeature/README.md new file mode 100644 index 0000000..97604d9 --- /dev/null +++ b/openfeature/README.md @@ -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` (``) | +| flagd provider `dev.openfeature.contrib.providers:flagd` | 0.15.0 | `maven-metadata.xml` (``) | +| flagd daemon | 0.19.0 | built with `go install github.com/open-feature/flagd/flagd@v0.19.0` (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. diff --git a/openfeature/flags/flags.json b/openfeature/flags/flags.json new file mode 100644 index 0000000..c4c2408 --- /dev/null +++ b/openfeature/flags/flags.json @@ -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" + } + } +} diff --git a/openfeature/output/01-typed-evaluation.txt b/openfeature/output/01-typed-evaluation.txt new file mode 100644 index 0000000..691ebbf --- /dev/null +++ b/openfeature/output/01-typed-evaluation.txt @@ -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 diff --git a/openfeature/output/02-targeting.txt b/openfeature/output/02-targeting.txt new file mode 100644 index 0000000..ae9da69 --- /dev/null +++ b/openfeature/output/02-targeting.txt @@ -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 diff --git a/openfeature/output/03-gradual-rollout.txt b/openfeature/output/03-gradual-rollout.txt new file mode 100644 index 0000000..4e048f5 --- /dev/null +++ b/openfeature/output/03-gradual-rollout.txt @@ -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 diff --git a/openfeature/output/04-live-reload.txt b/openfeature/output/04-live-reload.txt new file mode 100644 index 0000000..9439917 --- /dev/null +++ b/openfeature/output/04-live-reload.txt @@ -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) diff --git a/openfeature/output/05-flagd-down.txt b/openfeature/output/05-flagd-down.txt new file mode 100644 index 0000000..d71c866 --- /dev/null +++ b/openfeature/output/05-flagd-down.txt @@ -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...) diff --git a/openfeature/output/06-errors.txt b/openfeature/output/06-errors.txt new file mode 100644 index 0000000..af236a2 --- /dev/null +++ b/openfeature/output/06-errors.txt @@ -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) diff --git a/openfeature/output/07-file-resolver.txt b/openfeature/output/07-file-resolver.txt new file mode 100644 index 0000000..15f6a97 --- /dev/null +++ b/openfeature/output/07-file-resolver.txt @@ -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) diff --git a/openfeature/output/08-test-both-states.txt b/openfeature/output/08-test-both-states.txt new file mode 100644 index 0000000..e8d4400 --- /dev/null +++ b/openfeature/output/08-test-both-states.txt @@ -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 diff --git a/openfeature/output/09-http-demo.txt b/openfeature/output/09-http-demo.txt new file mode 100644 index 0000000..94c1509 --- /dev/null +++ b/openfeature/output/09-http-demo.txt @@ -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: asha@ankurm.com' 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 diff --git a/openfeature/pom.xml b/openfeature/pom.xml new file mode 100644 index 0000000..c7f0686 --- /dev/null +++ b/openfeature/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + openfeature + 1.0.0 + openfeature + 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 + + + 25 + 1.23.0 + 0.15.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + dev.openfeature + sdk + ${openfeature.sdk.version} + + + dev.openfeature.contrib.providers + flagd + ${flagd.provider.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/openfeature/scripts/http-demo.sh b/openfeature/scripts/http-demo.sh new file mode 100755 index 0000000..55fb572 --- /dev/null +++ b/openfeature/scripts/http-demo.sh @@ -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