dd-trace
Version:
Datadog APM tracing client for JavaScript
126 lines (109 loc) • 3.19 kB
JavaScript
'use strict'
const util = require('util')
const { AUTO_KEEP } = require('../../../../ext/priority')
// the lowercase, hex encoded upper 64 bits of a 128-bit trace id, if present
const TRACE_ID_128 = '_dd.p.tid'
class DatadogSpanContext {
constructor (props) {
props = props || {}
this._traceId = props.traceId
this._spanId = props.spanId
this._isRemote = props.isRemote ?? true
this._parentId = props.parentId || null
this._name = props.name
this._isFinished = props.isFinished || false
this._tags = props.tags || {}
this._sampling = props.sampling || {}
this._spanSampling = undefined
this._links = props.links || []
this._baggageItems = props.baggageItems || {}
this._traceparent = props.traceparent
this._tracestate = props.tracestate
this._noop = props.noop || null
this._trace = props.trace || {
started: [],
finished: [],
tags: {},
}
this._otelSpanContext = undefined
this._otelActiveSpan = undefined
}
[util.inspect.custom] () {
return {
...this,
_trace: {
...this._trace,
started: '[Array]',
finished: '[Array]',
},
}
}
toTraceId (get128bitId = false) {
if (get128bitId) {
return this._traceId.toBuffer().length <= 8 && this._trace.tags[TRACE_ID_128]
? this._trace.tags[TRACE_ID_128] + this._traceId.toString(16).padStart(16, '0')
: this._traceId.toString(16).padStart(32, '0')
}
return this._traceId.toString(10)
}
toSpanId (get128bitId = false) {
if (get128bitId) {
return this._spanId.toString(16).padStart(16, '0')
}
return this._spanId.toString(10)
}
toBigIntSpanId () {
return this._spanId.toBigInt()
}
toTraceparent () {
const flags = this._sampling.priority >= AUTO_KEEP ? '01' : '00'
const traceId = this.toTraceId(true)
const spanId = this.toSpanId(true)
const version = (this._traceparent && this._traceparent.version) || '00'
return `${version}-${traceId}-${spanId}-${flags}`
}
/**
* Set a tag value.
* @param {string} key - Tag key
* @param {unknown} value - Tag value
*/
setTag (key, value) {
this._tags[key] = value
}
/**
* Get a tag value.
* @param {string} key - Tag key
* @returns {unknown} Tag value or undefined
*/
getTag (key) {
return this._tags[key]
}
/**
* Check if a tag exists.
* @param {string} key - Tag key
* @returns {boolean}
*/
hasTag (key) { return Object.hasOwn(this._tags, key) }
/**
* Delete a tag.
* @param {string} key - Tag key
*/
deleteTag (key) { delete this._tags[key] }
/**
* Get the live internal tags map. The returned reference is mutable;
* callers may assign or delete keys directly (e.g.
* `Object.assign(getTags(), tags)` in span.js). Subclasses may have
* additional sync side effects on the individual `setTag` / `deleteTag`
* setters; mutating the returned map bypasses those.
*
* @returns {object}
*/
getTags () {
return this._tags
}
/**
* Clear all tags.
*/
clearTags () { this._tags = Object.create(null) }
}
module.exports = DatadogSpanContext