Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make TraceParent a local class module #2669

Merged
merged 4 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Notes:
[float]
===== Features

- Pulled `traceparent` NPM module into local class file.

- Add a `parent` option to `agent.captureError(err[, options][, cb])` to allow
passing in a Transaction or Span to use as the parent for the error. Before
this change the *current* span or transaction, if any, was always used.
Expand Down
2 changes: 1 addition & 1 deletion lib/tracecontext/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict'
const TraceParent = require('traceparent')
const { TraceParent } = require('./traceparent')
const TraceState = require('./tracestate')

class TraceContext {
Expand Down
156 changes: 156 additions & 0 deletions lib/tracecontext/traceparent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
'use strict'

const { randomFillSync } = require('random-poly-fill') // TODO: Remove when Node.js 6 is no longer supported
astorm marked this conversation as resolved.
Show resolved Hide resolved

const SIZES = {
version: 1,
traceId: 16,
id: 8,
flags: 1,
parentId: 8,

// Aggregate sizes
ids: 24, // traceId + id
all: 34
}

const OFFSETS = {
version: 0,
traceId: SIZES.version,
id: SIZES.version + SIZES.traceId,
flags: SIZES.version + SIZES.ids,

// Additional parentId is stored after the header content
parentId: SIZES.version + SIZES.ids + SIZES.flags
}

const FLAGS = {
recorded: 0b00000001
}

function defineLazyProp (obj, prop, fn) {
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
get () {
const value = fn()
if (value !== undefined) {
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
value
})
}
return value
}
})
}

function hexSliceFn (buffer, offset, length) {
return () => buffer.slice(offset, length).toString('hex')
}

function maybeHexSliceFn (buffer, offset, length) {
const fn = hexSliceFn(buffer, offset, length)
return () => {
const value = fn()
// Check for any non-zero characters to identify a valid ID
if (/[1-9a-f]/.test(value)) {
return value
}
}
}

function makeChild (buffer) {
// Move current id into parentId region
buffer.copy(buffer, OFFSETS.parentId, OFFSETS.id, OFFSETS.flags)

// Generate new id
randomFillSync(buffer, OFFSETS.id, SIZES.id)

return new TraceParent(buffer)
}

function isValidHeader (header) {
return /^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$/.test(header)
}

// NOTE: The version byte is not fully supported yet, but is not important until
// we use the official header name rather than elastic-apm-traceparent.
// https://w3c.github.io/distributed-tracing/report-trace-context.html#versioning-of-traceparent
function headerToBuffer (header) {
const buffer = Buffer.alloc(SIZES.all)
buffer.write(header.replace(/-/g, ''), 'hex')
return buffer
}

function resume (header) {
return makeChild(headerToBuffer(header))
}

function start (sampled = false) {
const buffer = Buffer.alloc(SIZES.all)

// Generate new ids
randomFillSync(buffer, OFFSETS.traceId, SIZES.ids)

if (sampled) {
buffer[OFFSETS.flags] |= FLAGS.recorded
}

return new TraceParent(buffer)
}

const bufferSymbol = Symbol('trace-context-buffer')

class TraceParent {
constructor (buffer) {
this[bufferSymbol] = buffer
Object.defineProperty(this, 'recorded', {
value: !!(buffer[OFFSETS.flags] & FLAGS.recorded),
enumerable: true
})

defineLazyProp(this, 'version', hexSliceFn(buffer, OFFSETS.version, OFFSETS.traceId))
defineLazyProp(this, 'traceId', hexSliceFn(buffer, OFFSETS.traceId, OFFSETS.id))
defineLazyProp(this, 'id', hexSliceFn(buffer, OFFSETS.id, OFFSETS.flags))
defineLazyProp(this, 'flags', hexSliceFn(buffer, OFFSETS.flags, OFFSETS.parentId))
defineLazyProp(this, 'parentId', maybeHexSliceFn(buffer, OFFSETS.parentId))
}

static startOrResume (childOf, conf) {
if (childOf instanceof TraceParent) return childOf.child()
if (childOf && childOf._context instanceof TraceParent) return childOf._context.child()

return isValidHeader(childOf)
? resume(childOf)
: start(Math.random() <= conf.transactionSampleRate)
}

static fromString (header) {
return new TraceParent(headerToBuffer(header))
}

ensureParentId () {
let id = this.parentId
if (!id) {
randomFillSync(this[bufferSymbol], OFFSETS.parentId, SIZES.id)
id = this.parentId
}
return id
}

child () {
return makeChild(Buffer.from(this[bufferSymbol]))
}

toString () {
return `${this.version}-${this.traceId}-${this.id}-${this.flags}`
}
}

TraceParent.FLAGS = FLAGS

module.exports = {
TraceParent
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"object-identity-map": "^1.0.2",
"original-url": "^1.2.3",
"pino": "^6.11.2",
"random-poly-fill": "^1.0.1",
"read-pkg-up": "^7.0.1",
"relative-microtime": "^2.0.0",
"require-in-the-middle": "^5.0.3",
Expand All @@ -109,7 +110,6 @@
"shallow-clone-shim": "^2.0.0",
"source-map": "^0.8.0-beta.0",
"sql-summary": "^1.0.1",
"traceparent": "^1.0.0",
"traverse": "^0.6.6",
"unicode-byte-truncate": "^1.0.0"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const es = require(esClientPkgName)

const { Readable } = require('stream')
const test = require('tape')
const TraceParent = require('traceparent')
const { TraceParent } = require('../../../../lib/tracecontext/traceparent')

const findObjInArray = require('../../../_utils').findObjInArray
const mockClient = require('../../../_mock_http_client')
Expand Down
2 changes: 1 addition & 1 deletion test/instrumentation/modules/http/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var test = require('tape')

var assert = require('./_assert')
var mockClient = require('../../../_mock_http_client')
var TraceParent = require('traceparent')
var { TraceParent } = require('../../../../lib/tracecontext/traceparent')

test('http.createServer', function (t) {
t.test('direct callback', function (t) {
Expand Down
2 changes: 1 addition & 1 deletion test/instrumentation/modules/http/outgoing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var test = require('tape')

var echoServer = require('./_echo_server_util').echoServer
var mockClient = require('../../../_mock_http_client')
var TraceParent = require('traceparent')
var { TraceParent } = require('../../../../lib/tracecontext/traceparent')

var methods = ['request', 'get']

Expand Down
2 changes: 1 addition & 1 deletion test/tracecontext/tracecontext.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const agent = require('../..').start({
const tape = require('tape')
const TraceContext = require('../../lib/tracecontext')
const TraceState = require('../../lib/tracecontext/tracestate')
const TraceParent = require('traceparent')
const { TraceParent } = require('../../lib/tracecontext/traceparent')

tape.test('propagateTraceContextHeaders tests', function (suite) {
suite.test('Span test', function (t) {
Expand Down
Loading