@@ -14,6 +14,7 @@ module TracerHelpers
1414 # Returns the current tracer instance
1515 def tracer
1616 Datadog ::Tracing . send ( :tracer )
17+ @write_lock = Mutex . new
1718 end
1819
1920 # Returns spans and caches it (similar to +let(:spans)+).
@@ -35,20 +36,24 @@ def fetch_traces(tracer = self.tracer)
3536 # Retrieves and sorts all spans in the current tracer instance.
3637 # This method does not cache its results.
3738 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
4451 else
45- a . start_time <=> b . start_time
52+ a . resource <=> b . resource
4653 end
4754 else
48- a . resource <=> b . resource
55+ a . name <=> b . name
4956 end
50- else
51- a . name <=> b . name
5257 end
5358 end
5459 end
@@ -57,6 +62,7 @@ def fetch_spans(tracer = self.tracer)
5762 # busts cache of +#spans+ and +#span+.
5863 def clear_traces!
5964 tracer . instance_variable_set ( :@traces , [ ] )
65+ tracer . instance_variable_set ( :@write_lock , Mutex . new )
6066
6167 @traces = nil
6268 @trace = nil
@@ -73,10 +79,9 @@ def clear_traces!
7379 instance = method . call ( **args , &block )
7480
7581 # The mutex must be eagerly initialized to prevent race conditions on lazy initialization
76- write_lock = Mutex . new
7782 allow ( instance ) . to receive ( :write ) do |trace |
7883 instance . instance_exec do
79- write_lock . synchronize do
84+ tracer . instance_variable_get ( :@ write_lock) . synchronize do
8085 @traces ||= [ ]
8186 @traces << trace
8287 end
0 commit comments