From 55f979d521ca4ce12e29136c055af18a243aca62 Mon Sep 17 00:00:00 2001 From: Ashish Thakur Date: Fri, 4 Dec 2026 15:26:20 +0530 Subject: [PATCH 1/2] fix(core): enforce a rolling reconciliation rate limit Add SlidingWindowRateLimiter and keep the deprecated LinearRateLimiter as the default for compatibility. Both use a per-resource ring buffer to track when permits expire. Fixes #3740 Signed-off-by: Ashish Thakur --- .../en/docs/documentation/rate-limiting.md | 17 +-- .../event/rate/LinearRateLimiter.java | 43 +++---- .../processing/event/rate/RateState.java | 38 +----- .../event/rate/SlidingWindowRateLimiter.java | 89 +++++++++++++++ .../event/rate/SlidingWindowRateState.java | 43 +++++++ .../event/rate/LinearRateLimiterTest.java | 108 ------------------ .../rate/SlidingWindowRateLimiterTest.java | 103 +++++++++++++++++ .../config/BaseConfigurationServiceTest.java | 13 +++ .../config/loader/ConfigLoaderTest.java | 26 +++++ 9 files changed, 305 insertions(+), 175 deletions(-) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java delete mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java create mode 100644 operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java diff --git a/docs/content/en/docs/documentation/rate-limiting.md b/docs/content/en/docs/documentation/rate-limiting.md index c1d0147807..1122c8b4cc 100644 --- a/docs/content/en/docs/documentation/rate-limiting.md +++ b/docs/content/en/docs/documentation/rate-limiting.md @@ -15,13 +15,15 @@ implementation, in particular, on how long a typical reconciliation takes. Rate limiting is configured per controller, see [ControllerConfiguration](https://github.com/operator-framework/java-operator-sdk/blob/e976fb80d62f6bd0f714d78cec0a7a38d9b4a928/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java#L81). -## The default LinearRateLimiter +## Default rate limiter -We provide a generic rate limiter implementation: -[`LinearRateLimiter`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java). +The SDK uses `LinearRateLimiter` by default for compatibility with existing +applications. This deprecated class delegates to +[`SlidingWindowRateLimiter`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java). To configure it, use the `@RateLimited` annotation on your `Reconciler` class. The following -configuration limits each resource to reconcile at most twice within a 3 second interval: +configuration allows each resource up to two reconciliation submissions in any rolling +three-second interval: ```java @RateLimited(maxReconciliations = 2, within = 3, unit = TimeUnit.SECONDS) @@ -31,10 +33,9 @@ public class MyReconciler implements Reconciler { } ``` -Thus, if a given resource was reconciled twice in one second, no further reconciliation for this -resource will happen before two seconds have elapsed. Note that, since rate limiting is on a -per-resource basis, other resources can still be reconciled at the same time, as long as -they stay within their own rate limits. +A resource can use both permits in quick succession. Once it uses both, its next +reconciliation is eligible three seconds after the older submission. Each resource +has its own rate limit. ## Custom Rate Limiter diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java index 86e88ff112..f5d31275eb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java @@ -20,19 +20,22 @@ import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; -/** A simple rate limiter that limits the number of permission for a time interval. */ +/** + * @deprecated Use {@link SlidingWindowRateLimiter} instead. + */ +@Deprecated public class LinearRateLimiter implements RateLimiter, AnnotationConfigurable { /** To turn off rate limiting set limit for period to a non-positive number */ - public static final int NO_LIMIT_PERIOD = -1; + public static final int NO_LIMIT_PERIOD = SlidingWindowRateLimiter.NO_LIMIT_PERIOD; - public static final int DEFAULT_REFRESH_PERIOD_SECONDS = 10; + public static final int DEFAULT_REFRESH_PERIOD_SECONDS = + SlidingWindowRateLimiter.DEFAULT_REFRESH_PERIOD_SECONDS; public static final Duration DEFAULT_REFRESH_PERIOD = - Duration.ofSeconds(DEFAULT_REFRESH_PERIOD_SECONDS); + SlidingWindowRateLimiter.DEFAULT_REFRESH_PERIOD; - private Duration refreshPeriod; - private int limitForPeriod; + private final SlidingWindowRateLimiter delegate; public static LinearRateLimiter deactivatedRateLimiter() { return new LinearRateLimiter(); @@ -43,48 +46,36 @@ public LinearRateLimiter() { } public LinearRateLimiter(Duration refreshPeriod, int limitForPeriod) { - this.refreshPeriod = refreshPeriod; - this.limitForPeriod = limitForPeriod; + delegate = new SlidingWindowRateLimiter(refreshPeriod, limitForPeriod); } @Override public Optional isLimited(RateLimitState rateLimitState) { - if (!isActivated() || !(rateLimitState instanceof RateState actualState)) { - return Optional.empty(); - } - var now = System.nanoTime(); - var periodNanos = refreshPeriod.toNanos(); - var elapsedNanos = now - actualState.getLastRefreshNanos(); - if (elapsedNanos > periodNanos) { - actualState.reset(now); - } - if (actualState.getCount() < limitForPeriod) { - actualState.increaseCount(); + if (!isActivated() || !(rateLimitState instanceof RateState)) { return Optional.empty(); } - return Optional.of(Duration.ofNanos(Math.max(0, periodNanos - elapsedNanos))); + return delegate.isLimited(rateLimitState); } @Override public RateState initState() { - return RateState.initialState(); + return new RateState(); } @Override public void initFrom(RateLimited configuration) { - this.refreshPeriod = Duration.of(configuration.within(), configuration.unit().toChronoUnit()); - this.limitForPeriod = configuration.maxReconciliations(); + delegate.initFrom(configuration); } public boolean isActivated() { - return limitForPeriod > 0; + return delegate.isActivated(); } public int getLimitForPeriod() { - return limitForPeriod; + return delegate.getLimitForPeriod(); } public Duration getRefreshPeriod() { - return refreshPeriod; + return delegate.getRefreshPeriod(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java index aad7b74554..f284af9fba 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/RateState.java @@ -15,36 +15,8 @@ */ package io.javaoperatorsdk.operator.processing.event.rate; -import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState; - -class RateState implements RateLimitState { - - private long lastRefreshNanos; - private int count; - - public static RateState initialState() { - return new RateState(System.nanoTime(), 0); - } - - RateState(long lastRefreshNanos, int count) { - this.lastRefreshNanos = lastRefreshNanos; - this.count = count; - } - - public void increaseCount() { - count = count + 1; - } - - public void reset(long nowNanos) { - lastRefreshNanos = nowNanos; - count = 0; - } - - public long getLastRefreshNanos() { - return lastRefreshNanos; - } - - public int getCount() { - return count; - } -} +/** + * @deprecated Use {@link SlidingWindowRateState} instead. + */ +@Deprecated +class RateState extends SlidingWindowRateState {} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java new file mode 100644 index 0000000000..04e15661fc --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java @@ -0,0 +1,89 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.processing.event.rate; + +import java.time.Duration; +import java.util.Optional; +import java.util.function.LongSupplier; + +import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; + +/** Limits reconciliation submissions per resource over a rolling time window. */ +public class SlidingWindowRateLimiter + implements RateLimiter, AnnotationConfigurable { + + /** To turn off rate limiting set limit for period to a non-positive number */ + public static final int NO_LIMIT_PERIOD = -1; + + public static final int DEFAULT_REFRESH_PERIOD_SECONDS = 10; + public static final Duration DEFAULT_REFRESH_PERIOD = + Duration.ofSeconds(DEFAULT_REFRESH_PERIOD_SECONDS); + + private final LongSupplier nanoTime; + private Duration refreshPeriod; + private int limitForPeriod; + + public static SlidingWindowRateLimiter deactivatedRateLimiter() { + return new SlidingWindowRateLimiter(); + } + + public SlidingWindowRateLimiter() { + this(DEFAULT_REFRESH_PERIOD, NO_LIMIT_PERIOD); + } + + public SlidingWindowRateLimiter(Duration refreshPeriod, int limitForPeriod) { + this(refreshPeriod, limitForPeriod, System::nanoTime); + } + + SlidingWindowRateLimiter(Duration refreshPeriod, int limitForPeriod, LongSupplier nanoTime) { + this.nanoTime = nanoTime; + this.refreshPeriod = refreshPeriod; + this.limitForPeriod = limitForPeriod; + } + + @Override + public Optional isLimited(RateLimitState rateLimitState) { + if (!isActivated() || !(rateLimitState instanceof SlidingWindowRateState actualState)) { + return Optional.empty(); + } + var waitNanos = + actualState.tryAcquire(nanoTime.getAsLong(), refreshPeriod.toNanos(), limitForPeriod); + return waitNanos == 0 ? Optional.empty() : Optional.of(Duration.ofNanos(waitNanos)); + } + + @Override + public SlidingWindowRateState initState() { + return new SlidingWindowRateState(); + } + + @Override + public void initFrom(RateLimited configuration) { + this.refreshPeriod = Duration.of(configuration.within(), configuration.unit().toChronoUnit()); + this.limitForPeriod = configuration.maxReconciliations(); + } + + public boolean isActivated() { + return limitForPeriod > 0; + } + + public int getLimitForPeriod() { + return limitForPeriod; + } + + public Duration getRefreshPeriod() { + return refreshPeriod; + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java new file mode 100644 index 0000000000..f8ca68359b --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java @@ -0,0 +1,43 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.processing.event.rate; + +import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState; + +public class SlidingWindowRateState implements RateLimitState { + + private long[] grants; + private int nextGrantIndex; + private boolean full; + + long tryAcquire(long now, long periodNanos, int limit) { + if (grants == null) { + grants = new long[limit]; + } + if (full) { + var elapsedNanos = now - grants[nextGrantIndex]; + if (elapsedNanos < periodNanos) { + return periodNanos - elapsedNanos; + } + } + grants[nextGrantIndex++] = now; + if (nextGrantIndex == grants.length) { + nextGrantIndex = 0; + full = true; + } + return 0; + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java deleted file mode 100644 index 89c88b6598..0000000000 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright Java Operator SDK Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.javaoperatorsdk.operator.processing.event.rate; - -import java.time.Duration; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -class LinearRateLimiterTest { - - public static final Duration REFRESH_PERIOD = Duration.ofMillis(300); - private RateState state; - - @BeforeEach - void initState() { - state = RateState.initialState(); - } - - @Test - void acquirePermissionForNewResource() { - var rl = new LinearRateLimiter(REFRESH_PERIOD, 2); - var res = rl.isLimited(state); - assertThat(res).isEmpty(); - res = rl.isLimited(state); - assertThat(res).isEmpty(); - - res = rl.isLimited(state); - assertThat(res).isNotEmpty(); - } - - @Test - void returnsMinimalDurationToAcquirePermission() { - var rl = new LinearRateLimiter(REFRESH_PERIOD, 1); - var res = rl.isLimited(state); - assertThat(res).isEmpty(); - - res = rl.isLimited(state); - - assertThat(res).isPresent(); - assertThat(res.get()).isLessThanOrEqualTo(REFRESH_PERIOD); - // the whole period is still ahead of us, so the reported wait must be close to it - assertThat(res.get()).isGreaterThan(REFRESH_PERIOD.dividedBy(2)); - } - - @Test - void reportedDurationIsTheTimeRemainingNotTheTimeElapsed() throws InterruptedException { - var rl = new LinearRateLimiter(REFRESH_PERIOD, 1); - assertThat(rl.isLimited(state)).isEmpty(); - - var justAfterLimit = rl.isLimited(state).orElseThrow(); - Thread.sleep(REFRESH_PERIOD.toMillis() / 2); - var halfWayThroughPeriod = rl.isLimited(state).orElseThrow(); - - // as the refresh period elapses, less time remains until a permission is available again - assertThat(halfWayThroughPeriod).isLessThan(justAfterLimit); - } - - @Test - void resetsPeriodAfterLimit() throws InterruptedException { - var rl = new LinearRateLimiter(REFRESH_PERIOD, 1); - var res = rl.isLimited(state); - assertThat(res).isEmpty(); - res = rl.isLimited(state); - assertThat(res).isPresent(); - - // sleep plus some slack - Thread.sleep(REFRESH_PERIOD.toMillis() + REFRESH_PERIOD.toMillis() / 3); - - res = rl.isLimited(state); - assertThat(res).isEmpty(); - } - - @Test - void rateLimitCanBeTurnedOff() { - var rl = new LinearRateLimiter(REFRESH_PERIOD, LinearRateLimiter.NO_LIMIT_PERIOD); - - var res = rl.isLimited(state); - - assertThat(res).isEmpty(); - } - - @Test - void expiredPeriodIsResetEvenIfLimitWasNotReached() { - var rl = new LinearRateLimiter(REFRESH_PERIOD, 2); - var staleState = - new RateState(System.nanoTime() - REFRESH_PERIOD.multipliedBy(10).toNanos(), 1); - - assertThat(rl.isLimited(staleState)).isEmpty(); - assertThat(rl.isLimited(staleState)).isEmpty(); - assertThat(rl.isLimited(staleState)).isPresent(); - } -} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java new file mode 100644 index 0000000000..f185f4e541 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java @@ -0,0 +1,103 @@ +/* + * Copyright Java Operator SDK Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.javaoperatorsdk.operator.processing.event.rate; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SlidingWindowRateLimiterTest { + + private static final Duration PERIOD = Duration.ofSeconds(3); + private long nowNanos; + + @Test + void enforcesRollingLimitAcrossWindowBoundary() { + var limiter = new SlidingWindowRateLimiter(PERIOD, 2, () -> nowNanos); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(2900); + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(150); + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(10); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(2840)); + + advanceMillis(2839); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1)); + advanceMillis(1); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(150)); + } + + @Test + void permitsBurstsIndependentlyForEachResource() { + var limiter = new SlidingWindowRateLimiter(PERIOD, 2, () -> nowNanos); + var first = limiter.initState(); + var second = limiter.initState(); + + assertThat(limiter.isLimited(first)).isEmpty(); + assertThat(limiter.isLimited(first)).isEmpty(); + assertThat(limiter.isLimited(first)).contains(PERIOD); + assertThat(limiter.isLimited(second)).isEmpty(); + + advanceMillis(3000); + assertThat(limiter.isLimited(first)).isEmpty(); + assertThat(limiter.isLimited(first)).isEmpty(); + assertThat(limiter.isLimited(first)).contains(PERIOD); + } + + @Test + void returnsRemainingTimeForSinglePermit() { + var limiter = new SlidingWindowRateLimiter(PERIOD, 1, () -> nowNanos); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(PERIOD); + advanceMillis(1500); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1500)); + advanceMillis(1500); + assertThat(limiter.isLimited(state)).isEmpty(); + } + + @Test + void expiredGrantDoesNotReduceCapacityWhenTheBufferWasNotFull() { + var limiter = new SlidingWindowRateLimiter(PERIOD, 2, () -> nowNanos); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(3001); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(PERIOD); + } + + @Test + void rateLimitCanBeTurnedOff() { + var limiter = SlidingWindowRateLimiter.deactivatedRateLimiter(); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).isEmpty(); + } + + private void advanceMillis(long millis) { + nowNanos += Duration.ofMillis(millis).toNanos(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java index ffd0f6b904..c1f96e7b37 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java @@ -57,6 +57,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig; import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter; import io.javaoperatorsdk.operator.processing.event.rate.RateLimited; +import io.javaoperatorsdk.operator.processing.event.rate.SlidingWindowRateLimiter; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; import io.javaoperatorsdk.operator.processing.retry.GradualRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; @@ -215,6 +216,14 @@ void configuringRateAndRetryViaAnnotationsShouldWork() { assertEquals(Duration.ofSeconds(3), rateLimiter.getRefreshPeriod()); } + @Test + void configuringSlidingWindowRateLimiterViaAnnotationShouldWork() { + var config = configFor(new SlidingWindowRateLimiterReconciler()); + var limiter = assertInstanceOf(SlidingWindowRateLimiter.class, config.getRateLimiter()); + assertEquals(7, limiter.getLimitForPeriod()); + assertEquals(Duration.ofSeconds(3), limiter.getRefreshPeriod()); + } + @Test void configuringRateLimitAndGradualRetryViaSuperClassShouldWork() { var config = configFor(new GradualRetryAndRateLimitedOnSuperClass()); @@ -498,6 +507,10 @@ public UpdateControl reconcile(ConfigMap resource, Context } } + @ControllerConfiguration(rateLimiter = SlidingWindowRateLimiter.class) + private static class SlidingWindowRateLimiterReconciler + extends ConfigurableRateLimitAndRetryReconciler {} + @GradualRetry( maxAttempts = CheckRetryingGraduallyConfiguration.MAX_ATTEMPTS, initialInterval = CheckRetryingGraduallyConfiguration.INITIAL_INTERVAL, diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java index 0cd384e936..891ccb9961 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/loader/ConfigLoaderTest.java @@ -32,6 +32,7 @@ import io.javaoperatorsdk.operator.api.config.ConfigurationServiceOverrider; import io.javaoperatorsdk.operator.api.config.ControllerConfigurationOverrider; import io.javaoperatorsdk.operator.api.reconciler.Constants; +import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -266,6 +267,31 @@ void controllerKeyPrefixIsJosdkControllerDot() { // -- rate limiter ----------------------------------------------------------- + @Test + @SuppressWarnings("deprecation") + void applyControllerConfigsPreservesRateLimiterType() { + var refreshPeriod = Duration.ofSeconds(3); + var loader = + new ConfigLoader( + mapProvider( + Map.of( + "josdk.controller.ctrl.rate-limiter.refresh-period", + refreshPeriod, + "josdk.controller.ctrl.rate-limiter.limit-for-period", + 2))); + var overrider = ControllerConfigurationOverrider.override(baseControllerConfig()); + + loader.applyControllerConfigs("ctrl").accept(overrider); + + assertThat(overrider.build().getRateLimiter()) + .isInstanceOfSatisfying( + LinearRateLimiter.class, + limiter -> { + assertThat(limiter.getRefreshPeriod()).isEqualTo(refreshPeriod); + assertThat(limiter.getLimitForPeriod()).isEqualTo(2); + }); + } + @Test void rateLimiterQueriesExpectedKeys() { var queriedKeys = new ArrayList(); From 178d08d433f4ab936bd785fbe135dd6c11628e3d Mon Sep 17 00:00:00 2001 From: Ashish Thakur Date: Fri, 4 Dec 2026 16:30:16 +0530 Subject: [PATCH 2/2] fix(core): fix fixes Signed-off-by: Ashish Thakur --- .../en/docs/documentation/rate-limiting.md | 3 +- .../event/rate/LinearRateLimiter.java | 7 +- .../event/rate/SlidingWindowRateState.java | 42 ++++--- .../rate/SlidingWindowRateLimiterTest.java | 104 ++++++++++++++++-- 4 files changed, 132 insertions(+), 24 deletions(-) diff --git a/docs/content/en/docs/documentation/rate-limiting.md b/docs/content/en/docs/documentation/rate-limiting.md index 1122c8b4cc..e8e1e2fff1 100644 --- a/docs/content/en/docs/documentation/rate-limiting.md +++ b/docs/content/en/docs/documentation/rate-limiting.md @@ -35,7 +35,8 @@ public class MyReconciler implements Reconciler { A resource can use both permits in quick succession. Once it uses both, its next reconciliation is eligible three seconds after the older submission. Each resource -has its own rate limit. +has its own rate limit. If you change the permit limit with `initFrom`, submissions +already recorded in the rolling window count toward the new limit. ## Custom Rate Limiter diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java index f5d31275eb..c327fcf754 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java @@ -17,6 +17,7 @@ import java.time.Duration; import java.util.Optional; +import java.util.function.LongSupplier; import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; @@ -46,7 +47,11 @@ public LinearRateLimiter() { } public LinearRateLimiter(Duration refreshPeriod, int limitForPeriod) { - delegate = new SlidingWindowRateLimiter(refreshPeriod, limitForPeriod); + this(refreshPeriod, limitForPeriod, System::nanoTime); + } + + LinearRateLimiter(Duration refreshPeriod, int limitForPeriod, LongSupplier nanoTime) { + delegate = new SlidingWindowRateLimiter(refreshPeriod, limitForPeriod, nanoTime); } @Override diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java index f8ca68359b..fad37f849a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateState.java @@ -20,24 +20,40 @@ public class SlidingWindowRateState implements RateLimitState { private long[] grants; - private int nextGrantIndex; - private boolean full; + private int firstGrantIndex; + private int size; long tryAcquire(long now, long periodNanos, int limit) { - if (grants == null) { - grants = new long[limit]; + while (size > 0 && now - grants[firstGrantIndex] >= periodNanos) { + firstGrantIndex = grantIndex(1); + size--; } - if (full) { - var elapsedNanos = now - grants[nextGrantIndex]; - if (elapsedNanos < periodNanos) { - return periodNanos - elapsedNanos; - } + if (size >= limit) { + var elapsedNanos = now - grants[grantIndex(size - limit)]; + return periodNanos - elapsedNanos; } - grants[nextGrantIndex++] = now; - if (nextGrantIndex == grants.length) { - nextGrantIndex = 0; - full = true; + if (grants == null) { + grants = new long[1]; + } else if (size == grants.length) { + grow(limit); } + grants[grantIndex(size)] = now; + size++; return 0; } + + private int grantIndex(int offset) { + var remaining = grants.length - firstGrantIndex; + return offset < remaining ? firstGrantIndex + offset : offset - remaining; + } + + private void grow(int limit) { + var capacity = grants.length; + var expanded = new long[capacity + Math.min(capacity, limit - capacity)]; + var remaining = capacity - firstGrantIndex; + System.arraycopy(grants, firstGrantIndex, expanded, 0, remaining); + System.arraycopy(grants, 0, expanded, remaining, firstGrantIndex); + grants = expanded; + firstGrantIndex = 0; + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java index f185f4e541..aa59c8d130 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiterTest.java @@ -28,22 +28,84 @@ class SlidingWindowRateLimiterTest { @Test void enforcesRollingLimitAcrossWindowBoundary() { - var limiter = new SlidingWindowRateLimiter(PERIOD, 2, () -> nowNanos); + assertRollingLimitAcrossWindowBoundary(new SlidingWindowRateLimiter(PERIOD, 2, () -> nowNanos)); + } + + @Test + void defaultRateLimiterEnforcesRollingLimitAcrossWindowBoundary() { + assertRollingLimitAcrossWindowBoundary(new LinearRateLimiter(PERIOD, 2, () -> nowNanos)); + } + + @Test + void acceptsSparseTrafficWithMaximumPermitLimit() { + var limiter = new SlidingWindowRateLimiter(PERIOD, Integer.MAX_VALUE, () -> nowNanos); var state = limiter.initState(); assertThat(limiter.isLimited(state)).isEmpty(); - advanceMillis(2900); assertThat(limiter.isLimited(state)).isEmpty(); - advanceMillis(150); + advanceMillis(3000); assertThat(limiter.isLimited(state)).isEmpty(); - advanceMillis(10); - assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(2840)); + } + + @Test + void firstGrantAllocatesOneTimestampPerResource() throws ReflectiveOperationException { + var limiter = new SlidingWindowRateLimiter(PERIOD, 100_000, () -> nowNanos); + var grants = SlidingWindowRateState.class.getDeclaredField("grants"); + grants.setAccessible(true); + + for (var resource = 0; resource < 1_000; resource++) { + var state = limiter.initState(); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat((long[]) grants.get(state)).hasSize(1); + } + } + + @Test + void existingLinearRateStateHonorsLowerLimitAfterFirstGrant() { + var limiter = new LinearRateLimiter(PERIOD, 2, () -> nowNanos); + var state = limiter.initState(); - advanceMillis(2839); - assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1)); - advanceMillis(1); assertThat(limiter.isLimited(state)).isEmpty(); - assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(150)); + limiter.initFrom(SinglePermit.class.getAnnotation(RateLimited.class)); + + assertThat(limiter.getLimitForPeriod()).isEqualTo(1); + assertThat(limiter.isLimited(state)).contains(PERIOD); + advanceMillis(3000); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(PERIOD); + } + + @Test + void loweringLimitWaitsForEnoughGrantsToExpire() { + var limiter = new LinearRateLimiter(PERIOD, 2, () -> nowNanos); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(1000); + assertThat(limiter.isLimited(state)).isEmpty(); + limiter.initFrom(SinglePermit.class.getAnnotation(RateLimited.class)); + + assertThat(limiter.isLimited(state)).contains(PERIOD); + advanceMillis(2000); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1000)); + advanceMillis(1000); + assertThat(limiter.isLimited(state)).isEmpty(); + } + + @Test + void raisingLimitPreservesGrantsWhenHistoryWraps() { + var limiter = new LinearRateLimiter(PERIOD, 2, () -> nowNanos); + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(1000); + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(2000); + assertThat(limiter.isLimited(state)).isEmpty(); + limiter.initFrom(ThreePermits.class.getAnnotation(RateLimited.class)); + + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1000)); } @Test @@ -97,7 +159,31 @@ void rateLimitCanBeTurnedOff() { assertThat(limiter.isLimited(state)).isEmpty(); } + private void assertRollingLimitAcrossWindowBoundary(RateLimiter limiter) { + var state = limiter.initState(); + + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(2900); + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(150); + assertThat(limiter.isLimited(state)).isEmpty(); + advanceMillis(10); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(2840)); + + advanceMillis(2839); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(1)); + advanceMillis(1); + assertThat(limiter.isLimited(state)).isEmpty(); + assertThat(limiter.isLimited(state)).contains(Duration.ofMillis(150)); + } + private void advanceMillis(long millis) { nowNanos += Duration.ofMillis(millis).toNanos(); } + + @RateLimited(maxReconciliations = 1, within = 3) + private static class SinglePermit {} + + @RateLimited(maxReconciliations = 3, within = 3) + private static class ThreePermits {} }