|
7 | 7 | import datadog.trace.bootstrap.instrumentation.api.ScopeState; |
8 | 8 |
|
9 | 9 | public class FiberContext { |
10 | | - private final ScopeState state; |
11 | | - private AgentScope.Continuation continuation; |
12 | | - private AgentScope scope; |
13 | | - private ScopeState oldState; |
| 10 | + private final ScopeState scopeState; |
| 11 | + private final AgentScope.Continuation continuation; |
14 | 12 |
|
15 | | - private FiberContext(ScopeState state) { |
16 | | - this.state = state; |
17 | | - this.scope = null; |
18 | | - this.oldState = null; |
19 | | - this.continuation = captureActiveSpan(); |
20 | | - } |
| 13 | + private ScopeState oldScopeState; |
21 | 14 |
|
22 | | - public static FiberContext create() { |
23 | | - final ScopeState state = AgentTracer.get().newScopeState(); |
24 | | - return new FiberContext(state); |
| 15 | + public FiberContext() { |
| 16 | + // copy scope stack to use for this fiber |
| 17 | + this.scopeState = AgentTracer.get().oldScopeState().copy(); |
| 18 | + // stop enclosing trace from finishing early |
| 19 | + this.continuation = captureActiveSpan(); |
25 | 20 | } |
26 | 21 |
|
27 | | - public void onEnd() { |
28 | | - if (this.scope != null) { |
29 | | - this.scope.close(); |
30 | | - this.scope = null; |
31 | | - } |
32 | | - if (continuation != null) { |
33 | | - continuation.cancel(); |
34 | | - continuation = null; |
35 | | - } |
36 | | - |
37 | | - if (this.oldState != null) { |
38 | | - this.oldState.activate(); |
39 | | - this.oldState = null; |
40 | | - } |
| 22 | + public void onResume() { |
| 23 | + oldScopeState = AgentTracer.get().oldScopeState(); |
| 24 | + scopeState.activate(); // swap in the fiber's scope stack |
41 | 25 | } |
42 | 26 |
|
43 | 27 | public void onSuspend() { |
44 | | - if (this.scope != null && continuation != null) { |
45 | | - this.scope.close(); |
46 | | - this.scope = null; |
47 | | - } |
48 | | - if (this.oldState != null) { |
49 | | - this.oldState.activate(); |
50 | | - this.oldState = null; |
| 28 | + if (oldScopeState != null) { |
| 29 | + oldScopeState.activate(); // swap bock the original scope stack |
| 30 | + oldScopeState = null; |
51 | 31 | } |
52 | 32 | } |
53 | 33 |
|
54 | | - public void onResume() { |
55 | | - this.oldState = AgentTracer.get().oldScopeState(); |
56 | | - |
57 | | - this.state.activate(); |
58 | | - |
59 | | - if (this.continuation != null) { |
60 | | - this.scope = continuation.activate(); |
61 | | - continuation = null; |
| 34 | + public void onEnd() { |
| 35 | + if (continuation != null) { |
| 36 | + // release enclosing trace now the fiber has ended |
| 37 | + continuation.cancel(); |
62 | 38 | } |
63 | 39 | } |
64 | 40 | } |
0 commit comments