Skip to content

Commit d1adfe2

Browse files
committed
feat(time): Add Timestamp, Timing and EpochClock (JAVA-572)
SentryDate is asked to be four things at once: an epoch instant to serialize, one endpoint of a monotonic interval, a carrier of a hidden System.nanoTime() reading, and an opaque foreign timestamp. Nothing in the type separates them, so the guarantees are decided by the runtime class of both operands -- SentryNanotimeDate.diff() is monotonic only when the other date is also a SentryNanotimeDate, and falls back to subtracting two wall-clock readings otherwise, silently. These three types split that apart along the line that matters, which is whether a value means anything outside this process: Timestamp an epoch instant. Serialize it, compare it against another machine's value -- but it offers no arithmetic between instants, because subtracting two wall-clock readings gives a duration the device's clock can lengthen or reverse. Timing a Timestamp anchor plus a Stopwatch, captured together. end() is the anchor plus the measured duration, which is what the span protocol needs: it carries two instants and no duration field, so the server subtracts them. EpochClock now() to stamp a moment, start() to measure something. A call site has to say which it is doing, and neither result can do the other's job. Timing composes Stopwatch rather than repeating it, so there is one implementation of a monotonic delta. Both measure on MonotonicClock, which counts deep sleep: an interval that excluded it, paired with wall-clock anchors, would produce an end() that falls further behind real time the longer the device sleeps. Nothing calls any of it yet.
1 parent 271cf66 commit d1adfe2

9 files changed

Lines changed: 372 additions & 0 deletions

File tree

‎sentry/api/sentry.api‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3707,6 +3707,7 @@ public class io/sentry/SentryOptions {
37073707
public fun getEnvelopeDiskCache ()Lio/sentry/cache/IEnvelopeCache;
37083708
public fun getEnvelopeReader ()Lio/sentry/IEnvelopeReader;
37093709
public fun getEnvironment ()Ljava/lang/String;
3710+
public fun getEpochClock ()Lio/sentry/time/EpochClock;
37103711
public fun getEventProcessors ()Ljava/util/List;
37113712
public fun getExecutorService ()Lio/sentry/ISentryExecutorService;
37123713
public fun getExperimental ()Lio/sentry/ExperimentalOptions;
@@ -7606,6 +7607,11 @@ public final class io/sentry/time/Deadline {
76067607
public fun remaining (Ljava/util/concurrent/TimeUnit;)J
76077608
}
76087609

7610+
public abstract interface class io/sentry/time/EpochClock {
7611+
public abstract fun now ()Lio/sentry/time/Timestamp;
7612+
public abstract fun start ()Lio/sentry/time/Timing;
7613+
}
7614+
76097615
public final class io/sentry/time/JavaMonotonicClock : io/sentry/time/MonotonicClock {
76107616
public static fun getInstance ()Lio/sentry/time/MonotonicClock;
76117617
public fun tickNanos ()J
@@ -7621,6 +7627,22 @@ public final class io/sentry/time/Stopwatch {
76217627
public static fun started (Lio/sentry/time/MonotonicClock;)Lio/sentry/time/Stopwatch;
76227628
}
76237629

7630+
public final class io/sentry/time/Timestamp {
7631+
public fun epochNanos ()J
7632+
public fun equals (Ljava/lang/Object;)Z
7633+
public fun hashCode ()I
7634+
public static fun ofEpochNanos (J)Lio/sentry/time/Timestamp;
7635+
public fun plusNanos (J)Lio/sentry/time/Timestamp;
7636+
public fun toString ()Ljava/lang/String;
7637+
}
7638+
7639+
public final class io/sentry/time/Timing {
7640+
public fun durationNanos ()J
7641+
public fun end ()Lio/sentry/time/Timestamp;
7642+
public fun start ()Lio/sentry/time/Timestamp;
7643+
public static fun started (Lio/sentry/time/Timestamp;Lio/sentry/time/MonotonicClock;)Lio/sentry/time/Timing;
7644+
}
7645+
76247646
public final class io/sentry/transport/AsyncHttpTransport : io/sentry/transport/ITransport {
76257647
public fun <init> (Lio/sentry/SentryOptions;Lio/sentry/transport/RateLimiter;Lio/sentry/transport/ITransportGate;Lio/sentry/RequestDetails;)V
76267648
public fun <init> (Lio/sentry/transport/QueuedThreadPoolExecutor;Lio/sentry/SentryOptions;Lio/sentry/transport/RateLimiter;Lio/sentry/transport/ITransportGate;Lio/sentry/transport/HttpConnection;)V
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package io.sentry;
2+
3+
import io.sentry.time.EpochClock;
4+
import io.sentry.time.MonotonicClock;
5+
import io.sentry.time.Timestamp;
6+
import io.sentry.time.Timing;
7+
import org.jetbrains.annotations.ApiStatus;
8+
import org.jetbrains.annotations.NotNull;
9+
10+
/**
11+
* An {@link EpochClock} that takes its anchor from the configured {@link SentryDateProvider} and
12+
* measures durations on the monotonic clock.
13+
*
14+
* <p>The bridge runs in this direction on purpose. Reimplementing {@link SentryDateProvider} on top
15+
* of {@link EpochClock} would change serialized values today: a {@link SentryNanotimeDate} carries
16+
* {@link System#nanoTime()} as its tick, {@code SpanFrameMetricsCollector} and the SQLite driver
17+
* spans compare that tick against {@code System.nanoTime()} directly, and a {@link Timing} measures
18+
* on the monotonic clock instead, which counts deep sleep. Swapping the tick source would change
19+
* span durations across deep sleep and break those two comparisons, so it waits for the next major.
20+
*
21+
* <p>Reading through the options rather than capturing the provider keeps {@link
22+
* SentryOptions#setDateProvider} working after the clock is built.
23+
*/
24+
@ApiStatus.Internal
25+
final class DateProviderEpochClock implements EpochClock {
26+
27+
private final @NotNull SentryOptions options;
28+
29+
DateProviderEpochClock(final @NotNull SentryOptions options) {
30+
this.options = options;
31+
}
32+
33+
@Override
34+
public @NotNull Timestamp now() {
35+
return Timestamp.ofEpochNanos(options.getDateProvider().now().nanoTimestamp());
36+
}
37+
38+
@Override
39+
public @NotNull Timing start() {
40+
final @NotNull MonotonicClock clock = options.getMonotonicClock();
41+
return Timing.started(now(), clock);
42+
}
43+
}

‎sentry/src/main/java/io/sentry/SentryOptions.java‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import io.sentry.metrics.IMetricsBatchProcessorFactory;
2222
import io.sentry.protocol.SdkVersion;
2323
import io.sentry.protocol.SentryTransaction;
24+
import io.sentry.time.EpochClock;
2425
import io.sentry.time.JavaMonotonicClock;
2526
import io.sentry.time.MonotonicClock;
2627
import io.sentry.transport.ITransport;
@@ -527,6 +528,9 @@ public class SentryOptions {
527528
private final @NotNull LazyEvaluator<SentryDateProvider> dateProvider =
528529
new LazyEvaluator<>(() -> new SentryAutoDateProvider());
529530

531+
private final @NotNull LazyEvaluator<EpochClock> epochClock =
532+
new LazyEvaluator<>(() -> new DateProviderEpochClock(this));
533+
530534
private final @NotNull List<IPerformanceCollector> performanceCollectors = new ArrayList<>();
531535

532536
/** Performance collector that collect performance stats while transactions run. */
@@ -3061,6 +3065,18 @@ public void setDateProvider(final @NotNull SentryDateProvider dateProvider) {
30613065
this.dateProvider.setValue(dateProvider);
30623066
}
30633067

3068+
/**
3069+
* Returns the wall clock, for stamping an instant that will be serialized or for starting
3070+
* something whose duration will be reported.
3071+
*
3072+
* <p>Backed by {@link #getDateProvider()}, so a provider set through {@link #setDateProvider} is
3073+
* honoured here too.
3074+
*/
3075+
@ApiStatus.Internal
3076+
public @NotNull EpochClock getEpochClock() {
3077+
return epochClock.getValue();
3078+
}
3079+
30643080
/**
30653081
* Returns the clock used to measure elapsed time, such as rate-limit windows, cache expiry and
30663082
* ANR thresholds.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
6+
/**
7+
* The source of wall-clock time.
8+
*
9+
* <p>Two entry points, because there are two questions and they need different answers. {@link
10+
* #now()} stamps a moment — an event, a breadcrumb, a session — and hands back an instant with no
11+
* arithmetic on it. {@link #start()} begins something whose duration will be reported, and hands
12+
* back a {@link Timing} that measures on a monotonic clock.
13+
*
14+
* <p>The split is the point. A call site has to say which it is doing, and neither result can do
15+
* the other's job, so a duration cannot quietly end up being the difference between two wall-clock
16+
* readings.
17+
*/
18+
@ApiStatus.Internal
19+
public interface EpochClock {
20+
21+
/** The current instant. Serialize it; do not subtract it from another one. */
22+
@NotNull
23+
Timestamp now();
24+
25+
/** Starts measuring now. */
26+
@NotNull
27+
Timing start();
28+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
import org.jetbrains.annotations.Nullable;
6+
7+
/**
8+
* An instant on the wall clock, as nanoseconds since the Unix epoch.
9+
*
10+
* <p>The counterpart to {@link MonotonicClock}, and its opposite in every respect that matters: a
11+
* timestamp is anchored to an epoch, so it is meaningful outside this process — it can be
12+
* serialized, stored, and compared against a value produced by another machine. A tick can do none
13+
* of those things.
14+
*
15+
* <p>What a timestamp deliberately cannot do is measure an interval. Subtracting two wall-clock
16+
* readings gives a duration that the device's clock can lengthen, shorten or make negative, so this
17+
* type offers no arithmetic between instants. Pair it with a {@link Stopwatch} — which is what
18+
* {@link Timing} is — and the duration comes from a monotonic clock instead.
19+
*
20+
* <p>Nanoseconds since the epoch overflow a long in the year 2262.
21+
*/
22+
@ApiStatus.Internal
23+
public final class Timestamp {
24+
25+
private final long epochNanos;
26+
27+
private Timestamp(final long epochNanos) {
28+
this.epochNanos = epochNanos;
29+
}
30+
31+
public static @NotNull Timestamp ofEpochNanos(final long epochNanos) {
32+
return new Timestamp(epochNanos);
33+
}
34+
35+
public long epochNanos() {
36+
return epochNanos;
37+
}
38+
39+
/** This instant moved forward by {@code nanos}, for deriving an end from a measured duration. */
40+
public @NotNull Timestamp plusNanos(final long nanos) {
41+
return new Timestamp(epochNanos + nanos);
42+
}
43+
44+
@Override
45+
public boolean equals(final @Nullable Object other) {
46+
if (this == other) {
47+
return true;
48+
}
49+
if (!(other instanceof Timestamp)) {
50+
return false;
51+
}
52+
return epochNanos == ((Timestamp) other).epochNanos;
53+
}
54+
55+
@Override
56+
public int hashCode() {
57+
return (int) (epochNanos ^ (epochNanos >>> 32));
58+
}
59+
60+
@Override
61+
public @NotNull String toString() {
62+
return "Timestamp{epochNanos=" + epochNanos + '}';
63+
}
64+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
6+
/**
7+
* Something whose start instant is reported and whose duration is measured.
8+
*
9+
* <p>A span, a profile or a replay segment needs two facts that no single clock can supply: when it
10+
* began, in epoch terms, so it can be lined up with events from other systems; and how long it
11+
* took, measured on a clock that cannot jump. So this holds both — a {@link Timestamp} anchor and a
12+
* {@link Stopwatch} — captured together, and derives the end from them.
13+
*
14+
* <p>That derivation is the reason the type exists. The span protocol carries a start and an end
15+
* instant and no duration, so the server subtracts them; emitting a separately-read wall-clock end
16+
* would throw away the monotonic measurement and report whatever the device's clock did in between.
17+
* {@link #end()} is therefore the anchor plus the measured duration, computed in one place instead
18+
* of at every call site.
19+
*/
20+
@ApiStatus.Internal
21+
public final class Timing {
22+
23+
private final @NotNull Timestamp start;
24+
private final @NotNull Stopwatch stopwatch;
25+
26+
private Timing(final @NotNull Timestamp start, final @NotNull Stopwatch stopwatch) {
27+
this.start = start;
28+
this.stopwatch = stopwatch;
29+
}
30+
31+
/**
32+
* Starts measuring, anchored at {@code start}.
33+
*
34+
* <p>{@link MonotonicClock} counts deep sleep, which is what pairing with a wall-clock anchor
35+
* requires: an interval that excluded it would produce an {@link #end()} that falls further
36+
* behind real time the longer the device sleeps.
37+
*/
38+
public static @NotNull Timing started(
39+
final @NotNull Timestamp start, final @NotNull MonotonicClock clock) {
40+
return new Timing(start, Stopwatch.started(clock));
41+
}
42+
43+
public @NotNull Timestamp start() {
44+
return start;
45+
}
46+
47+
public long durationNanos() {
48+
return stopwatch.elapsedNanos();
49+
}
50+
51+
/** The anchor plus the duration measured so far. */
52+
public @NotNull Timestamp end() {
53+
return start.plusNanos(durationNanos());
54+
}
55+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package io.sentry
2+
3+
import io.sentry.time.MonotonicClock
4+
import io.sentry.time.TestMonotonicClock
5+
import java.util.concurrent.TimeUnit.MILLISECONDS
6+
import java.util.concurrent.TimeUnit.SECONDS
7+
import kotlin.test.Test
8+
import kotlin.test.assertEquals
9+
10+
class DateProviderEpochClockTest {
11+
private val fixedNanos = SECONDS.toNanos(1_700_000_000)
12+
13+
private fun options(nanos: Long = fixedNanos) =
14+
SentryOptions().apply { setDateProvider { SentryLongDate(nanos) } }
15+
16+
@Test
17+
fun `now reads the configured date provider`() {
18+
assertEquals(fixedNanos, options().epochClock.now().epochNanos())
19+
}
20+
21+
@Test
22+
fun `now follows a date provider set after the clock was built`() {
23+
val options = options()
24+
val clock = options.epochClock
25+
26+
options.setDateProvider { SentryLongDate(1) }
27+
28+
assertEquals(1, clock.now().epochNanos())
29+
}
30+
31+
@Test
32+
fun `start anchors on the date provider and measures on the elapsed real-time clock`() {
33+
val ticker = TestMonotonicClock()
34+
// the elapsed-real-time clock is overridden rather than set, the way SentryAndroidOptions does
35+
val options =
36+
object : SentryOptions() {
37+
override fun getMonotonicClock(): MonotonicClock = ticker
38+
}
39+
options.setDateProvider { SentryLongDate(fixedNanos) }
40+
41+
val timing = options.epochClock.start()
42+
ticker.advance(120, MILLISECONDS)
43+
44+
assertEquals(fixedNanos, timing.start().epochNanos())
45+
assertEquals(MILLISECONDS.toNanos(120), timing.durationNanos())
46+
assertEquals(fixedNanos + MILLISECONDS.toNanos(120), timing.end().epochNanos())
47+
}
48+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package io.sentry.time
2+
3+
import java.util.concurrent.TimeUnit.MILLISECONDS
4+
import kotlin.test.Test
5+
import kotlin.test.assertEquals
6+
import kotlin.test.assertNotEquals
7+
8+
class TimestampTest {
9+
@Test
10+
fun `keeps the epoch value it was given`() {
11+
assertEquals(
12+
1_700_000_000_000_000_000,
13+
Timestamp.ofEpochNanos(1_700_000_000_000_000_000).epochNanos(),
14+
)
15+
}
16+
17+
@Test
18+
fun `moves forward without mutating the original`() {
19+
val start = Timestamp.ofEpochNanos(1_000)
20+
val later = start.plusNanos(MILLISECONDS.toNanos(5))
21+
22+
assertEquals(1_000, start.epochNanos())
23+
assertEquals(1_000 + MILLISECONDS.toNanos(5), later.epochNanos())
24+
}
25+
26+
@Test
27+
fun `compares by value`() {
28+
assertEquals(Timestamp.ofEpochNanos(42), Timestamp.ofEpochNanos(42))
29+
assertEquals(Timestamp.ofEpochNanos(42).hashCode(), Timestamp.ofEpochNanos(42).hashCode())
30+
assertNotEquals(Timestamp.ofEpochNanos(42), Timestamp.ofEpochNanos(43))
31+
}
32+
}

0 commit comments

Comments
 (0)