Class: DeadBro::RedisSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/dead_bro/redis_subscriber.rb

Constant Summary collapse

THREAD_LOCAL_KEY =
:dead_bro_redis_events
MAX_TRACKED_EVENTS =
1000

Class Method Summary collapse

Class Method Details

.build_event(name, data, duration_ms) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/dead_bro/redis_subscriber.rb', line 242

def self.build_event(name, data, duration_ms)
  cmd = extract_command(data)
  {
    event: name.to_s,
    command: cmd[:command],
    key: cmd[:key],
    args_count: cmd[:args_count],
    duration_ms: duration_ms,
    db: safe_db(data[:db])
  }
rescue
  nil
end

.extract_command(data) ⇒ Object



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
# File 'lib/dead_bro/redis_subscriber.rb', line 256

def self.extract_command(data)
  return {command: nil, key: nil, args_count: nil} unless data.is_a?(Hash)

  parts = if data[:command]
    Array(data[:command]).map(&:to_s)
  elsif data[:commands]
    Array(data[:commands]).flatten.map(&:to_s)
  elsif data[:cmd]
    Array(data[:cmd]).map(&:to_s)
  else
    []
  end

  command_name = parts.first&.upcase
  key = parts[1]
  args_count = parts.length - 1 if parts.any?

  {
    command: safe_command(command_name),
    key: safe_key(key),
    args_count: args_count
  }
rescue
  {command: nil, key: nil, args_count: nil}
end

.install_notifications_subscription!Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/dead_bro/redis_subscriber.rb', line 196

def self.install_notifications_subscription!
  # Try to subscribe to ActiveSupport::Notifications if available
  # This covers cases where other libraries emit redis.* events
  if defined?(ActiveSupport::Notifications)
    begin
      ActiveSupport::Notifications.subscribe(/\Aredis\..+\z/) do |name, started, finished, _unique_id, data|
        next unless Thread.current[THREAD_LOCAL_KEY]
        duration_ms = ((finished - started) * 1000.0).round(2)
        event = build_event(name, data, duration_ms)
        if event && should_continue_tracking?
          Thread.current[THREAD_LOCAL_KEY] << event
        end
      end
    rescue
    end
  end
end

.install_redis_client!Object



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
# File 'lib/dead_bro/redis_subscriber.rb', line 25

def self.install_redis_client!
  # Only instrument if Redis::Client actually has the call method
  # Check both public and private methods
  has_call = ::Redis::Client.method_defined?(:call, false) ||
    ::Redis::Client.private_method_defined?(:call, false)
  return unless has_call

  mod = Module.new do
    # Use method_missing alternative or alias_method pattern
    # We'll use prepend but make the method signature as flexible as possible
    def call(*args, &block)
      # Extract command from args - first arg is typically the command array
      command = args.first
      # Only track if thread-local storage is set up
      if Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] && !command.nil?
        record_redis_command(command) do
          super(*args, &block)
        end
      else
        # If not tracking, just pass through unchanged
        super
      end
    end

    def call_pipeline(pipeline)
      record_redis_pipeline(pipeline) do
        super
      end
    end

    def call_multi(multi)
      record_redis_multi(multi) do
        super
      end
    end

    private

    def record_redis_command(command)
      return yield unless Thread.current[RedisSubscriber::THREAD_LOCAL_KEY]

      start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      error = nil
      begin
        result = yield
        result
      rescue Exception => e
        error = e
        raise
      ensure
        finish_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        duration_ms = ((finish_time - start_time) * 1000.0).round(2)

        begin
          cmd_info = extract_command_info(command)
          event = {
            event: "redis.command",
            command: cmd_info[:command],
            key: cmd_info[:key],
            args_count: cmd_info[:args_count],
            duration_ms: duration_ms,
            db: safe_db(@db),
            error: error ? error.class.name : nil
          }

          if Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] && RedisSubscriber.should_continue_tracking?
            Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] << event
          end
        rescue
        end
      end
    end

    def record_redis_pipeline(pipeline)
      return yield unless Thread.current[RedisSubscriber::THREAD_LOCAL_KEY]

      start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      begin
        result = yield
        result
      ensure
        finish_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        duration_ms = ((finish_time - start_time) * 1000.0).round(2)

        begin
          commands_count = pipeline.commands&.length || 0
          event = {
            event: "redis.pipeline",
            commands_count: commands_count,
            duration_ms: duration_ms,
            db: safe_db(@db)
          }

          if Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] && RedisSubscriber.should_continue_tracking?
            Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] << event
          end
        rescue
        end
      end
    end

    def record_redis_multi(multi)
      return yield unless Thread.current[RedisSubscriber::THREAD_LOCAL_KEY]

      start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      begin
        result = yield
        result
      ensure
        finish_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        duration_ms = ((finish_time - start_time) * 1000.0).round(2)

        begin
          commands_count = multi.commands&.length || 0
          event = {
            event: "redis.multi",
            commands_count: commands_count,
            duration_ms: duration_ms,
            db: safe_db(@db)
          }

          if Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] && RedisSubscriber.should_continue_tracking?
            Thread.current[RedisSubscriber::THREAD_LOCAL_KEY] << event
          end
        rescue
        end
      end
    end

    def extract_command_info(command)
      parts = Array(command).map(&:to_s)
      command_name = parts.first&.upcase
      key = parts[1]
      args_count = (parts.length > 1) ? parts.length - 1 : 0

      {
        command: safe_command(command_name),
        key: safe_key(key),
        args_count: args_count
      }
    rescue
      {command: nil, key: nil, args_count: nil}
    end

    def safe_command(cmd)
      return nil if cmd.nil?
      cmd.to_s[0, 20]
    rescue
      nil
    end

    def safe_key(key)
      return nil if key.nil?
      s = key.to_s
      (s.length > 200) ? s[0, 200] + "" : s
    rescue
      nil
    end

    def safe_db(db)
      Integer(db)
    rescue
      nil
    end
  end

  ::Redis::Client.prepend(mod) unless ::Redis::Client.ancestors.include?(mod)
rescue
  # Redis::Client may not be available or may have different structure
end

.install_redis_instrumentation!Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/dead_bro/redis_subscriber.rb', line 14

def self.install_redis_instrumentation!
  # Only instrument Redis::Client - this is where commands actually execute
  # Don't instrument Redis class as it has public methods with different signatures
  if defined?(::Redis::Client)
    install_redis_client!
  end

  # Also try ActiveSupport::Notifications if events are available
  install_notifications_subscription!
end

.safe_command(cmd) ⇒ Object



282
283
284
285
286
287
# File 'lib/dead_bro/redis_subscriber.rb', line 282

def self.safe_command(cmd)
  return nil if cmd.nil?
  cmd.to_s[0, 20]
rescue
  nil
end

.safe_db(db) ⇒ Object



297
298
299
300
301
# File 'lib/dead_bro/redis_subscriber.rb', line 297

def self.safe_db(db)
  Integer(db)
rescue
  nil
end

.safe_key(key) ⇒ Object



289
290
291
292
293
294
295
# File 'lib/dead_bro/redis_subscriber.rb', line 289

def self.safe_key(key)
  return nil if key.nil?
  s = key.to_s
  (s.length > 200) ? s[0, 200] + "" : s
rescue
  nil
end

.should_continue_tracking?Boolean

Check if we should continue tracking based on count and time limits

Returns:

  • (Boolean)


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/dead_bro/redis_subscriber.rb', line 225

def self.should_continue_tracking?
  events = Thread.current[THREAD_LOCAL_KEY]
  return false unless events

  # Check count limit
  return false if events.length >= MAX_TRACKED_EVENTS

  # Check time limit
  start_time = Thread.current[DeadBro::TRACKING_START_TIME_KEY]
  if start_time
    elapsed_seconds = Time.now - start_time
    return false if elapsed_seconds >= DeadBro::MAX_TRACKING_DURATION_SECONDS
  end

  true
end

.start_request_trackingObject



214
215
216
# File 'lib/dead_bro/redis_subscriber.rb', line 214

def self.start_request_tracking
  Thread.current[THREAD_LOCAL_KEY] = []
end

.stop_request_trackingObject



218
219
220
221
222
# File 'lib/dead_bro/redis_subscriber.rb', line 218

def self.stop_request_tracking
  events = Thread.current[THREAD_LOCAL_KEY]
  Thread.current[THREAD_LOCAL_KEY] = nil
  events || []
end

.subscribe!Object



8
9
10
11
12
# File 'lib/dead_bro/redis_subscriber.rb', line 8

def self.subscribe!
  install_redis_instrumentation!
rescue
  # Never raise from instrumentation install
end