Class: Sidekiq::Status::ServerMiddleware

Inherits:
Object
  • Object
show all
Includes:
Storage
Defined in:
lib/sidekiq-status/server_middleware.rb

Overview

Should be in the server middleware chain

Constant Summary collapse

DEFAULT_MAX_RETRY_ATTEMPTS =
Sidekiq.major_version >= 5 ? Sidekiq::JobRetry::DEFAULT_MAX_RETRY_ATTEMPTS : 25

Constants included from Storage

Sidekiq::Status::Storage::BATCH_LIMIT, Sidekiq::Status::Storage::RESERVED_FIELDS

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ ServerMiddleware

Parameterized initialization, use it when adding middleware to server chain chain.add Sidekiq::Status::ServerMiddleware, :expiration => 60 * 5

Parameters:

  • opts (Hash) (defaults to: {})

    middleware initialization options

Options Hash (opts):

  • :expiration (Fixnum)

    ttl for complete jobs


17
18
19
# File 'lib/sidekiq-status/server_middleware.rb', line 17

def initialize(opts = {})
  @expiration = opts[:expiration]
end

Instance Method Details

#call(worker, msg, queue) ⇒ Object

Uses sidekiq's internal jid as id puts :working status into Redis hash initializes worker instance with id

Exception handler sets :failed status, re-inserts worker and re-throws the exception Worker::Stopped exception type are processed separately - :stopped status is set, no re-throwing

Parameters:

  • worker (Worker)

    worker instance, processed here if its class includes Status::Worker

  • msg (Array)

    job args, should have jid format

  • queue (String)

    queue name


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sidekiq-status/server_middleware.rb', line 31

def call(worker, msg, queue)

  # Initial assignment to prevent SystemExit & co. from excepting
  expiry = @expiration

  # Determine the actual job class
  klass = msg["args"][0]["job_class"] || msg["class"] rescue msg["class"]
  job_class = klass.is_a?(Class) ? klass : Module.const_get(klass)

  # Bypass unless this is a Sidekiq::Status::Worker job
  unless job_class.ancestors.include?(Sidekiq::Status::Worker)
    yield
    return
  end

  # Determine job expiration
  expiry = job_class.new.expiration || @expiration rescue @expiration

  store_status worker.jid, :working,  expiry
  yield
  store_status worker.jid, :complete, expiry
rescue Worker::Stopped
  store_status worker.jid, :stopped, expiry
rescue SystemExit, Interrupt
  store_status worker.jid, :interrupted, expiry
  raise
rescue Exception
  status = :failed
  if msg['retry']
    if retry_attempt_number(msg) < retry_attempts_from(msg['retry'], DEFAULT_MAX_RETRY_ATTEMPTS)
      status = :retrying
    end
  end
  store_status(worker.jid, status, expiry) if job_class && job_class.ancestors.include?(Sidekiq::Status::Worker)
  raise
end