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

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

Options Hash (opts):

  • :expiration (Fixnum)

    ttl for complete jobs



12
13
14
# File 'lib/sidekiq-status/server_middleware.rb', line 12

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



26
27
28
29
30
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
# File 'lib/sidekiq-status/server_middleware.rb', line 26

def call(worker, msg, queue)

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

  # Determine the actual job class
  klass = (!msg["args"][0].is_a?(String) && 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

  begin
    # 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'], Sidekiq::JobRetry::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
end