Skip to content

Commit f08f875

Browse files
committed
start / finish events are sent by the instrumenter
1 parent 60736fe commit f08f875

File tree

2 files changed

+41
-7
lines changed

2 files changed

+41
-7
lines changed

activesupport/lib/active_support/notifications/fanout.rb

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ def unsubscribe(subscriber)
2020
@listeners_for.clear
2121
end
2222

23+
def start(name, id, payload)
24+
listeners_for(name).each { |s| s.start(name, id, payload) }
25+
end
26+
27+
def finish(name, id, payload)
28+
listeners_for(name).each { |s| s.finish(name, id, payload) }
29+
end
30+
2331
def publish(name, *args)
2432
listeners_for(name).each { |s| s.publish(name, *args) }
2533
end
@@ -39,7 +47,7 @@ def wait
3947
module Subscribers # :nodoc:
4048
def self.new(pattern, block)
4149
if pattern
42-
Subscriber.new pattern, block
50+
TimedSubscriber.new pattern, block
4351
else
4452
AllMessages.new pattern, block
4553
end
@@ -51,8 +59,12 @@ def initialize(pattern, delegate)
5159
@delegate = delegate
5260
end
5361

54-
def publish(message, *args)
55-
@delegate.call(message, *args)
62+
def start(name, id, payload)
63+
raise NotImplementedError
64+
end
65+
66+
def finish(name, id, payload)
67+
raise NotImplementedError
5668
end
5769

5870
def subscribed_to?(name)
@@ -65,7 +77,29 @@ def matches?(subscriber_or_name)
6577
end
6678
end
6779

68-
class AllMessages < Subscriber # :nodoc:
80+
class TimedSubscriber < Subscriber
81+
def initialize(pattern, delegate)
82+
@timestack = Hash.new { |h,id|
83+
h[id] = Hash.new { |ids,name| ids[name] = [] }
84+
}
85+
super
86+
end
87+
88+
def publish(name, *args)
89+
@delegate.call name, *args
90+
end
91+
92+
def start(name, id, payload)
93+
@timestack[id][name].push Time.now
94+
end
95+
96+
def finish(name, id, payload)
97+
started = @timestack[id][name].pop
98+
@delegate.call(name, started, Time.now, id, payload)
99+
end
100+
end
101+
102+
class AllMessages < TimedSubscriber # :nodoc:
69103
def subscribed_to?(name)
70104
true
71105
end

activesupport/lib/active_support/notifications/instrumenter.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module ActiveSupport
22
module Notifications
3+
# Instrumentors are stored in a thread local.
34
class Instrumenter
45
attr_reader :id
56

@@ -12,15 +13,14 @@ def initialize(notifier)
1213
# and publish it. Notice that events get sent even if an error occurs
1314
# in the passed-in block
1415
def instrument(name, payload={})
15-
started = Time.now
16-
16+
@notifier.start(name, @id, payload)
1717
begin
1818
yield
1919
rescue Exception => e
2020
payload[:exception] = [e.class.name, e.message]
2121
raise e
2222
ensure
23-
@notifier.publish(name, started, Time.now, @id, payload)
23+
@notifier.finish(name, @id, payload)
2424
end
2525
end
2626

0 commit comments

Comments
 (0)