-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding a new rate limiting method ("onAverageEvery(N)") which uses a …
…pseudo random number generator rather than counting the number of logs processed. This is useful in cases where regular rate limiting is too "predictable" (e.g. if application behaviour is very repeatable). RELNOTES=Adding new PRNG based "onAverageEvery(N)" rate limiting method. PiperOrigin-RevId: 520335712
- Loading branch information
Showing
5 changed files
with
271 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
api/src/main/java/com/google/common/flogger/SamplingRateLimiter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
/* | ||
* Copyright (C) 2023 The Flogger 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 com.google.common.flogger; | ||
|
||
import static com.google.common.flogger.LogContext.Key.LOG_SAMPLE_EVERY_N; | ||
import static com.google.common.flogger.RateLimitStatus.DISALLOW; | ||
|
||
import com.google.common.flogger.backend.Metadata; | ||
import java.util.Random; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
import org.checkerframework.checker.nullness.compatqual.NullableDecl; | ||
|
||
/** | ||
* Rate limiter to support {@code onAverageEvery(N)} functionality. | ||
* | ||
* <p>Instances of this class are created for each unique {@link LogSiteKey} for which rate limiting | ||
* via the {@code LOG_SAMPLE_EVERY_N} metadata key is required. This class implements {@code | ||
* RateLimitStatus} as a mechanism for resetting its own state. | ||
* | ||
* <p>This class is thread safe. | ||
*/ | ||
final class SamplingRateLimiter extends RateLimitStatus { | ||
private static final LogSiteMap<SamplingRateLimiter> map = | ||
new LogSiteMap<SamplingRateLimiter>() { | ||
@Override | ||
protected SamplingRateLimiter initialValue() { | ||
return new SamplingRateLimiter(); | ||
} | ||
}; | ||
|
||
@NullableDecl | ||
static RateLimitStatus check(Metadata metadata, LogSiteKey logSiteKey) { | ||
Integer rateLimitCount = metadata.findValue(LOG_SAMPLE_EVERY_N); | ||
if (rateLimitCount == null || rateLimitCount <= 0) { | ||
// Without valid rate limiter specific metadata, this limiter has no effect. | ||
return null; | ||
} | ||
return map.get(logSiteKey, metadata).sampleOneIn(rateLimitCount); | ||
} | ||
|
||
// Even though Random is synchonized, we have to put it in a ThreadLocal to avoid thread | ||
// contention. We cannot use ThreadLocalRandom (yet) due to JDK level. | ||
private static final ThreadLocal<Random> random = new ThreadLocal<Random>() { | ||
@Override | ||
protected Random initialValue() { | ||
return new Random(); | ||
} | ||
}; | ||
|
||
// Visible for testing. | ||
final AtomicInteger pendingCount = new AtomicInteger(); | ||
|
||
// Visible for testing. | ||
SamplingRateLimiter() {} | ||
|
||
RateLimitStatus sampleOneIn(int rateLimitCount) { | ||
// Always "roll the dice" and adjust the count if necessary (even if we were already | ||
// pending). This means that in the long run we will account for every time we roll a | ||
// zero and the number of logs will end up statistically close to 1-in-N (even if at | ||
// times they can be "bursty" due to the action of other rate limiting mechanisms). | ||
int pending; | ||
if (random.get().nextInt(rateLimitCount) == 0) { | ||
pending = pendingCount.incrementAndGet(); | ||
} else { | ||
pending = pendingCount.get(); | ||
} | ||
return pending > 0 ? this : DISALLOW; | ||
} | ||
|
||
@Override | ||
public void reset() { | ||
pendingCount.decrementAndGet(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
78 changes: 78 additions & 0 deletions
78
api/src/test/java/com/google/common/flogger/SamplingRateLimiterTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
/* | ||
* Copyright (C) 2023 The Flogger 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 com.google.common.flogger; | ||
|
||
import static com.google.common.flogger.LogContext.Key.LOG_SAMPLE_EVERY_N; | ||
import static com.google.common.truth.Truth.assertThat; | ||
|
||
import com.google.common.collect.Range; | ||
import com.google.common.flogger.backend.Metadata; | ||
import com.google.common.flogger.testing.FakeLogSite; | ||
import com.google.common.flogger.testing.FakeMetadata; | ||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
import org.junit.runners.JUnit4; | ||
|
||
@RunWith(JUnit4.class) | ||
public class SamplingRateLimiterTest { | ||
@Test | ||
public void testInvalidCount() { | ||
Metadata metadata = new FakeMetadata().add(LOG_SAMPLE_EVERY_N, 0); | ||
assertThat(SamplingRateLimiter.check(metadata, FakeLogSite.unique())).isNull(); | ||
} | ||
|
||
@Test | ||
public void testPendingCount() { | ||
SamplingRateLimiter limiter = new SamplingRateLimiter(); | ||
// Initially we are not "pending", so disallow logging for an "impossible" sample rate. | ||
assertThat(limiter.pendingCount.get()).isEqualTo(0); | ||
assertThat(limiter.sampleOneIn(Integer.MAX_VALUE)).isEqualTo(RateLimitStatus.DISALLOW); | ||
for (int i = 0; i < 100; i++) { | ||
RateLimitStatus unused = limiter.sampleOneIn(5); | ||
} | ||
// Statistically we should be pending at least once. | ||
int pendingCount = limiter.pendingCount.get(); | ||
assertThat(pendingCount).isGreaterThan(0); | ||
// Now we are pending, we allow logging even for an "impossible" sample rate. | ||
assertThat(limiter.sampleOneIn(Integer.MAX_VALUE)).isNotEqualTo(RateLimitStatus.DISALLOW); | ||
limiter.reset(); | ||
assertThat(limiter.pendingCount.get()).isEqualTo(pendingCount - 1); | ||
} | ||
|
||
@Test | ||
public void testSamplingRate() { | ||
// Chance is less than one-millionth of 1% that this will fail spuriously. | ||
Metadata metadata = new FakeMetadata().add(LOG_SAMPLE_EVERY_N, 2); | ||
assertThat(countNSamples(1000, metadata)).isIn(Range.closed(400, 600)); | ||
|
||
// Expected average is 20 logs out of 1000. Seeing 0 or > 100 is enormously unlikely. | ||
metadata = new FakeMetadata().add(LOG_SAMPLE_EVERY_N, 50); | ||
assertThat(countNSamples(1000, metadata)).isIn(Range.closed(1, 100)); | ||
} | ||
|
||
private static int countNSamples(int n, Metadata metadata) { | ||
LogSite logSite = FakeLogSite.unique(); | ||
int sampled = 0; | ||
while (n-- > 0) { | ||
if (RateLimitStatus.checkStatus( | ||
SamplingRateLimiter.check(metadata, logSite), logSite, metadata) >= 0) { | ||
sampled++; | ||
} | ||
} | ||
return sampled; | ||
} | ||
} |