首页
/ Sidekiq中CurrentAttributes在回调中丢失的问题分析与解决

Sidekiq中CurrentAttributes在回调中丢失的问题分析与解决

2025-05-17 10:24:43作者:范靓好Udolf

在Rails应用开发中,我们经常会使用Sidekiq来处理后台任务。近期在使用Sidekiq 7.3.1版本时,发现了一个关于CurrentAttributes在回调中丢失的问题,这个问题可能会影响到依赖CurrentAttributes的业务逻辑。

问题现象

当在Sidekiq作业的回调方法中尝试访问CurrentAttributes时,发现这些属性值为nil。这与预期行为不符,因为按照Sidekiq的设计,CurrentAttributes应该在作业之间传递。

问题根源

经过分析,这个问题源于Sidekiq中间件的执行顺序。具体来说:

  1. Sidekiq的CurrentAttributes中间件默认被"添加"到中间件链中,而不是"前置"插入
  2. Batch中间件在CurrentAttributes中间件之后执行
  3. 当作业执行完成后,中间件开始"解栈"(unwind)执行
  4. CurrentAttributes中间件先被解栈,清除了Current属性
  5. 然后Batch中间件才开始处理回调逻辑

这种执行顺序导致了回调方法中无法访问到CurrentAttributes。

解决方案

临时解决方案

在等待官方修复前,可以采用手动传递Current属性的方式:

class Workflow
  def create_step_batch
    callback_params = Current.to_sidekiq_callback_params(**@params)
    
    step_batch = Sidekiq::Batch.new
    step_batch.on(:success, "#{self.class.name}#callback", **callback_params)
    step_batch
  end

  def callback(status, data)
    @params = Current.from_sidekiq_callback_params(data.symbolize_keys)
    finish
  end
end

class Current < ActiveSupport::CurrentAttributes
  def to_sidekiq_callback_params(**params)
    params.merge(current: { sidekiq_wid: })
  end

  def from_sidekiq_callback_params(data)
    data = data.symbolize_keys

    if (sidekiq = data[:current].symbolize_keys)
      self.sidekiq_wid = sidekiq[:sidekiq_wid]
    end

    data.except(:current)
  end
end

官方修复方案

Sidekiq官方已经修复了这个问题,解决方案是调整CurrentAttributes中间件的加载方式:

  1. 不再使用Rails的to_prepare回调
  2. 直接使用字符串形式的类名进行持久化配置
Sidekiq::CurrentAttributes.persist("::Current")

这个修复确保了CurrentAttributes中间件能够正确地在中间件链的最前面插入,从而保证在回调方法中也能访问到CurrentAttributes。

最佳实践建议

  1. 当需要在Sidekiq回调中使用CurrentAttributes时,建议升级到包含此修复的Sidekiq版本
  2. 如果暂时无法升级,可以采用手动传递属性的方式作为临时解决方案
  3. 在初始化Sidekiq时,避免使用Rails的to_prepare回调来配置CurrentAttributes
  4. 使用字符串形式的类名(包含命名空间)来配置CurrentAttributes持久化

这个问题提醒我们,在使用框架提供的线程局部变量时,需要特别注意中间件的执行顺序和生命周期管理,特别是在异步任务和回调场景中。

登录后查看全文
热门项目推荐