-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathAwsXrayIdGenerator.java
55 lines (43 loc) · 1.73 KB
/
AwsXrayIdGenerator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.awsxray;
import io.opentelemetry.api.trace.TraceId;
import io.opentelemetry.sdk.trace.IdGenerator;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Generates tracing ids compatible with the AWS X-Ray tracing service. In the X-Ray system the
* first 32 bits of the trace id are the Unix epoch time in secords. Spans (AWS calls them segments)
* submitted with trace id timestamps outside of the last 30 days are rejected.
*
* @see <a
* href="https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids">Generating
* Trace IDs</a>
*/
public final class AwsXrayIdGenerator implements IdGenerator {
private static final AwsXrayIdGenerator INSTANCE = new AwsXrayIdGenerator();
private static final IdGenerator RANDOM_ID_GENERATOR = IdGenerator.random();
/** Returns a singleton instance of {@link AwsXrayIdGenerator}. */
public static AwsXrayIdGenerator getInstance() {
return INSTANCE;
}
@Override
public String generateSpanId() {
return RANDOM_ID_GENERATOR.generateSpanId();
}
@Override
public String generateTraceId() {
// hi - 4 bytes timestamp, 4 bytes random
// low - 8 bytes random.
// Since we include timestamp, impossible to be invalid.
Random random = ThreadLocalRandom.current();
long timestampSecs = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
long hiRandom = random.nextInt() & 0xFFFFFFFFL;
long lowRandom = random.nextLong();
return TraceId.fromLongs(timestampSecs << 32 | hiRandom, lowRandom);
}
private AwsXrayIdGenerator() {}
}