diff --git a/README.md b/README.md index 6aeb236..a9522b0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ discovery-server :8761 (Eureka) every service registers here and finds the othe | `product-service` | `GET /products`, `GET /products/{id}` | | `inventory-service` | stock levels, `POST /inventory/{id}/reserve`, a switch to simulate an outage | | `openfeign-demo` | standalone, **not** part of the build above: OpenFeign vs `@HttpExchange` on Boot 4.2.0 / Cloud 2026.0.0; see its own README | +| `gateway-mvc` | standalone, **not** part of the build above: Gateway Server MVC 5.1 on Boot 4.2.0 / Cloud 2026.0.0 with virtual threads, retry, Redis rate limiting; see its own README | | `order-service` | `POST /orders`; calls product-service and inventory-service through the load balancer and a Resilience4j circuit breaker | ## Run it (no Docker needed) diff --git a/gateway-mvc/.gitignore b/gateway-mvc/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/gateway-mvc/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/gateway-mvc/README.md b/gateway-mvc/README.md new file mode 100644 index 0000000..62aa92a --- /dev/null +++ b/gateway-mvc/README.md @@ -0,0 +1,28 @@ +# gateway-mvc + +Spring Cloud Gateway Server MVC 5.1.0 on Spring Boot 4.2.0 / Spring Cloud 2026.0.0, JDK 25, virtual threads. +Standalone: it has its own parent POM and is **not** part of the root build (the rest of the repo is on Boot 4.1 / Cloud 2025.1). + +The walkthrough lives in the blog post; everything quoted there comes from `output/`. + +| Path | What it is | +|---|---| +| `src/main/java/com/ankurm/gwmvc/RoutesConfig.java` | routes in the Java DSL: strip prefix, header filters, retry, rate limit, 504 mapping, a diagnostics endpoint | +| `src/main/java/com/ankurm/gwmvc/RateLimiterConfig.java` | the `AsyncProxyManager` the `rateLimit()` filter needs: Redis (Lettuce), Caffeine or none | +| `src/main/resources/application.yml` | the YAML flavour of a route, Tomcat limited to 10 threads, virtual threads on, `platform` profile | +| `scripts/Upstream.java` | a dependency-free backend: `/hello`, `/limited`, `/slow`, `/flaky`, `/headers` | +| `scripts/LoadClient.java` | fires N concurrent requests and prints a status summary and elapsed time | +| `scripts/run-all.sh` | rebuilds and regenerates every file in `output/` (needs JDK 25, Maven, `redis-server`) | + +```bash +mvn -DskipTests package +java scripts/Upstream.java 9091 & +java -jar target/gateway-mvc-1.0.0.jar --demo.store=redis # Redis on localhost:6379 +curl -i localhost:8080/api/hello +``` + +Switches: `--demo.store=redis|caffeine|none`, `--spring.profiles.active=platform` (no virtual threads), +`--demo.rl-timeout=300ms`, `--spring.http.clients.read-timeout=1s`, +`--spring.cloud.gateway.server.webmvc.trusted-proxies='.*'`. + +Timing figures (`elapsed_ms`, `time_total`) drift between runs; everything else in `output/` is deterministic. diff --git a/gateway-mvc/output/01-routes.txt b/gateway-mvc/output/01-routes.txt new file mode 100644 index 0000000..fb5da6f --- /dev/null +++ b/gateway-mvc/output/01-routes.txt @@ -0,0 +1,40 @@ +$ curl -i localhost:8080/api/hello +HTTP/1.1 200 +X-Gateway-Thread: virtual +Content-Type: application/json + +{"service":"upstream","message":"hello from the backend"} + +$ curl -i localhost:8080/yaml/hello +HTTP/1.1 200 +Content-Type: application/json + +{"service":"upstream","message":"hello from the backend"} + +$ curl -i localhost:8080/diag/thread +HTTP/1.1 200 +Content-Type: application/json + +{"virtual":true,"thread":"VirtualThread[#58,tomcat-handler-5]/runnable@ForkJoinPool-1-worker-1"} + +# what the backend receives by default; note a client-supplied X-Forwarded-For is stripped +$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers +accept: */* +accept-encoding: gzip,deflate +connection: Upgrade, HTTP2-Settings +host: localhost:9091 +http2-settings: AAEAAEAAAAIAAAAAAAMAAAAAAAQBAAAAAAUAAEAAAAYABgAA +upgrade: h2c +user-agent: curl/8.5.0 +x-gateway-route: headers + + +# same request with spring.cloud.gateway.server.webmvc.trusted-proxies=.* +$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers +forwarded: proto=http;host="localhost:8080";for="127.0.0.1:41308" +x-forwarded-for: 1.2.3.4,127.0.0.1 +x-forwarded-host: localhost:8080 +x-forwarded-port: 8080 +x-forwarded-prefix: /api +x-forwarded-proto: http +x-gateway-route: headers diff --git a/gateway-mvc/output/02-retry.txt b/gateway-mvc/output/02-retry.txt new file mode 100644 index 0000000..c2b7796 --- /dev/null +++ b/gateway-mvc/output/02-retry.txt @@ -0,0 +1,44 @@ +# the backend fails its first 2 calls with 503; the gateway route retries up to 3 times +$ curl -i localhost:9091/flaky/reset +HTTP/1.1 200 OK +Content-type: application/json + +{"reset":true} + +$ curl -i localhost:8080/api/flaky?failFirst=2 +HTTP/1.1 200 +Content-Type: application/json + +{"call":3,"result":"ok"} + +# how many calls did the backend actually see? (failFirst=0 just returns the counter) +$ curl -i localhost:9091/flaky?failFirst=0 +HTTP/1.1 200 OK +Content-type: application/json + +{"call":4,"result":"ok"} + +# now a backend that never recovers: after the 3 retries the gateway gives up with a 500, not the backend's 503 +$ curl -i localhost:9091/flaky/reset +HTTP/1.1 200 OK +Content-type: application/json + +{"reset":true} + +$ curl -i localhost:8080/api/flaky?failFirst=99 +HTTP/1.1 500 +Content-Type: application/json + +{"timestamp":"2026-11-25T19:22:37.164Z","status":500,"error":"Internal Server Error","path":"/api/flaky"} + +# the backend saw the original try plus 3 retries = 4 calls, so the counter now reads 5 +$ curl -i localhost:9091/flaky?failFirst=99 +HTTP/1.1 503 Service Unavailable +Content-type: application/json + +{"call":5,"result":"unavailable"} + +# log line behind that 500: +Request processing failed: org.springframework.core.retry.RetryException: Retry policy for operation ... (FrameworkRetryFilterFunctions lambda) +# which retry implementation did the gateway pick? (DEBUG log at startup) +Retry filter selection: Spring Retry on classpath=false, useFrameworkRetry=false, selected filter=FrameworkRetryFilterFunctions diff --git a/gateway-mvc/output/03-ratelimit.txt b/gateway-mvc/output/03-ratelimit.txt new file mode 100644 index 0000000..6daf017 --- /dev/null +++ b/gateway-mvc/output/03-ratelimit.txt @@ -0,0 +1,17 @@ +# 5 tokens per 10 seconds per X-Api-Key, Caffeine store +alice #1 HTTP/1.1 200 X-RateLimit-Remaining: 4 +alice #2 HTTP/1.1 200 X-RateLimit-Remaining: 3 +alice #3 HTTP/1.1 200 X-RateLimit-Remaining: 2 +alice #4 HTTP/1.1 200 X-RateLimit-Remaining: 1 +alice #5 HTTP/1.1 200 X-RateLimit-Remaining: 0 +alice #6 HTTP/1.1 429 X-RateLimit-Remaining: 0 +alice #7 HTTP/1.1 429 X-RateLimit-Remaining: 0 +# a different key has its own bucket +bob #1 HTTP/1.1 200 X-RateLimit-Remaining: 4 +# no X-Api-Key: the key resolver returns null +$ curl -i localhost:8080/api/limited +HTTP/1.1 403 + + +# wait 11 seconds: the bucket refills +alice #8 HTTP/1.1 200 X-RateLimit-Remaining: 4 diff --git a/gateway-mvc/output/04-shared-redis.txt b/gateway-mvc/output/04-shared-redis.txt new file mode 100644 index 0000000..fbaffbb --- /dev/null +++ b/gateway-mvc/output/04-shared-redis.txt @@ -0,0 +1,12 @@ +# same key, alternating between two gateway instances that share Redis +carol #1 via :8081 HTTP/1.1 200 X-RateLimit-Remaining: 4 +carol #2 via :8080 HTTP/1.1 200 X-RateLimit-Remaining: 3 +carol #3 via :8081 HTTP/1.1 200 X-RateLimit-Remaining: 2 +carol #4 via :8080 HTTP/1.1 200 X-RateLimit-Remaining: 1 +carol #5 via :8081 HTTP/1.1 200 X-RateLimit-Remaining: 0 +carol #6 via :8080 HTTP/1.1 429 X-RateLimit-Remaining: 0 +# what Redis holds +$ redis-cli --scan +carol +$ redis-cli pttl carol (time to live in ms; the bucket expires once it would be full again) +positive TTL, as expected diff --git a/gateway-mvc/output/05-failure-modes.txt b/gateway-mvc/output/05-failure-modes.txt new file mode 100644 index 0000000..d140028 --- /dev/null +++ b/gateway-mvc/output/05-failure-modes.txt @@ -0,0 +1,38 @@ +## A. read timeout: spring.http.clients.read-timeout=1s, backend sleeps 3s +$ curl -i localhost:8080/api/slow?ms=3000 +HTTP/1.1 500 +Content-Type: application/json + +{"timestamp":"2026-11-25T19:23:31.069Z","status":500,"error":"Internal Server Error","path":"/api/slow"} + +# log line behind that 500: +Request processing failed: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9091/slow" + +## B. same timeout, route with onError(ResourceAccessException) mapped to 504 +$ curl -i localhost:8080/api/slow-mapped?ms=3000 +HTTP/1.1 504 +Content-Type: application/json + +{"error":"upstream did not answer in time"} + +## C. Redis stops while the gateway is up; no timeout configured on rateLimit() +$ curl --max-time 5 -H 'X-Api-Key: dave' localhost:8080/api/limited +curl exit after 5.001396s, http_code=000 + +## D. same outage, with demo.rl-timeout=300ms (setTimeout on the filter) +$ curl -H 'X-Api-Key: dave' localhost:8080/api/limited +http_code=500 time_total_under_1s=yes +# log line behind that 500: +Request processing failed: java.util.concurrent.TimeoutException +# Redis back: the next request works again, no restart needed +http_code=200 + +## E. no AsyncProxyManager bean at all (--demo.store=none) +$ curl -i -H 'X-Api-Key: erin' localhost:8080/api/limited +HTTP/1.1 500 +Content-Type: application/json + +{"timestamp":"2026-11-25T19:24:09.127Z","status":500,"error":"Internal Server Error","path":"/api/limited"} + +# log line behind that 500: +Request processing failed: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.bucket4j.distributed.proxy.AsyncProxyManager' available diff --git a/gateway-mvc/output/06-virtual-threads.txt b/gateway-mvc/output/06-virtual-threads.txt new file mode 100644 index 0000000..991789a --- /dev/null +++ b/gateway-mvc/output/06-virtual-threads.txt @@ -0,0 +1,20 @@ +## virtual threads (server.tomcat.threads.max=10) +$ curl -i localhost:8080/diag/thread +HTTP/1.1 200 +Content-Type: application/json + +{"thread":"VirtualThread[#N,tomcat-handler-1]/runnable@ForkJoinPool-1-worker-1","virtual":true} + +$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200 +requests=200 statuses={200=200} elapsed_ms=2154 + +## platform threads (server.tomcat.threads.max=10) +$ curl -i localhost:8080/diag/thread +HTTP/1.1 200 +Content-Type: application/json + +{"virtual":false,"thread":"Thread[#N,http-nio-8080-exec-3,5,main]"} + +$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200 +requests=200 statuses={200=200} elapsed_ms=10903 + diff --git a/gateway-mvc/pom.xml b/gateway-mvc/pom.xml new file mode 100644 index 0000000..9e14a40 --- /dev/null +++ b/gateway-mvc/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm.shop + gateway-mvc + 1.0.0 + gateway-mvc + + + 25 + 2026.0.0 + 8.23.0 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-gateway-server-webmvc + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.bucket4j + bucket4j_jdk17-core + ${bucket4j.version} + + + com.bucket4j + bucket4j_jdk17-lettuce + ${bucket4j.version} + + + com.bucket4j + bucket4j_jdk17-caffeine + ${bucket4j.version} + + + com.github.ben-manes.caffeine + caffeine + + + io.lettuce + lettuce-core + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.ankurm.gwmvc.GatewayMvcApplication + + + + + diff --git a/gateway-mvc/scripts/LoadClient.java b/gateway-mvc/scripts/LoadClient.java new file mode 100644 index 0000000..b914790 --- /dev/null +++ b/gateway-mvc/scripts/LoadClient.java @@ -0,0 +1,40 @@ +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** java scripts/LoadClient.java : fires them all at once and prints a summary. */ +public class LoadClient { + public static void main(String[] args) throws Exception { + String url = args[0]; + int n = Integer.parseInt(args[1]); + Map statuses = new ConcurrentHashMap<>(); + HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); + long t0 = System.nanoTime(); + try (var pool = Executors.newVirtualThreadPerTaskExecutor()) { + for (int i = 0; i < n; i++) { + pool.submit(() -> { + int code; + try { + code = client.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(60)).build(), + HttpResponse.BodyHandlers.discarding()).statusCode(); + } catch (Exception e) { + code = -1; + } + statuses.computeIfAbsent(code, k -> new AtomicInteger()).incrementAndGet(); + }); + } + pool.shutdown(); + pool.awaitTermination(2, TimeUnit.MINUTES); + } + long ms = (System.nanoTime() - t0) / 1_000_000; + System.out.println("requests=" + n + " statuses=" + new TreeMap<>(statuses) + " elapsed_ms=" + ms); + } +} diff --git a/gateway-mvc/scripts/Upstream.java b/gateway-mvc/scripts/Upstream.java new file mode 100644 index 0000000..f6fff5c --- /dev/null +++ b/gateway-mvc/scripts/Upstream.java @@ -0,0 +1,90 @@ +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A deliberately boring backend for the gateway to proxy to. No Spring, no dependencies: + * java scripts/Upstream.java [port] + * Endpoints: /hello, /limited, /slow?ms=500, /flaky?failFirst=2, /flaky/reset, /headers + */ +public class Upstream { + + static final AtomicInteger flakyCalls = new AtomicInteger(); + + public static void main(String[] args) throws IOException { + int port = args.length > 0 ? Integer.parseInt(args[0]) : 9091; + HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); + server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); + + server.createContext("/hello", ex -> + send(ex, 200, "{\"service\":\"upstream\",\"message\":\"hello from the backend\"}")); + + server.createContext("/limited", ex -> + send(ex, 200, "{\"service\":\"upstream\",\"message\":\"you got through the rate limiter\"}")); + + server.createContext("/slow", ex -> { + long ms = Long.parseLong(param(ex, "ms", "500")); + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + send(ex, 200, "{\"slept\":" + ms + "}"); + }); + + server.createContext("/flaky/reset", ex -> { + flakyCalls.set(0); + send(ex, 200, "{\"reset\":true}"); + }); + + server.createContext("/flaky", ex -> { + int failFirst = Integer.parseInt(param(ex, "failFirst", "2")); + int n = flakyCalls.incrementAndGet(); + if (n <= failFirst) { + send(ex, 503, "{\"call\":" + n + ",\"result\":\"unavailable\"}"); + } else { + send(ex, 200, "{\"call\":" + n + ",\"result\":\"ok\"}"); + } + }); + + server.createContext("/headers", ex -> { + Map sorted = new TreeMap<>(); + ex.getRequestHeaders().forEach((k, v) -> sorted.put(k.toLowerCase(), String.join(",", v))); + StringBuilder sb = new StringBuilder(); + sorted.forEach((k, v) -> sb.append(k).append(": ").append(v).append('\n')); + ex.getResponseHeaders().set("Content-Type", "text/plain"); + byte[] b = sb.toString().getBytes(StandardCharsets.UTF_8); + ex.sendResponseHeaders(200, b.length); + ex.getResponseBody().write(b); + ex.close(); + }); + + server.start(); + System.out.println("upstream listening on " + port); + } + + static String param(HttpExchange ex, String name, String def) { + String q = ex.getRequestURI().getQuery(); + if (q == null) return def; + for (String kv : q.split("&")) { + String[] p = kv.split("=", 2); + if (p[0].equals(name) && p.length == 2) return p[1]; + } + return def; + } + + static void send(HttpExchange ex, int status, String body) throws IOException { + byte[] b = body.getBytes(StandardCharsets.UTF_8); + ex.getResponseHeaders().set("Content-Type", "application/json"); + ex.sendResponseHeaders(status, b.length); + ex.getResponseBody().write(b); + ex.close(); + } +} diff --git a/gateway-mvc/scripts/env.sh b/gateway-mvc/scripts/env.sh new file mode 100755 index 0000000..9cc5327 --- /dev/null +++ b/gateway-mvc/scripts/env.sh @@ -0,0 +1,3 @@ +# Source me. Picks JDK 25 if present at /tmp/tools, otherwise whatever java is on PATH. +if [ -d /tmp/tools/jdk-25.0.5.1+2 ]; then export JAVA_HOME=/tmp/tools/jdk-25.0.5.1+2; export PATH=$JAVA_HOME/bin:$PATH; fi +export JAVA_TOOL_OPTIONS= _JAVA_OPTIONS= diff --git a/gateway-mvc/scripts/lib.sh b/gateway-mvc/scripts/lib.sh new file mode 100755 index 0000000..f13446e --- /dev/null +++ b/gateway-mvc/scripts/lib.sh @@ -0,0 +1,33 @@ +# Shared helpers. Source me from the other scripts. +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +. "$HERE/scripts/env.sh" +JAR="$HERE/target/gateway-mvc-1.0.0.jar" +LOGDIR="${LOGDIR:-/tmp/gwmvc-logs}"; mkdir -p "$LOGDIR" + +# Kill by main-class pattern kept in a variable so this very script's command line never matches it. +stop_all() { + local pat='gateway-mvc-1.0.0[.]jar|scripts/Upstream[.]java' + for p in $(ps -eo pid,args | grep -E "$pat" | grep -v grep | awk '{print $1}'); do kill "$p" 2>/dev/null; done + sleep 2 +} + +wait_http() { for _ in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; return 1; } + +start_upstream() { + setsid nohup java "$HERE/scripts/Upstream.java" 9091 > "$LOGDIR/upstream.log" 2>&1 < /dev/null & + wait_http http://localhost:9091/hello +} + +# start_gateway [extra spring args...] +start_gateway() { + local port="$1"; shift + setsid nohup java -jar "$JAR" --server.port="$port" "$@" > "$LOGDIR/gateway-$port.log" 2>&1 < /dev/null & + wait_http "http://localhost:$port/diag/thread" +} + +# show : prints the command, then status line + interesting headers + body +show() { + echo "\$ curl -i $*" + curl -si "$@" | tr -d '\r' | grep -viE '^(date|content-length|connection|keep-alive|transfer-encoding):' + echo +} diff --git a/gateway-mvc/scripts/run-all.sh b/gateway-mvc/scripts/run-all.sh new file mode 100755 index 0000000..8c37019 --- /dev/null +++ b/gateway-mvc/scripts/run-all.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs: JDK 25, Maven, redis-server on PATH. +# ./scripts/run-all.sh +# Timing figures (elapsed_ms, curl time) drift a little between runs; everything else is deterministic. +set -u +. "$(dirname "$0")/lib.sh" +OUT="$HERE/output"; mkdir -p "$OUT" +cd "$HERE" +[ -f "$JAR" ] || mvn -B -q -DskipTests package + +redis_up() { redis-cli ping >/dev/null 2>&1 || { redis-server --port 6379 --save "" --daemonize yes >/dev/null; sleep 1; }; } +redis_down() { redis-cli shutdown nosave >/dev/null 2>&1; sleep 1; } +redis_up; redis-cli flushall >/dev/null +stop_all; start_upstream + +# ---------------------------------------------------------------- 01 routes +start_gateway 8080 +{ + show localhost:8080/api/hello + show localhost:8080/yaml/hello + show localhost:8080/diag/thread + echo "# what the backend receives by default; note a client-supplied X-Forwarded-For is stripped" + echo "\$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers" + curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers + echo +} > "$OUT/01-routes.txt" +stop_all; start_upstream +start_gateway 8080 --spring.cloud.gateway.server.webmvc.trusted-proxies='.*' +{ + echo + echo "# same request with spring.cloud.gateway.server.webmvc.trusted-proxies=.*" + echo "\$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers" + curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers | grep -iE 'forward|x-gateway' +} >> "$OUT/01-routes.txt" +stop_all; start_upstream; start_gateway 8080 + +# ---------------------------------------------------------------- 02 retry +{ + echo "# the backend fails its first 2 calls with 503; the gateway route retries up to 3 times" + show localhost:9091/flaky/reset + show 'localhost:8080/api/flaky?failFirst=2' + echo "# how many calls did the backend actually see? (failFirst=0 just returns the counter)" + show 'localhost:9091/flaky?failFirst=0' + echo "# now a backend that never recovers: after the 3 retries the gateway gives up with a 500, not the backend's 503" + show localhost:9091/flaky/reset + show 'localhost:8080/api/flaky?failFirst=99' + echo "# the backend saw the original try plus 3 retries = 4 calls, so the counter now reads 5" + show 'localhost:9091/flaky?failFirst=99' + echo "# log line behind that 500:" + grep -m1 'RetryException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/' | sed -E 's/(RetryException: Retry policy for operation).*/\1 ... (FrameworkRetryFilterFunctions lambda)/' +} > "$OUT/02-retry.txt" +stop_all; start_upstream +start_gateway 8080 --logging.level.org.springframework.cloud.gateway=DEBUG +{ + echo "# which retry implementation did the gateway pick? (DEBUG log at startup)" + grep -m1 'Retry filter selection' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Retry filter selection)/\1/' +} >> "$OUT/02-retry.txt" +stop_all; start_upstream + +# ---------------------------------------------------------------- 03 rate limit (Caffeine, single JVM) +start_gateway 8080 +{ + echo "# 5 tokens per 10 seconds per X-Api-Key, Caffeine store" + for i in 1 2 3 4 5 6 7; do + printf 'alice #%s ' "$i"; curl -s -o /dev/null -D - -H 'X-Api-Key: alice' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo + done + echo "# a different key has its own bucket" + printf 'bob #1 '; curl -s -o /dev/null -D - -H 'X-Api-Key: bob' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo + echo "# no X-Api-Key: the key resolver returns null" + show localhost:8080/api/limited + echo "# wait 11 seconds: the bucket refills" + sleep 11 + printf 'alice #8 '; curl -s -o /dev/null -D - -H 'X-Api-Key: alice' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo +} > "$OUT/03-ratelimit.txt" +stop_all; start_upstream + +# ---------------------------------------------------------------- 04 two gateways, one Redis +start_gateway 8080 --demo.store=redis +start_gateway 8081 --demo.store=redis +{ + echo "# same key, alternating between two gateway instances that share Redis" + for i in 1 2 3 4 5 6; do + port=$((8080 + (i % 2))) + printf 'carol #%s via :%s ' "$i" "$port"; curl -s -o /dev/null -D - -H 'X-Api-Key: carol' localhost:$port/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo + done + echo "# what Redis holds" + echo "\$ redis-cli --scan"; redis-cli --scan + echo "\$ redis-cli pttl carol (time to live in ms; the bucket expires once it would be full again)" + redis-cli pttl carol | awk '{ if ($1 > 0) print "positive TTL, as expected"; else print $1 }' +} > "$OUT/04-shared-redis.txt" +stop_all; start_upstream + +# ---------------------------------------------------------------- 05 failure modes +{ + echo "## A. read timeout: spring.http.clients.read-timeout=1s, backend sleeps 3s" + start_gateway 8080 --spring.http.clients.read-timeout=1s + show 'localhost:8080/api/slow?ms=3000' + echo "# log line behind that 500:" + grep -m1 'ResourceAccessException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^"]*"[^"]*").*$/\1/' + echo + echo "## B. same timeout, route with onError(ResourceAccessException) mapped to 504" + show 'localhost:8080/api/slow-mapped?ms=3000' + stop_all; start_upstream + + echo "## C. Redis stops while the gateway is up; no timeout configured on rateLimit()" + redis_up + start_gateway 8080 --demo.store=redis + curl -s -o /dev/null -H 'X-Api-Key: warm' localhost:8080/api/limited # open the Redis connection while it is up + redis_down + echo "\$ curl --max-time 5 -H 'X-Api-Key: dave' localhost:8080/api/limited" + curl -s --max-time 5 -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'curl exit after %{time_total}s, http_code=%{http_code}\n' + stop_all; start_upstream + + echo + echo "## D. same outage, with demo.rl-timeout=300ms (setTimeout on the filter)" + redis_up + start_gateway 8080 --demo.store=redis --demo.rl-timeout=300ms + curl -s -o /dev/null -H 'X-Api-Key: warm' localhost:8080/api/limited # open the Redis connection while it is up + redis_down + echo "\$ curl -H 'X-Api-Key: dave' localhost:8080/api/limited" + curl -s -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'http_code=%{http_code} time_total_under_1s=%{time_total}\n' | sed -E 's/time_total_under_1s=0\.[0-9]+/time_total_under_1s=yes/' + echo "# log line behind that 500:" + grep -m1 'TimeoutException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/' + redis_up + echo "# Redis back: the next request works again, no restart needed" + curl -s -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'http_code=%{http_code}\n' + stop_all; start_upstream + + echo + echo "## E. no AsyncProxyManager bean at all (--demo.store=none)" + start_gateway 8080 --demo.store=none + echo "\$ curl -i -H 'X-Api-Key: erin' localhost:8080/api/limited" + curl -si -H 'X-Api-Key: erin' localhost:8080/api/limited | tr -d '\r' | grep -viE '^(date|content-length|connection|transfer-encoding):' + echo + echo "# log line behind that 500:" + grep -m1 -E 'NoSuchBeanDefinition|AsyncProxyManager' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/' | cut -c1-300 +} 2>&1 | grep -v "^Picked up " > "$OUT/05-failure-modes.txt" +stop_all; start_upstream + +# ---------------------------------------------------------------- 06 virtual vs platform threads +{ + for mode in virtual platform; do + if [ "$mode" = virtual ]; then start_gateway 8080; else start_gateway 8080 --spring.profiles.active=platform; fi + echo "## $mode threads (server.tomcat.threads.max=10)" + show localhost:8080/diag/thread | sed -E 's/#[0-9]+/#N/' + echo "\$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200" + java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200 + echo + stop_all; start_upstream + done +} 2>&1 | grep -v "^Picked up " > "$OUT/06-virtual-threads.txt" +stop_all +echo "done: $(ls "$OUT" | wc -l) files in $OUT" diff --git a/gateway-mvc/src/main/java/com/ankurm/gwmvc/GatewayMvcApplication.java b/gateway-mvc/src/main/java/com/ankurm/gwmvc/GatewayMvcApplication.java new file mode 100644 index 0000000..4ef5e33 --- /dev/null +++ b/gateway-mvc/src/main/java/com/ankurm/gwmvc/GatewayMvcApplication.java @@ -0,0 +1,12 @@ +package com.ankurm.gwmvc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GatewayMvcApplication { + + public static void main(String[] args) { + SpringApplication.run(GatewayMvcApplication.class, args); + } +} diff --git a/gateway-mvc/src/main/java/com/ankurm/gwmvc/RateLimiterConfig.java b/gateway-mvc/src/main/java/com/ankurm/gwmvc/RateLimiterConfig.java new file mode 100644 index 0000000..bcd632f --- /dev/null +++ b/gateway-mvc/src/main/java/com/ankurm/gwmvc/RateLimiterConfig.java @@ -0,0 +1,47 @@ +package com.ankurm.gwmvc; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; + +import com.github.benmanes.caffeine.cache.Caffeine; +import io.github.bucket4j.caffeine.CaffeineProxyManager; +import io.github.bucket4j.distributed.ExpirationAfterWriteStrategy; +import io.github.bucket4j.distributed.proxy.AsyncProxyManager; +import io.github.bucket4j.distributed.proxy.ProxyManager; +import io.github.bucket4j.redis.lettuce.cas.LettuceBasedProxyManager; +import io.lettuce.core.RedisClient; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; + +/** + * The rateLimit() filter does not ship a store. It looks for an + * {@code AsyncProxyManager} bean, so we provide one: Redis (shared by + * every gateway instance, {@code --demo.store=redis}) or Caffeine (one JVM only, the default). + * {@code --demo.store=none} registers nothing, which is how the post shows the missing-bean failure. + */ +@Configuration +class RateLimiterConfig { + + @Bean + @ConditionalOnProperty(name = "demo.store", havingValue = "redis") + AsyncProxyManager redisProxyManager(@Value("${demo.redis-uri:redis://localhost:6379}") String uri) { + RedisClient client = RedisClient.create(uri); + ProxyManager pm = LettuceBasedProxyManager.builderFor(client) + // let Redis forget a bucket once it would be full again anyway + .withExpirationStrategy( + ExpirationAfterWriteStrategy.basedOnTimeForRefillingBucketUpToMax(Duration.ofMinutes(1))) + .build(); + return pm.withMapper(key -> key.getBytes(StandardCharsets.UTF_8)).asAsync(); + } + + @Bean + @ConditionalOnProperty(name = "demo.store", havingValue = "caffeine", matchIfMissing = true) + @SuppressWarnings({ "unchecked", "rawtypes" }) + AsyncProxyManager caffeineProxyManager() { + Caffeine builder = Caffeine.newBuilder().maximumSize(10_000); + return new CaffeineProxyManager(builder, Duration.ofMinutes(1)).asAsync(); + } +} diff --git a/gateway-mvc/src/main/java/com/ankurm/gwmvc/RoutesConfig.java b/gateway-mvc/src/main/java/com/ankurm/gwmvc/RoutesConfig.java new file mode 100644 index 0000000..571f7f6 --- /dev/null +++ b/gateway-mvc/src/main/java/com/ankurm/gwmvc/RoutesConfig.java @@ -0,0 +1,111 @@ +package com.ankurm.gwmvc; + +import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.addRequestHeader; +import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.setPath; +import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix; +import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; +import static org.springframework.cloud.gateway.server.mvc.filter.Bucket4jFilterFunctions.rateLimit; +import static org.springframework.cloud.gateway.server.mvc.filter.RetryFilterFunctions.retry; +import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; +import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; + +import java.time.Duration; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.servlet.function.HandlerFilterFunction; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerResponse; + +/** Routes declared in Java. The same idea in YAML lives in application.yml (the /yaml/** route). */ +@Configuration +class RoutesConfig { + + /** Adds the name of the thread that handled the request, and whether it was virtual, to the response. */ + static HandlerFilterFunction threadReport() { + return HandlerFilterFunction.ofResponseProcessor((request, response) -> { + Thread t = Thread.currentThread(); + response.headers().add("X-Gateway-Thread", t.isVirtual() ? "virtual" : t.getName()); + return response; + }); + } + + @Bean + RouterFunction plainRoutes(@Value("${demo.upstream:http://localhost:9091}") String upstream) { + return route("hello") + .GET("/api/hello", http()) + .before(uri(upstream)) + .before(stripPrefix(1)) + .filter(threadReport()) + .build() + .and(route("slow") + .GET("/api/slow", http()) + .before(uri(upstream)) + .before(stripPrefix(1)) + .filter(threadReport()) + .build()) + .and(route("slow-mapped") + .GET("/api/slow-mapped", http()) + .before(uri(upstream)) + .before(setPath("/slow")) + // a read timeout surfaces as ResourceAccessException; without this it becomes a bare 500 + .onError(ResourceAccessException.class, (e, request) -> ServerResponse + .status(HttpStatus.GATEWAY_TIMEOUT) + .body(Map.of("error", "upstream did not answer in time"))) + .build()) + .and(route("headers") + .GET("/api/headers", http()) + .before(uri(upstream)) + .before(stripPrefix(1)) + .before(addRequestHeader("X-Gateway-Route", "headers")) + .build()); + } + + /** Retry: the backend returns 503 twice, the gateway quietly asks again. */ + @Bean + RouterFunction retryRoute(@Value("${demo.upstream:http://localhost:9091}") String upstream) { + return route("flaky") + .GET("/api/flaky", http()) + .before(uri(upstream)) + .before(stripPrefix(1)) + .filter(retry(c -> c.setRetries(3) + .setSeries(java.util.Set.of(org.springframework.http.HttpStatus.Series.SERVER_ERROR)) + .setMethods(java.util.Set.of(HttpMethod.GET)) + .setBackoff(Duration.ofMillis(50), Duration.ofMillis(500), 2))) + .build(); + } + + /** 5 requests per 10 seconds per X-Api-Key. No key means no bucket, which means 403. */ + @Bean + RouterFunction limitedRoute(@Value("${demo.upstream:http://localhost:9091}") String upstream, + @Value("${demo.rl-timeout:0ms}") Duration rlTimeout) { + return route("limited") + .GET("/api/limited", http()) + .before(uri(upstream)) + .before(stripPrefix(1)) + .filter(rateLimit(c -> { + c.setCapacity(5) + .setPeriod(Duration.ofSeconds(10)) + .setKeyResolver(request -> request.headers().firstHeader("X-Api-Key")); + if (!rlTimeout.isZero()) { + c.setTimeout(rlTimeout); // how long to wait for the store before giving up + } + })) + .build(); + } + + /** A local endpoint on the gateway itself (not proxied) that shows which thread serves requests. */ + @Bean + RouterFunction diagnostics() { + return org.springframework.web.servlet.function.RouterFunctions.route() + .GET("/diag/thread", request -> ServerResponse.ok().body(Map.of( + "thread", Thread.currentThread().toString(), + "virtual", Thread.currentThread().isVirtual()))) + .build(); + } +} diff --git a/gateway-mvc/src/main/resources/application.yml b/gateway-mvc/src/main/resources/application.yml new file mode 100644 index 0000000..fdda53d --- /dev/null +++ b/gateway-mvc/src/main/resources/application.yml @@ -0,0 +1,44 @@ +server: + port: 8080 + tomcat: + threads: + max: 10 # deliberately tiny so platform-thread starvation is visible in seconds + +spring: + application: + name: gateway-mvc + threads: + virtual: + enabled: true + cloud: + gateway: + server: + webmvc: + routes: + # The YAML flavour of a route: same predicates and filters, no Java. + - id: yaml-hello + uri: http://localhost:9091 + predicates: + - Path=/yaml/** + filters: + - StripPrefix=1 + - AddRequestHeader=X-Gateway-Route, yaml-hello + +management: + endpoints: + web: + exposure: + include: health,info,mappings + +logging: + level: + org.springframework.cloud.gateway: INFO + +--- +spring: + config: + activate: + on-profile: platform + threads: + virtual: + enabled: false