Skip to content

Commit aba9b09

Browse files
committed
fix: Measure synchronizer deadlines with a monotonic clock
1 parent a700bff commit aba9b09

5 files changed

Lines changed: 134 additions & 36 deletions

File tree

‎lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv2DataSource.java‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,8 @@ private void runSynchronizers() {
355355
// Fallback and recovery apply only when another synchronizer can take over.
356356
boolean canFallBack = sourceManager.getAvailableSynchronizerCount() > 1;
357357
boolean canRecover = canFallBack && !sourceManager.isPrimeSynchronizer();
358-
Instant recoveryTime = canRecover ? Instant.now().plus(recoveryTimeout) : null;
359-
Instant fallbackTime = null;
358+
MonotonicTime recoveryTime = canRecover ? MonotonicTime.now().plus(recoveryTimeout) : null;
359+
MonotonicTime fallbackTime = null;
360360
// True once the loop has seen the deadline pass.
361361
boolean recoveryMet = false;
362362
boolean fallbackMet = false;
@@ -371,7 +371,7 @@ private void runSynchronizers() {
371371
}
372372

373373
// Wait for the next result, or for the next deadline that the loop has not seen pass.
374-
Instant wakeTime = earliest(
374+
MonotonicTime wakeTime = earliest(
375375
recoveryMet ? null : recoveryTime,
376376
fallbackMet ? null : fallbackTime,
377377
sourceManager.getEarliestUnparkTime(),
@@ -407,7 +407,7 @@ private void runSynchronizers() {
407407
status.getState());
408408
// The fallback timeout runs from the first interruption.
409409
if (canFallBack && fallbackTime == null) {
410-
fallbackTime = Instant.now().plus(fallbackTimeout);
410+
fallbackTime = MonotonicTime.now().plus(fallbackTimeout);
411411
}
412412
dataSourceUpdates.updateStatus(
413413
DataSourceStatusProvider.State.INTERRUPTED,
@@ -451,7 +451,7 @@ private void runSynchronizers() {
451451
if (sourceManager.isCurrentSynchronizerFDv1Fallback()) {
452452
// A directive during the FDv1 fallback replaces its TTL, and FDv1 keeps running.
453453
Duration fallbackTTL = jittered(defaultFDv1FallbackTTL);
454-
sourceManager.startFDv1Fallback(Instant.now().plus(fallbackTTL));
454+
sourceManager.startFDv1Fallback(MonotonicTime.now().plus(fallbackTTL));
455455
logger.info("FDv2 retry scheduled in {}s.", fallbackTTL.getSeconds());
456456
} else {
457457
// A directive to fall back to FDv1 ends the run of an FDv2 synchronizer.
@@ -470,7 +470,7 @@ private void runSynchronizers() {
470470
}
471471

472472
// Check every deadline against the current time.
473-
Instant now = Instant.now();
473+
MonotonicTime now = MonotonicTime.now();
474474
sourceManager.unparkExpiredSynchronizers();
475475
if (sourceManager.endFDv1FallbackIfExpired()) {
476476
logger.info("Fallback TTL elapsed, restarting FDv2 data sources.");
@@ -579,14 +579,13 @@ private boolean waitUnlessClosed(Duration duration) {
579579
* @return true if the future completed
580580
* @throws InterruptedException if the thread is interrupted while waiting
581581
*/
582-
private boolean awaitUntil(CompletableFuture<?> future, Instant time) throws InterruptedException {
582+
private boolean awaitUntil(CompletableFuture<?> future, MonotonicTime time) throws InterruptedException {
583583
CompletableFuture<Object> futureOrClosed = CompletableFuture.anyOf(future, closeLatch.newFuture());
584584
try {
585585
if (time == null) {
586586
futureOrClosed.get();
587587
} else {
588-
futureOrClosed.get(
589-
Math.max(0, Duration.between(Instant.now(), time).toNanos()), TimeUnit.NANOSECONDS);
588+
futureOrClosed.get(Math.max(0, MonotonicTime.now().until(time).toNanos()), TimeUnit.NANOSECONDS);
590589
}
591590
} catch (TimeoutException e) {
592591
return false;
@@ -602,9 +601,9 @@ private boolean awaitUntil(CompletableFuture<?> future, Instant time) throws Int
602601
* @param times the times, any of which may be null
603602
* @return the earliest time, or null if every time is null
604603
*/
605-
private static Instant earliest(Instant... times) {
606-
Instant earliest = null;
607-
for (Instant time : times) {
604+
private static MonotonicTime earliest(MonotonicTime... times) {
605+
MonotonicTime earliest = null;
606+
for (MonotonicTime time : times) {
608607
if (time != null && (earliest == null || time.isBefore(earliest))) {
609608
earliest = time;
610609
}
@@ -643,7 +642,7 @@ private Duration parkDelay(int parkCount) {
643642
*/
644643
private void parkActiveSynchronizer(String synchronizerName, DataSourceStatusProvider.ErrorInfo errorInfo) {
645644
Duration parkDelay = parkDelay(sourceManager.incrementCurrentSynchronizerParkCount());
646-
sourceManager.parkCurrentSynchronizer(Instant.now().plus(parkDelay));
645+
sourceManager.parkCurrentSynchronizer(MonotonicTime.now().plus(parkDelay));
647646
logger.warn(
648647
"{} is backing off for {}s after an unexpected error ({}).",
649648
synchronizerName != null ? "Synchronizer '" + synchronizerName + "'"
@@ -660,7 +659,7 @@ private void parkActiveSynchronizer(String synchronizerName, DataSourceStatusPro
660659
* @param errorInfo the error that came with the directive, or null
661660
*/
662661
private void fallBackToFDv1(Duration fallbackTTL, DataSourceStatusProvider.ErrorInfo errorInfo) {
663-
sourceManager.startFDv1Fallback(Instant.now().plus(fallbackTTL));
662+
sourceManager.startFDv1Fallback(MonotonicTime.now().plus(fallbackTTL));
664663
if (sourceManager.hasFDv1Fallback()) {
665664
logger.info("Falling back to FDv1 fallback synchronizer.");
666665
} else {
@@ -703,23 +702,24 @@ private Synchronizer buildNextAvailableSynchronizer() {
703702
return synchronizer;
704703
}
705704

706-
Instant earliestUnparkTime = sourceManager.getEarliestUnparkTime();
707-
Instant fallbackEndTime = sourceManager.getFDv1FallbackEndTime();
705+
MonotonicTime earliestUnparkTime = sourceManager.getEarliestUnparkTime();
706+
MonotonicTime fallbackEndTime = sourceManager.getFDv1FallbackEndTime();
708707
Duration wait;
709708
if (earliestUnparkTime == null && fallbackEndTime == null) {
710709
// This should never happen.
711710
wait = parkInitialDelay;
712711
logger.error("No synchronizer can be started; checking again in {}s.", wait.getSeconds());
713712
} else if (earliestUnparkTime == null) {
714-
wait = Duration.between(Instant.now(), fallbackEndTime);
713+
wait = MonotonicTime.now().until(fallbackEndTime);
715714
logger.warn("No synchronizer is available until the FDv1 fallback ends in {}s.",
716715
Math.max(0, wait.getSeconds()));
717716
} else if (fallbackEndTime == null) {
718-
wait = Duration.between(Instant.now(), earliestUnparkTime);
717+
wait = MonotonicTime.now().until(earliestUnparkTime);
719718
logger.warn("All synchronizers are backing off for at least {}s.", Math.max(0, wait.getSeconds()));
720719
} else {
721-
Instant earliest = fallbackEndTime.isBefore(earliestUnparkTime) ? fallbackEndTime : earliestUnparkTime;
722-
wait = Duration.between(Instant.now(), earliest);
720+
MonotonicTime earliest =
721+
fallbackEndTime.isBefore(earliestUnparkTime) ? fallbackEndTime : earliestUnparkTime;
722+
wait = MonotonicTime.now().until(earliest);
723723
logger.warn("All synchronizers are backing off for at least {}s.", Math.max(0, wait.getSeconds()));
724724
}
725725
// No synchronizer is running until the wait ends.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.launchdarkly.sdk.server;
2+
3+
import java.time.Duration;
4+
5+
/**
6+
* A point in time on the monotonic clock of {@link System#nanoTime()}. Changes to the system clock do not affect it.
7+
* The value has no meaning as a date, so it is only useful to compare with other {@code MonotonicTime} values.
8+
*/
9+
final class MonotonicTime {
10+
private final long nanos;
11+
12+
private MonotonicTime(long nanos) {
13+
this.nanos = nanos;
14+
}
15+
16+
/**
17+
* The current time.
18+
*
19+
* @return the current time
20+
*/
21+
static MonotonicTime now() {
22+
return new MonotonicTime(System.nanoTime());
23+
}
24+
25+
/**
26+
* A time with the given value of {@link System#nanoTime()}. Visible for testing.
27+
*
28+
* @param nanos the value of {@link System#nanoTime()}
29+
* @return the time
30+
*/
31+
static MonotonicTime ofNanos(long nanos) {
32+
return new MonotonicTime(nanos);
33+
}
34+
35+
/**
36+
* The time after the given duration.
37+
*
38+
* @param duration the duration to add
39+
* @return the later time
40+
*/
41+
MonotonicTime plus(Duration duration) {
42+
return new MonotonicTime(nanos + duration.toNanos());
43+
}
44+
45+
/**
46+
* True if this time is before the other time.
47+
*
48+
* @param other the other time
49+
* @return true if this time is before the other time
50+
*/
51+
boolean isBefore(MonotonicTime other) {
52+
// The nanosecond count can overflow, so compare the difference instead of the counts.
53+
return nanos - other.nanos < 0;
54+
}
55+
56+
/**
57+
* The duration from this time until the other time. It is negative if the other time is before this time.
58+
*
59+
* @param other the other time
60+
* @return the duration until the other time
61+
*/
62+
Duration until(MonotonicTime other) {
63+
return Duration.ofNanos(other.nanos - nanos);
64+
}
65+
}

‎lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/SourceManager.java‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import java.io.Closeable;
66
import java.io.IOException;
7-
import java.time.Instant;
87
import java.util.List;
98

109
/**
@@ -41,7 +40,7 @@ class SourceManager implements Closeable {
4140
* The time at which the fallback to FDv1 ends, or null if the SDK is not falling back to FDv1. Accessed only
4241
* under activeSourceLock.
4342
*/
44-
private Instant fdv1FallbackEndTime;
43+
private MonotonicTime fdv1FallbackEndTime;
4544

4645
public SourceManager(List<SynchronizerFactoryWithState> synchronizers, List<FDv2DataSource.DataSourceFactory<Initializer>> initializers) {
4746
this.synchronizers = synchronizers;
@@ -81,7 +80,7 @@ public boolean hasFDv2Synchronizers() {
8180
*
8281
* @param endTime the time at which the fallback to FDv1 ends
8382
*/
84-
public void startFDv1Fallback(Instant endTime) {
83+
public void startFDv1Fallback(MonotonicTime endTime) {
8584
synchronized (activeSourceLock) {
8685
fdv1FallbackEndTime = endTime;
8786
for (SynchronizerFactoryWithState factory : synchronizers) {
@@ -99,7 +98,7 @@ public void startFDv1Fallback(Instant endTime) {
9998
*/
10099
public void unparkExpiredSynchronizers() {
101100
synchronized (activeSourceLock) {
102-
Instant now = Instant.now();
101+
MonotonicTime now = MonotonicTime.now();
103102
for (SynchronizerFactoryWithState factory : synchronizers) {
104103
factory.unparkIfExpired(now);
105104
}
@@ -111,7 +110,7 @@ public void unparkExpiredSynchronizers() {
111110
*
112111
* @return the end time, or null if the SDK is not falling back to FDv1
113112
*/
114-
public Instant getFDv1FallbackEndTime() {
113+
public MonotonicTime getFDv1FallbackEndTime() {
115114
synchronized (activeSourceLock) {
116115
return fdv1FallbackEndTime;
117116
}
@@ -125,7 +124,7 @@ public Instant getFDv1FallbackEndTime() {
125124
*/
126125
public boolean endFDv1FallbackIfExpired() {
127126
synchronized (activeSourceLock) {
128-
if (fdv1FallbackEndTime == null || Instant.now().isBefore(fdv1FallbackEndTime)) {
127+
if (fdv1FallbackEndTime == null || MonotonicTime.now().isBefore(fdv1FallbackEndTime)) {
129128
return false;
130129
}
131130
fdv1FallbackEndTime = null;
@@ -259,7 +258,7 @@ public void resetCurrentSynchronizerParkCount() {
259258
}
260259
}
261260

262-
public void parkCurrentSynchronizer(Instant unparkTime) {
261+
public void parkCurrentSynchronizer(MonotonicTime unparkTime) {
263262
synchronized (activeSourceLock) {
264263
currentSynchronizerFactory.park(unparkTime);
265264
}
@@ -270,11 +269,11 @@ public void parkCurrentSynchronizer(Instant unparkTime) {
270269
*
271270
* @return the earliest unpark time, or null if no available synchronizer is parked
272271
*/
273-
public Instant getEarliestUnparkTime() {
272+
public MonotonicTime getEarliestUnparkTime() {
274273
synchronized (activeSourceLock) {
275-
Instant earliest = null;
274+
MonotonicTime earliest = null;
276275
for (SynchronizerFactoryWithState factory : synchronizers) {
277-
Instant unparkTime = factory.getUnparkTime();
276+
MonotonicTime unparkTime = factory.getUnparkTime();
278277
if (factory.getState() == SynchronizerFactoryWithState.State.Available
279278
&& unparkTime != null
280279
&& (earliest == null || unparkTime.isBefore(earliest))) {

‎lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/SynchronizerFactoryWithState.java‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
import com.launchdarkly.sdk.server.datasources.Synchronizer;
44

5-
import java.time.Instant;
6-
75
class SynchronizerFactoryWithState {
86
public enum State {
97
/**
@@ -31,7 +29,7 @@ public enum State {
3129
/**
3230
* The time at which the synchronizer stops being parked, or null if it is not parked.
3331
*/
34-
private Instant unparkTime = null;
32+
private MonotonicTime unparkTime = null;
3533

3634

3735
public SynchronizerFactoryWithState(FDv2DataSource.DataSourceFactory<Synchronizer> factory) {
@@ -77,7 +75,7 @@ public void resetParkCount() {
7775
parkCount = 0;
7876
}
7977

80-
public void park(Instant unparkTime) {
78+
public void park(MonotonicTime unparkTime) {
8179
this.unparkTime = unparkTime;
8280
}
8381

@@ -86,7 +84,7 @@ public void park(Instant unparkTime) {
8684
*
8785
* @return the unpark time, or null if the synchronizer is not parked
8886
*/
89-
public Instant getUnparkTime() {
87+
public MonotonicTime getUnparkTime() {
9088
return unparkTime;
9189
}
9290

@@ -95,7 +93,7 @@ public Instant getUnparkTime() {
9593
*
9694
* @param now the current time
9795
*/
98-
public void unparkIfExpired(Instant now) {
96+
public void unparkIfExpired(MonotonicTime now) {
9997
if (unparkTime != null && !now.isBefore(unparkTime)) {
10098
unparkTime = null;
10199
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.launchdarkly.sdk.server;
2+
3+
import org.junit.Test;
4+
5+
import java.time.Duration;
6+
7+
import static org.junit.Assert.assertEquals;
8+
import static org.junit.Assert.assertFalse;
9+
import static org.junit.Assert.assertTrue;
10+
11+
@SuppressWarnings("javadoc")
12+
public class MonotonicTimeTest {
13+
@Test
14+
public void timeAfterOverflowIsAfterTimeBeforeOverflow() {
15+
MonotonicTime beforeOverflow = MonotonicTime.ofNanos(Long.MAX_VALUE);
16+
17+
// Move one second past the point where the nanosecond count overflows.
18+
MonotonicTime afterOverflow = beforeOverflow.plus(Duration.ofSeconds(1));
19+
20+
// The later time compares as later.
21+
assertTrue(beforeOverflow.isBefore(afterOverflow));
22+
assertFalse(afterOverflow.isBefore(beforeOverflow));
23+
}
24+
25+
@Test
26+
public void untilMeasuresDurationAcrossOverflow() {
27+
MonotonicTime beforeOverflow = MonotonicTime.ofNanos(Long.MAX_VALUE);
28+
29+
// Move one second past the point where the nanosecond count overflows.
30+
MonotonicTime afterOverflow = beforeOverflow.plus(Duration.ofSeconds(1));
31+
32+
// The duration is one second forward, and negative one second back.
33+
assertEquals(Duration.ofSeconds(1), beforeOverflow.until(afterOverflow));
34+
assertEquals(Duration.ofSeconds(-1), afterOverflow.until(beforeOverflow));
35+
}
36+
}

0 commit comments

Comments
 (0)