@@ -5,23 +5,39 @@ const { ContinuationLocalStorage } = require('asyncctx')
5
5
const cls = new ContinuationLocalStorage ( )
6
6
cls . setRootContext ( { } )
7
7
8
- function assign ( context ) {
8
+ /**
9
+ * @function assign
10
+ * @return {SpanContext } spanContext
11
+ */
12
+ function assign ( spanContext ) {
9
13
const currentContext = cls . getContext ( ) || { }
10
- const newContext = Object . assign ( currentContext , context )
14
+ const newContext = Object . assign ( currentContext , spanContext )
15
+
11
16
cls . setContext ( newContext )
12
17
}
13
18
19
+ /**
20
+ * @function getRootSpan
21
+ * @return {Span }
22
+ */
14
23
function getRootSpan ( ) {
15
24
const context = cls . getContext ( ) || cls . getRootContext ( )
16
25
return context . currentSpan
17
26
}
18
27
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
+ } )
25
41
26
42
cls . assign ( {
27
43
currentSpan : span
@@ -30,14 +46,21 @@ function startRootSpan (tracer, operationName, spanContext) {
30
46
return span
31
47
}
32
48
49
+ /**
50
+ * @function startChildSpan
51
+ * @param {Tracer } tracer
52
+ * @param {String } operationName
53
+ * @return {Span }
54
+ */
33
55
function startChildSpan ( tracer , operationName ) {
34
- const context = cls . getContext ( ) || cls . getRootContext ( )
56
+ const parentSpan = getRootSpan ( )
57
+ const parentSpanContext = parentSpan ? parentSpan . context ( ) : undefined
35
58
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
+ } )
41
64
42
65
return span
43
66
}
0 commit comments