Sidekiq在运行时导致StackLevelTooDeep错误

时间:2013-06-07 16:13:32

标签: ruby ruby-on-rails-3 sidekiq

以下是我的Sidekiq设置:

调用我的后台进程的控制器

BackgroundStatCalculator.perform_async @game.athlete.id, @game.id, current_athlete_sport.id

Sidekiq工人:

class BackgroundStatCalculator
  include Sidekiq::Worker

  def perform(user_id, game_id, sport_id)
    sport = Sport.find sport_id
    sport.stat_type_categories.each do |st_cat|
      calc = "StatCalculators::#{st_cat.name}".constantize.new(user_id, game_id)
      calc.run_calculations
    end
  end
end

计算器:

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      @user = User.find(user_id)
      @game = Game.find(game_id)
    end

    def save_completion_percentage
      completions = Stat.for_type("Completions").for_user(@user).sum(:float_value)
      attempts = Stat.for_type("Pass Attempts").for_user(@user).sum(:float_value)
      value = completions/attempts
      stat = Stat.new(value: value, game_id: @game.id, athlete_id: @user.id, float_value: value)
      stat.save(validate: false)
    end

    def run_calculations
      klass = self.class
      klass.instance_methods(false).each do |method|
        klass.instance_method(method).bind(self).call
      end
    end
  end
end

堆栈跟踪:

2013-06-07T17:55:34Z 73625 TID-ov6v51sww BackgroundStatCalculator JID-5bab7cec30523a4b12dd6438 INFO: fail: 5.155 sec
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: {"retry"=>true, "queue"=>"default", "class"=>"BackgroundStatCalculator", "args"=>[58, 68, 6], "jid"=>"5bab7cec30523a4b12dd6438", "error_message"=>"stack level too deep", "error_class"=>"SystemStackError", "failed_at"=>"2013-06-07T17:42:01Z", "retry_count"=>5, "retried_at"=>2013-06-07 17:55:34 UTC}
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: stack level too deep
2013-06-07T17:55:34Z 73625 TID-ov6v51sww WARN: /Users/dennismonsewicz/.rvm/gems/ruby-1.9.3-p429/gems/sidekiq-2.7.4/lib/sidekiq/processor.rb:88

出于某种原因,在调用.perform_async时,它不会只执行一次并完成...它会将100行转储到我的数据库中。

之前有人遇到过这个问题吗?我对Sidekiq工作相当新,所以我为我的无知道歉

1 个答案:

答案 0 :(得分:2)

你创建了一个无限循环的调用,导致堆栈溢出。

您的run_calculations方法会调用其所在对象上的每个实例方法,其中包括run_calculations。您需要从列表中筛选出此方法或更好的方法,找到一种方法来仅列出您要调用的计算方法。也许使用像“计算_”这样的前缀。

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      ...
    end

    def calculate_completion_percentage
       ...
    end

    def run_calculations
      klass = self.class
      calculation_methods = klass.instance_methods(false).select do |method|
         method.to_s.match /calculate_/
      end
      calculation_methods.each do |method|
        klass.instance_method(method).bind(self).call
      end
    end
  end
end