Skip to content

Commit 9f94cdf

Browse files
author
Peter Marton
committed
fix(cls): validate span context
1 parent a57b853 commit 9f94cdf

File tree

1 file changed

+37
-14
lines changed

1 file changed

+37
-14
lines changed

Diff for: src/cls.js

+37-14
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,39 @@ const { ContinuationLocalStorage } = require('asyncctx')
55
const cls = new ContinuationLocalStorage()
66
cls.setRootContext({})
77

8-
function assign (context) {
8+
/**
9+
* @function assign
10+
* @return {SpanContext} spanContext
11+
*/
12+
function assign (spanContext) {
913
const currentContext = cls.getContext() || {}
10-
const newContext = Object.assign(currentContext, context)
14+
const newContext = Object.assign(currentContext, spanContext)
15+
1116
cls.setContext(newContext)
1217
}
1318

19+
/**
20+
* @function getRootSpan
21+
* @return {Span}
22+
*/
1423
function getRootSpan () {
1524
const context = cls.getContext() || cls.getRootContext()
1625
return context.currentSpan
1726
}
1827

19-
function startRootSpan (tracer, operationName, spanContext) {
20-
const span = spanContext ?
21-
tracer.startSpan(operationName, {
22-
childOf: spanContext
23-
})
24-
: tracer.startSpan(operationName)
28+
/**
29+
* @function startRootSpan
30+
* @param {Tracer} tracer
31+
* @param {String} operationName
32+
* @param {SpanContext} [parentSpanContext]
33+
* @return {Span}
34+
*/
35+
function startRootSpan (tracer, operationName, parentSpanContext) {
36+
const span = tracer.startSpan(operationName, {
37+
childOf: parentSpanContext && parentSpanContext.isValid
38+
? parentSpanContext
39+
: undefined
40+
})
2541

2642
cls.assign({
2743
currentSpan: span
@@ -30,14 +46,21 @@ function startRootSpan (tracer, operationName, spanContext) {
3046
return span
3147
}
3248

49+
/**
50+
* @function startChildSpan
51+
* @param {Tracer} tracer
52+
* @param {String} operationName
53+
* @return {Span}
54+
*/
3355
function startChildSpan (tracer, operationName) {
34-
const context = cls.getContext() || cls.getRootContext()
56+
const parentSpan = getRootSpan()
57+
const parentSpanContext = parentSpan ? parentSpan.context() : undefined
3558

36-
const span = context.currentSpan ?
37-
tracer.startSpan(operationName, {
38-
childOf: context.currentSpan.context()
39-
})
40-
: tracer.startSpan(operationName)
59+
const span = tracer.startSpan(operationName, {
60+
childOf: parentSpanContext && parentSpanContext.isValid
61+
? parentSpanContext
62+
: undefined
63+
})
4164

4265
return span
4366
}

0 commit comments

Comments
 (0)