Class: Faye::Redis::SubscriptionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/faye/redis/subscription_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, options = {}) ⇒ SubscriptionManager

Returns a new instance of SubscriptionManager.



6
7
8
9
10
# File 'lib/faye/redis/subscription_manager.rb', line 6

def initialize(connection, options = {})
  @connection = connection
  @options = options
  @pattern_cache = {}  # Cache compiled regexes for pattern matching performance
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



4
5
6
# File 'lib/faye/redis/subscription_manager.rb', line 4

def connection
  @connection
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/faye/redis/subscription_manager.rb', line 4

def options
  @options
end

Instance Method Details

#channel_matches_pattern?(channel, pattern) ⇒ Boolean

Check if a channel matches a pattern Uses memoization to cache compiled regexes for performance

Returns:

  • (Boolean)


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/faye/redis/subscription_manager.rb', line 212

def channel_matches_pattern?(channel, pattern)
  # Get or compile regex for this pattern
  regex = @pattern_cache[pattern] ||= begin
    # Escape the pattern first to handle special regex characters
    # Then replace escaped wildcards with regex patterns
    # ** matches multiple segments (including /), * matches one segment (no /)
    escaped = Regexp.escape(pattern)

    regex_pattern = escaped
      .gsub(Regexp.escape('**'), '.*')        # ** → .* (match anything)
      .gsub(Regexp.escape('*'), '[^/]+')      # * → [^/]+ (match one segment)

    Regexp.new("^#{regex_pattern}$")
  end

  !!(channel =~ regex)
rescue RegexpError => e
  log_error("Invalid pattern #{pattern}: #{e.message}")
  false
end

#cleanup_client_subscriptions(client_id) ⇒ Object

Clean up subscriptions for a client



234
235
236
# File 'lib/faye/redis/subscription_manager.rb', line 234

def cleanup_client_subscriptions(client_id)
  unsubscribe_all(client_id)
end

#cleanup_orphaned_data(active_client_ids, &callback) ⇒ Object

Comprehensive cleanup of orphaned subscription data This should be called periodically during garbage collection Processes in batches to avoid blocking the connection pool



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
# File 'lib/faye/redis/subscription_manager.rb', line 241

def cleanup_orphaned_data(active_client_ids, &callback)
  active_set = active_client_ids.to_set
  namespace = @options[:namespace] || 'faye'
  batch_size = @options[:cleanup_batch_size] || 50

  # Validate and clamp batch_size to safe range (1-1000)
  batch_size = [[batch_size.to_i, 1].max, 1000].min

  # Phase 1: Scan for orphaned subscriptions
  scan_orphaned_subscriptions(active_set, namespace) do |orphaned_subscriptions|
    # Phase 2: Clean up orphaned subscriptions in batches
    cleanup_orphaned_subscriptions_batched(orphaned_subscriptions, namespace, batch_size) do
      # Phase 3: Clean up orphaned message queues
      cleanup_orphaned_message_queues_async(active_set, namespace, batch_size) do
        # Phase 4: Clean up empty channels (yields between operations)
        cleanup_empty_channels_async(namespace) do
          # Phase 5: Clean up unused patterns
          cleanup_unused_patterns_async do
            callback.call if callback
          end
        end
      end
    end
  end
rescue => e
  log_error("Failed to cleanup orphaned data: #{e.message}")
  EventMachine.next_tick { callback.call } if callback
end

#get_client_subscriptions(client_id, &callback) ⇒ Object

Get all channels a client is subscribed to



151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/faye/redis/subscription_manager.rb', line 151

def get_client_subscriptions(client_id, &callback)
  channels = @connection.with_redis do |redis|
    redis.smembers(client_subscriptions_key(client_id))
  end

  EventMachine.next_tick { callback.call(channels) } if callback
  channels
rescue => e
  log_error("Failed to get subscriptions for client #{client_id}: #{e.message}")
  EventMachine.next_tick { callback.call([]) } if callback
  []
end

#get_pattern_subscribers(channel) ⇒ Object

Get subscribers matching wildcard patterns



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/faye/redis/subscription_manager.rb', line 185

def get_pattern_subscribers(channel)
  patterns = @connection.with_redis do |redis|
    redis.smembers(patterns_key)
  end

  # Filter to only matching patterns first
  matching_patterns = patterns.select { |pattern| channel_matches_pattern?(channel, pattern) }
  return [] if matching_patterns.empty?

  # Use pipelining to fetch all matching pattern subscribers in one network round-trip
  results = @connection.with_redis do |redis|
    redis.pipelined do |pipeline|
      matching_patterns.each do |pattern|
        pipeline.smembers(channel_subscribers_key(pattern))
      end
    end
  end

  # Flatten and deduplicate results
  results.flatten.uniq
rescue => e
  log_error("Failed to get pattern subscribers for channel #{channel}: #{e.message}")
  []
end

#get_subscribers(channel, &callback) ⇒ Object

Get all clients subscribed to a channel



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/faye/redis/subscription_manager.rb', line 165

def get_subscribers(channel, &callback)
  # Get direct subscribers
  direct_subscribers = @connection.with_redis do |redis|
    redis.smembers(channel_subscribers_key(channel))
  end

  # Get pattern subscribers
  pattern_subscribers = get_pattern_subscribers(channel)

  all_subscribers = (direct_subscribers + pattern_subscribers).uniq

  EventMachine.next_tick { callback.call(all_subscribers) } if callback
  all_subscribers
rescue => e
  log_error("Failed to get subscribers for channel #{channel}: #{e.message}")
  EventMachine.next_tick { callback.call([]) } if callback
  []
end

#refresh_client_subscriptions_ttl(client_id) ⇒ Object

Refresh TTL for all subscription keys related to a client Called during ping to keep subscriptions alive as long as client is connected



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
# File 'lib/faye/redis/subscription_manager.rb', line 123

def refresh_client_subscriptions_ttl(client_id)
  subscription_ttl = @options[:subscription_ttl] || 3600

  @connection.with_redis do |redis|
    # Get all channels this client is subscribed to
    channels = redis.smembers(client_subscriptions_key(client_id))
    return if channels.empty?

    # Use pipeline to refresh all TTLs efficiently
    redis.pipelined do |pipeline|
      # Refresh client's subscriptions set
      pipeline.expire(client_subscriptions_key(client_id), subscription_ttl)

      # Refresh each subscription metadata and channel subscriber set
      channels.each do |channel|
        pipeline.expire(subscription_key(client_id, channel), subscription_ttl)
        pipeline.expire(channel_subscribers_key(channel), subscription_ttl)
      end

      # Refresh patterns set if it exists
      pipeline.expire(patterns_key, subscription_ttl)
    end
  end
rescue => e
  log_error("Failed to refresh subscription TTL for client #{client_id}: #{e.message}")
end

#subscribe(client_id, channel, &callback) ⇒ Object

Subscribe a client to a channel



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
# File 'lib/faye/redis/subscription_manager.rb', line 13

def subscribe(client_id, channel, &callback)
  timestamp = Time.now.to_i
  subscription_ttl = @options[:subscription_ttl] || 3600  # 1 hour default (matches message_ttl)

  client_subs_key = client_subscriptions_key(client_id)
  channel_subs_key = channel_subscribers_key(channel)
  sub_key = subscription_key(client_id, channel)

  @connection.with_redis do |redis|
    # Use Lua script to atomically add subscriptions and set TTL only if keys have no TTL
    # This prevents resetting TTL on re-subscription
    redis.eval(<<-LUA, keys: [client_subs_key, channel_subs_key, sub_key], argv: [channel, client_id, timestamp.to_s, subscription_ttl])
      -- Add channel to client's subscriptions
      redis.call('SADD', KEYS[1], ARGV[1])
      local ttl1 = redis.call('TTL', KEYS[1])
      if ttl1 == -1 then
        redis.call('EXPIRE', KEYS[1], ARGV[4])
      end

      -- Add client to channel's subscribers
      redis.call('SADD', KEYS[2], ARGV[2])
      local ttl2 = redis.call('TTL', KEYS[2])
      if ttl2 == -1 then
        redis.call('EXPIRE', KEYS[2], ARGV[4])
      end

      -- Store subscription metadata
      redis.call('HSET', KEYS[3], 'subscribed_at', ARGV[3], 'channel', ARGV[1], 'client_id', ARGV[2])
      local ttl3 = redis.call('TTL', KEYS[3])
      if ttl3 == -1 then
        redis.call('EXPIRE', KEYS[3], ARGV[4])
      end

      return 1
    LUA

    # Handle wildcard patterns separately
    if channel.include?('*')
      redis.eval(<<-LUA, keys: [patterns_key], argv: [channel, subscription_ttl])
        redis.call('SADD', KEYS[1], ARGV[1])
        local ttl = redis.call('TTL', KEYS[1])
        if ttl == -1 then
          redis.call('EXPIRE', KEYS[1], ARGV[2])
        end
        return 1
      LUA
    end
  end

  EventMachine.next_tick { callback.call(true) } if callback
rescue => e
  log_error("Failed to subscribe client #{client_id} to #{channel}: #{e.message}")
  EventMachine.next_tick { callback.call(false) } if callback
end

#unsubscribe(client_id, channel, &callback) ⇒ Object

Unsubscribe a client from a channel



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/faye/redis/subscription_manager.rb', line 69

def unsubscribe(client_id, channel, &callback)
  @connection.with_redis do |redis|
    redis.multi do |multi|
      # Remove channel from client's subscriptions
      multi.srem?(client_subscriptions_key(client_id), channel)

      # Remove client from channel's subscribers
      multi.srem?(channel_subscribers_key(channel), client_id)

      # Delete subscription metadata
      multi.del(subscription_key(client_id, channel))
    end
  end

  # Clean up wildcard pattern if no more subscribers
  if channel.include?('*')
    cleanup_pattern_if_unused(channel)
  end

  EventMachine.next_tick { callback.call(true) } if callback
rescue => e
  log_error("Failed to unsubscribe client #{client_id} from #{channel}: #{e.message}")
  EventMachine.next_tick { callback.call(false) } if callback
end

#unsubscribe_all(client_id, &callback) ⇒ Object

Unsubscribe a client from all channels



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
# File 'lib/faye/redis/subscription_manager.rb', line 95

def unsubscribe_all(client_id, &callback)
  # Get all channels the client is subscribed to
  get_client_subscriptions(client_id) do |channels|
    if channels.empty?
      callback.call(true) if callback
    else
      # Unsubscribe from each channel
      remaining = channels.size
      callback_called = false  # Prevent race condition
      channels.each do |channel|
        unsubscribe(client_id, channel) do
          remaining -= 1
          # Check flag to prevent multiple callback invocations
          if remaining == 0 && !callback_called && callback
            callback_called = true
            callback.call(true)
          end
        end
      end
    end
  end
rescue => e
  log_error("Failed to unsubscribe client #{client_id} from all channels: #{e.message}")
  EventMachine.next_tick { callback.call(false) } if callback
end