@@ -14,6 +14,7 @@ module TracerHelpers
14
14
# Returns the current tracer instance
15
15
def tracer
16
16
Datadog ::Tracing . send ( :tracer )
17
+ @write_lock = Mutex . new
17
18
end
18
19
19
20
# Returns spans and caches it (similar to +let(:spans)+).
@@ -35,20 +36,24 @@ def fetch_traces(tracer = self.tracer)
35
36
# Retrieves and sorts all spans in the current tracer instance.
36
37
# This method does not cache its results.
37
38
def fetch_spans ( tracer = self . tracer )
38
- traces = fetch_traces ( tracer )
39
- traces . collect ( &:spans ) . flatten . sort! do |a , b |
40
- if a . name == b . name
41
- if a . resource == b . resource
42
- if a . start_time == b . start_time
43
- a . end_time <=> b . end_time
39
+ lock = tracer . instance_variable_get ( :@write_lock )
40
+ return [ ] if lock . nil?
41
+ lock . synchronize do
42
+ traces = fetch_traces ( tracer )
43
+ traces . collect ( &:spans ) . flatten . sort! do |a , b |
44
+ if a . name == b . name
45
+ if a . resource == b . resource
46
+ if a . start_time == b . start_time
47
+ a . end_time <=> b . end_time
48
+ else
49
+ a . start_time <=> b . start_time
50
+ end
44
51
else
45
- a . start_time <=> b . start_time
52
+ a . resource <=> b . resource
46
53
end
47
54
else
48
- a . resource <=> b . resource
55
+ a . name <=> b . name
49
56
end
50
- else
51
- a . name <=> b . name
52
57
end
53
58
end
54
59
end
@@ -57,6 +62,7 @@ def fetch_spans(tracer = self.tracer)
57
62
# busts cache of +#spans+ and +#span+.
58
63
def clear_traces!
59
64
tracer . instance_variable_set ( :@traces , [ ] )
65
+ tracer . instance_variable_set ( :@write_lock , Mutex . new )
60
66
61
67
@traces = nil
62
68
@trace = nil
@@ -73,10 +79,9 @@ def clear_traces!
73
79
instance = method . call ( **args , &block )
74
80
75
81
# The mutex must be eagerly initialized to prevent race conditions on lazy initialization
76
- write_lock = Mutex . new
77
82
allow ( instance ) . to receive ( :write ) do |trace |
78
83
instance . instance_exec do
79
- write_lock . synchronize do
84
+ tracer . instance_variable_get ( :@ write_lock) . synchronize do
80
85
@traces ||= [ ]
81
86
@traces << trace
82
87
end
0 commit comments