Elffuss BraidHub

kikocis/java-driver public

Merge pull request #705 from datastax/java1055

JAVA-1055: ErrorAware load balancing policy.
Changeset6795b189968d2b2ac7e72370d4fe314891a8b7179fb2d9c4bbb18703d6765942
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-27 10:08 -07:00
CommitterGitHub <noreply@github.com> · 2016-07-27 10:08 -07:00
Parents05a9af8a479d, 5bca3551c327

Browse the files at this changeset

10 files changed

modified changelog/README.md +1 −0
@@ -13,6 +13,7 @@
1313 - [new feature] JAVA-541: Add polymorphism support to object mapper.
1414 - [new feature] JAVA-636: Allow @Column annotations on getters/setters as well as fields.
1515 - [new feature] JAVA-984: Allow non-void setters in object mapping.
16+- [new feature] JAVA-1055: Add ErrorAware load balancing policy.
1617
1718 Merged from 3.0.x branch:
1819
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +8 −9
@@ -471,7 +471,7 @@
471471 * Registers the provided tracker to be updated with hosts read
472472 * latencies.
473473 * <p/>
474- * Registering the same listener multiple times is a no-op.
474+ * Registering the same tracker multiple times is a no-op.
475475 * <p/>
476476 * Beware that the registered tracker's
477477 * {@link LatencyTracker#update(Host, Statement, Exception, long) update}
@@ -490,7 +490,7 @@
490490 */
491491 public Cluster register(LatencyTracker tracker) {
492492 checkNotClosed(manager);
493- boolean added = manager.trackers.add(tracker);
493+ boolean added = manager.latencyTrackers.add(tracker);
494494 if (added)
495495 tracker.onRegister(this);
496496 return this;
@@ -508,7 +508,7 @@
508508 */
509509 public Cluster unregister(LatencyTracker tracker) {
510510 checkNotClosed(manager);
511- boolean removed = manager.trackers.remove(tracker);
511+ boolean removed = manager.latencyTrackers.remove(tracker);
512512 if (removed)
513513 tracker.onUnregister(this);
514514 return this;
@@ -1341,7 +1341,7 @@
13411341 ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries;
13421342
13431343 final Set<Host.StateListener> listeners;
1344- final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1344+ final Set<LatencyTracker> latencyTrackers = new CopyOnWriteArraySet<LatencyTracker>();
13451345 final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
13461346
13471347 EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
@@ -1484,11 +1484,10 @@
14841484 configuration.getPolicies().getRetryPolicy().init(Cluster.this);
14851485 reconnectionPolicy().init(Cluster.this);
14861486 configuration.getPolicies().getAddressTranslator().init(Cluster.this);
1487- for (LatencyTracker tracker : trackers)
1487+ for (LatencyTracker tracker : latencyTrackers)
14881488 tracker.onRegister(Cluster.this);
14891489 for (Host.StateListener listener : listeners)
14901490 listener.onRegister(Cluster.this);
1491-
14921491 for (Host host : removedContactPointHosts) {
14931492 loadBalancingPolicy().onRemove(host);
14941493 for (Host.StateListener listener : listeners)
@@ -1592,8 +1591,8 @@
15921591 return sessions.remove(session);
15931592 }
15941593
1595- void reportLatency(Host host, Statement statement, Exception exception, long latencyNanos) {
1596- for (LatencyTracker tracker : trackers) {
1594+ void reportQuery(Host host, Statement statement, Exception exception, long latencyNanos) {
1595+ for (LatencyTracker tracker : latencyTrackers) {
15971596 tracker.update(host, statement, exception, latencyNanos);
15981597 }
15991598 }
@@ -1634,7 +1633,7 @@
16341633 configuration.getPolicies().getRetryPolicy().close();
16351634 reconnectionPolicy().close();
16361635 configuration.getPolicies().getAddressTranslator().close();
1637- for (LatencyTracker tracker : trackers)
1636+ for (LatencyTracker tracker : latencyTrackers)
16381637 tracker.onUnregister(Cluster.this);
16391638 for (Host.StateListener listener : listeners)
16401639 listener.onUnregister(Cluster.this);
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −4
@@ -638,8 +638,9 @@
638638 exceptionToReport = e;
639639 setFinalException(connection, e);
640640 } finally {
641- if (queriedHost != null && statement != Statement.DEFAULT)
642- manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
641+ if (queriedHost != null && statement != Statement.DEFAULT) {
642+ manager.cluster.manager.reportQuery(queriedHost, statement, exceptionToReport, latency);
643+ }
643644 }
644645 }
645646
@@ -746,7 +747,7 @@
746747 setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e));
747748 } finally {
748749 if (queriedHost != null && statement != Statement.DEFAULT)
749- manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency);
750+ manager.cluster.manager.reportQuery(queriedHost, statement, exception, latency);
750751 }
751752 }
752753
@@ -774,7 +775,7 @@
774775 setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
775776 } finally {
776777 if (queriedHost != null && statement != Statement.DEFAULT)
777- manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency);
778+ manager.cluster.manager.reportQuery(queriedHost, statement, timeoutException, latency);
778779 }
779780 return true;
780781 }
added driver-core/src/main/java/com/datastax/driver/core/policies/Clock.java +27 −0
@@ -0,0 +1,27 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+/**
19+ * Wraps System.nanoTime() to make it easy to mock in tests.
20+ */
21+class Clock {
22+ static final Clock DEFAULT = new Clock();
23+
24+ long nanoTime() {
25+ return System.nanoTime();
26+ }
27+}
added driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java +364 −0
@@ -0,0 +1,364 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.*;
20+import com.google.common.annotations.Beta;
21+import com.google.common.annotations.VisibleForTesting;
22+import com.google.common.collect.AbstractIterator;
23+import com.google.common.collect.ImmutableList;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
26+
27+import java.util.Collection;
28+import java.util.Iterator;
29+import java.util.List;
30+import java.util.concurrent.ConcurrentHashMap;
31+import java.util.concurrent.ConcurrentMap;
32+import java.util.concurrent.TimeUnit;
33+
34+import static java.util.concurrent.TimeUnit.MINUTES;
35+import static java.util.concurrent.TimeUnit.NANOSECONDS;
36+
37+/**
38+ * Chainable load balancing policy that filters out hosts based on their error rates.
39+ * <p/>
40+ * When creating a query plan, this policy gathers a list of candidate hosts from its child policy; for each candidate
41+ * host, it then determines whether it should be included into or excluded from the final query plan, based on its
42+ * current error rate (measured over the last minute, with a 5-second granularity).
43+ * <p/>
44+ * Note that the policy should not blindly count all errors in its measurements: some type of errors (e.g. CQL syntax
45+ * errors) can originate from the client and occur on all hosts, therefore they should not count towards the exclusion
46+ * threshold or all hosts could become excluded. You can provide your own {@link ErrorFilter} to customize that logic.
47+ * <p/>
48+ * The policy follows the builder pattern to be created, the {@link Builder} class can be created with
49+ * {@link #builder} method.
50+ * <p/>
51+ * This policy is currently in BETA mode and its behavior might be changing throughout different driver versions.
52+ */
53+@Beta
54+public class ErrorAwarePolicy implements ChainableLoadBalancingPolicy {
55+
56+ private static final Logger logger = LoggerFactory.getLogger(ErrorAwarePolicy.class);
57+
58+ private final LoadBalancingPolicy childPolicy;
59+
60+ private final long retryPeriodNanos;
61+
62+ PerHostErrorTracker errorTracker;
63+
64+ private ErrorAwarePolicy(Builder builder) {
65+ this.childPolicy = builder.childPolicy;
66+ this.retryPeriodNanos = builder.retryPeriodNanos;
67+ this.errorTracker = new PerHostErrorTracker(builder.maxErrorsPerMinute, builder.errorFilter, builder.clock);
68+ }
69+
70+ @Override
71+ public LoadBalancingPolicy getChildPolicy() {
72+ return childPolicy;
73+ }
74+
75+ @Override
76+ public void init(Cluster cluster, Collection<Host> hosts) {
77+ childPolicy.init(cluster, hosts);
78+ cluster.register(this.errorTracker);
79+ }
80+
81+ @Override
82+ public HostDistance distance(Host host) {
83+ return childPolicy.distance(host);
84+ }
85+
86+ @Override
87+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
88+ final Iterator<Host> childQueryPlan = childPolicy.newQueryPlan(loggedKeyspace, statement);
89+
90+ return new AbstractIterator<Host>() {
91+
92+ @Override
93+ protected Host computeNext() {
94+ while (childQueryPlan.hasNext()) {
95+ Host host = childQueryPlan.next();
96+ if (!errorTracker.isExcluded(host)) {
97+ return host;
98+ }
99+ }
100+ return endOfData();
101+ }
102+ };
103+ }
104+
105+ @Override
106+ public void onAdd(Host host) {
107+ childPolicy.onAdd(host);
108+ }
109+
110+ @Override
111+ public void onUp(Host host) {
112+ childPolicy.onUp(host);
113+ }
114+
115+ @Override
116+ public void onDown(Host host) {
117+ childPolicy.onDown(host);
118+ }
119+
120+ @Override
121+ public void onRemove(Host host) {
122+ childPolicy.onRemove(host);
123+ }
124+
125+ /**
126+ * Creates a new error aware policy builder given the child policy
127+ * that the resulting policy should wrap.
128+ *
129+ * @param childPolicy the load balancing policy to wrap with error
130+ * awareness.
131+ * @return the created builder.
132+ */
133+ public static Builder builder(LoadBalancingPolicy childPolicy) {
134+ return new Builder(childPolicy);
135+ }
136+
137+ @Override
138+ public void close() {
139+ childPolicy.close();
140+ }
141+
142+ /**
143+ * Utility class to create a {@link ErrorAwarePolicy}.
144+ */
145+ public static class Builder {
146+ final LoadBalancingPolicy childPolicy;
147+
148+ private int maxErrorsPerMinute = 1;
149+ private long retryPeriodNanos = NANOSECONDS.convert(2, MINUTES);
150+ private Clock clock = Clock.DEFAULT;
151+
152+ private ErrorFilter errorFilter = new DefaultErrorFilter();
153+
154+ /**
155+ * Creates a {@link Builder} instance.
156+ *
157+ * @param childPolicy the load balancing policy to wrap with error
158+ * awareness.
159+ */
160+ public Builder(LoadBalancingPolicy childPolicy) {
161+ this.childPolicy = childPolicy;
162+ }
163+
164+ /**
165+ * Defines the maximum number of errors allowed per minute for each host.
166+ * <p/>
167+ * The policy keeps track of the number of errors on each host (filtered by
168+ * {@link #withErrorsFilter(ErrorFilter)}) over a sliding 1-minute window. If a host had more than this number
169+ * of errors, it will be excluded from the query plan for the duration defined by
170+ * {@link #withRetryPeriod(long, TimeUnit)}.
171+ * <p/>
172+ * Default value for the threshold is 1.
173+ *
174+ * @param maxErrorsPerMinute the number.
175+ * @return this {@link Builder} instance, for method chaining.
176+ */
177+ public Builder withMaxErrorsPerMinute(int maxErrorsPerMinute) {
178+ this.maxErrorsPerMinute = maxErrorsPerMinute;
179+ return this;
180+ }
181+
182+ /**
183+ * Defines the time during which a host is excluded by the policy once it has exceeded
184+ * {@link #withMaxErrorsPerMinute(int)}.
185+ * <p/>
186+ * Default value for the retry period is 2 minutes.
187+ *
188+ * @param retryPeriod the period of exclusion for a host.
189+ * @param retryPeriodTimeUnit the time unit for the retry period.
190+ * @return this {@link Builder} instance, for method chaining.
191+ */
192+ public Builder withRetryPeriod(long retryPeriod, TimeUnit retryPeriodTimeUnit) {
193+ this.retryPeriodNanos = retryPeriodTimeUnit.toNanos(retryPeriod);
194+ return this;
195+ }
196+
197+ /**
198+ * Provides a filter that will decide which errors are counted towards {@link #withMaxErrorsPerMinute(int)}.
199+ * <p/>
200+ * The default implementation will exclude from the error counting, the following exception types:
201+ * <ul>
202+ * <li>{@link QueryConsistencyException} and {@link UnavailableException}: the assumption is that these errors
203+ * are most often caused by other replicas being unavailable, not by something wrong on the coordinator;</li>
204+ * <li>{@link InvalidQueryException}, {@link AlreadyExistsException}, {@link SyntaxError}: these are likely
205+ * caused by a bad query in client code, that will fail on all hosts. Excluding hosts could lead to complete
206+ * loss of connectivity, rather the solution is to fix the query;</li>
207+ * <li>{@link FunctionExecutionException}: similarly, this is caused by a bad function definition and likely to
208+ * fail on all hosts.</li>
209+ * </ul>
210+ *
211+ * @param errorFilter the filter class that the policy will use.
212+ * @return this {@link Builder} instance, for method chaining.
213+ */
214+ public Builder withErrorsFilter(ErrorFilter errorFilter) {
215+ this.errorFilter = errorFilter;
216+ return this;
217+ }
218+
219+ @VisibleForTesting
220+ Builder withClock(Clock clock) {
221+ this.clock = clock;
222+ return this;
223+ }
224+
225+ /**
226+ * Creates the {@link ErrorAwarePolicy} instance.
227+ *
228+ * @return the newly created {@link ErrorAwarePolicy}.
229+ */
230+ public ErrorAwarePolicy build() {
231+ return new ErrorAwarePolicy(this);
232+ }
233+ }
234+
235+ class PerHostErrorTracker implements LatencyTracker {
236+
237+ private final int maxErrorsPerMinute;
238+ private final ErrorFilter errorFilter;
239+ private final Clock clock;
240+ private final ConcurrentMap<Host, RollingCount> hostsCounts = new ConcurrentHashMap<Host, RollingCount>();
241+ private final ConcurrentMap<Host, Long> exclusionTimes = new ConcurrentHashMap<Host, Long>();
242+
243+ PerHostErrorTracker(int maxErrorsPerMinute, ErrorFilter errorFilter, Clock clock) {
244+ this.maxErrorsPerMinute = maxErrorsPerMinute;
245+ this.errorFilter = errorFilter;
246+ this.clock = clock;
247+ }
248+
249+ @Override
250+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
251+ if (exception == null) {
252+ return;
253+ }
254+ if (!errorFilter.shouldConsiderError(exception, host, statement)) {
255+ return;
256+ }
257+ RollingCount hostCount = getOrCreateCount(host);
258+ hostCount.increment();
259+ }
260+
261+ boolean isExcluded(Host host) {
262+ Long excludedTime = exclusionTimes.get(host);
263+ boolean expired = excludedTime != null && clock.nanoTime() - excludedTime >= retryPeriodNanos;
264+ if (excludedTime == null || expired) {
265+ if (maybeExcludeNow(host, excludedTime)) {
266+ return true;
267+ }
268+ if (expired) {
269+ // Cleanup, but make sure we don't overwrite if another thread just set it
270+ exclusionTimes.remove(host, excludedTime);
271+ }
272+ return false;
273+ } else { // host is already excluded
274+ return true;
275+ }
276+ }
277+
278+ // Exclude if we're over the threshold
279+ private boolean maybeExcludeNow(Host host, Long previousTime) {
280+ RollingCount rollingCount = getOrCreateCount(host);
281+ long count = rollingCount.get();
282+ if (count > maxErrorsPerMinute) {
283+ excludeNow(host, count, previousTime);
284+ return true;
285+ } else {
286+ return false;
287+ }
288+ }
289+
290+ // Set the exclusion time to now, handling potential races
291+ private void excludeNow(Host host, long count, Long previousTime) {
292+ long now = clock.nanoTime();
293+ boolean didNotRace = (previousTime == null)
294+ ? exclusionTimes.putIfAbsent(host, now) == null
295+ : exclusionTimes.replace(host, previousTime, now);
296+
297+ if (didNotRace && logger.isDebugEnabled()) {
298+ logger.debug(String.format("Host %s encountered %d errors in the last minute, which is more " +
299+ "than the maximum allowed (%d). It will be excluded from query plans for the " +
300+ "next %d nanoseconds.",
301+ host, count, maxErrorsPerMinute, retryPeriodNanos));
302+ }
303+ }
304+
305+ private RollingCount getOrCreateCount(Host host) {
306+ RollingCount hostCount = hostsCounts.get(host);
307+ if (hostCount == null) {
308+ RollingCount tmp = new RollingCount(clock);
309+ hostCount = hostsCounts.putIfAbsent(host, tmp);
310+ if (hostCount == null)
311+ hostCount = tmp;
312+ }
313+ return hostCount;
314+ }
315+
316+ @Override
317+ public void onRegister(Cluster cluster) {
318+ // nothing to do.
319+ }
320+
321+ @Override
322+ public void onUnregister(Cluster cluster) {
323+ // nothing to do.
324+ }
325+ }
326+
327+ static class DefaultErrorFilter implements ErrorFilter {
328+ private static final List<Class<? extends Exception>> IGNORED_EXCEPTIONS =
329+ ImmutableList.<Class<? extends Exception>>builder()
330+ .add(FunctionExecutionException.class)
331+ .add(QueryConsistencyException.class)
332+ .add(UnavailableException.class)
333+ .add(AlreadyExistsException.class)
334+ .add(InvalidQueryException.class)
335+ .add(SyntaxError.class)
336+ .build();
337+
338+ @Override
339+ public boolean shouldConsiderError(Exception e, Host host, Statement statement) {
340+ for (Class<? extends Exception> ignoredException : IGNORED_EXCEPTIONS) {
341+ if (ignoredException.isInstance(e))
342+ return false;
343+ }
344+ return true;
345+ }
346+ }
347+
348+ /**
349+ * A filter for the errors considered by {@link ErrorAwarePolicy}.
350+ * <p/>
351+ * Only errors that indicate something wrong with a host should lead to its exclusion from query plans.
352+ */
353+ public interface ErrorFilter {
354+ /**
355+ * Whether an error should be counted in the host's error rate.
356+ *
357+ * @param e the exception.
358+ * @param host the host.
359+ * @param statement the statement that caused the exception.
360+ * @return {@code true} if the exception should be counted.
361+ */
362+ boolean shouldConsiderError(Exception e, Host host, Statement statement);
363+ }
364+}
added driver-core/src/main/java/com/datastax/driver/core/policies/RollingCount.java +118 −0
@@ -0,0 +1,118 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import java.util.concurrent.TimeUnit;
19+import java.util.concurrent.atomic.AtomicLong;
20+import java.util.concurrent.atomic.AtomicLongArray;
21+import java.util.concurrent.atomic.AtomicReference;
22+
23+/**
24+ * A "rolling" count over a 1-minute sliding window.
25+ */
26+class RollingCount {
27+ // Divide the minute into 5-second intervals
28+ private static final long INTERVAL_SIZE = TimeUnit.SECONDS.toNanos(5);
29+
30+ // A circular buffer containing the counts over the 12 previous intervals. Their sum is the count we're looking for.
31+ // If we're at t = 61s this would span [0,60[
32+ private final AtomicLongArray previousIntervals = new AtomicLongArray(12);
33+ // The interval we're currently recording events for. It hasn't completed yet, so it's not included in the count.
34+ // If we're at t = 61s this would span [60,65[
35+ // Note that we don't expect very high concurrency on RollingCount (it's used to count errors), so AtomicLong is
36+ // good enough here.
37+ private final AtomicLong currentInterval = new AtomicLong();
38+ // Other mutable state, grouped in an object for atomic updates
39+ private final AtomicReference<State> state;
40+ private final Clock clock;
41+
42+ RollingCount(Clock clock) {
43+ this.state = new AtomicReference<State>(new State(clock.nanoTime()));
44+ this.clock = clock;
45+ }
46+
47+ void increment() {
48+ add(1);
49+ }
50+
51+ void add(long amount) {
52+ tickIfNecessary();
53+ currentInterval.addAndGet(amount);
54+ }
55+
56+ long get() {
57+ tickIfNecessary();
58+ return state.get().totalCount;
59+ }
60+
61+ private void tickIfNecessary() {
62+ State oldState = state.get();
63+ long newTick = clock.nanoTime();
64+ long age = newTick - oldState.lastTick;
65+ if (age >= INTERVAL_SIZE) {
66+ long currentCount = currentInterval.get();
67+
68+ long newIntervalStartTick = newTick - age % INTERVAL_SIZE;
69+ long elapsedIntervals = Math.min(age / INTERVAL_SIZE, 12);
70+ int newOffset = (int) ((oldState.offset + elapsedIntervals) % 12);
71+
72+ long newTotal;
73+ if (elapsedIntervals == 12) {
74+ // We wrapped around the circular buffer, all our values are stale
75+ // Don't mutate previousIntervals yet because this part of the code is still multi-threaded.
76+ newTotal = 0;
77+ } else {
78+ // Add the current interval that just completed
79+ newTotal = oldState.totalCount + currentCount;
80+ // Subtract all elapsed intervals: they're either idle ones, or the one at the old offset that we're
81+ // about to replace
82+ for (int i = 1; i <= elapsedIntervals; i++) {
83+ newTotal -= previousIntervals.get((newOffset + 12 - i) % 12);
84+ }
85+ }
86+
87+ State newState = new State(newIntervalStartTick, newOffset, newTotal);
88+ if (state.compareAndSet(oldState, newState)) {
89+ // Only one thread gets here, so we can now:
90+ // - reset the current count (don't use reset because other threads might already have started updating
91+ // it)
92+ currentInterval.addAndGet(-currentCount);
93+ // - store the interval that just completed (or clear it if we wrapped)
94+ previousIntervals.set(oldState.offset, elapsedIntervals < 12 ? currentCount : 0);
95+ // - clear any idle interval
96+ for (int i = 1; i < elapsedIntervals; i++) {
97+ previousIntervals.set((newOffset + 12 - i) % 12, 0);
98+ }
99+ }
100+ }
101+ }
102+
103+ static class State {
104+ final long lastTick; // last time the state was modified
105+ final int offset; // the offset that the current interval will replace once it's complete
106+ final long totalCount; // cache of sum(previousIntervals)
107+
108+ State(long lastTick) {
109+ this(lastTick, 0, 0);
110+ }
111+
112+ State(long lastTick, int offset, long totalCount) {
113+ this.lastTick = lastTick;
114+ this.offset = offset;
115+ this.totalCount = totalCount;
116+ }
117+ }
118+}
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +35 −17
@@ -15,7 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.util.concurrent.Futures;
18+import com.datastax.driver.core.exceptions.CoordinatorException;
1919 import com.google.common.util.concurrent.ListenableFuture;
2020 import com.google.common.util.concurrent.Uninterruptibles;
2121 import org.assertj.core.util.Maps;
@@ -36,7 +36,7 @@
3636 * which hosts were queried.
3737 */
3838 public class QueryTracker {
39- static final String QUERY = "select * from test.foo";
39+ public static final String QUERY = "select * from test.foo";
4040
4141 Map<InetAddress, Integer> coordinators = Maps.newConcurrentHashMap();
4242
@@ -48,20 +48,28 @@
4848 query(session, times, cl, null);
4949 }
5050
51+ public void query(Session session, int times, InetSocketAddress expectedHost) {
52+ query(session, times, new SimpleStatement(QUERY), null, expectedHost);
53+ }
54+
55+ public void query(Session session, int times, Class<? extends Exception> expectedException, InetSocketAddress expectedHost) {
56+ query(session, times, new SimpleStatement(QUERY), expectedException, expectedHost);
57+ }
58+
5159 public void query(Session session, int times, ConsistencyLevel cl, Class<? extends Exception> expectedException) {
5260 Statement statement = new SimpleStatement(QUERY);
5361 if (cl != null) {
5462 statement.setConsistencyLevel(cl);
5563 }
5664
57- query(session, times, statement, expectedException);
65+ query(session, times, statement, expectedException, null);
5866 }
5967
6068 public void query(Session session, int times, Statement statement) {
61- query(session, times, statement, null);
69+ query(session, times, statement, null, null);
6270 }
6371
64- public void query(Session session, int times, Statement statement, Class<? extends Exception> expectedException) {
72+ public void query(Session session, int times, Statement statement, Class<? extends Exception> expectedException, InetSocketAddress expectedHost) {
6573 List<ListenableFuture<ResultSet>> futures = newArrayList();
6674
6775 for (int i = 0; i < times; i++) {
@@ -69,18 +77,28 @@
6977 }
7078
7179 try {
72- List<ResultSet> results = Uninterruptibles.getUninterruptibly(Futures.allAsList(futures), 1, TimeUnit.MINUTES);
73- for (ResultSet result : results) {
74- InetAddress coordinator = result.getExecutionInfo().getQueriedHost().getAddress();
75- Integer n = coordinators.get(coordinator);
76- coordinators.put(coordinator, n == null ? 1 : n + 1);
77- }
78- } catch (ExecutionException ex) {
79- Throwable cause = ex.getCause();
80- if (expectedException == null) {
81- fail("Queries failed", ex);
82- } else {
83- assertThat(cause).isInstanceOf(expectedException);
80+ for (ListenableFuture<ResultSet> future : futures) {
81+ try {
82+ ResultSet result = Uninterruptibles.getUninterruptibly(future, 1, TimeUnit.SECONDS);
83+ InetSocketAddress address = result.getExecutionInfo().getQueriedHost().getSocketAddress();
84+ InetAddress coordinator = address.getAddress();
85+ Integer n = coordinators.get(coordinator);
86+ coordinators.put(coordinator, n == null ? 1 : n + 1);
87+ if (expectedHost != null) {
88+ assertThat(address).isEqualTo(expectedHost);
89+ }
90+ } catch (ExecutionException ex) {
91+ Throwable cause = ex.getCause();
92+ if (expectedException == null) {
93+ fail("Query fail", ex);
94+ } else {
95+ assertThat(cause).isInstanceOf(expectedException);
96+ }
97+
98+ if (cause instanceof CoordinatorException) {
99+ assertThat(((CoordinatorException) cause).getAddress()).isEqualTo(expectedHost);
100+ }
101+ }
84102 }
85103 } catch (Exception e) {
86104 fail("Queries failed", e);
added driver-core/src/test/java/com/datastax/driver/core/policies/ErrorAwarePolicyIntegrationTest.java +378 −0
@@ -0,0 +1,378 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.*;
20+import org.scassandra.http.client.Result;
21+import org.testng.annotations.AfterMethod;
22+import org.testng.annotations.BeforeMethod;
23+import org.testng.annotations.Test;
24+
25+import java.util.concurrent.Callable;
26+import java.util.concurrent.TimeUnit;
27+import java.util.concurrent.atomic.AtomicInteger;
28+
29+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
30+import static java.util.concurrent.TimeUnit.SECONDS;
31+import static org.mockito.Mockito.mock;
32+import static org.mockito.Mockito.when;
33+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
34+import static org.scassandra.http.client.PrimingRequest.then;
35+import static org.scassandra.http.client.Result.*;
36+
37+public class ErrorAwarePolicyIntegrationTest {
38+
39+ private QueryTracker queryTracker;
40+ private Clock clock;
41+ private ScassandraCluster sCluster;
42+ private AtomicInteger errorCounter;
43+ private LatencyTracker latencyTracker;
44+
45+ @BeforeMethod(groups = "short")
46+ public void setUp() {
47+ queryTracker = new QueryTracker();
48+ clock = mock(Clock.class);
49+ sCluster = ScassandraCluster.builder().withNodes(2).build();
50+ sCluster.init();
51+ errorCounter = new AtomicInteger(0);
52+ latencyTracker = new LatencyTracker() {
53+ @Override
54+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
55+ if (exception != null)
56+ errorCounter.incrementAndGet();
57+ }
58+
59+ @Override
60+ public void onRegister(Cluster cluster) {
61+ }
62+
63+ @Override
64+ public void onUnregister(Cluster cluster) {
65+ }
66+ };
67+ // By default node 1 should always fail, 2 succeed.
68+ prime(1, unauthorized);
69+ prime(2, success);
70+ }
71+
72+ @AfterMethod(groups = "short")
73+ public void tearDown() {
74+ sCluster.stop();
75+ }
76+
77+ private Cluster.Builder builder(LoadBalancingPolicy lbp) {
78+ return Cluster.builder()
79+ .withNettyOptions(nonQuietClusterCloseOptions)
80+ .addContactPoints(sCluster.address(1).getAddress())
81+ .withPort(sCluster.getBinaryPort())
82+ .withLoadBalancingPolicy(lbp);
83+ }
84+
85+ private void prime(int node, Result result) {
86+ sCluster.node(node).primingClient().prime(
87+ queryBuilder()
88+ .withQuery(QueryTracker.QUERY)
89+ .withThen(then().withResult(result))
90+ .build()
91+ );
92+ }
93+
94+ /**
95+ * Checks that {@link LatencyTracker#update} was called at least expectedCount times within 5 seconds.
96+ * <p/>
97+ * Note that the usefulness of this is dependent on the {@link ErrorAwarePolicy.PerHostErrorTracker} being invoked
98+ * before the latency tracker being used to track error invocations in this test. The existing implementation
99+ * seems to invoke update on latency trackers in order that they are registered.
100+ *
101+ * @param expectedCount Expected number of errors to have been invoked.
102+ */
103+ private void awaitTrackerUpdate(final int expectedCount) {
104+ ConditionChecker.check()
105+ .every(10)
106+ .that(new Callable<Boolean>() {
107+ @Override
108+ public Boolean call() throws Exception {
109+ return errorCounter.get() >= expectedCount;
110+ }
111+ })
112+ .before(5000)
113+ .becomesTrue();
114+ }
115+
116+ private void setTime(long time, TimeUnit timeUnit) {
117+ when(clock.nanoTime()).thenReturn(TimeUnit.NANOSECONDS.convert(time, timeUnit));
118+ }
119+
120+ /**
121+ * Validates that {@link ErrorAwarePolicy} properly excludes a host after the maximum number of errors is exceeded.
122+ * <p/>
123+ * This test configures a maximum of 1 error per minute and executes 2 failing queries against host1 during the
124+ * first 5 simulated seconds. host1 should be excluded as soon as the rolling count updates over the next 5-second
125+ * interval.
126+ * <p/>
127+ * It then makes another query and ensures it is executed against host2 and that the response was successful.
128+ *
129+ * @jira_ticket JAVA-1055
130+ * @test_category load_balancing:error_aware
131+ * @since 3.1.0
132+ */
133+ @Test(groups = "short")
134+ public void should_exclude_host_after_reaching_maximum_errors() throws InterruptedException {
135+ LoadBalancingPolicy lbp = ErrorAwarePolicy.builder(new SortingLoadBalancingPolicy())
136+ .withMaxErrorsPerMinute(1)
137+ .withClock(clock)
138+ .build();
139+
140+ Cluster cluster = builder(lbp).build();
141+
142+ try {
143+ Session session = cluster.connect();
144+ cluster.register(latencyTracker);
145+
146+ setTime(0, SECONDS);
147+ // Make 2 queries producing a count higher than the threshold
148+ queryTracker.query(session, 2, UnauthorizedException.class, sCluster.address(1));
149+ awaitTrackerUpdate(2);
150+
151+ // Advance time so that RollingCount ticks and updates its count.
152+ setTime(5, SECONDS);
153+
154+ // The next query should succeed and hit node 2 since node 1 is now ignored.
155+ queryTracker.query(session, 1, sCluster.address(2));
156+ } finally {
157+ cluster.close();
158+ }
159+ }
160+
161+ /**
162+ * Validates that {@link ErrorAwarePolicy} will include a previously excluded host after the configured retry
163+ * period has elapsed.
164+ * <p/>
165+ * The test executes queries with error to get host1 excluded. It then executes queries over 70 simulated seconds
166+ * and then executes another query after this time has elapsed and ensures that the next query execution uses host1.
167+ *
168+ * @jira_ticket JAVA-1055
169+ * @test_category load_balancing:error_aware
170+ * @since 3.1.0
171+ */
172+ @Test(groups = "short")
173+ public void should_resurrect_host_after_retry_period() throws InterruptedException {
174+ LoadBalancingPolicy lbp = ErrorAwarePolicy.builder(new SortingLoadBalancingPolicy())
175+ .withMaxErrorsPerMinute(1)
176+ .withRetryPeriod(70, SECONDS)
177+ .withClock(clock)
178+ .build();
179+
180+ Cluster cluster = builder(lbp).build();
181+ try {
182+ Session session = cluster.connect();
183+ cluster.register(latencyTracker);
184+
185+ setTime(0, SECONDS);
186+ // Make 2 queries producing a count higher than the threshold
187+ queryTracker.query(session, 2, UnauthorizedException.class, sCluster.address(1));
188+ awaitTrackerUpdate(2);
189+
190+ // Advance time so that RollingCount ticks and updates its count.
191+ setTime(5, SECONDS);
192+
193+ // Execute some queries, these should all succeed and hit host2 since host1 is excluded.
194+ queryTracker.query(session, 5, sCluster.address(2));
195+
196+ // Advance time after the retry period
197+ setTime(75, SECONDS);
198+
199+ // At this the load balancing policy should resurrect node 1 which will be used and fail.
200+ queryTracker.query(session, 1, UnauthorizedException.class, sCluster.address(1));
201+
202+ } finally {
203+ cluster.close();
204+ }
205+ }
206+
207+ /**
208+ * Validates that {@link ErrorAwarePolicy} will not penalize errors that are not considered in the default
209+ * {@link ErrorAwarePolicy.ErrorFilter} implementation.
210+ * <p/>
211+ * Executes 10 queries with each error type and ensures that host1 is used each time, verifying that it was
212+ * never excluded.
213+ *
214+ * @jira_ticket JAVA-1055
215+ * @test_category load_balancing:error_aware
216+ * @since 3.1.0
217+ */
218+ @Test(groups = "short")
219+ public void should_not_penalize_default_ignored_exceptions() throws InterruptedException {
220+ LoadBalancingPolicy lbp = ErrorAwarePolicy.builder(new SortingLoadBalancingPolicy())
221+ .withMaxErrorsPerMinute(1)
222+ .withClock(clock)
223+ .build();
224+
225+ // Use fall through retry policy so other hosts aren't tried.
226+ Cluster cluster = builder(lbp).withRetryPolicy(FallthroughRetryPolicy.INSTANCE).build();
227+ try {
228+ Session session = cluster.connect();
229+ cluster.register(latencyTracker);
230+
231+ setTime(0, SECONDS);
232+ // TODO: Add Read and Write Failure, FunctionExecution exception when Scassandra supports v4.
233+ prime(1, read_request_timeout);
234+ queryTracker.query(session, 10, ReadTimeoutException.class, sCluster.address(1));
235+ awaitTrackerUpdate(10);
236+
237+ setTime(5, SECONDS);
238+
239+ prime(1, write_request_timeout);
240+ queryTracker.query(session, 10, WriteTimeoutException.class, sCluster.address(1));
241+ awaitTrackerUpdate(20);
242+
243+ setTime(10, SECONDS);
244+
245+ prime(1, unavailable);
246+ queryTracker.query(session, 10, UnavailableException.class, sCluster.address(1));
247+ awaitTrackerUpdate(30);
248+
249+ setTime(15, SECONDS);
250+
251+ prime(1, already_exists);
252+ queryTracker.query(session, 10, AlreadyExistsException.class, sCluster.address(1));
253+ awaitTrackerUpdate(40);
254+
255+ setTime(20, SECONDS);
256+
257+ prime(1, invalid);
258+ queryTracker.query(session, 10, InvalidQueryException.class, sCluster.address(1));
259+ awaitTrackerUpdate(50);
260+
261+ setTime(25, SECONDS);
262+
263+ prime(1, syntax_error);
264+ queryTracker.query(session, 10, SyntaxError.class, sCluster.address(1));
265+ awaitTrackerUpdate(60);
266+
267+ setTime(30, SECONDS);
268+
269+ // ensure host1 still used after another tick.
270+ queryTracker.query(session, 10, SyntaxError.class, sCluster.address(1));
271+ } finally {
272+ cluster.close();
273+ }
274+ }
275+
276+ /**
277+ * Validates that {@link ErrorAwarePolicy} will regard a custom {@link ErrorAwarePolicy.ErrorFilter} by only
278+ * penalizing a node when it produces exceptions that evaluate to true in the filter implementation.
279+ * <p/>
280+ * It first executes 10 queries with an error type that is not considered and verify that host1 is never excluded.
281+ * <p/>
282+ * It then executes queries with an error type that is considered and verifies that host1 is then excluded and host2
283+ * is used instead.
284+ *
285+ * @jira_ticket JAVA-1055
286+ * @test_category load_balancing:error_aware
287+ * @since 3.1.0
288+ */
289+ @Test(groups = "short")
290+ public void should_only_consider_exceptions_based_on_errors_filter() throws InterruptedException {
291+ ErrorAwarePolicy.ErrorFilter iqeOnlyFilter = new ErrorAwarePolicy.ErrorFilter() {
292+ @Override
293+ public boolean shouldConsiderError(Exception e, Host host, Statement statement) {
294+ return e.getClass().isAssignableFrom(InvalidQueryException.class);
295+ }
296+ };
297+
298+ LoadBalancingPolicy lbp = ErrorAwarePolicy.builder(new SortingLoadBalancingPolicy())
299+ .withMaxErrorsPerMinute(1)
300+ .withClock(clock)
301+ .withErrorsFilter(iqeOnlyFilter)
302+ .build();
303+
304+ // Use fall through retry policy so other hosts aren't tried.
305+ Cluster cluster = builder(lbp).withRetryPolicy(FallthroughRetryPolicy.INSTANCE).build();
306+ try {
307+ Session session = cluster.connect();
308+ cluster.register(latencyTracker);
309+
310+ setTime(0, SECONDS);
311+ // UnauthorizedException evaluates to false in the filter, so it should not be considered.
312+ prime(1, unauthorized);
313+ queryTracker.query(session, 10, UnauthorizedException.class, sCluster.address(1));
314+ awaitTrackerUpdate(10);
315+
316+ setTime(5, SECONDS);
317+ // should still query host1
318+ queryTracker.query(session, 1, UnauthorizedException.class, sCluster.address(1));
319+
320+ // InvalidQueryException evaluates to true, so it *should* be considered increment the count
321+ prime(1, invalid);
322+ queryTracker.query(session, 2, InvalidQueryException.class, sCluster.address(1));
323+ awaitTrackerUpdate(13);
324+
325+ // Advance time so that the rolling count updates the next time we query.
326+ // The first errors that were considered were at t = 5 seconds and this is when the rolling count was
327+ // initialized, so we want to be at t > 5 + 5 for the rolling count to update
328+ setTime(10, SECONDS);
329+
330+ // The next query should succeed and hit node 2 since node 1 is now ignored.
331+ queryTracker.query(session, 1, sCluster.address(2));
332+ } finally {
333+ cluster.close();
334+ }
335+ }
336+
337+ /**
338+ * Validates that an {@link ErrorAwarePolicy} configured with its defaults behaves as documented, that being that
339+ * the maximum number of errors is 1 and the retry period is 120 seconds.
340+ *
341+ * @jira_ticket JAVA-1055
342+ * @test_category load_balancing:error_aware
343+ * @since 3.1.0
344+ */
345+ @Test(groups = "short")
346+ public void should_regard_defaults() throws InterruptedException {
347+ LoadBalancingPolicy lbp = ErrorAwarePolicy.builder(new SortingLoadBalancingPolicy())
348+ .withClock(clock)
349+ .build();
350+
351+ Cluster cluster = builder(lbp).build();
352+ try {
353+ Session session = cluster.connect();
354+ cluster.register(latencyTracker);
355+
356+ setTime(0, SECONDS);
357+ // Make 2 queries producing a count higher than the threshold
358+ queryTracker.query(session, 2, UnauthorizedException.class, sCluster.address(1));
359+ awaitTrackerUpdate(2);
360+
361+ // Advance time so the rolling count ticks, next query should go to host 2
362+ setTime(5, SECONDS);
363+ queryTracker.query(session, 5, sCluster.address(2));
364+
365+ // Advance clock 30 seconds, this is within the retry period so host 1 should still be excluded.
366+ setTime(35, SECONDS);
367+ queryTracker.query(session, 5, sCluster.address(2));
368+
369+ // At this point 120 seconds have elapsed, the load balancing policy should see that the retry period has
370+ // elapsed and resurrect node 1 which will be used and fail.
371+ setTime(125, SECONDS);
372+ queryTracker.query(session, 1, UnauthorizedException.class, sCluster.address(1));
373+
374+ } finally {
375+ cluster.close();
376+ }
377+ }
378+}
added driver-core/src/test/java/com/datastax/driver/core/policies/RollingCountTest.java +149 −0
@@ -0,0 +1,149 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import org.mockito.Mock;
19+import org.mockito.MockitoAnnotations;
20+import org.testng.annotations.BeforeMethod;
21+import org.testng.annotations.Test;
22+
23+import java.util.concurrent.TimeUnit;
24+
25+import static com.datastax.driver.core.Assertions.assertThat;
26+import static java.util.concurrent.TimeUnit.NANOSECONDS;
27+import static java.util.concurrent.TimeUnit.SECONDS;
28+import static org.mockito.Mockito.when;
29+
30+public class RollingCountTest {
31+ @Mock
32+ Clock clock;
33+
34+ RollingCount rollingCount;
35+
36+ @BeforeMethod(groups = "unit")
37+ public void setup() {
38+ MockitoAnnotations.initMocks(this);
39+ assertThat(clock.nanoTime()).isEqualTo(0);
40+ rollingCount = new RollingCount(clock);
41+ }
42+
43+ @Test(groups = "unit")
44+ public void should_record_adds_in_first_interval() {
45+ // t = 0
46+ rollingCount.increment();
47+ setTime(1, SECONDS);
48+ rollingCount.increment();
49+ setTime(2, SECONDS);
50+ rollingCount.increment();
51+
52+ // the count does not update in real time...
53+ assertThat(rollingCount.get()).isEqualTo(0);
54+
55+ // but only at the end of each 5-second interval
56+ setTime(5, SECONDS);
57+ assertThat(rollingCount.get()).isEqualTo(3);
58+ }
59+
60+ @Test(groups = "unit")
61+ public void should_record_adds_over_two_intervals() {
62+ rollingCount.add(2);
63+
64+ setTime(5, SECONDS); // 2nd interval
65+ rollingCount.add(3);
66+
67+ setTime(10, SECONDS);
68+ assertThat(rollingCount.get()).isEqualTo(5);
69+ }
70+
71+ @Test(groups = "unit")
72+ public void should_record_adds_separated_by_idle_intervals() {
73+ rollingCount.add(2);
74+
75+ setTime(10, SECONDS); // 3rd interval
76+ rollingCount.add(3);
77+
78+ setTime(15, SECONDS);
79+ assertThat(rollingCount.get()).isEqualTo(5);
80+ }
81+
82+ @Test(groups = "unit")
83+ public void should_rotate() {
84+ // 2 in [0,5[, then 1 every 5 seconds in [5,60[
85+ rollingCount.add(2);
86+ for (int i = 1; i < 12; i++) {
87+ setTime(i * 5, SECONDS);
88+ rollingCount.add(1);
89+ }
90+ setTime(60, SECONDS);
91+ // the previous minute is now [0,60[
92+ assertThat(rollingCount.get()).isEqualTo(13);
93+
94+ rollingCount.add(1);
95+ setTime(65, SECONDS);
96+ // the previous minute is now [5,65[, so the 2 events from [0,5[ should be forgotten
97+ assertThat(rollingCount.get()).isEqualTo(12);
98+ }
99+
100+ @Test(groups = "unit")
101+ public void should_rotate_with_idle_intervals() {
102+ // 1 every 5 seconds in [0,60[
103+ for (int i = 0; i < 12; i++) {
104+ setTime(i * 5, SECONDS);
105+ rollingCount.add(1);
106+ }
107+ // idle in [60, 75[, then 1 in [75,80[
108+ setTime(75, SECONDS);
109+ rollingCount.add(1);
110+
111+ setTime(80, SECONDS);
112+ // the last minute is [20,80[, with 1 every 5 seconds except during 15 seconds
113+ assertThat(rollingCount.get()).isEqualTo(9);
114+ }
115+
116+ @Test(groups = "unit")
117+ public void should_rotate_when_idle_for_full_period() {
118+ // 1 every 5 seconds in [0,60[
119+ for (int i = 0; i < 12; i++) {
120+ setTime(i * 5, SECONDS);
121+ rollingCount.add(1);
122+ }
123+ // idle for the next minute [60,120[, then 1 in [120,125[
124+ setTime(120, SECONDS);
125+ rollingCount.add(1);
126+
127+ setTime(125, SECONDS);
128+ assertThat(rollingCount.get()).isEqualTo(1);
129+ }
130+
131+ @Test(groups = "unit")
132+ public void should_rotate_when_idle_for_more_than_full_period() {
133+ // 1 every 5 seconds in [0,60[
134+ for (int i = 0; i < 12; i++) {
135+ setTime(i * 5, SECONDS);
136+ rollingCount.add(1);
137+ }
138+ // idle for the next minute and 5 seconds [60,125[, then 1 in [125,130[
139+ setTime(125, SECONDS);
140+ rollingCount.add(1);
141+
142+ setTime(130, SECONDS);
143+ assertThat(rollingCount.get()).isEqualTo(1);
144+ }
145+
146+ private void setTime(long time, TimeUnit unit) {
147+ when(clock.nanoTime()).thenReturn(NANOSECONDS.convert(time, unit));
148+ }
149+}
modified pom.xml +1 −1
@@ -230,7 +230,7 @@
230230 <!-- I can haz math in my javadoc (see http://zverovich.net/2012/01/14/beautiful-math-in-javadoc.html) -->
231231 <header>
232232 &lt;script type="text/javascript"
233- src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"&gt;&lt;/script&gt;
233+ src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"&gt;&lt;/script&gt;
234234 </header>
235235 <!-- open external links in a separate window -->
236236 <bottom>