or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context.mdindex.mdplatform.mdpropagation.mdtiming.mdtrace-state.mdutilities.mdvalidation.md

trace-state.mddocs/

0

# Trace State

1

2

W3C TraceState specification-compliant key-value store for vendor-specific trace information with immutable operations and serialization support.

3

4

## Capabilities

5

6

### TraceState Class

7

8

Manages tracestate key-value pairs per W3C specification with immutable operations and proper serialization.

9

10

```typescript { .api }

11

/**

12

* TraceState manages key-value pairs for trace vendor information

13

* according to W3C Trace Context specification.

14

* Operations are immutable - methods return new TraceState instances.

15

*/

16

class TraceState implements api.TraceState {

17

/**

18

* Create a new TraceState instance

19

* @param rawTraceState - Optional tracestate header string to parse

20

*/

21

constructor(rawTraceState?: string);

22

23

/**

24

* Get value for a specific key

25

* @param key - Key to retrieve value for

26

* @returns Value for the key, or undefined if not found

27

*/

28

get(key: string): string | undefined;

29

30

/**

31

* Set a key-value pair (returns new TraceState instance)

32

* Modified keys are moved to the beginning of the list

33

* @param key - Key to set

34

* @param value - Value to set

35

* @returns New TraceState instance with the key-value pair

36

*/

37

set(key: string, value: string): TraceState;

38

39

/**

40

* Remove a key-value pair (returns new TraceState instance)

41

* @param key - Key to remove

42

* @returns New TraceState instance without the key

43

*/

44

unset(key: string): TraceState;

45

46

/**

47

* Serialize TraceState to header string format

48

* @returns Serialized tracestate string (key1=value1,key2=value2)

49

*/

50

serialize(): string;

51

}

52

```

53

54

**Usage Examples:**

55

56

```typescript

57

import { TraceState } from "@opentelemetry/core";

58

59

// Create TraceState from header string

60

const traceState = new TraceState("vendor1=value1,vendor2=value2");

61

62

// Get values

63

const vendor1Value = traceState.get("vendor1");

64

console.log(vendor1Value); // "value1"

65

66

// Set new values (immutable - returns new instance)

67

const updatedState = traceState

68

.set("vendor3", "value3")

69

.set("vendor1", "newvalue1"); // Updates existing key

70

71

// Original traceState is unchanged

72

console.log(traceState.get("vendor1")); // "value1"

73

console.log(updatedState.get("vendor1")); // "newvalue1"

74

75

// Remove keys

76

const cleanedState = updatedState.unset("vendor2");

77

78

// Serialize for HTTP header

79

const headerValue = cleanedState.serialize();

80

console.log(headerValue); // "vendor1=newvalue1,vendor3=value3"

81

82

// Create empty TraceState and build it up

83

let state = new TraceState();

84

state = state.set("tenant", "production");

85

state = state.set("service", "user-api");

86

state = state.set("version", "1.2.3");

87

88

console.log(state.serialize()); // "version=1.2.3,service=user-api,tenant=production"

89

```

90

91

### Trace Parent Parsing

92

93

Function to parse W3C traceparent header values into SpanContext objects.

94

95

```typescript { .api }

96

/**

97

* Parse traceparent header value into SpanContext

98

* @param traceParent - Traceparent header value in format: version-traceId-spanId-flags

99

* @returns SpanContext object or null if parsing fails

100

*/

101

function parseTraceParent(traceParent: string): SpanContext | null;

102

103

/**

104

* Traceparent header name constant

105

*/

106

const TRACE_PARENT_HEADER: string;

107

108

/**

109

* Tracestate header name constant

110

*/

111

const TRACE_STATE_HEADER: string;

112

```

113

114

**Usage Examples:**

115

116

```typescript

117

import { parseTraceParent, TRACE_PARENT_HEADER, TRACE_STATE_HEADER } from "@opentelemetry/core";

118

119

// Parse valid traceparent header

120

const traceParent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";

121

const spanContext = parseTraceParent(traceParent);

122

123

if (spanContext) {

124

console.log("Trace ID:", spanContext.traceId); // "4bf92f3577b34da6a3ce929d0e0e4736"

125

console.log("Span ID:", spanContext.spanId); // "00f067aa0ba902b7"

126

console.log("Trace Flags:", spanContext.traceFlags); // 1 (sampled)

127

console.log("Is Remote:", spanContext.isRemote); // undefined (set by propagator)

128

}

129

130

// Handle invalid traceparent

131

const invalidParent = "invalid-format";

132

const invalidContext = parseTraceParent(invalidParent);

133

console.log(invalidContext); // null

134

135

// Use constants for header names

136

const headers: Record<string, string> = {};

137

headers[TRACE_PARENT_HEADER] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";

138

headers[TRACE_STATE_HEADER] = "vendor1=value1,vendor2=value2";

139

140

// Process headers

141

const parsedContext = parseTraceParent(headers[TRACE_PARENT_HEADER]);

142

const traceState = new TraceState(headers[TRACE_STATE_HEADER]);

143

144

if (parsedContext && traceState) {

145

// Combine for complete span context

146

const completeContext = {

147

...parsedContext,

148

traceState: traceState

149

};

150

}

151

```

152

153

### Integration with OpenTelemetry API

154

155

TraceState integrates seamlessly with OpenTelemetry API's Context and span management.

156

157

**Usage Examples:**

158

159

```typescript

160

import { TraceState } from "@opentelemetry/core";

161

import { trace } from "@opentelemetry/api";

162

163

// Get current span and its trace state

164

const span = trace.getActiveSpan();

165

const spanContext = span?.spanContext();

166

const currentTraceState = spanContext?.traceState;

167

168

if (currentTraceState instanceof TraceState) {

169

// Add vendor-specific information

170

const enhancedState = currentTraceState

171

.set("my-vendor", "processing-user-request")

172

.set("datacenter", "us-west-2")

173

.set("canary", "10percent");

174

175

// Create new span context with enhanced trace state

176

const newSpanContext = {

177

...spanContext,

178

traceState: enhancedState

179

};

180

181

// Use in child span creation

182

const childSpan = trace.getTracer("my-service").startSpan("child-operation", {

183

parent: trace.setSpanContext(trace.context.active(), newSpanContext)

184

});

185

}

186

187

// Extract trace state from incoming request headers

188

function handleIncomingRequest(headers: Record<string, string>) {

189

const traceStateValue = headers['tracestate'];

190

191

if (traceStateValue) {

192

const traceState = new TraceState(traceStateValue);

193

194

// Check vendor-specific values

195

const canaryPercentage = traceState.get("canary");

196

const datacenter = traceState.get("datacenter");

197

198

if (canaryPercentage === "10percent") {

199

// Route to canary deployment

200

console.log("Routing to canary deployment");

201

}

202

203

if (datacenter === "us-west-2") {

204

// Use west coast database

205

console.log("Using west coast database");

206

}

207

}

208

}

209

```