diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyBuilder.java b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyBuilder.java new file mode 100644 index 0000000..f0bf626 --- /dev/null +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyBuilder.java @@ -0,0 +1,103 @@ +package com.yashdotdev.distributed_traffic_control.config; + +import com.yashdotdev.distributed_traffic_control.lease.GlobalCapacityKey; +import com.yashdotdev.distributed_traffic_control.traffic.TrafficSubject; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; + +public class RedisKeyBuilder { + + private final String namespace; + + public RedisKeyBuilder(String namespace) { + if (namespace == null || namespace.isBlank() || namespace.endsWith(":")) { + throw new IllegalArgumentException( + "Redis key namespace must not be null or blank and must not end with ':'" + ); + } + this.namespace = namespace; + } + + public RedisKeyBuilder(RedisKeyProperties properties) { + if (properties == null) { + throw new IllegalArgumentException("properties must not be null"); + } + String ns = properties.getKeyNamespace(); + if (ns == null || ns.isBlank() || ns.endsWith(":")) { + throw new IllegalArgumentException( + "Redis key namespace must not be null or blank and must not end with ':'" + ); + } + this.namespace = ns; + } + + public String getNamespace() { + return namespace; + } + + public String defaultPolicyKey() { + return namespace + ":policies:default"; + } + + public String resourcePolicyKey(String resource) { + return namespace + ":policies:resource:" + encode(resource); + } + + public String subjectPolicyKey( + TrafficSubject subject, + String resource) { + + Objects.requireNonNull(subject, "subject must not be null"); + + return namespace + ":policies:subject:" + + encode(subject.getType().name()) + + ":" + + encode(subject.getSubjectId()) + + ":" + + encode(resource); + } + + public String resourceIndexKey() { + return namespace + ":policies:resources"; + } + + public String globalCapacityKey(GlobalCapacityKey capacityKey) { + Objects.requireNonNull(capacityKey, "capacityKey must not be null"); + + return namespace + ":quota:" + + capacityKey.policyId() + + ":" + + capacityKey.resource(); + } + + public String leaseRegistryKey(GlobalCapacityKey capacityKey) { + Objects.requireNonNull(capacityKey, "capacityKey must not be null"); + return globalCapacityKey(capacityKey) + ":leases"; + } + + public String leaseKey(String leaseId) { + if (leaseId == null || leaseId.isBlank()) { + throw new IllegalArgumentException( + "leaseId must not be null or blank"); + } + + return namespace + ":lease:" + leaseId; + } + + public String tokenBucketKey(GlobalCapacityKey capacityKey) { + Objects.requireNonNull(capacityKey, "capacityKey must not be null"); + + return namespace + ":token-bucket:" + + capacityKey.policyId() + + ":" + + capacityKey.resource(); + } + + private String encode(String value) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyNamespaceValidator.java b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyNamespaceValidator.java new file mode 100644 index 0000000..83c3600 --- /dev/null +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyNamespaceValidator.java @@ -0,0 +1,21 @@ + +package com.yashdotdev.distributed_traffic_control.config; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class RedisKeyNamespaceValidator + implements ConstraintValidator { + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context) { + + if (value == null) { + return true; + } + + return !value.endsWith(":"); + } +} diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyProperties.java b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyProperties.java new file mode 100644 index 0000000..e2c96e9 --- /dev/null +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyProperties.java @@ -0,0 +1,30 @@ +package com.yashdotdev.distributed_traffic_control.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +import jakarta.validation.constraints.NotBlank; + +@ConfigurationProperties(prefix = "traffic-control.redis") +@Validated +public class RedisKeyProperties { + + @NotBlank(message = "Redis key prefix must not be blank") + @ValidRedisKeyNamespace + private String keyNamespace = "traffic-control"; + + public RedisKeyProperties() { + } + + public RedisKeyProperties(String keyNamespace) { + this.keyNamespace = keyNamespace; + } + + public String getKeyNamespace() { + return keyNamespace; + } + + public void setKeyNamespace(String keyNamespace) { + this.keyNamespace = keyNamespace; + } +} diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/config/TrafficControlConfiguration.java b/src/main/java/com/yashdotdev/distributed_traffic_control/config/TrafficControlConfiguration.java index 25968ed..c9fe2a7 100644 --- a/src/main/java/com/yashdotdev/distributed_traffic_control/config/TrafficControlConfiguration.java +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/config/TrafficControlConfiguration.java @@ -19,6 +19,8 @@ import com.yashdotdev.distributed_traffic_control.traffic.TrafficDecisionEngine; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.observation.ObservationRegistry; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -28,6 +30,7 @@ @Configuration @Import(AllocationStrategyConfiguration.class) +@EnableConfigurationProperties(RedisKeyProperties.class) public class TrafficControlConfiguration { @Bean @@ -66,9 +69,11 @@ public QuotaCoordinator quotaCoordinator(Clock clock) { public LeaseCoordinator leaseCoordinator( StringRedisTemplate redisTemplate, Clock clock, - ObservationRegistry observationRegistry) { + ObservationRegistry observationRegistry, + RedisKeyBuilder redisKeyBuilder) { return new RedisLeaseCoordinator( redisTemplate, + redisKeyBuilder, clock, observationRegistry); } @@ -109,4 +114,8 @@ public TrafficControlMetrics trafficControlMetrics(MeterRegistry meterRegistry) return new TrafficControlMetrics(meterRegistry); } -} \ No newline at end of file + @Bean + public RedisKeyBuilder redisKeyBuilder(RedisKeyProperties properties) { + return new RedisKeyBuilder(properties); + } +} diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/config/ValidRedisKeyNamespace.java b/src/main/java/com/yashdotdev/distributed_traffic_control/config/ValidRedisKeyNamespace.java new file mode 100644 index 0000000..9dec4ae --- /dev/null +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/config/ValidRedisKeyNamespace.java @@ -0,0 +1,26 @@ + +package com.yashdotdev.distributed_traffic_control.config; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = RedisKeyNamespaceValidator.class) +@Target({ + ElementType.FIELD, + ElementType.PARAMETER, + ElementType.ANNOTATION_TYPE +}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ValidRedisKeyNamespace { + + String message() default "Redis key namespace must not end with a colon"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/lease/GlobalCapacityKey.java b/src/main/java/com/yashdotdev/distributed_traffic_control/lease/GlobalCapacityKey.java index 55ec207..1a9eefb 100644 --- a/src/main/java/com/yashdotdev/distributed_traffic_control/lease/GlobalCapacityKey.java +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/lease/GlobalCapacityKey.java @@ -1,6 +1,5 @@ package com.yashdotdev.distributed_traffic_control.lease; - public record GlobalCapacityKey(String policyId, String resource) { public GlobalCapacityKey { diff --git a/src/main/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinator.java b/src/main/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinator.java index d8523d8..0b5d7aa 100644 --- a/src/main/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinator.java +++ b/src/main/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinator.java @@ -1,5 +1,6 @@ package com.yashdotdev.distributed_traffic_control.lease; +import com.yashdotdev.distributed_traffic_control.config.RedisKeyBuilder; import com.yashdotdev.distributed_traffic_control.quota.QuotaKey; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; @@ -16,10 +17,7 @@ public class RedisLeaseCoordinator implements LeaseCoordinator, DistributedTokenBucket { - private static final String QUOTA_KEY_PREFIX = "traffic-control:quota:"; - private static final String LEASE_KEY_PREFIX = "traffic-control:lease:"; - private static final String LEASE_REGISTRY_SUFFIX = ":leases"; - + private static final String DEFAULT_NAMESPACE = "traffic-control"; private static final String TOKEN_BUCKET_KEY_PREFIX = "traffic-control:token-bucket:"; @@ -93,8 +91,6 @@ public class RedisLeaseCoordinator return math.floor(tokens) """, Long.class); - - private static final DefaultRedisScript INITIALIZE_TOKEN_BUCKET_SCRIPT = new DefaultRedisScript<>(""" if redis.call('EXISTS', KEYS[1]) == 1 then @@ -115,8 +111,6 @@ public class RedisLeaseCoordinator return 1 """, Long.class); - - /** * Atomically: *

@@ -445,32 +439,63 @@ public class RedisLeaseCoordinator """, Long.class); private final StringRedisTemplate redisTemplate; + private final RedisKeyBuilder keyBuilder; private final Clock clock; private final ObservationRegistry observationRegistry; public RedisLeaseCoordinator(StringRedisTemplate redisTemplate) { - this(redisTemplate, Clock.systemUTC(), null); + this(redisTemplate, new RedisKeyBuilder(DEFAULT_NAMESPACE), Clock.systemUTC(), null); } public RedisLeaseCoordinator(StringRedisTemplate redisTemplate, Clock clock) { - this(redisTemplate, clock, null); + this(redisTemplate, new RedisKeyBuilder(DEFAULT_NAMESPACE), clock, null); + } + + public RedisLeaseCoordinator( + StringRedisTemplate redisTemplate, + Clock clock, + ObservationRegistry observationRegistry) { + this(redisTemplate, new RedisKeyBuilder(DEFAULT_NAMESPACE), clock, observationRegistry); + } + + public RedisLeaseCoordinator( + StringRedisTemplate redisTemplate, + RedisKeyBuilder keyBuilder) { + this(redisTemplate, keyBuilder, Clock.systemUTC(), null); } public RedisLeaseCoordinator( StringRedisTemplate redisTemplate, + RedisKeyBuilder keyBuilder, + Clock clock) { + this(redisTemplate, keyBuilder, clock, null); + } + + public RedisLeaseCoordinator( + StringRedisTemplate redisTemplate, + RedisKeyBuilder keyBuilder, Clock clock, ObservationRegistry observationRegistry) { if (redisTemplate == null) { throw new IllegalArgumentException("redisTemplate must not be null"); } + if (keyBuilder == null) { + throw new IllegalArgumentException("keyBuilder must not be null"); + } if (clock == null) { throw new IllegalArgumentException("clock must not be null"); } this.redisTemplate = redisTemplate; + this.keyBuilder = keyBuilder; this.clock = clock; this.observationRegistry = observationRegistry; } + + public RedisKeyBuilder getKeyBuilder() { + return keyBuilder; + } + @Override public void registerCapacity(GlobalCapacityKey capacityKey, long capacity) { if (capacityKey == null) { @@ -483,7 +508,7 @@ public void registerCapacity(GlobalCapacityKey capacityKey, long capacity) { } redisTemplate.opsForValue().setIfAbsent( - buildGlobalCapacityRedisKey(capacityKey), + keyBuilder.globalCapacityKey(capacityKey), String.valueOf(capacity)); redisTemplate.execute( @@ -500,7 +525,7 @@ public boolean removeCapacity(GlobalCapacityKey capacityKey) { } Boolean capacityDeleted = redisTemplate.delete( - buildGlobalCapacityRedisKey(capacityKey)); + keyBuilder.globalCapacityKey(capacityKey)); Boolean tokenBucketDeleted = redisTemplate.delete( buildTokenBucketRedisKey(capacityKey)); @@ -509,7 +534,6 @@ public boolean removeCapacity(GlobalCapacityKey capacityKey) { || Boolean.TRUE.equals(tokenBucketDeleted); } - @Override public Optional acquireLease(QuotaKey quotaKey, String nodeId, long requestedCapacity, Duration leaseDuration) { validateQuotaKey(quotaKey); @@ -528,9 +552,9 @@ public Optional acquireLease(QuotaKey quotaKey, String nodeId, long Instant expiresAt = issuedAt.plus(leaseDuration); String leaseId = UUID.randomUUID().toString(); GlobalCapacityKey capacityKey = new GlobalCapacityKey(quotaKey.getPolicyId(), quotaKey.getResources()); - String quotaRedisKey = buildGlobalCapacityRedisKey(capacityKey); - String leaseRedisKey = buildLeaseRedisKey(leaseId); - String leaseRegistryRedisKey = buildLeaseRegistryRedisKey(capacityKey); + String quotaRedisKey = keyBuilder.globalCapacityKey(capacityKey); + String leaseRedisKey = keyBuilder.leaseKey(leaseId); + String leaseRegistryRedisKey = keyBuilder.leaseRegistryKey(capacityKey); Long result = observe( "redis.lease.acquire", () -> redisTemplate.execute( @@ -560,7 +584,7 @@ public LeaseConsumptionResult tryConsume(QuotaLease lease, String nodeId, Instan if (currentTime == null) { throw new IllegalArgumentException("currentTime must not be null"); } - String leaseRedisKey = buildLeaseRedisKey(lease.getLeaseId()); + String leaseRedisKey = keyBuilder.leaseKey(lease.getLeaseId()); Long result = observe( "redis.lease.consume", @@ -605,9 +629,9 @@ public boolean renewLease(QuotaLease lease, String nodeId, Duration extension) { throw new IllegalArgumentException("extension must be greater than zero"); } - String leaseRedisKey = buildLeaseRedisKey(lease.getLeaseId()); + String leaseRedisKey = keyBuilder.leaseKey(lease.getLeaseId()); GlobalCapacityKey capacityKey = new GlobalCapacityKey(lease.getQuotaKey().getPolicyId(), lease.getQuotaKey().getResources()); - String leaseRegistryRedisKey = buildLeaseRegistryRedisKey(capacityKey); + String leaseRegistryRedisKey = keyBuilder.leaseRegistryKey(capacityKey); Instant currentTime = clock.instant(); Long result = observe( "redis.lease.renew", @@ -633,11 +657,11 @@ public boolean releaseLease(QuotaLease lease) { throw new IllegalArgumentException("lease must not be null"); } - String leaseRedisKey = buildLeaseRedisKey(lease.getLeaseId()); + String leaseRedisKey = keyBuilder.leaseKey(lease.getLeaseId()); QuotaKey quotaKey = lease.getQuotaKey(); GlobalCapacityKey capacityKey = new GlobalCapacityKey(quotaKey.getPolicyId(), quotaKey.getResources()); - String quotaRedisKey = buildGlobalCapacityRedisKey(capacityKey); - String leaseRegistryRedisKey = buildLeaseRegistryRedisKey(capacityKey); + String quotaRedisKey = keyBuilder.globalCapacityKey(capacityKey); + String leaseRegistryRedisKey = keyBuilder.leaseRegistryKey(capacityKey); Long result = observe( "redis.lease.release", () -> redisTemplate.execute( @@ -667,21 +691,11 @@ public long tryConsume(GlobalCapacityKey capacityKey, long capacity, long refill return result == null ? -1L : result; } - private String buildGlobalCapacityRedisKey(GlobalCapacityKey capacityKey) { - return QUOTA_KEY_PREFIX + capacityKey.policyId() + ":" + capacityKey.resource(); - } - private String buildTokenBucketRedisKey(GlobalCapacityKey capacityKey) { return TOKEN_BUCKET_KEY_PREFIX + capacityKey.policyId() + ":" + capacityKey.resource(); } - private String buildLeaseRegistryRedisKey(GlobalCapacityKey capacityKey) { - return buildGlobalCapacityRedisKey(capacityKey) + LEASE_REGISTRY_SUFFIX; - } - private String buildLeaseRedisKey(String leaseId) { - return LEASE_KEY_PREFIX + leaseId; - } private void validateQuotaKey(QuotaKey quotaKey) { if (quotaKey == null) { throw new IllegalArgumentException("quotaKey must not be null"); @@ -699,4 +713,4 @@ private T observe( .observe(operation); } -} \ No newline at end of file +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 48aa4a9..2e1dc90 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -28,4 +28,7 @@ management.endpoint.health.show-details=never # Global capacity bootstrap resilience allocation.bootstrap.max-attempts=${ALLOCATION_BOOTSTRAP_MAX_ATTEMPTS:5} -allocation.bootstrap.retry-delay-ms=${ALLOCATION_BOOTSTRAP_RETRY_DELAY_MS:1000} \ No newline at end of file +allocation.bootstrap.retry-delay-ms=${ALLOCATION_BOOTSTRAP_RETRY_DELAY_MS:1000} + +# Redis key namespace for global capacity and lease coordination +traffic-control.redis.key-namespace=${REDIS_KEY_NAMESPACE:traffic-control} diff --git a/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyConfigurationIntegrationTest.java b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyConfigurationIntegrationTest.java new file mode 100644 index 0000000..68a5051 --- /dev/null +++ b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyConfigurationIntegrationTest.java @@ -0,0 +1,69 @@ +package com.yashdotdev.distributed_traffic_control.config; + +import com.yashdotdev.distributed_traffic_control.lease.LeaseCoordinator; +import com.yashdotdev.distributed_traffic_control.lease.RedisLeaseCoordinator; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +import static org.junit.jupiter.api.Assertions.*; + +class RedisKeyConfigurationIntegrationTest { + + @SpringBootTest + @Nested + class DefaultConfigurationTest { + @Autowired + private RedisKeyProperties properties; + + @Autowired + private RedisKeyBuilder keyBuilder; + + @Autowired + private LeaseCoordinator leaseCoordinator; + + @Test + void shouldLoadDefaultKeyConfiguration() { + assertNotNull(properties); + assertEquals("traffic-control", properties.getKeyNamespace()); + + assertNotNull(keyBuilder); + assertEquals("traffic-control", keyBuilder.getNamespace()); + + assertNotNull(leaseCoordinator); + assertInstanceOf(RedisLeaseCoordinator.class, leaseCoordinator); + RedisLeaseCoordinator redisLeaseCoordinator = (RedisLeaseCoordinator) leaseCoordinator; + assertEquals("traffic-control", redisLeaseCoordinator.getKeyBuilder().getNamespace()); + } + } + + @SpringBootTest + @TestPropertySource(properties = "traffic-control.redis.key-namespace=staging:traffic-control") + @Nested + class CustomConfigurationTest { + @Autowired + private RedisKeyProperties properties; + + @Autowired + private RedisKeyBuilder keyBuilder; + + @Autowired + private LeaseCoordinator leaseCoordinator; + + @Test + void shouldLoadCustomKeyConfiguration() { + assertNotNull(properties); + assertEquals("staging:traffic-control", properties.getKeyNamespace()); + + assertNotNull(keyBuilder); + assertEquals("staging:traffic-control", keyBuilder.getNamespace()); + + assertNotNull(leaseCoordinator); + assertInstanceOf(RedisLeaseCoordinator.class, leaseCoordinator); + RedisLeaseCoordinator redisLeaseCoordinator = (RedisLeaseCoordinator) leaseCoordinator; + assertEquals("staging:traffic-control", redisLeaseCoordinator.getKeyBuilder().getNamespace()); + } + } +} diff --git a/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyEnvironmentVariableTest.java b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyEnvironmentVariableTest.java new file mode 100644 index 0000000..47ed561 --- /dev/null +++ b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyEnvironmentVariableTest.java @@ -0,0 +1,34 @@ +package com.yashdotdev.distributed_traffic_control.config; + +import com.yashdotdev.distributed_traffic_control.lease.LeaseCoordinator; +import com.yashdotdev.distributed_traffic_control.lease.RedisLeaseCoordinator; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class RedisKeyEnvironmentVariableTest { + + @Autowired + private RedisKeyProperties properties; + + @Autowired + private RedisKeyBuilder keyBuilder; + + @Autowired + private LeaseCoordinator leaseCoordinator; + + @Test + void shouldPickUpConfiguredNamespaceFromEnvironmentOrProperty() { + String expected = System.getenv("REDIS_KEY_NAMESPACE"); + if (expected == null || expected.isBlank()) { + expected = "traffic-control"; + } + assertEquals(expected, properties.getKeyNamespace()); + assertEquals(expected, keyBuilder.getNamespace()); + assertInstanceOf(RedisLeaseCoordinator.class, leaseCoordinator); + assertEquals(expected, ((RedisLeaseCoordinator) leaseCoordinator).getKeyBuilder().getNamespace()); + } +} diff --git a/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyPropertiesValidationTest.java b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyPropertiesValidationTest.java new file mode 100644 index 0000000..9a5eff0 --- /dev/null +++ b/src/test/java/com/yashdotdev/distributed_traffic_control/config/RedisKeyPropertiesValidationTest.java @@ -0,0 +1,128 @@ +package com.yashdotdev.distributed_traffic_control.config; + +import com.yashdotdev.distributed_traffic_control.lease.GlobalCapacityKey; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; + +class RedisKeyPropertiesValidationTest { + + private Validator validator; + private RedisKeyNamespaceValidator namespaceValidator; + + @BeforeEach + void setUp() { + try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { + validator = factory.getValidator(); + } + namespaceValidator = new RedisKeyNamespaceValidator(); + } + + @Test + void shouldAcceptDefaultKeyProperties() { + RedisKeyProperties properties = new RedisKeyProperties(); + Set> violations = validator.validate(properties); + assertTrue(violations.isEmpty(), "Default properties should be valid"); + assertEquals("traffic-control", properties.getKeyNamespace()); + } + + @ParameterizedTest + @ValueSource(strings = { + "traffic-control", + "dev:traffic-control", + "staging:traffic-control", + "prod:traffic-control", + "custom-ns", + "app.env.v1" + }) + void shouldAcceptValidKeyNamespaces(String namespace) { + RedisKeyProperties properties = new RedisKeyProperties(namespace); + Set> violations = validator.validate(properties); + assertTrue(violations.isEmpty(), "Namespace should be valid: " + namespace); + assertTrue(namespaceValidator.isValid(namespace, null)); + } + + @Test + void shouldRejectNullKeyNamespace() { + RedisKeyProperties properties = new RedisKeyProperties(null); + Set> violations = validator.validate(properties); + assertFalse(violations.isEmpty(), "Null namespace should cause validation failure"); + assertTrue(violations.stream().anyMatch(v -> v.getPropertyPath().toString().equals("keyNamespace"))); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "\t", "\n"}) + void shouldRejectBlankKeyNamespace(String blankNamespace) { + RedisKeyProperties properties = new RedisKeyProperties(blankNamespace); + Set> violations = validator.validate(properties); + assertFalse(violations.isEmpty(), "Blank namespace should cause validation failure"); + } + + @ParameterizedTest + @ValueSource(strings = {"traffic-control:", "dev:", "a:b:c:", ":"}) + void shouldRejectNamespaceEndingWithColon(String colonNamespace) { + RedisKeyProperties properties = new RedisKeyProperties(colonNamespace); + Set> violations = validator.validate(properties); + assertFalse(violations.isEmpty(), "Namespace ending with colon should fail validation"); + assertTrue(violations.stream().anyMatch(v -> v.getMessage().contains("must not end with a colon"))); + assertFalse(namespaceValidator.isValid(colonNamespace, null)); + } + + @Test + void shouldHandleNullInConstraintValidatorGracefully() { + // Bean validation standard: validator returns true for null, @NotBlank catches null + assertTrue(namespaceValidator.isValid(null, null)); + } + + @Test + void shouldBuildExpectedKeysWithDefaultNamespace() { + RedisKeyBuilder builder = new RedisKeyBuilder(new RedisKeyProperties()); + GlobalCapacityKey capacityKey = new GlobalCapacityKey("policy-1", "/api/orders"); + + assertEquals("traffic-control:quota:policy-1:/api/orders", builder.globalCapacityKey(capacityKey)); + assertEquals("traffic-control:quota:policy-1:/api/orders:leases", builder.leaseRegistryKey(capacityKey)); + assertEquals("traffic-control:lease:lease-123", builder.leaseKey("lease-123")); + assertEquals("traffic-control:token-bucket:policy-1:/api/orders", builder.tokenBucketKey(capacityKey)); + } + + @Test + void shouldBuildExpectedKeysWithCustomNamespace() { + RedisKeyBuilder builder = new RedisKeyBuilder("staging:traffic-control"); + GlobalCapacityKey capacityKey = new GlobalCapacityKey("policy-1", "/api/orders"); + + assertEquals("staging:traffic-control:quota:policy-1:/api/orders", builder.globalCapacityKey(capacityKey)); + assertEquals("staging:traffic-control:quota:policy-1:/api/orders:leases", builder.leaseRegistryKey(capacityKey)); + assertEquals("staging:traffic-control:lease:lease-123", builder.leaseKey("lease-123")); + assertEquals("staging:traffic-control:token-bucket:policy-1:/api/orders", builder.tokenBucketKey(capacityKey)); + } + + @Test + void shouldRejectInvalidArgumentsInKeyBuilder() { + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder((String) null)); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder("")); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder(" ")); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder("invalid:")); + + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder((RedisKeyProperties) null)); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder(new RedisKeyProperties(null))); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder(new RedisKeyProperties(""))); + assertThrows(IllegalArgumentException.class, () -> new RedisKeyBuilder(new RedisKeyProperties("ends-with-colon:"))); + + RedisKeyBuilder builder = new RedisKeyBuilder("test-ns"); + assertThrows(NullPointerException.class, () -> builder.globalCapacityKey(null)); + assertThrows(NullPointerException.class, () -> builder.leaseRegistryKey(null)); + assertThrows(NullPointerException.class, () -> builder.tokenBucketKey(null)); + assertThrows(IllegalArgumentException.class, () -> builder.leaseKey(null)); + assertThrows(IllegalArgumentException.class, () -> builder.leaseKey("")); + assertThrows(IllegalArgumentException.class, () -> builder.leaseKey(" ")); + } +} diff --git a/src/test/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinatorIntegrationTest.java b/src/test/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinatorIntegrationTest.java index e58257b..2036465 100644 --- a/src/test/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinatorIntegrationTest.java +++ b/src/test/java/com/yashdotdev/distributed_traffic_control/lease/RedisLeaseCoordinatorIntegrationTest.java @@ -1,5 +1,6 @@ package com.yashdotdev.distributed_traffic_control.lease; +import com.yashdotdev.distributed_traffic_control.config.RedisKeyBuilder; import com.yashdotdev.distributed_traffic_control.quota.QuotaKey; import com.yashdotdev.distributed_traffic_control.traffic.TrafficSubject; import com.yashdotdev.distributed_traffic_control.traffic.TrafficSubjectType; @@ -239,6 +240,241 @@ void shouldShareTokenBucketAcrossCoordinatorInstances() { assertEquals(-1L, secondCoordinator.tryConsume(capacityKey, 5, 1, Instant.now())); } + @Test + void shouldPreserveExactDefaultKeyFormatsForBackwardCompatibility() { + StringRedisTemplate redisTemplate = createRedisTemplate(); + // Construct coordinator using legacy default constructor + RedisLeaseCoordinator coordinator = new RedisLeaseCoordinator(redisTemplate); + + String policyId = "compat-policy-" + UUID.randomUUID(); + String resource = "/api/v1/orders"; + GlobalCapacityKey capacityKey = new GlobalCapacityKey(policyId, resource); + QuotaKey quotaKey = new QuotaKey(policyId, new TrafficSubject("test-user", TrafficSubjectType.USER), resource); + + coordinator.registerCapacity(capacityKey, 50); + + // Verify exact legacy global capacity key format: traffic-control:quota:: + String expectedGlobalKey = "traffic-control:quota:" + policyId + ":" + resource; + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(expectedGlobalKey)), + "Legacy global capacity key must exist in Redis"); + assertEquals("50", redisTemplate.opsForValue().get(expectedGlobalKey)); + + // Acquire lease and verify exact legacy lease key format: traffic-control:lease: + Optional acquiredLease = coordinator.acquireLease(quotaKey, "node-compat", 10, Duration.ofSeconds(60)); + assertTrue(acquiredLease.isPresent()); + String leaseId = acquiredLease.get().getLeaseId(); + + String expectedLeaseKey = "traffic-control:lease:" + leaseId; + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(expectedLeaseKey)), + "Legacy lease key must exist in Redis"); + + // Verify exact legacy registry key format: traffic-control:quota:::leases + String expectedRegistryKey = expectedGlobalKey + ":leases"; + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(expectedRegistryKey)), + "Legacy lease registry key must exist in Redis"); + + Set registryMembers = redisTemplate.opsForZSet().range(expectedRegistryKey, 0, -1); + assertNotNull(registryMembers); + assertTrue(registryMembers.contains(expectedLeaseKey), + "Lease registry must contain exact legacy namespaced lease key"); + } + + @Test + void shouldIsolateCapacityBetweenDifferentNamespaces() { + StringRedisTemplate redisTemplate = createRedisTemplate(); + + RedisKeyBuilder builderA = new RedisKeyBuilder("dev:traffic-control"); + RedisKeyBuilder builderB = new RedisKeyBuilder("prod:traffic-control"); + + RedisLeaseCoordinator coordinatorA = new RedisLeaseCoordinator(redisTemplate, builderA); + RedisLeaseCoordinator coordinatorB = new RedisLeaseCoordinator(redisTemplate, builderB); + + String sharedPolicyId = "shared-policy-" + UUID.randomUUID(); + String sharedResource = "/api/checkout"; + GlobalCapacityKey capacityKey = new GlobalCapacityKey(sharedPolicyId, sharedResource); + QuotaKey quotaKey = new QuotaKey(sharedPolicyId, new TrafficSubject("user-1", TrafficSubjectType.USER), sharedResource); + + // Register capacity in namespace A only + coordinatorA.registerCapacity(capacityKey, 50); + + String keyA = "dev:traffic-control:quota:" + sharedPolicyId + ":" + sharedResource; + String keyB = "prod:traffic-control:quota:" + sharedPolicyId + ":" + sharedResource; + + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(keyA))); + assertFalse(Boolean.TRUE.equals(redisTemplate.hasKey(keyB))); + + // Coordinator B cannot acquire lease because capacity is not registered in namespace B + Optional leaseBAttempt = coordinatorB.acquireLease(quotaKey, "node-b", 10, Duration.ofSeconds(60)); + assertTrue(leaseBAttempt.isEmpty(), "Namespace B must not read or acquire capacity from namespace A"); + + // Register separate capacity in namespace B + coordinatorB.registerCapacity(capacityKey, 100); + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(keyB))); + assertEquals("50", redisTemplate.opsForValue().get(keyA)); + assertEquals("100", redisTemplate.opsForValue().get(keyB)); + + // Coordinator A acquires 30 units: namespace A capacity becomes 20, namespace B remains 100 + Optional leaseA = coordinatorA.acquireLease(quotaKey, "node-a", 30, Duration.ofSeconds(60)); + assertTrue(leaseA.isPresent()); + assertEquals("20", redisTemplate.opsForValue().get(keyA)); + assertEquals("100", redisTemplate.opsForValue().get(keyB)); + + // Coordinator B can still acquire full 100 units independently + Optional leaseB = coordinatorB.acquireLease(quotaKey, "node-b", 100, Duration.ofSeconds(60)); + assertTrue(leaseB.isPresent()); + assertEquals("0", redisTemplate.opsForValue().get(keyB)); + assertEquals("20", redisTemplate.opsForValue().get(keyA)); + + // Registry keys are isolated + String registryKeyA = keyA + ":leases"; + String registryKeyB = keyB + ":leases"; + Set membersA = redisTemplate.opsForZSet().range(registryKeyA, 0, -1); + Set membersB = redisTemplate.opsForZSet().range(registryKeyB, 0, -1); + assertNotNull(membersA); + assertNotNull(membersB); + assertEquals(1, membersA.size()); + assertEquals(1, membersB.size()); + assertTrue(membersA.contains("dev:traffic-control:lease:" + leaseA.get().getLeaseId())); + assertTrue(membersB.contains("prod:traffic-control:lease:" + leaseB.get().getLeaseId())); + + // Removing capacity in coordinator A does not affect coordinator B + assertTrue(coordinatorA.removeCapacity(capacityKey)); + assertFalse(Boolean.TRUE.equals(redisTemplate.hasKey(keyA))); + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(keyB))); + } + + @Test + void shouldIsolateLeaseOperationsAcrossNamespaces() { + StringRedisTemplate redisTemplate = createRedisTemplate(); + + RedisKeyBuilder builderA = new RedisKeyBuilder("dev:traffic-control"); + RedisKeyBuilder builderB = new RedisKeyBuilder("prod:traffic-control"); + + RedisLeaseCoordinator coordinatorA = new RedisLeaseCoordinator(redisTemplate, builderA); + RedisLeaseCoordinator coordinatorB = new RedisLeaseCoordinator(redisTemplate, builderB); + + String policyId = "lease-iso-policy-" + UUID.randomUUID(); + String resource = "/api/payments"; + GlobalCapacityKey capacityKey = new GlobalCapacityKey(policyId, resource); + QuotaKey quotaKey = new QuotaKey(policyId, new TrafficSubject("user-2", TrafficSubjectType.USER), resource); + + coordinatorA.registerCapacity(capacityKey, 50); + Optional leaseAOpt = coordinatorA.acquireLease(quotaKey, "node-shared", 20, Duration.ofSeconds(60)); + assertTrue(leaseAOpt.isPresent()); + QuotaLease leaseA = leaseAOpt.get(); + + String namespacedLeaseKeyA = "dev:traffic-control:lease:" + leaseA.getLeaseId(); + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(namespacedLeaseKeyA))); + + // 1. Coordinator B cannot consume lease A + LeaseConsumptionResult consumeResultB = coordinatorB.tryConsume(leaseA, "node-shared", Instant.now()); + assertFalse(consumeResultB.isConsumed(), "Coordinator B should not be able to consume lease from namespace A"); + assertEquals(20, leaseA.getRemainingCapacity()); + assertEquals("20", redisTemplate.opsForHash().get(namespacedLeaseKeyA, "remainingCapacity")); + + // 2. Coordinator B cannot renew lease A + boolean renewedByB = coordinatorB.renewLease(leaseA, "node-shared", Duration.ofSeconds(30)); + assertFalse(renewedByB, "Coordinator B should not be able to renew lease from namespace A"); + + // 3. Coordinator B cannot release lease A + boolean releasedByB = coordinatorB.releaseLease(leaseA); + assertFalse(releasedByB, "Coordinator B should not be able to release lease from namespace A"); + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(namespacedLeaseKeyA)), + "Namespace A lease must not be deleted by namespace B"); + + // 4. Coordinator A can consume, renew, and release its own lease + LeaseConsumptionResult consumeResultA = coordinatorA.tryConsume(leaseA, "node-shared", Instant.now()); + assertTrue(consumeResultA.isConsumed()); + assertEquals(19, consumeResultA.getRemainingCapacity()); + assertEquals("19", redisTemplate.opsForHash().get(namespacedLeaseKeyA, "remainingCapacity")); + + boolean renewedByA = coordinatorA.renewLease(leaseA, "node-shared", Duration.ofSeconds(30)); + assertTrue(renewedByA); + + boolean releasedByA = coordinatorA.releaseLease(leaseA); + assertTrue(releasedByA); + assertFalse(Boolean.TRUE.equals(redisTemplate.hasKey(namespacedLeaseKeyA))); + + // Capacity restored in namespace A: 30 remaining + 19 returned unused = 49 + String keyA = "dev:traffic-control:quota:" + policyId + ":" + resource; + assertEquals("49", redisTemplate.opsForValue().get(keyA)); + } + + @Test + void shouldUseNamespacedKeysInAllLuaScripts() { + MutableClock clock = new MutableClock(Instant.parse("2026-08-28T10:00:00Z")); + StringRedisTemplate redisTemplate = createRedisTemplate(); + String namespace = "staging:traffic-control"; + RedisKeyBuilder builder = new RedisKeyBuilder(namespace); + RedisLeaseCoordinator coordinator = new RedisLeaseCoordinator(redisTemplate, builder, clock); + + String policyId = "lua-policy-" + UUID.randomUUID(); + String resource = "/api/data"; + GlobalCapacityKey capacityKey = new GlobalCapacityKey(policyId, resource); + QuotaKey quotaKey = new QuotaKey(policyId, new TrafficSubject("lua-user", TrafficSubjectType.USER), resource); + + coordinator.registerCapacity(capacityKey, 100); + + String expectedCapacityKey = namespace + ":quota:" + policyId + ":" + resource; + String expectedRegistryKey = expectedCapacityKey + ":leases"; + + // 1. Acquire script with namespaced keys + Optional lease1Opt = coordinator.acquireLease(quotaKey, "node-1", 20, Duration.ofSeconds(30)); + assertTrue(lease1Opt.isPresent()); + QuotaLease lease1 = lease1Opt.get(); + String expectedLease1Key = namespace + ":lease:" + lease1.getLeaseId(); + + // Verify Redis state created by acquire script + assertTrue(Boolean.TRUE.equals(redisTemplate.hasKey(expectedLease1Key))); + assertEquals("node-1", redisTemplate.opsForHash().get(expectedLease1Key, "nodeId")); + assertEquals("20", redisTemplate.opsForHash().get(expectedLease1Key, "allocatedCapacity")); + assertEquals("20", redisTemplate.opsForHash().get(expectedLease1Key, "remainingCapacity")); + assertEquals("80", redisTemplate.opsForValue().get(expectedCapacityKey)); + + // Verify sorted set registry entry has namespaced lease key + Set registry = redisTemplate.opsForZSet().range(expectedRegistryKey, 0, -1); + assertNotNull(registry); + assertTrue(registry.contains(expectedLease1Key)); + + // 2. Consume script with namespaced key + LeaseConsumptionResult consumeResult = coordinator.tryConsume(lease1, "node-1", clock.instant()); + assertTrue(consumeResult.isConsumed()); + assertEquals(19, consumeResult.getRemainingCapacity()); + assertEquals("19", redisTemplate.opsForHash().get(expectedLease1Key, "remainingCapacity")); + + // 3. Renew script with namespaced key and registry key + boolean renewed = coordinator.renewLease(lease1, "node-1", Duration.ofSeconds(45)); + assertTrue(renewed); + Double score = redisTemplate.opsForZSet().score(expectedRegistryKey, expectedLease1Key); + assertNotNull(score); + assertEquals((double) lease1.getExpiresAt().toEpochMilli(), score); + + // 4. Expired lease reclamation inside acquire script + // Advance clock past renewed expiry + clock.advanceSeconds(80); + // Node 2 acquires 95 units: Lua script reclaims lease 1's 19 remaining capacity (80 + 19 = 99), then allocates 95 + Optional lease2Opt = coordinator.acquireLease(quotaKey, "node-2", 95, Duration.ofSeconds(30)); + assertTrue(lease2Opt.isPresent()); + String expectedLease2Key = namespace + ":lease:" + lease2Opt.get().getLeaseId(); + + // Verify lease 1 was deleted and removed from registry during reclamation + assertFalse(Boolean.TRUE.equals(redisTemplate.hasKey(expectedLease1Key))); + Set registryAfterReclaim = redisTemplate.opsForZSet().range(expectedRegistryKey, 0, -1); + assertNotNull(registryAfterReclaim); + assertFalse(registryAfterReclaim.contains(expectedLease1Key)); + assertTrue(registryAfterReclaim.contains(expectedLease2Key)); + assertEquals("4", redisTemplate.opsForValue().get(expectedCapacityKey)); + + // 5. Release script with namespaced keys + boolean released = coordinator.releaseLease(lease2Opt.get()); + assertTrue(released); + assertFalse(Boolean.TRUE.equals(redisTemplate.hasKey(expectedLease2Key))); + Set registryAfterRelease = redisTemplate.opsForZSet().range(expectedRegistryKey, 0, -1); + assertNotNull(registryAfterRelease); + assertFalse(registryAfterRelease.contains(expectedLease2Key)); + assertEquals("99", redisTemplate.opsForValue().get(expectedCapacityKey)); + } + @BeforeEach void cleanRedis() { StringRedisTemplate redisTemplate = createRedisTemplate(); @@ -273,4 +509,4 @@ private QuotaKey createQuotaKey() { String uniqueId = UUID.randomUUID().toString(); return new QuotaKey("redis-test-policy-" + uniqueId, new TrafficSubject("redis-test-user-" + uniqueId, TrafficSubjectType.USER), "/api/orders"); } -} \ No newline at end of file +}