Skip to content

Commit a9562e2

Browse files
authored
Merge pull request rails#50779 from Shopify/debug-ar-time
Fix `ActiveSupport::Notifications.publish_event` to preserve units
2 parents 2fb0595 + de779f2 commit a9562e2

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

activesupport/lib/active_support/notifications/instrumenter.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def unique_id
104104
end
105105

106106
class Event
107-
attr_reader :name, :time, :end, :transaction_id
107+
attr_reader :name, :transaction_id
108108
attr_accessor :payload
109109

110110
def initialize(name, start, ending, transaction_id, payload)
@@ -119,7 +119,15 @@ def initialize(name, start, ending, transaction_id, payload)
119119
@allocation_count_finish = 0
120120
end
121121

122-
def record
122+
def time
123+
@time / 1000.0 if @time
124+
end
125+
126+
def end
127+
@end / 1000.0 if @end
128+
end
129+
130+
def record # :nodoc:
123131
start!
124132
begin
125133
yield payload if block_given?
@@ -195,7 +203,7 @@ def parent_of?(event) # :nodoc:
195203
#
196204
# @event.duration # => 1000.138
197205
def duration
198-
self.end - time
206+
@end - @time
199207
end
200208

201209
private

activesupport/test/subscriber_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,25 @@ def test_supports_publish_event
127127
ensure
128128
TestSubscriber.detach_from :doodle
129129
end
130+
131+
def test_publish_event_preserve_units
132+
event = ActiveSupport::Notifications::Event.new("publish_event.test", nil, nil, 42, {})
133+
event.record { sleep 0.1 }
134+
135+
computed_duration = nil
136+
callback = -> (_, start, finish, _, _) { computed_duration = finish - start }
137+
138+
ActiveSupport::Notifications.subscribed(callback, "publish_event.test") do
139+
ActiveSupport::Notifications.publish_event(event)
140+
end
141+
142+
# Event#duration is in milliseconds, start and finish in seconds
143+
assert_in_delta event.duration / 1_000.0, computed_duration, 0.05
144+
145+
ActiveSupport::Notifications.subscribed(callback, "publish_event.test", monotonic: true) do
146+
ActiveSupport::Notifications.publish_event(event)
147+
end
148+
149+
assert_in_delta event.duration / 1_000.0, computed_duration, 0.05
150+
end
130151
end

0 commit comments

Comments
 (0)