OAuth2 身份验证后,ActiveJob 失败并出现“未初始化的常量 GuestsCleanupJob”错误

ActiveJob Fails with 'Uninitialized Constant GuestsCleanupJob' Error After OAuth2 Authentication

提问人:Moin Ahmed 提问时间:11/4/2023 最后编辑:Moin Ahmed 更新时间:11/4/2023 访问量:29

问:

我目前正在使用ActionCable在用户通过身份验证后广播JWT令牌。我已将广播安排在身份验证后 4 秒进行,因为我首先将客户端重定向到登录页面,然后想要广播 JWT 令牌。

应用程序作业类

class ApplicationJob < ActiveJob::Base
  queue_as :mailers

  def perform(devise_mailer, method,user_id, *args)
    user = User.find(user_id)
    devise_maier.send(method,user,*args).deliver_now
  end

end

在 OmniauthCallbacksController 中的google_oauth2操作中,我有以下代码:

  def google_oauth2
  # You need to implement the method below in your model (e.g. app/models/user.rb)
  @user = User.from_omniauth(request.env['omniauth.auth'])
  if @user.persisted?
    flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'        
    sign_in @user, event: :authentication #this will throw if @user is not activated
    token = Warden::JWTAuth::UserEncoder.new.call(@user, :user, nil)[0].to_s                          
    binding.pry
    GuestsCleanupJob.set(wait: 2.second).perform_now(token)
    redirect_to "http://127.0.0.1:3002/", allow_other_host: true  
  else
    session['devise.google_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
    redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
  end

结束

我通过将广播传递给在 Sidekiq 中运行的 ActiveJob 队列来安排广播。下面是相关代码:

   class GuestsCleanupJob < ApplicationJob
  queue_as :default

  def perform(token)
    ActionCable.server.broadcast "ChatChannel", {"type":"token","token":"Bearer #{token}"}       
  end
end

但是,ActiveJob 失败,并显示以下错误日志:

2023-11-03T05:13:31.936Z pid=87046 tid=1fjq WARN: 
2023-11-03T05:13:52.419Z pid=87046 tid=1fl6 class=GuestsCleanupJob jid=5b449cba56dbda04714ea023 INFO: start
2023-11-03T05:13:52.471Z pid=87046 tid=1fl6 class=GuestsCleanupJob jid=5b449cba56dbda04714ea023 elapsed=0.053 INFO: fail
2023-11-03T05:13:52.471Z pid=87046 tid=1fl6 WARN: {"context":"Job raised exception","job":{"retry":true,"queue":"default","class":"ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper","wrapped":"GuestsCleanupJob","args":[{"job_class":"GuestsCleanupJob","job_id":"f3e429cb-2ad3-4259-92e1-4816b8b674af","provider_job_id":null,"queue_name":"default","priority":null,"arguments":["eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmYjA1NDQ0Zi03ZmQ0LTRhZTItYTMwOS0xOTMwZTc3ZWFjYWQiLCJmb28iOiJiYXIiLCJzdWIiOiIxIiwic2NwIjoidXNlciIsImF1ZCI6bnVsbCwiaWF0IjoxNjk4OTg4MzYxLCJleHAiOjE2OTg5OTAxNjF9.0yEhVrnFuYo8ZYE3G3cpbMe34dGJDU8jeTX3g8plqWU"],"executions":0,"exception_executions":{},"locale":"en","timezone":"UTC","enqueued_at":"2023-11-03T05:13:07Z"}],"jid":"5b449cba56dbda04714ea023","created_at":1698988387.1106932,"enqueued_at":1698988432.414398,"error_message":"uninitialized constant GuestsCleanupJob\n\n      Object.const_get(camel_cased_word)\n            ^^^^^^^^^^","error_class":"NameError","failed_at":1698988389.918184,"retry_count":1,"retried_at":1698988411.9304},"_config":{"labels":"#<Set: {}>","require":".","environment":"development","concurrency":1,"timeout":25,"poll_interval_average":null,"average_scheduled_poll_interval":5,"on_complex_arguments":"raise","error_handlers":["#<Proc:0x000000010fe27560 /Users/moinahmed/moin_blog/backendapp/.bundle/ruby/3.1.0/gems/sidekiq-7.1.2/lib/sidekiq/config.rb:37 (lambda)>"],"death_handlers":[],"lifecycle_events":{"startup":[],"quiet":[],"shutdown":[],"heartbeat":[],"beat":["#<Proc:0x00000001105365b8 /Users/moinahmed/moin_blog/backendapp/.bundle/ruby/3.1.0/gems/sidekiq-7.1.2/lib/sidekiq/metrics/tracking.rb:133>"]},"dead_max_jobs":10000,"dead_timeout_in_seconds":15552000,"reloader":"#<Sidekiq::Rails::Reloader @app=Backend::Application>","backtrace_cleaner":"#<Proc:0x00000001128ebe40 /Users/moinahmed/moin_blog/backendapp/.bundle/ruby/3.1.0/gems/sidekiq-7.1.2/lib/sidekiq/rails.rb:59 (lambda)>","queues":["default","mailers"],"config_file":"./config/sidekiq.yml","tag":"backendapp","identity":"Moins-MacBook-Air.local:87046:f520db71521f"}}
2023-11-03T05:13:52.473Z pid=87046 tid=1fl6 WARN: NameError: uninitialized constant GuestsCleanupJob

      Object.const_get(camel_cased_word)

我将不胜感激任何帮助或见解,说明为什么 ActiveJob 失败并出现“未初始化的常量 GuestsCleanupJob”错误。

我尝试在我的ActiveJob类周围添加命名空间

    module Jobs
class GuestsCleanupJob < ApplicationJob
  queue_as :default

  def perform(token)
    ActionCable.server.broadcast "ChatChannel", {"type":"token","token":"Bearer #{token}"}       
  end
end
end

但是上述更改会引发相同的错误

NameError:未初始化的常量作业

仅供参考,发送设计邮件的应用程序作业工作正常,没有任何问题

RUBY 版本: 3..铁轨。7

Ruby-on-Rails Sidekiq 操作电缆 导轨-ActiveJob

评论

0赞 Moin Ahmed 11/4/2023
我明白了,GuestsCleanupJob.rb 的路径是 app/jobs/guests_cleanup_job.rb
0赞 Moin Ahmed 11/4/2023
在类定义周围添加命名空间后,我收到以下错误------------------ ------------------错误 Zeitwerk::NameError: expected file /Users/moinahmed/backendapp/app/jobs/guests_cleanup_job.rb 来定义常量 GuestsCleanupJob,但没有ruby module Jobs class GuestsCleanupJob < ApplicationJob queue_as :default ruby Copy code def perform(token) ActionCable.server.broadcast "ChatChannel", {"type":"token","token":"Bearer #{token}"} end end end
0赞 Moin Ahmed 11/4/2023
我尝试在控制台中运行 GuestsCleanupJob.set(wait: 2.second).perform_later('token'),再次出现同样的错误,它返回以下对象 tough #<GuestsCleanupJob:0x00000001096296c0 @arguments=[“token”], @exception_executions={}, @executions=0, @job_id=“3fe2b92f-a269-4576-a90c-164b44d64af4”, @priority=nil, @provider_job_id=“287e7b2624a36065d86986df”, @queue_name=“default”, @scheduled_at=1699045838.294488, @successfully_enqueued=true, @timezone=“UTC”>
0赞 dbugger 11/4/2023
三件事:1)确保没有其他名为 GuestsCleanupJob 的类。2) 尝试注释掉 ApplicationJob 类中的 perform 方法。 3) 如果删除 .set() 调用,控制台中的调用是否有效?
0赞 Moin Ahmed 11/4/2023
如果使用perform_now,则该工作工作正常,没有设置任何延迟,perform_later,我收到错误,所以问题出在稍后执行

答: 暂无答案