From ef04f3879ac3bd7ec6dddd6cb843c8cdb79a1175 Mon Sep 17 00:00:00 2001 From: multiple creatures Date: Wed, 7 Aug 2019 01:08:07 -0500 Subject: add option to automatically space out boosts over configurable random intervals --- app/workers/reblog_status_worker.rb | 17 +++++++++++ app/workers/scheduler/boosts_scheduler.rb | 49 +++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 app/workers/reblog_status_worker.rb create mode 100644 app/workers/scheduler/boosts_scheduler.rb (limited to 'app/workers') diff --git a/app/workers/reblog_status_worker.rb b/app/workers/reblog_status_worker.rb new file mode 100644 index 000000000..c0b2153b2 --- /dev/null +++ b/app/workers/reblog_status_worker.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +class ReblogStatusWorker + include Sidekiq::Worker + + sidekiq_options unique: :until_executed + + def perform(account_id, status_id, reblog_params = {}) + account = Account.find(account_id) + status = Status.find(status_id) + return false if status.destroyed? + ReblogService.new.call(account, status, reblog_params.symbolize_keys) + true + rescue ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid + true + end +end diff --git a/app/workers/scheduler/boosts_scheduler.rb b/app/workers/scheduler/boosts_scheduler.rb new file mode 100644 index 000000000..de0d89992 --- /dev/null +++ b/app/workers/scheduler/boosts_scheduler.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +class Scheduler::BoostsScheduler + include Sidekiq::Worker + include Redisable + + sidekiq_options unique: :until_executed, retry: 0 + + def perform + process_queued_boosts! + end + + private + + def process_queued_boosts! + queued_accounts.find_each do |account| + next if redis.exists("queued_boost:#{account.id}") || account&.user.nil? + + q = next_boost(account.id, account.user.boost_random?) + next if q.empty? + + from_interval = account.user.boost_interval_from + to_interval = account.user.boost_interval_to + + if from_interval > to_interval + from_interval, to_interval = [to_interval, from_interval] + end + + interval = rand(from_interval .. to_interval).minutes + + redis.setex("queued_boost:#{account.id}", interval, 1) + ReblogStatusWorker.perform_async(account.id, q.first.status_id, distribute: true) + q.destroy_all + end + end + + def queued_accounts + Account.where(id: queued_account_ids) + end + + def queued_account_ids + QueuedBoost.distinct.pluck(:account_id) + end + + def next_boost(account_id, boost_random = false) + q = QueuedBoost.where(account_id: account_id) + (boost_random ? q.order(Arel.sql('RANDOM()')) : q.order(:id)).limit(1) + end +end -- cgit