2015-02-25 01:19:12 -05:00
|
|
|
class RandomTopicSelector
|
|
|
|
|
|
|
|
BACKFILL_SIZE = 3000
|
|
|
|
BACKFILL_LOW_WATER_MARK = 500
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def self.backfill(category = nil)
|
2015-02-25 01:19:12 -05:00
|
|
|
exclude = category.try(:topic_id)
|
|
|
|
|
|
|
|
# don't leak private categories into the "everything" group
|
|
|
|
user = category ? CategoryFeaturedTopic.fake_admin : nil
|
|
|
|
|
|
|
|
options = {
|
2017-03-01 12:03:12 -05:00
|
|
|
per_page: category ? category.num_featured_topics : 3,
|
2015-02-25 01:19:12 -05:00
|
|
|
visible: true,
|
|
|
|
no_definitions: true
|
|
|
|
}
|
|
|
|
|
|
|
|
options[:except_topic_ids] = [category.topic_id] if exclude
|
|
|
|
options[:category] = category.id if category
|
|
|
|
|
|
|
|
query = TopicQuery.new(user, options)
|
2016-07-03 20:34:54 -04:00
|
|
|
|
2015-02-25 01:19:12 -05:00
|
|
|
results = query.latest_results.order('RANDOM()')
|
2017-07-27 21:20:09 -04:00
|
|
|
.where(closed: false, archived: false)
|
|
|
|
.where("topics.created_at > ?", SiteSetting.suggested_topics_max_days_old.days.ago)
|
|
|
|
.limit(BACKFILL_SIZE)
|
|
|
|
.reorder('RANDOM()')
|
|
|
|
.pluck(:id)
|
2015-02-25 01:19:12 -05:00
|
|
|
|
|
|
|
key = cache_key(category)
|
|
|
|
results.each do |id|
|
|
|
|
$redis.rpush(key, id)
|
|
|
|
end
|
|
|
|
$redis.expire(key, 2.days)
|
|
|
|
|
|
|
|
results
|
|
|
|
end
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def self.next(count, category = nil)
|
2015-02-25 01:19:12 -05:00
|
|
|
key = cache_key(category)
|
|
|
|
|
|
|
|
results = []
|
|
|
|
|
2015-10-02 01:00:51 -04:00
|
|
|
return results if count < 1
|
2015-02-25 01:19:12 -05:00
|
|
|
|
2015-10-02 01:00:51 -04:00
|
|
|
results = $redis.multi do
|
2017-07-27 21:20:09 -04:00
|
|
|
$redis.lrange(key, 0, count - 1)
|
2015-10-02 01:00:51 -04:00
|
|
|
$redis.ltrim(key, count, -1)
|
2015-02-25 01:19:12 -05:00
|
|
|
end
|
|
|
|
|
2016-03-02 19:26:45 -05:00
|
|
|
if !results.is_a?(Array) # Redis is in readonly mode
|
2017-07-27 21:20:09 -04:00
|
|
|
results = $redis.lrange(key, 0, count - 1)
|
2016-03-02 19:26:45 -05:00
|
|
|
else
|
|
|
|
results = results[0]
|
|
|
|
end
|
|
|
|
|
2015-10-02 01:00:51 -04:00
|
|
|
results.map!(&:to_i)
|
|
|
|
|
|
|
|
left = count - results.length
|
|
|
|
|
2015-02-25 01:19:12 -05:00
|
|
|
backfilled = false
|
|
|
|
if left > 0
|
|
|
|
ids = backfill(category)
|
|
|
|
backfilled = true
|
|
|
|
results += ids[0...count]
|
|
|
|
results.uniq!
|
|
|
|
results = results[0...count]
|
|
|
|
end
|
|
|
|
|
|
|
|
if !backfilled && $redis.llen(key) < BACKFILL_LOW_WATER_MARK
|
|
|
|
Scheduler::Defer.later("backfill") do
|
|
|
|
backfill(category)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
results
|
|
|
|
end
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def self.cache_key(category = nil)
|
2015-02-25 01:19:12 -05:00
|
|
|
"random_topic_cache_#{category.try(:id)}"
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|