File: fanout.rb

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (446 lines) | stat: -rw-r--r-- 12,768 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# frozen_string_literal: true

require "concurrent/map"
require "set"
require "active_support/core_ext/object/try"

module ActiveSupport
  module Notifications
    class InstrumentationSubscriberError < RuntimeError
      attr_reader :exceptions

      def initialize(exceptions)
        @exceptions = exceptions
        exception_class_names = exceptions.map { |e| e.class.name }
        super "Exception(s) occurred within instrumentation subscribers: #{exception_class_names.join(', ')}"
      end
    end

    module FanoutIteration # :nodoc:
      private
        def iterate_guarding_exceptions(collection)
          exceptions = nil

          collection.each do |s|
            yield s
          rescue Exception => e
            exceptions ||= []
            exceptions << e
          end

          if exceptions
            exceptions = exceptions.flat_map do |exception|
              exception.is_a?(InstrumentationSubscriberError) ? exception.exceptions : [exception]
            end
            if exceptions.size == 1
              raise exceptions.first
            else
              raise InstrumentationSubscriberError.new(exceptions), cause: exceptions.first
            end
          end

          collection
        end
    end

    # This is a default queue implementation that ships with Notifications.
    # It just pushes events to all registered log subscribers.
    #
    # This class is thread safe. All methods are reentrant.
    class Fanout
      def initialize
        @mutex = Mutex.new
        @string_subscribers = Concurrent::Map.new { |h, k| h.compute_if_absent(k) { [] } }
        @other_subscribers = []
        @all_listeners_for = Concurrent::Map.new
        @groups_for = Concurrent::Map.new
        @silenceable_groups_for = Concurrent::Map.new
      end

      def inspect # :nodoc:
        total_patterns = @string_subscribers.size + @other_subscribers.size
        "#<#{self.class} (#{total_patterns} patterns)>"
      end

      def subscribe(pattern = nil, callable = nil, monotonic: false, &block)
        subscriber = Subscribers.new(pattern, callable || block, monotonic)
        @mutex.synchronize do
          case pattern
          when String
            @string_subscribers[pattern] << subscriber
            clear_cache(pattern)
          when NilClass, Regexp
            @other_subscribers << subscriber
            clear_cache
          else
            raise ArgumentError,  "pattern must be specified as a String, Regexp or empty"
          end
        end
        subscriber
      end

      def unsubscribe(subscriber_or_name)
        @mutex.synchronize do
          case subscriber_or_name
          when String
            @string_subscribers[subscriber_or_name].clear
            clear_cache(subscriber_or_name)
            @other_subscribers.each { |sub| sub.unsubscribe!(subscriber_or_name) }
          else
            pattern = subscriber_or_name.try(:pattern)
            if String === pattern
              @string_subscribers[pattern].delete(subscriber_or_name)
              clear_cache(pattern)
            else
              @other_subscribers.delete(subscriber_or_name)
              clear_cache
            end
          end
        end
      end

      def clear_cache(key = nil) # :nodoc:
        if key
          @all_listeners_for.delete(key)
          @groups_for.delete(key)
          @silenceable_groups_for.delete(key)
        else
          @all_listeners_for.clear
          @groups_for.clear
          @silenceable_groups_for.clear
        end
      end

      class BaseGroup # :nodoc:
        include FanoutIteration

        def initialize(listeners, name, id, payload)
          @listeners = listeners
        end

        def each(&block)
          iterate_guarding_exceptions(@listeners, &block)
        end
      end

      class BaseTimeGroup < BaseGroup # :nodoc:
        def start(name, id, payload)
          @start_time = now
        end

        def finish(name, id, payload)
          stop_time = now
          each do |listener|
            listener.call(name, @start_time, stop_time, id, payload)
          end
        end
      end

      class MonotonicTimedGroup < BaseTimeGroup # :nodoc:
        private
          def now
            Process.clock_gettime(Process::CLOCK_MONOTONIC)
          end
      end

      class TimedGroup < BaseTimeGroup # :nodoc:
        private
          def now
            Time.now
          end
      end

      class EventedGroup < BaseGroup # :nodoc:
        def start(name, id, payload)
          each do |s|
            s.start(name, id, payload)
          end
        end

        def finish(name, id, payload)
          each do |s|
            s.finish(name, id, payload)
          end
        end
      end

      class EventObjectGroup < BaseGroup # :nodoc:
        def start(name, id, payload)
          @event = build_event(name, id, payload)
          @event.start!
        end

        def finish(name, id, payload)
          @event.payload = payload
          @event.finish!

          each do |s|
            s.call(@event)
          end
        end

        private
          def build_event(name, id, payload)
            ActiveSupport::Notifications::Event.new name, nil, nil, id, payload
          end
      end

      def groups_for(name) # :nodoc:
        groups = @groups_for.compute_if_absent(name) do
          all_listeners_for(name).reject(&:silenceable).group_by(&:group_class).transform_values do |s|
            s.map(&:delegate)
          end
        end

        silenceable_groups = @silenceable_groups_for.compute_if_absent(name) do
          all_listeners_for(name).select(&:silenceable).group_by(&:group_class).transform_values do |s|
            s.map(&:delegate)
          end
        end

        unless silenceable_groups.empty?
          groups = groups.dup
          silenceable_groups.each do |group_class, subscriptions|
            active_subscriptions = subscriptions.reject { |s| s.silenced?(name) }
            unless active_subscriptions.empty?
              groups[group_class] = (groups[group_class] || []) + active_subscriptions
            end
          end
        end

        groups
      end

      # A +Handle+ is used to record the start and finish time of event.
      #
      # Both #start and #finish must each be called exactly once.
      #
      # Where possible, it's best to use the block form: ActiveSupport::Notifications.instrument.
      # +Handle+ is a low-level API intended for cases where the block form can't be used.
      #
      #   handle = ActiveSupport::Notifications.instrumenter.build_handle("my.event", {})
      #   begin
      #     handle.start
      #     # work to be instrumented
      #   ensure
      #     handle.finish
      #   end
      class Handle
        include FanoutIteration

        def initialize(notifier, name, id, payload) # :nodoc:
          @name = name
          @id = id
          @payload = payload
          @groups = notifier.groups_for(name).map do |group_klass, grouped_listeners|
            group_klass.new(grouped_listeners, name, id, payload)
          end
          @state = :initialized
        end

        def start
          ensure_state! :initialized
          @state = :started

          iterate_guarding_exceptions(@groups) do |group|
            group.start(@name, @id, @payload)
          end
        end

        def finish
          finish_with_values(@name, @id, @payload)
        end

        def finish_with_values(name, id, payload) # :nodoc:
          ensure_state! :started
          @state = :finished

          iterate_guarding_exceptions(@groups) do |group|
            group.finish(name, id, payload)
          end
        end

        private
          def ensure_state!(expected)
            if @state != expected
              raise ArgumentError, "expected state to be #{expected.inspect} but was #{@state.inspect}"
            end
          end
      end

      include FanoutIteration

      def build_handle(name, id, payload)
        Handle.new(self, name, id, payload)
      end

      def start(name, id, payload)
        handle_stack = (IsolatedExecutionState[:_fanout_handle_stack] ||= [])
        handle = build_handle(name, id, payload)
        handle_stack << handle
        handle.start
      end

      def finish(name, id, payload, listeners = nil)
        handle_stack = IsolatedExecutionState[:_fanout_handle_stack]
        handle = handle_stack.pop
        handle.finish_with_values(name, id, payload)
      end

      def publish(name, *args)
        iterate_guarding_exceptions(listeners_for(name)) { |s| s.publish(name, *args) }
      end

      def publish_event(event)
        iterate_guarding_exceptions(listeners_for(event.name)) { |s| s.publish_event(event) }
      end

      def all_listeners_for(name)
        # this is correctly done double-checked locking (Concurrent::Map's lookups have volatile semantics)
        @all_listeners_for[name] || @mutex.synchronize do
          # use synchronisation when accessing @subscribers
          @all_listeners_for[name] ||=
            @string_subscribers[name] + @other_subscribers.select { |s| s.subscribed_to?(name) }
        end
      end

      def listeners_for(name)
        all_listeners_for(name).reject { |s| s.silenced?(name) }
      end

      def listening?(name)
        all_listeners_for(name).any? { |s| !s.silenced?(name) }
      end

      # This is a sync queue, so there is no waiting.
      def wait
      end

      module Subscribers # :nodoc:
        def self.new(pattern, listener, monotonic)
          subscriber_class = monotonic ? MonotonicTimed : Timed

          if listener.respond_to?(:start) && listener.respond_to?(:finish)
            subscriber_class = Evented
          else
            # Doing this to detect a single argument block or callable
            # like `proc { |x| }` vs `proc { |*x| }`, `proc { |**x| }`,
            # or `proc { |x, **y| }`
            procish = listener.respond_to?(:parameters) ? listener : listener.method(:call)

            if procish.arity == 1 && procish.parameters.length == 1
              subscriber_class = EventObject
            end
          end

          subscriber_class.new(pattern, listener)
        end

        class Matcher # :nodoc:
          attr_reader :pattern, :exclusions

          def self.wrap(pattern)
            if String === pattern
              pattern
            elsif pattern.nil?
              AllMessages.new
            else
              new(pattern)
            end
          end

          def initialize(pattern)
            @pattern = pattern
            @exclusions = Set.new
          end

          def unsubscribe!(name)
            exclusions << -name if pattern === name
          end

          def ===(name)
            pattern === name && !exclusions.include?(name)
          end

          class AllMessages
            def ===(name)
              true
            end

            def unsubscribe!(*)
              false
            end
          end
        end

        class Evented # :nodoc:
          attr_reader :pattern, :delegate, :silenceable

          def initialize(pattern, delegate)
            @pattern = Matcher.wrap(pattern)
            @delegate = delegate
            @silenceable = delegate.respond_to?(:silenced?)
            @can_publish = delegate.respond_to?(:publish)
            @can_publish_event = delegate.respond_to?(:publish_event)
          end

          def group_class
            EventedGroup
          end

          def publish(name, *args)
            if @can_publish
              @delegate.publish name, *args
            end
          end

          def publish_event(event)
            if @can_publish_event
              @delegate.publish_event event
            else
              publish(event.name, event.time, event.end, event.transaction_id, event.payload)
            end
          end

          def silenced?(name)
            @silenceable && @delegate.silenced?(name)
          end

          def subscribed_to?(name)
            pattern === name
          end

          def unsubscribe!(name)
            pattern.unsubscribe!(name)
          end
        end

        class Timed < Evented # :nodoc:
          def group_class
            TimedGroup
          end

          def publish(name, *args)
            @delegate.call name, *args
          end
        end

        class MonotonicTimed < Timed # :nodoc:
          def group_class
            MonotonicTimedGroup
          end
        end

        class EventObject < Evented
          def group_class
            EventObjectGroup
          end

          def publish_event(event)
            @delegate.call event
          end
        end
      end
    end
  end
end