feat: add production capability foundations

This commit is contained in:
donghyeon-ka
2026-07-31 23:50:44 +09:00
parent b3add0162d
commit 567422f2e5
757 changed files with 132385 additions and 2146 deletions
+2
View File
@@ -19,6 +19,8 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat
- Error code contract (`error/ApiErrorCode` interface, `error/OperationalError` enum).
- Cross-cutting mapper sentinel (`error/MappingException`).
- Request value contract (`request/Patch`).
- Framework-neutral Redis operational snapshot (`health/RedisHealthSnapshotProvider`) used by
adapters and bootstrap health composition without leaking Actuator or native client types.
- Tracing contract types (`tracing/TraceParent`, `tracing/BaggageAllowlist`,
`tracing/SpanErrorRecorder`) — W3C `traceparent` value type, baggage allowlist,
and the span-error-recording seam (feature-distributed-tracing-contract; the OTel
+19
View File
@@ -12,6 +12,25 @@ Micrometer·OTel 같은 프레임워크 타입을 import 하지 않는다. 그
persistence·outbound)이 프레임워크 충돌 없이 이 타입들을 공유할 수 있고, HTTP status 같은
전송 개념도 프레임워크 타입이 아니라 평범한 `int` 로 표현한다(매핑은 web 어댑터가 한다).
`health/RedisHealthSnapshotProvider`도 같은 원칙을 따른다. Redis adapter는 native client나
예외를 노출하지 않고 bounded role/capability 상태만 제공하며, bootstrap이 이를 Actuator
health로 변환한다.
---
## ratelimit — edge enforcement 계약
`EdgeRateLimitPort`는 inbound와 Redis adapter 사이의 provider-neutral edge enforcement
경계다. Business quota나 entitlement policy를 담는 application use case가 아니며, 이미
pseudonymized된 subject digest와 bounded policy ID/cost/deadline만 받는다.
`RateLimitPolicy`는 fixed window, sliding-window counter, token bucket 중 하나의 exact parameter
subtype을 고정하고 Lua의 `2^53-1` 안전 정수, 1일 window/refill/cleanup, 1시간 clock regression,
`FAIL_CLOSED`만 허용한다. 결과는 evaluated, known pre-send unavailable, post-dispatch
indeterminate, schema/program/reply incompatible로 분리하므로 adapter가 장애를 allow나 평범한
deny로 숨길 수 없다. 이 패키지는 Java 표준 라이브러리만 사용하며 Redis key, command, Lua,
Spring/Lettuce 타입을 노출하지 않는다.
---
## error — 에러 코드 계약
+26
View File
@@ -1,3 +1,29 @@
// Skeleton-wide operational contracts only. No business/domain concepts.
dependencies {
}
sourceSets {
edgeRateLimitContractTest {
java.srcDir 'src/edgeRateLimitContractTest/java'
resources.srcDir 'src/edgeRateLimitContractTest/resources'
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
}
}
configurations {
edgeRateLimitContractTestImplementation.extendsFrom testImplementation
edgeRateLimitContractTestCompileOnly.extendsFrom testCompileOnly
edgeRateLimitContractTestRuntimeOnly.extendsFrom testRuntimeOnly
}
tasks.register('edgeRateLimitContractTest', Test) {
group = 'redis verification'
description = 'Runs the provider-neutral edge rate-limit shared contract.'
testClassesDirs = sourceSets.edgeRateLimitContractTest.output.classesDirs
classpath = sourceSets.edgeRateLimitContractTest.runtimeClasspath
useJUnitPlatform()
failOnNoDiscoveredTests = true
outputs.upToDateWhen { false }
jvmArgs '-Duser.timezone=UTC'
}
+32 -32
View File
@@ -1,40 +1,40 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.github.ben-manes.caffeine:caffeine:3.2.3=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.ben-manes.caffeine:caffeine:3.2.3=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
javax.inject:javax.inject:1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.0=spotbugs
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
@@ -50,31 +50,31 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.6=testCompileClasspath,testRuntimeClasspath
org.apiguardian:apiguardian-api:1.1.2=edgeRateLimitContractTestCompileClasspath,testCompileClasspath
org.assertj:assertj-core:3.27.6=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.0=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.1=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.1=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.1=testRuntimeClasspath
org.junit:junit-bom:6.0.1=testCompileClasspath,testRuntimeClasspath
org.jspecify:jspecify:1.0.0=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,edgeRateLimitContractTestCompileClasspath,testAnnotationProcessor,testCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.1=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.1=edgeRateLimitContractTestRuntimeClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.1=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.1=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.1=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.1=edgeRateLimitContractTestRuntimeClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.1=edgeRateLimitContractTestRuntimeClasspath,testRuntimeClasspath
org.junit:junit-bom:6.0.1=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.pcollections:pcollections:4.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.slf4j:slf4j-api:2.0.17=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=checkstyle,spotbugsSlf4j
@@ -0,0 +1,75 @@
package dev.caskeleton.shared.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.Test;
class EdgeRateLimitProviderNeutralContractTest {
@Test
void allPortableAlgorithmsHaveBoundedProviderNeutralPolicies() {
List<RateLimitPolicy> policies =
List.of(
policy(
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(100, Duration.ofMinutes(1))),
policy(
RateLimitAlgorithm.SLIDING_COUNTER,
new RateParameters.SlidingCounter(100, Duration.ofMinutes(1))),
policy(
RateLimitAlgorithm.TOKEN_BUCKET,
new RateParameters.TokenBucket(100, 10, Duration.ofSeconds(1))));
assertThat(policies)
.extracting(RateLimitPolicy::algorithm)
.containsExactlyElementsOf(List.of(RateLimitAlgorithm.values()));
assertThat(policies)
.allSatisfy(
policy -> {
assertThat(policy.failurePolicy()).isEqualTo(RateLimitFailurePolicy.FAIL_CLOSED);
assertThat(policy.evaluationDedupPolicy().maximumEntries())
.isLessThanOrEqualTo(RateLimitEvaluationDedupPolicy.MAXIMUM_ENTRIES);
});
}
@Test
void requestAcceptsOnlyPseudonymousSubjectAndBoundedEvaluationIdentity() {
RateLimitSubjectDigest digest = new RateLimitSubjectDigest("v1:" + "a".repeat(64));
RateLimitRequest request =
new RateLimitRequest(
"edge-default",
digest,
1,
"ev1:AAAAAAAAAAAAAAAAAAAAAA",
Instant.parse("2026-07-29T00:00:01Z"));
assertThat(request.subjectDigest()).isEqualTo(digest.value());
assertThatThrownBy(
() ->
new RateLimitRequest(
"edge-default",
"raw-user@example.com",
1,
"",
Instant.parse("2026-07-29T00:00:01Z")))
.isInstanceOf(IllegalArgumentException.class);
}
private static RateLimitPolicy policy(RateLimitAlgorithm algorithm, RateParameters parameters) {
return new RateLimitPolicy(
"edge-default",
"policy-v1",
algorithm,
parameters,
10,
Duration.ofSeconds(5),
Duration.ofSeconds(1),
RateLimitFailurePolicy.FAIL_CLOSED,
RateLimitEvaluationDedupPolicy.enabledDefaults());
}
}
@@ -0,0 +1,103 @@
package dev.caskeleton.shared.health;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Framework-neutral operational snapshot for canonically bound Redis roles.
*
* <p>The Redis adapter implements this contract; the bootstrap composition root maps it to its
* health framework. No command client, native connection, credential, or secret material crosses
* this boundary.
*/
public interface RedisHealthSnapshotProvider {
Snapshot snapshot();
record Snapshot(Instant observedAt, List<RoleHealth> roles) {
public Snapshot {
Objects.requireNonNull(observedAt, "observedAt must be non-null");
roles = List.copyOf(Objects.requireNonNull(roles, "roles must be non-null"));
}
}
record RoleHealth(
Role role,
String deploymentId,
boolean required,
EvictionPolicy expectedEviction,
EvictionAttestation evictionAttestation,
Set<Capability> capabilities,
State state,
Reason reason,
Instant semanticObservedAt,
long semanticAgeMillis,
boolean semanticStale) {
public RoleHealth {
Objects.requireNonNull(role, "role must be non-null");
Objects.requireNonNull(deploymentId, "deploymentId must be non-null");
Objects.requireNonNull(expectedEviction, "expectedEviction must be non-null");
Objects.requireNonNull(evictionAttestation, "evictionAttestation must be non-null");
capabilities =
Set.copyOf(Objects.requireNonNull(capabilities, "capabilities must be non-null"));
Objects.requireNonNull(state, "state must be non-null");
Objects.requireNonNull(reason, "reason must be non-null");
Objects.requireNonNull(semanticObservedAt, "semanticObservedAt must be non-null");
if (semanticAgeMillis < 0) {
throw new IllegalArgumentException("semanticAgeMillis must be non-negative");
}
}
}
enum Role {
CACHE,
COORDINATION,
SESSION
}
enum Capability {
CACHE,
RATE_LIMIT,
IDEMPOTENCY,
EFFICIENCY_LEASE,
SESSION
}
enum State {
AVAILABLE,
UNAVAILABLE,
OVERLOADED
}
enum Reason {
COMMAND_UNAVAILABLE,
ROUTE_CLOSED,
SEMANTIC_PROBE_SUCCEEDED,
SEMANTIC_READ_WRITE_FAILED,
SEMANTIC_PROGRAM_ACL_DENIED,
SEMANTIC_PROGRAM_FAILED,
SERVER_VERSION_UNSUPPORTED,
SEMANTIC_PROBE_IN_PROGRESS,
SEMANTIC_OBSERVATION_STALE,
COMMAND_SATURATED,
RECENT_COMMAND_FAILURE
}
enum EvictionPolicy {
ALLKEYS_LFU,
ALLKEYS_LRU,
NOEVICTION
}
/**
* The runtime never requests Redis CONFIG access. The configured expectation therefore needs an
* external conformance check against the server's effective maxmemory-policy.
*/
enum EvictionAttestation {
CONFIGURED_EXPECTATION_ONLY
}
}
@@ -0,0 +1,12 @@
package dev.caskeleton.shared.ratelimit;
/**
* Provider-neutral edge-enforcement boundary.
*
* <p>Business quota policy belongs to an application use case, not this technical edge port.
*/
@FunctionalInterface
public interface EdgeRateLimitPort {
RateLimitOutcome evaluate(RateLimitRequest request);
}
@@ -0,0 +1,43 @@
package dev.caskeleton.shared.ratelimit;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* Bounded canonical input to an {@link EdgeSubjectPseudonymizer}.
*
* <p>The identity is intentionally raw only at this short-lived pre-pseudonymization boundary. It
* must never be copied into a {@link RateLimitRequest}, provider key, log field, metric tag, or
* error response.
*/
public record EdgeRateLimitSubject(Kind kind, String canonicalIdentity, String operationId) {
private static final int MAXIMUM_IDENTITY_BYTES = 512;
private static final int MAXIMUM_OPERATION_BYTES = 256;
public EdgeRateLimitSubject {
Objects.requireNonNull(kind, "kind must not be null");
canonicalIdentity = boundedText(canonicalIdentity, "canonicalIdentity", MAXIMUM_IDENTITY_BYTES);
operationId = boundedText(operationId, "operationId", MAXIMUM_OPERATION_BYTES);
}
private static String boundedText(String value, String field, int maximumBytes) {
Objects.requireNonNull(value, field + " must not be null");
if (value.isBlank()) {
throw new IllegalArgumentException(field + " must not be blank");
}
if (value.chars().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException(field + " must not contain control characters");
}
if (value.getBytes(StandardCharsets.UTF_8).length > maximumBytes) {
throw new IllegalArgumentException(field + " exceeds " + maximumBytes + " UTF-8 bytes");
}
return value;
}
public enum Kind {
PRINCIPAL,
API_KEY,
CLIENT_IP
}
}
@@ -0,0 +1,13 @@
package dev.caskeleton.shared.ratelimit;
/**
* Converts a bounded canonical edge subject into a stable, versioned HMAC digest.
*
* <p>Implementations own secret access and rotation. Inbound adapters must not resolve or retain
* the HMAC secret themselves.
*/
@FunctionalInterface
public interface EdgeSubjectPseudonymizer {
RateLimitSubjectDigest pseudonymize(EdgeRateLimitSubject subject);
}
@@ -0,0 +1,7 @@
package dev.caskeleton.shared.ratelimit;
public enum RateLimitAlgorithm {
FIXED_WINDOW,
SLIDING_COUNTER,
TOKEN_BUCKET
}
@@ -0,0 +1,84 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
import java.util.Objects;
import java.util.regex.Pattern;
final class RateLimitBounds {
static final Duration MAXIMUM_WINDOW = Duration.ofDays(1);
static final Duration MAXIMUM_CLEANUP_GRACE = Duration.ofDays(1);
static final Duration MAXIMUM_CLOCK_REGRESSION = Duration.ofHours(1);
static final Duration MAXIMUM_RETRY_AFTER =
Duration.ofMillis(RateParameters.MAXIMUM_EXACT_INTEGER);
private static final Pattern POLICY_ID = Pattern.compile("[a-z][a-z0-9-]{0,62}");
private static final Pattern POLICY_REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,63}");
private static final Pattern SUBJECT_DIGEST =
Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{15,127}");
private static final Pattern EVALUATION_ID =
Pattern.compile("ev[1-9][0-9]{0,3}:[A-Za-z0-9_-]{22,64}");
private RateLimitBounds() {}
static String policyId(String value) {
return boundedIdentifier(value, "policyId", POLICY_ID);
}
static String policyRevision(String value) {
return boundedIdentifier(value, "policyRevision", POLICY_REVISION);
}
static String subjectDigest(String value) {
return boundedIdentifier(value, "subjectDigest", SUBJECT_DIGEST);
}
static String optionalEvaluationId(String value) {
Objects.requireNonNull(value, "evaluationId must not be null");
if (value.isEmpty()) {
return value;
}
return boundedIdentifier(value, "evaluationId", EVALUATION_ID);
}
static Duration positiveDuration(Duration value, String field, Duration maximum) {
return duration(value, field, false, maximum);
}
static Duration nonNegativeDuration(Duration value, String field, Duration maximum) {
return duration(value, field, true, maximum);
}
private static String boundedIdentifier(String value, String field, Pattern pattern) {
Objects.requireNonNull(value, field + " must not be null");
if (!pattern.matcher(value).matches()) {
throw new IllegalArgumentException(field + " has an invalid bounded representation");
}
return value;
}
private static Duration duration(
Duration value, String field, boolean zeroAllowed, Duration maximum) {
Objects.requireNonNull(value, field + " must not be null");
Objects.requireNonNull(maximum, "maximum must not be null");
if (value.isNegative() || (!zeroAllowed && value.isZero())) {
throw new IllegalArgumentException(
field + (zeroAllowed ? " must not be negative" : " must be positive"));
}
if (value.compareTo(maximum) > 0) {
throw new IllegalArgumentException(field + " exceeds its maximum duration of " + maximum);
}
long milliseconds;
try {
milliseconds = value.toMillis();
} catch (ArithmeticException exception) {
throw new IllegalArgumentException(
field + " exceeds the supported milliseconds range", exception);
}
if (!Duration.ofMillis(milliseconds).equals(value)) {
throw new IllegalArgumentException(field + " must use whole milliseconds");
}
return value;
}
}
@@ -0,0 +1,59 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
public record RateLimitDecision(
boolean allowed,
long limit,
long remaining,
Duration retryAfter,
Instant resetAt,
String policyId,
String policyRevision,
DecisionSource source,
DecisionCertainty certainty) {
public RateLimitDecision {
if (limit <= 0 || limit > RateParameters.MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
"limit must be positive and within the exact integer range");
}
if (remaining < 0 || remaining > limit) {
throw new IllegalArgumentException("remaining must be between zero and limit");
}
RateLimitBounds.nonNegativeDuration(
retryAfter, "retryAfter", RateLimitBounds.MAXIMUM_RETRY_AFTER);
if (allowed && !retryAfter.isZero()) {
throw new IllegalArgumentException("retryAfter must be zero for an allowed decision");
}
if (!allowed && retryAfter.isZero()) {
throw new IllegalArgumentException("retryAfter must be positive for a denied decision");
}
Objects.requireNonNull(resetAt, "resetAt must not be null");
try {
long resetAtMillis = resetAt.toEpochMilli();
if (resetAtMillis < 0 || resetAtMillis > RateParameters.MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
"resetAt must be within the non-negative exact integer range");
}
} catch (ArithmeticException exception) {
throw new IllegalArgumentException(
"resetAt must be representable as epoch milliseconds", exception);
}
RateLimitBounds.policyId(policyId);
RateLimitBounds.policyRevision(policyRevision);
Objects.requireNonNull(source, "source must not be null");
Objects.requireNonNull(certainty, "certainty must not be null");
}
public enum DecisionSource {
GLOBAL_REDIS
}
public enum DecisionCertainty {
CERTAIN,
APPROXIMATE_ALGORITHM
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
import java.util.Objects;
/**
* Bounded response-loss replay policy for one rate-limit policy.
*
* <p>The byte limit covers the logical evaluation-ID and decision payload retained by the Redis
* program. Redis allocator overhead remains deployment/version evidence, not a portable byte
* contract.
*/
public record RateLimitEvaluationDedupPolicy(
boolean enabled, Duration timeToLive, int maximumEntries, int maximumStoredBytes) {
public static final int MAXIMUM_EVALUATION_ID_BYTES = 71;
public static final int MAXIMUM_DECISION_BYTES = 128;
public static final int MAXIMUM_ENTRIES = 1024;
public static final int MAXIMUM_STORED_BYTES = 262_144;
public static final Duration MAXIMUM_TIME_TO_LIVE = Duration.ofMinutes(5);
public RateLimitEvaluationDedupPolicy {
Objects.requireNonNull(timeToLive, "timeToLive must not be null");
if (!enabled) {
if (!timeToLive.isZero() || maximumEntries != 0 || maximumStoredBytes != 0) {
throw new IllegalArgumentException(
"disabled evaluation dedup must not allocate TTL, entries, or stored bytes");
}
} else {
RateLimitBounds.positiveDuration(timeToLive, "timeToLive", MAXIMUM_TIME_TO_LIVE);
if (maximumEntries < 1 || maximumEntries > MAXIMUM_ENTRIES) {
throw new IllegalArgumentException("maximumEntries must be in 1.." + MAXIMUM_ENTRIES);
}
if (maximumStoredBytes < 1 || maximumStoredBytes > MAXIMUM_STORED_BYTES) {
throw new IllegalArgumentException(
"maximumStoredBytes must be in 1.." + MAXIMUM_STORED_BYTES);
}
long requiredLogicalBytes =
(long) maximumEntries * (MAXIMUM_EVALUATION_ID_BYTES + MAXIMUM_DECISION_BYTES);
if (requiredLogicalBytes > maximumStoredBytes) {
throw new IllegalArgumentException(
"maximumStoredBytes cannot bound every configured evaluation entry");
}
}
}
public static RateLimitEvaluationDedupPolicy enabledDefaults() {
return new RateLimitEvaluationDedupPolicy(true, Duration.ofSeconds(5), 256, 65_536);
}
public static RateLimitEvaluationDedupPolicy disabled() {
return new RateLimitEvaluationDedupPolicy(false, Duration.ZERO, 0, 0);
}
}
@@ -0,0 +1,6 @@
package dev.caskeleton.shared.ratelimit;
/** V1 deliberately does not claim fail-open or local fallback semantics. */
public enum RateLimitFailurePolicy {
FAIL_CLOSED
}
@@ -0,0 +1,59 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
import java.util.Objects;
public sealed interface RateLimitOutcome
permits RateLimitOutcome.Evaluated,
RateLimitOutcome.Unavailable,
RateLimitOutcome.Indeterminate,
RateLimitOutcome.Incompatible {
record Evaluated(RateLimitDecision decision) implements RateLimitOutcome {
public Evaluated {
Objects.requireNonNull(decision, "decision must not be null");
}
}
record Unavailable(String policyId, Duration retryAfter, UnavailableCategory category)
implements RateLimitOutcome {
public Unavailable {
RateLimitBounds.policyId(policyId);
RateLimitBounds.positiveDuration(
retryAfter, "retryAfter", RateLimitBounds.MAXIMUM_RETRY_AFTER);
Objects.requireNonNull(category, "category must not be null");
}
}
record Indeterminate(String policyId, Duration retryAfter) implements RateLimitOutcome {
public Indeterminate {
RateLimitBounds.policyId(policyId);
RateLimitBounds.positiveDuration(
retryAfter, "retryAfter", RateLimitBounds.MAXIMUM_RETRY_AFTER);
}
}
record Incompatible(String policyId, IncompatibleCategory category) implements RateLimitOutcome {
public Incompatible {
RateLimitBounds.policyId(policyId);
Objects.requireNonNull(category, "category must not be null");
}
}
public enum UnavailableCategory {
ADMISSION_REJECTED,
UNAVAILABLE_BEFORE_SEND,
NO_MUTATION_CONFIRMED,
CLOCK_UNSAFE
}
public enum IncompatibleCategory {
STATE_INCOMPATIBLE,
PROGRAM_INCOMPATIBLE,
REPLY_INCOMPATIBLE
}
}
@@ -0,0 +1,155 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
import java.util.Objects;
public record RateLimitPolicy(
String policyId,
String policyRevision,
RateLimitAlgorithm algorithm,
RateParameters parameters,
long maximumCost,
Duration cleanupGrace,
Duration maximumClockRegression,
RateLimitFailurePolicy failurePolicy,
RateLimitEvaluationDedupPolicy evaluationDedupPolicy) {
public RateLimitPolicy(
String policyId,
String policyRevision,
RateLimitAlgorithm algorithm,
RateParameters parameters,
long maximumCost,
Duration cleanupGrace,
Duration maximumClockRegression,
RateLimitFailurePolicy failurePolicy) {
this(
policyId,
policyRevision,
algorithm,
parameters,
maximumCost,
cleanupGrace,
maximumClockRegression,
failurePolicy,
RateLimitEvaluationDedupPolicy.enabledDefaults());
}
public RateLimitPolicy {
RateLimitBounds.policyId(policyId);
RateLimitBounds.policyRevision(policyRevision);
Objects.requireNonNull(algorithm, "algorithm must not be null");
Objects.requireNonNull(parameters, "parameters must not be null");
if (maximumCost <= 0 || maximumCost > RateParameters.MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
"maximumCost must be positive and within Lua's exact integer range");
}
RateLimitBounds.positiveDuration(
cleanupGrace, "cleanupGrace", RateLimitBounds.MAXIMUM_CLEANUP_GRACE);
RateLimitBounds.nonNegativeDuration(
maximumClockRegression, "maximumClockRegression", RateLimitBounds.MAXIMUM_CLOCK_REGRESSION);
Objects.requireNonNull(failurePolicy, "failurePolicy must not be null");
Objects.requireNonNull(evaluationDedupPolicy, "evaluationDedupPolicy must not be null");
if (failurePolicy != RateLimitFailurePolicy.FAIL_CLOSED) {
throw new IllegalArgumentException("only FAIL_CLOSED is supported in v1");
}
switch (algorithm) {
case FIXED_WINDOW -> validateFixedWindow(parameters, maximumCost, cleanupGrace);
case SLIDING_COUNTER -> validateSlidingCounter(parameters, maximumCost, cleanupGrace);
case TOKEN_BUCKET -> validateTokenBucket(parameters, maximumCost, cleanupGrace);
default -> throw new IllegalArgumentException("unsupported rate-limit algorithm");
}
}
private static void validateFixedWindow(
RateParameters parameters, long maximumCost, Duration cleanupGrace) {
if (!(parameters instanceof RateParameters.FixedWindow fixedWindow)) {
throw algorithmMismatch(RateLimitAlgorithm.FIXED_WINDOW, parameters);
}
requireMaximumCost(maximumCost, fixedWindow.limit());
RateParameters.exactSum(
"fixed-window consumed plus maximumCost", fixedWindow.limit(), maximumCost);
RateParameters.exactSum(
"fixed-window state TTL", fixedWindow.window().toMillis(), cleanupGrace.toMillis());
}
private static void validateSlidingCounter(
RateParameters parameters, long maximumCost, Duration cleanupGrace) {
if (!(parameters instanceof RateParameters.SlidingCounter slidingCounter)) {
throw algorithmMismatch(RateLimitAlgorithm.SLIDING_COUNTER, parameters);
}
requireMaximumCost(maximumCost, slidingCounter.limit());
long maximumUnscaledConsumption =
RateParameters.exactSum(
"sliding-counter previous/current consumption",
slidingCounter.limit(),
slidingCounter.limit(),
maximumCost);
RateParameters.exactProduct(
"sliding-counter weighted consumption", maximumUnscaledConsumption, RateParameters.SCALE);
RateParameters.exactProduct(
"sliding-counter window weight", slidingCounter.window().toMillis(), RateParameters.SCALE);
long twoWindows =
RateParameters.exactProduct(
"sliding-counter state TTL", slidingCounter.window().toMillis(), 2);
RateParameters.exactSum("sliding-counter state TTL", twoWindows, cleanupGrace.toMillis());
}
private static void validateTokenBucket(
RateParameters parameters, long maximumCost, Duration cleanupGrace) {
if (!(parameters instanceof RateParameters.TokenBucket tokenBucket)) {
throw algorithmMismatch(RateLimitAlgorithm.TOKEN_BUCKET, parameters);
}
requireMaximumCost(maximumCost, tokenBucket.capacity());
if (tokenBucket.refillTokens() > tokenBucket.capacity()) {
throw new IllegalArgumentException("refillTokens must not exceed token-bucket capacity");
}
long scaledCapacity =
RateParameters.exactProduct(
"token-bucket capacity scale", tokenBucket.capacity(), RateParameters.SCALE);
long scaledMaximumCost =
RateParameters.exactProduct(
"token-bucket maximumCost scale", maximumCost, RateParameters.SCALE);
RateParameters.exactSum(
"token-bucket tokens plus maximumCost", scaledCapacity, scaledMaximumCost);
RateParameters.exactProduct(
"token-bucket refill time product", scaledCapacity, tokenBucket.refillPeriod().toMillis());
long scaledRefill =
RateParameters.exactProduct(
"token-bucket refill scale", tokenBucket.refillTokens(), RateParameters.SCALE);
long fullRefillPeriods = ceilingDivide(scaledCapacity, scaledRefill);
RateParameters.exactProduct(
"token-bucket full-refill horizon",
fullRefillPeriods,
tokenBucket.refillPeriod().toMillis());
RateParameters.exactSum(
"token-bucket state TTL",
RateParameters.exactProduct(
"token-bucket state TTL", fullRefillPeriods, tokenBucket.refillPeriod().toMillis()),
cleanupGrace.toMillis());
}
private static void requireMaximumCost(long maximumCost, long algorithmLimit) {
if (maximumCost > algorithmLimit) {
throw new IllegalArgumentException(
"maximumCost must not exceed the algorithm limit or capacity");
}
}
private static long ceilingDivide(long dividend, long divisor) {
return dividend / divisor + (dividend % divisor == 0 ? 0 : 1);
}
private static IllegalArgumentException algorithmMismatch(
RateLimitAlgorithm expected, RateParameters actual) {
return new IllegalArgumentException(
"algorithm "
+ expected
+ " does not match parameter type "
+ actual.getClass().getSimpleName());
}
}
@@ -0,0 +1,43 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Instant;
import java.util.Objects;
public record RateLimitRequest(
String policyId, String subjectDigest, long cost, String evaluationId, Instant callerDeadline) {
public RateLimitRequest(
String policyId,
RateLimitSubjectDigest subject,
long cost,
String evaluationId,
Instant callerDeadline) {
this(
policyId,
Objects.requireNonNull(subject, "subject must not be null").value(),
cost,
evaluationId,
callerDeadline);
}
public RateLimitRequest {
RateLimitBounds.policyId(policyId);
RateLimitBounds.subjectDigest(subjectDigest);
if (cost <= 0 || cost > RateParameters.MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
"cost must be positive and within the exact integer range");
}
RateLimitBounds.optionalEvaluationId(evaluationId);
Objects.requireNonNull(callerDeadline, "callerDeadline must not be null");
try {
long epochMillis = callerDeadline.toEpochMilli();
if (Instant.ofEpochMilli(epochMillis).isAfter(callerDeadline)) {
throw new IllegalArgumentException(
"callerDeadline must have a non-forward epoch millisecond representation");
}
} catch (ArithmeticException exception) {
throw new IllegalArgumentException(
"callerDeadline must be representable as epoch milliseconds", exception);
}
}
}
@@ -0,0 +1,19 @@
package dev.caskeleton.shared.ratelimit;
import java.util.Objects;
import java.util.regex.Pattern;
/** Versioned lowercase HMAC-SHA-256 representation safe to cross the provider port boundary. */
public record RateLimitSubjectDigest(String value) {
private static final Pattern VERSIONED_HMAC_SHA256 =
Pattern.compile("v[1-9][0-9]{0,3}:[0-9a-f]{64}");
public RateLimitSubjectDigest {
Objects.requireNonNull(value, "value must not be null");
if (!VERSIONED_HMAC_SHA256.matcher(value).matches()) {
throw new IllegalArgumentException(
"subject digest must be a bounded versioned HMAC-SHA-256 representation");
}
}
}
@@ -0,0 +1,73 @@
package dev.caskeleton.shared.ratelimit;
import java.time.Duration;
public sealed interface RateParameters
permits RateParameters.FixedWindow, RateParameters.SlidingCounter, RateParameters.TokenBucket {
long MAXIMUM_EXACT_INTEGER = 9_007_199_254_740_991L;
long SCALE = 1_000_000L;
record FixedWindow(long limit, Duration window) implements RateParameters {
public FixedWindow {
requirePositiveExactInteger(limit, "limit");
RateLimitBounds.positiveDuration(window, "window", RateLimitBounds.MAXIMUM_WINDOW);
}
}
record SlidingCounter(long limit, Duration window) implements RateParameters {
public SlidingCounter {
requirePositiveExactInteger(limit, "limit");
RateLimitBounds.positiveDuration(window, "window", RateLimitBounds.MAXIMUM_WINDOW);
requireExactProduct("sliding-counter limit scale", limit, SCALE);
}
}
record TokenBucket(long capacity, long refillTokens, Duration refillPeriod)
implements RateParameters {
public TokenBucket {
requirePositiveExactInteger(capacity, "capacity");
requirePositiveExactInteger(refillTokens, "refillTokens");
RateLimitBounds.positiveDuration(
refillPeriod, "refillPeriod", RateLimitBounds.MAXIMUM_WINDOW);
requireExactProduct("token-bucket capacity scale", capacity, SCALE);
requireExactProduct("token-bucket refill scale", refillTokens, SCALE);
}
}
private static void requirePositiveExactInteger(long value, String field) {
if (value <= 0 || value > MAXIMUM_EXACT_INTEGER) {
throw new IllegalArgumentException(
field + " must be positive and within Lua's exact integer range");
}
}
static long exactSum(String operation, long... terms) {
long result = 0;
for (long term : terms) {
if (term < 0 || result > MAXIMUM_EXACT_INTEGER - term) {
throw new IllegalArgumentException(operation + " exceeds Lua's exact integer range");
}
result += term;
}
return result;
}
static long exactProduct(String operation, long... factors) {
long result = 1;
for (long factor : factors) {
if (factor < 0 || (factor != 0 && result > MAXIMUM_EXACT_INTEGER / factor)) {
throw new IllegalArgumentException(operation + " exceeds Lua's exact integer range");
}
result *= factor;
}
return result;
}
private static void requireExactProduct(String operation, long... factors) {
exactProduct(operation, factors);
}
}
@@ -0,0 +1,189 @@
package dev.caskeleton.shared.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.Test;
class RateLimitContractTest {
private static final String SUBJECT_DIGEST = "a".repeat(64);
private static final String VERSIONED_SUBJECT_DIGEST = "v1:" + SUBJECT_DIGEST;
@Test
void edgeSubjectIsBoundedBeforePseudonymizationAndRequestAcceptsOnlyTheDigestValue() {
EdgeRateLimitSubject subject =
new EdgeRateLimitSubject(
EdgeRateLimitSubject.Kind.PRINCIPAL, "user-42", "GET /v1/worklogs/{id}");
RateLimitSubjectDigest digest = new RateLimitSubjectDigest(VERSIONED_SUBJECT_DIGEST);
Instant deadline = Instant.now().plusSeconds(30);
RateLimitRequest request = new RateLimitRequest("login", digest, 1, "", deadline);
assertThat(subject.kind()).isEqualTo(EdgeRateLimitSubject.Kind.PRINCIPAL);
assertThat(subject.canonicalIdentity()).isEqualTo("user-42");
assertThat(subject.operationId()).isEqualTo("GET /v1/worklogs/{id}");
assertThat(request.subjectDigest()).isEqualTo(VERSIONED_SUBJECT_DIGEST);
assertThat(request.subjectDigest()).doesNotContain(subject.canonicalIdentity());
}
@Test
void edgeSubjectAndDigestRejectUnboundedRawOrNonVersionedRepresentations() {
assertThatThrownBy(
() ->
new EdgeRateLimitSubject(
EdgeRateLimitSubject.Kind.CLIENT_IP, "x".repeat(513), "GET /v1/worklogs"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("canonicalIdentity");
assertThatThrownBy(
() ->
new EdgeRateLimitSubject(
EdgeRateLimitSubject.Kind.PRINCIPAL, "user-42", "GET /" + "x".repeat(300)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("operationId");
assertThatThrownBy(() -> new RateLimitSubjectDigest(SUBJECT_DIGEST))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("versioned");
assertThatThrownBy(() -> new RateLimitSubjectDigest("v1:raw@example.com"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("versioned");
}
@Test
void requestRequiresBoundedPseudonymizedInputAndARepresentableDeadline() {
Instant deadline = Instant.now().plusSeconds(30);
String evaluationId = "ev1:" + "A".repeat(22);
RateLimitRequest request =
new RateLimitRequest("login", SUBJECT_DIGEST, 2, evaluationId, deadline);
assertThat(request.policyId()).isEqualTo("login");
assertThat(request.subjectDigest()).isEqualTo(SUBJECT_DIGEST);
assertThat(request.cost()).isEqualTo(2);
assertThat(request.evaluationId()).isEqualTo(evaluationId);
assertThat(request.callerDeadline()).isEqualTo(deadline);
assertThatThrownBy(
() -> new RateLimitRequest("login", SUBJECT_DIGEST, 1, "client-value", deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("evaluationId");
assertThatThrownBy(
() ->
new RateLimitRequest("login", SUBJECT_DIGEST, 1, "ev1:" + "A".repeat(65), deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("evaluationId");
assertThat(new RateLimitRequest("login", SUBJECT_DIGEST, 1, "", deadline).evaluationId())
.isEmpty();
assertThat(
new RateLimitRequest("login", SUBJECT_DIGEST, 1, "", Instant.now().minusSeconds(1))
.callerDeadline())
.isBefore(Instant.now());
assertThatThrownBy(() -> new RateLimitRequest("login", SUBJECT_DIGEST, 1, "", Instant.MAX))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("representable");
assertThatThrownBy(() -> new RateLimitRequest("login", "raw@example.com", 1, "", deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("subjectDigest");
}
@Test
void requestRejectsUnboundedIdentifiersAndCost() {
Instant deadline = Instant.now().plusSeconds(30);
assertThatThrownBy(() -> new RateLimitRequest("p".repeat(64), SUBJECT_DIGEST, 1, "", deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("policyId");
assertThatThrownBy(() -> new RateLimitRequest("login", "a".repeat(129), 1, "", deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("subjectDigest");
assertThatThrownBy(() -> new RateLimitRequest("login", SUBJECT_DIGEST, 0, "", deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cost");
assertThatThrownBy(
() ->
new RateLimitRequest(
"login",
SUBJECT_DIGEST,
RateParameters.MAXIMUM_EXACT_INTEGER + 1,
"",
deadline))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cost");
}
@Test
void decisionAndOutcomesCarryProviderNeutralEnforcementMeaning() {
Instant resetAt = Instant.parse("2026-07-28T00:01:00Z");
RateLimitDecision decision =
new RateLimitDecision(
false,
10,
0,
Duration.ofSeconds(2),
resetAt,
"login",
"v3",
RateLimitDecision.DecisionSource.GLOBAL_REDIS,
RateLimitDecision.DecisionCertainty.CERTAIN);
assertThat(new RateLimitOutcome.Evaluated(decision).decision()).isEqualTo(decision);
assertThat(
new RateLimitOutcome.Unavailable(
"login", Duration.ofSeconds(1), RateLimitOutcome.UnavailableCategory.CLOCK_UNSAFE))
.isInstanceOf(RateLimitOutcome.Unavailable.class);
assertThat(new RateLimitOutcome.Indeterminate("login", Duration.ofSeconds(1)))
.isInstanceOf(RateLimitOutcome.Indeterminate.class);
assertThat(
new RateLimitOutcome.Incompatible(
"login", RateLimitOutcome.IncompatibleCategory.PROGRAM_INCOMPATIBLE))
.isInstanceOf(RateLimitOutcome.Incompatible.class);
}
@Test
void decisionRejectsImpossibleRemainingAndRetrySemantics() {
Instant resetAt = Instant.parse("2026-07-28T00:01:00Z");
assertThatThrownBy(
() ->
new RateLimitDecision(
true,
10,
11,
Duration.ZERO,
resetAt,
"login",
"v3",
RateLimitDecision.DecisionSource.GLOBAL_REDIS,
RateLimitDecision.DecisionCertainty.CERTAIN))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("remaining");
assertThatThrownBy(
() ->
new RateLimitDecision(
false,
10,
0,
Duration.ZERO,
resetAt,
"login",
"v3",
RateLimitDecision.DecisionSource.GLOBAL_REDIS,
RateLimitDecision.DecisionCertainty.CERTAIN))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryAfter");
}
@Test
void failureOutcomesRequireBoundedPositiveRetryHints() {
assertThatThrownBy(
() ->
new RateLimitOutcome.Unavailable(
"login", Duration.ZERO, RateLimitOutcome.UnavailableCategory.CLOCK_UNSAFE))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryAfter");
assertThatThrownBy(() -> new RateLimitOutcome.Indeterminate("login", Duration.ofNanos(1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("milliseconds");
}
}
@@ -0,0 +1,39 @@
package dev.caskeleton.shared.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class RateLimitEvaluationDedupPolicyTest {
@Test
void enabledPolicyBoundsTtlEntriesAndStoredDataBytes() {
RateLimitEvaluationDedupPolicy policy =
new RateLimitEvaluationDedupPolicy(true, Duration.ofSeconds(5), 256, 65_536);
assertThat(policy.enabled()).isTrue();
assertThat(policy.timeToLive()).isEqualTo(Duration.ofSeconds(5));
assertThat(policy.maximumEntries()).isEqualTo(256);
assertThat(policy.maximumStoredBytes()).isEqualTo(65_536);
}
@Test
void disabledPolicyHasNoDedupStateAndEnabledPolicyRejectsUnsafeBounds() {
assertThat(RateLimitEvaluationDedupPolicy.disabled())
.isEqualTo(new RateLimitEvaluationDedupPolicy(false, Duration.ZERO, 0, 0));
assertThatThrownBy(
() -> new RateLimitEvaluationDedupPolicy(true, Duration.ofMinutes(6), 256, 65_536))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("timeToLive");
assertThatThrownBy(
() -> new RateLimitEvaluationDedupPolicy(true, Duration.ofSeconds(5), 1025, 262_144))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maximumEntries");
assertThatThrownBy(
() -> new RateLimitEvaluationDedupPolicy(true, Duration.ofSeconds(5), 256, 4096))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maximumStoredBytes");
}
}
@@ -0,0 +1,159 @@
package dev.caskeleton.shared.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class RateLimitPolicyTest {
@Test
void acceptsEachV1AlgorithmWithItsExactParameterSubtype() {
RateLimitPolicy fixed =
policy(
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(100, Duration.ofMinutes(1)),
10);
RateLimitPolicy sliding =
policy(
RateLimitAlgorithm.SLIDING_COUNTER,
new RateParameters.SlidingCounter(100, Duration.ofMinutes(1)),
10);
RateLimitPolicy token =
policy(
RateLimitAlgorithm.TOKEN_BUCKET,
new RateParameters.TokenBucket(100, 10, Duration.ofSeconds(1)),
10);
assertThat(fixed.parameters()).isInstanceOf(RateParameters.FixedWindow.class);
assertThat(sliding.parameters()).isInstanceOf(RateParameters.SlidingCounter.class);
assertThat(token.parameters()).isInstanceOf(RateParameters.TokenBucket.class);
assertThat(fixed.failurePolicy()).isEqualTo(RateLimitFailurePolicy.FAIL_CLOSED);
}
@Test
void rejectsAlgorithmParameterMismatchAndUnsupportedRequestCost() {
assertThatThrownBy(
() ->
policy(
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.TokenBucket(100, 10, Duration.ofSeconds(1)),
10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("algorithm");
assertThatThrownBy(
() ->
policy(
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(10, Duration.ofSeconds(1)),
11))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maximumCost");
}
@Test
void rejectsSlidingCounterIntermediatesBeyondLuaExactIntegerRange() {
long unsafeLimit = (RateParameters.MAXIMUM_EXACT_INTEGER / RateParameters.SCALE) / 2;
assertThatThrownBy(
() ->
policy(
RateLimitAlgorithm.SLIDING_COUNTER,
new RateParameters.SlidingCounter(unsafeLimit, Duration.ofSeconds(1)),
unsafeLimit))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("exact integer");
}
@Test
void rejectsTokenBucketFixedPointTimeProductsBeyondLuaExactIntegerRange() {
assertThatThrownBy(
() ->
policy(
RateLimitAlgorithm.TOKEN_BUCKET,
new RateParameters.TokenBucket(10_000_000, 1, Duration.ofDays(1)),
1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("exact integer");
}
@Test
void rejectsFixedWindowAdmissionSumBeyondLuaExactIntegerRange() {
assertThatThrownBy(
() ->
policy(
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(
RateParameters.MAXIMUM_EXACT_INTEGER, Duration.ofSeconds(1)),
1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("exact integer");
}
@Test
void rejectsSubMillisecondAndOverlongDurations() {
assertThatThrownBy(() -> new RateParameters.FixedWindow(10, Duration.ofNanos(1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("milliseconds");
assertThatThrownBy(() -> new RateParameters.FixedWindow(10, Duration.ofDays(2)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("PT24H");
assertThatThrownBy(
() ->
new RateLimitPolicy(
"login",
"v3",
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(10, Duration.ofSeconds(1)),
1,
Duration.ofNanos(1),
Duration.ofSeconds(1),
RateLimitFailurePolicy.FAIL_CLOSED))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("milliseconds");
}
@Test
void rejectsZeroGraceAndClockRegressionBeyondTheLuaProgramBounds() {
assertThatThrownBy(
() ->
new RateLimitPolicy(
"login",
"v3",
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(10, Duration.ofSeconds(1)),
1,
Duration.ZERO,
Duration.ofSeconds(1),
RateLimitFailurePolicy.FAIL_CLOSED))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cleanupGrace");
assertThatThrownBy(
() ->
new RateLimitPolicy(
"login",
"v3",
RateLimitAlgorithm.FIXED_WINDOW,
new RateParameters.FixedWindow(10, Duration.ofSeconds(1)),
1,
Duration.ofSeconds(1),
Duration.ofHours(1).plusMillis(1),
RateLimitFailurePolicy.FAIL_CLOSED))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maximumClockRegression");
}
private static RateLimitPolicy policy(
RateLimitAlgorithm algorithm, RateParameters parameters, long maximumCost) {
return new RateLimitPolicy(
"login",
"v3",
algorithm,
parameters,
maximumCost,
Duration.ofSeconds(5),
Duration.ofSeconds(1),
RateLimitFailurePolicy.FAIL_CLOSED);
}
}