Class: TgErrorNotifier::Grouper

Inherits:
Object
  • Object
show all
Defined in:
lib/tg_error_notifier/grouper.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

CLEANUP_INTERVAL =
100

Instance Method Summary collapse

Constructor Details

#initialize(window:) ⇒ Grouper

Returns a new instance of Grouper.



9
10
11
12
13
14
# File 'lib/tg_error_notifier/grouper.rb', line 9

def initialize(window:)
  @window = window
  @mutex = Mutex.new
  @entries = {}
  @call_count = 0
end

Instance Method Details

#grouping_key(exception) ⇒ Object



55
56
57
# File 'lib/tg_error_notifier/grouper.rb', line 55

def grouping_key(exception)
  "#{exception.class.name}:#{normalize_message(exception.message)}"
end

#process(key:, thread_id: nil) ⇒ Object

Returns:

{ action: :send, count: N, thread_id: id_or_nil }
{ action: :suppress }


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
# File 'lib/tg_error_notifier/grouper.rb', line 19

def process(key:, thread_id: nil)
  now = Time.now

  @mutex.synchronize do
    @call_count += 1
    lazy_cleanup!(now) if (@call_count % CLEANUP_INTERVAL).zero?

    entry = @entries[key]

    if entry.nil?
      @entries[key] = Entry.new(count: 0, first_at: now, last_sent_at: now, thread_id: thread_id)
      return { action: :send, count: 0, thread_id: thread_id }
    end

    entry.thread_id = thread_id if entry.thread_id.nil? && thread_id

    elapsed = now - entry.last_sent_at

    if elapsed >= @window
      accumulated = entry.count
      entry.count = 0
      entry.last_sent_at = now
      { action: :send, count: accumulated, thread_id: entry.thread_id }
    else
      entry.count += 1
      { action: :suppress }
    end
  end
end

#rollback(key) ⇒ Object



49
50
51
52
53
# File 'lib/tg_error_notifier/grouper.rb', line 49

def rollback(key)
  @mutex.synchronize do
    @entries.delete(key)
  end
end