forked from elastic/apm-agent-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracestate.js
More file actions
360 lines (311 loc) · 10.9 KB
/
tracestate.js
File metadata and controls
360 lines (311 loc) · 10.9 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
'use strict'
// Indirect usage of the singleton `Agent` to log.
function getLogger () {
return require('../..').logger
}
/**
* Class for Managing Tracestate
*
* Class that creates objects for managing trace state.
* This class is capable of parsing both tracestate strings
* and tracestate binary representations, allowing clients
* to get and set values in a single list-member/namespace
* while preserving values in the other namespaces.
*
* Capable of working with either the binary of string
* formatted tracestate values.
*
* Usage:
* const tracestate = TraceState.fromStringFormatString(headerTracestate, 'es')
* tracestate.setValue('s',1)
* const newHeader = tracestate.toW3cString()
*/
class TraceState {
constructor (sourceBuffer, listMemberNamespace = 'es', defaultValues = {}) {
if (!this._validateVendorKey(listMemberNamespace)) {
throw new Error('Vendor namespace failed validation.')
}
// buffer representation of the trace state string.
// The initial value of this.buffer will keep the
// values set in the listMemberNamespace list-member,
// but as soon as an initial value is set (via setValue)
// then the listMemberNamespace values will be removed
// from this.buffer and stored in the this.values. While
// slightly more complicated, this allows us to maintain
// the order of list-member keys in an un-mutated tracestate
// string, per the W3C spec
this.buffer = sourceBuffer
this.listMemberNamespace = listMemberNamespace
// values for our namespace, set via setValue to
// ensure names conform
this.values = {}
for (const key in defaultValues) {
const value = defaultValues[key]
this.setValue(key, value)
}
}
setValue (key, value) {
const strKey = String(key)
const strValue = String(value)
if (!this._validateElasicKeyAndValue(strKey, strValue)) {
getLogger().trace('could not set tracestate key, invalid characters detected')
return false
}
const isFirstSet = (Object.keys(this.values).length === 0)
const oldValue = this.values[strKey]
this.values[strKey] = value
// per: https://github.com/elastic/apm/blob/d5b2c87326548befcfec6731713932a00e430b99/specs/agents/tracing-distributed-tracing.md
// If adding another key/value pair to the es entry would exceed the limit
// of 256 chars, that key/value pair MUST be ignored by agents.
// The key/value and entry separators : and ; have to be considered as well.
const serializedValue = this._serializeValues(this.values)
if (serializedValue.length > 256 && (typeof oldValue === 'undefined')) {
delete this.values[strKey]
return false
}
if (serializedValue.length > 256 && (typeof oldValue !== 'undefined')) {
this.values[strKey] = oldValue
return false
}
// the first time we set a value, extract the mutable values from the
// buffer and set this.values appropriately
if (isFirstSet && Object.keys(this.values).length === 1) {
const [buffer, values] = TraceState._removeMemberNamespaceFromBuffer(
this.buffer,
this.listMemberNamespace
)
this.buffer = buffer
this.values = values
values[strKey] = value
}
return true
}
getValue (keyToGet) {
const allValues = this.toObject()
const rawValue = allValues[this.listMemberNamespace]
if (!rawValue) {
return rawValue
}
const values = TraceState._parseValues(rawValue)
return values[keyToGet]
}
toHexString () {
const newBuffer = Buffer.alloc(this.buffer.length)
let newBufferOffset = 0
for (let i = 0; i < this.buffer.length; i++) {
const byte = this.buffer[i]
if (byte === 0) {
const indexOfKeyLength = i + 1
const indexOfKey = i + 2
const lengthKey = this.buffer[indexOfKeyLength]
const indexOfValueLength = indexOfKey + lengthKey
const indexOfValue = indexOfValueLength + 1
const lengthValue = this.buffer[indexOfValueLength]
const key = this.buffer.slice(indexOfKey, indexOfKey + lengthKey).toString()
// bail out if this is our mutable namespace
if (key === this.listMemberNamespace) { continue }
// if this is not our key copy from the `0` byte to the end of the value
this.buffer.copy(newBuffer, newBufferOffset, i, indexOfValue + lengthValue)
newBufferOffset += (indexOfValue + lengthValue)
// skip ahead to first byte after end of value
i = indexOfValue + lengthValue - 1
continue
}
}
// now serialize the internal representation
const ourBytes = []
if (Object.keys(this.values).length > 0) {
// the zero byte
ourBytes.push(0)
// the length of the vendor namespace
ourBytes.push(this.listMemberNamespace.length)
// the chars of the vendor namespace
for (let i = 0; i < this.listMemberNamespace.length; i++) {
ourBytes.push(this.listMemberNamespace.charCodeAt(i))
}
// add the length of the value
const serializedValue = this._serializeValues(this.values)
ourBytes.push(serializedValue.length)
// add the bytes of the value
for (let i = 0; i < serializedValue.length; i++) {
ourBytes.push(serializedValue.charCodeAt(i))
}
}
const ourBuffer = Buffer.from(ourBytes)
return Buffer.concat(
[newBuffer, ourBuffer],
newBuffer.length + ourBuffer.length
).toString('hex')
}
/**
* Returns JSON reprenstation of tracestate key/value pairs
*
* Does not parse the mutable list namespace
*/
toObject () {
const map = this.toMap()
const obj = {}
for (const key of map.keys()) {
obj[key] = map.get(key)
}
return obj
}
toMap () {
const map = new Map()
// first, serialize values from the internal representation. This means
// The W3C spec dictates that mutated values need to be on
// the left of the new trace string
if (Object.keys(this.values).length) {
map.set(this.listMemberNamespace, this._serializeValues(
this.values
))
}
for (let i = 0; i < this.buffer.length; i++) {
const byte = this.buffer[i]
if (byte === 0) {
const indexOfKeyLength = i + 1
const indexOfKey = i + 2
const lengthKey = this.buffer[indexOfKeyLength]
const indexOfValueLength = indexOfKey + lengthKey
const indexOfValue = indexOfValueLength + 1
const lengthValue = this.buffer[indexOfValueLength]
const key = this.buffer.slice(indexOfKey, indexOfKey + lengthKey).toString()
const value = this.buffer.slice(indexOfValue, indexOfValue + lengthValue).toString()
map.set(key, value)
// skip ahead
i = indexOfValue + lengthValue - 1
continue
}
}
return map
}
toString () {
return this.toW3cString()
}
toW3cString () {
const json = this.toObject()
const chars = []
for (const key in json) {
const value = json[key]
if (!value) { continue }
chars.push(key)
chars.push('=')
chars.push(value)
chars.push(',')
}
chars.pop() // remove final comma
return chars.join('')
}
_serializeValues (keyValues) {
const chars = []
for (const key in keyValues) {
const value = keyValues[key]
chars.push(`${key}:${value}`)
chars.push(';')
}
chars.pop() // last semi-colon
return chars.join('')
}
_validateVendorKey (key) {
if (key.length > 256 || key.length < 1) {
return false
}
const re = /^[abcdefghijklmnopqrstuvwxyz0123456789_\-*/]*$/
if (!key.match(re)) {
return false
}
return true
}
_validateElasicKeyAndValue (key, value) {
// 0x20` to `0x7E WITHOUT `,` or `=` or `;` or `;`
const re = /^[ \][!"#$%&'()*+\-./0123456789<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_abcdefghijklmnopqrstuvwxyz{|}~]*$/
if (!key.match(re) || !value.match(re)) {
return false
}
if (key.length > 256 || value.length > 256) {
return false
}
return true
}
static fromBinaryFormatHexString (string, listMemberNamespace = 'es') {
return new TraceState(Buffer.from(string, 'hex'), listMemberNamespace)
}
static fromStringFormatString (string = '', listMemberNamespace = 'es') {
// converts string format to byte format
const bytes = []
const parts = string.split(',')
for (let part of parts) {
part = part.trim() // optional whitespace (OWS)
if (!part) { continue }
const [listMember, value] = part.split('=')
if (!listMember || !value) { continue }
bytes.push(0)
bytes.push(listMember.length)
for (let i = 0; i < listMember.length; i++) {
bytes.push(listMember.charCodeAt(i))
}
bytes.push(value.length)
for (let i = 0; i < value.length; i++) {
bytes.push(value.charCodeAt(i))
}
}
return new TraceState(Buffer.from(bytes), listMemberNamespace)
}
static _parseValues (rawValues) {
const parsedValues = {}
const parts = rawValues.split(';')
for (const keyValue of parts) {
if (!keyValue) { continue }
const [key, value] = keyValue.split(':')
if (!key || !value) { continue }
parsedValues[key] = value
}
return parsedValues
}
static _removeMemberNamespaceFromBuffer (buffer, listMemberNamespace) {
const newBuffer = Buffer.alloc(buffer.length)
let newBufferOffset = 0
const values = {}
for (let i = 0; i < buffer.length; i++) {
const byte = buffer[i]
if (byte === 0) {
const indexOfKeyLength = i + 1
const indexOfKey = i + 2
const lengthKey = buffer[indexOfKeyLength]
const indexOfValueLength = indexOfKey + lengthKey
const indexOfValue = indexOfValueLength + 1
const lengthValue = buffer[indexOfValueLength]
const key = buffer.slice(indexOfKey, indexOfKey + lengthKey).toString()
// if this is our mutable namespace extract
// and set the value in values, otherwise
// copy into new buffer
if (key === listMemberNamespace) {
const rawValues = buffer.slice(indexOfValue, indexOfValue + lengthValue).toString()
const parsedValues = TraceState._parseValues(rawValues)
for (const key in parsedValues) {
values[key] = parsedValues[key]
}
continue
} else {
buffer.copy(newBuffer, newBufferOffset, i, indexOfValue + lengthValue)
newBufferOffset += (indexOfValue + lengthValue - i)
}
// skip ahead to first byte after end of value
i = indexOfValue + lengthValue - 1
continue
}
}
// trim off extra 0 bytes
const trimmedBuffer = newBuffer.slice(0, newBufferOffset)
return [
trimmedBuffer,
values
]
}
}
module.exports = TraceState