class ApplicationJob < ActiveJob::Base
  RETRY_LIMIT = 20
  RETRY_WAIT  = 30

  def serialize
    super.merge('attempt_number' => (@attempt_number || 0) + 1)
  end

  def deserialize(job_data)
    super
    @attempt_number = job_data['attempt_number']
  end

  rescue_from(StandardError) do |exception|
    logger.error "Error #{exception.class}: #{exception.message}"
    attempt_number = (@attempt_number || 0)
    if attempt_number > RETRY_LIMIT
      logger.error "Retry limit exceeded! give up."
      raise exception
    end
    retry_job(wait: RETRY_WAIT * (attempt_number+1))
  end
end
