Skip to content
Edit this page View source of this page

If you're new to background jobs, read How jobs work and follow Run your first background job before you use this reference.

Mankai

mankai-jobs

mankai-jobs adds background jobs to Hanami apps. This page is the reference for its provider and job settings, results, enqueue API, events, testing helpers, CLI, and backend interface. It's for Hanami developers who already know what a job is. If you're new to jobs, follow Run your first background job and read How jobs work. For task-by-task instructions, see the jobs guides.

mankai-jobs follows these design choices:

  • Jobs are components. A file in app/jobs/ registers under the jobs container namespace, for example app/jobs/send_welcome.rb as jobs.send_welcome. This container key is the job's job key. A job gets its collaborators through Deps.
  • Enqueuing is explicit. You inject an enqueuer, and it returns a dry-monads Result instead of raising an exception.
  • Arguments are plain JSON. An optional dry-schema contract checks them when the job is enqueued and again before it runs. Other types need serializers that you opt in to.
  • Jobs are found by job key, never by Ruby constant name. Only keys under the jobs namespace that resolve to a job can run.
  • Behavior is declared on the job class. Retries, discards, and callbacks are visible in one place, and a replaceable RetryPolicy interprets them.
  • Storage is a backend that you choose per environment. Other gems can add backends.

Backends

A backend stores jobs and decides what runs them. The following table lists the available backends and when to use each one:

Backend Gem Use it for
:memory Built in Tests. Jobs wait until the test runs them with drain.
:inline Built in Scripts. Each job runs immediately, in the code that enqueues it.
:async Built in Trying jobs without a database. Jobs run on a thread pool in the current process, and nothing is stored.
Mankai::Jobs::SQL.backend(...) mankai-jobs-sql Development and production on PostgreSQL, MySQL 8 or later, MariaDB 10.6 or later, or SQLite.

The :memory, :inline, and :async backends are the built-in backends. Use the SQL backend in development too, with a worker process, so jobs behave the way they do in production.

Set config.backend to one of the built-in backends, to a backend from an adapter gem such as mankai-jobs-sql, or to your own. A backend ignores the job settings that it doesn't support: the job still enqueues and runs without them. The following table shows which features each backend supports:

Feature Memory Inline Async SQL
When jobs run When you call drain (tests) Immediately, in the caller On threads in the current process In worker processes (hanami jobs start)
Scheduling (at:, wait:) Yes Ignored Yes Yes
Retries and snoozes Yes No: a job runs once Yes Yes
priority Ignored: first in, first out Ignored Ignored Yes
Unique jobs Yes Yes Yes Yes
timeout Yes Yes Yes Yes
Concurrency limits Ignored Ignored Ignored Yes
transactional Ignored Ignored Ignored Yes
Keeps finished jobs (record_output, preserve_finished, hanami jobs clear) No No No Yes
Recurring tasks No No No Yes
Jobs survive a restart No Not applicable No Yes

The backend_options provider setting configures the built-in backends:

Backend Option Default Description
:inline raise_on_failure true If true, a job that doesn't succeed makes the enqueue return Failure[:backend_error, Mankai::Jobs::JobFailedError], so scripts notice. If false, the backend only logs the failure, and the enqueue succeeds.
:async threads 3 The number of threads that run jobs.
:async shutdown_timeout 5 The number of seconds that running jobs get to finish when the app stops. Jobs that are still waiting when the process exits are lost.

The :memory backend has no options.

hanami jobs start needs a backend with worker processes, such as the SQL backend. With a built-in backend, the command stops with an error, because those backends run jobs inside the process that enqueued them.

Installation

To add mankai-jobs to a Hanami app, follow these steps:

  1. Add the gems to your Gemfile. The :cli group adds the hanami jobs commands:

    # Gemfile
    gem "mankai-jobs", group: [:default, :cli]
    gem "mankai-jobs-sql", group: [:default, :cli]
    
  2. Install the bundle:

    bundle install
    
  3. Create a base job class in app/job.rb. The auto_register: false comment stops Hanami from registering the base class as a job:

    # app/job.rb
    # auto_register: false
    require "mankai/jobs"
    
    module Bookshelf
      class Job < Mankai::Jobs::Job
      end
    end
    
  4. Register the queue provider in config/providers/queue.rb. This example uses the memory backend in tests and the SQL backend everywhere else:

    # config/providers/queue.rb
    require "mankai/jobs"
    require "mankai/jobs/sql"
    
    Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
      configure do |config|
        config.backend =
          if Hanami.env?(:test)
            :memory
          else
            Mankai::Jobs::SQL.backend(workers: [{queues: ["default", "mailers"], threads: 3}])
          end
      end
    end
    
  5. Install the SQL backend's tables. See Installation in the mankai-jobs-sql reference.

  6. Start the jobs processes next to your web server. With the SQL backend, jobs run only in these separate processes. If you use bin/dev, add a worker line to Procfile.dev:

    web: bundle exec hanami server
    worker: bundle exec hanami jobs start
    

The examples on this page use Bookshelf as the app module. Replace it with your app's module.

Provider components

The provider registers the following components:

Component Description
queue.enqueuer The enqueuer. Inject it to enqueue jobs.
queue.backend The backend. Use it for administration and in tests.
queue.runner The runner, which runs one job and returns its outcome.
queue.builder The envelope builder, which turns a job key and arguments into an envelope.
queue.registry The registry, which resolves job keys across the app and its slices.

Give the provider a name that differs from the jobs namespace (jobs), so that its own components can never be mistaken for jobs. The examples use queue.

An envelope is the stored form of a job: its ID, job key, arguments, queue, priority, attempts, metadata, and scheduled time.

Provider settings

Set the following settings inside the provider's configure block:

Setting Default Description
backend :memory The backend: :memory, :inline, or :async; a factory that responds to call(context), such as SQL.backend(...); or a backend object.
backend_options {} Options for a built-in backend. See Backends.
jobs_namespace "jobs" The container namespace that jobs are resolved from.
middleware [] Perform middleware, outermost first. See Middleware.
enqueue_middleware [] Enqueue middleware, outermost first. See Middleware.
log_jobs true If true, logs the start and end of each job.
retry_policy nil The object that decides what happens after a failure. nil uses RetryPolicy.new. A replacement needs the same #call.
error_reporter nil A callable that receives (error, context) when a job fails permanently, or when a rule with report: true matches. context is {job:, id:, attempts:, status:}.
serializers [] Argument types that you opt in to. See Arguments.
queue_prefix nil A prefix for every queue name. For example, "staging" turns "default" into "staging_default".
capture_locale false If true, runs each job in the locale it was enqueued in. Needs an i18n component.
recurring {} Recurring task definitions. See Recurring tasks.
registry nil The job registry. nil uses a registry that spans the app and its slices.
logger_key "logger" The container key of the logger. Without a logger, logs go to $stdout.
notifications_key "notifications" The container key of the events bus. Without a bus, no events are published.
i18n_key "i18n" The container key of the I18n component that capture_locale uses.
clock -> { Time.now.utc } A callable that returns the current time. Override it in tests.

Jobs

The following job uses each kind of declaration:

# app/jobs/send_welcome.rb
module Bookshelf
  module Jobs
    class SendWelcome < Bookshelf::Job
      config.queue = "mailers"
      config.max_attempts = 3

      contract do
        required(:user_id).filled(:integer)
      end

      retry_on Net::ReadTimeout, "Faraday::TimeoutError", attempts: 5, wait: :exponential
      retry_on :rate_limited, attempts: :unlimited, wait: ->(attempt, _error) { 60 * attempt }
      discard_on :user_missing, report: true

      include Deps["repos.user_repo", "mailers.welcome"]

      def call(user_id:)
        user = user_repo.find(user_id) or return Failure(:user_missing)
        welcome.deliver(user:)
        Success()
      end
    end
  end
end

Caution: Outside tests, Hanami creates each component once and reuses it, so several threads might share one job instance. Don't keep per-run state in instance variables. Everything a run needs arrives as arguments.

To read the envelope inside a job, declare an envelope: keyword:

include Deps["logger"]

def call(user_id:, envelope:)
  logger.info("attempt #{envelope.attempts} of job #{envelope.id}")
  Success()
end

envelope and steps are reserved keyword names. The runner passes them only to a #call that declares them.

Job settings

Set these settings with config.NAME = VALUE on the job class. Subclasses inherit them, so put shared settings on Bookshelf::Job:

Setting Default Description
queue "default" The queue name, or a lambda that receives the arguments and returns a name.
priority 0 The priority within a queue, or a lambda that receives the arguments. Lower values run first. Only the SQL backend uses it.
max_attempts 1 The maximum number of runs, including the first, for errors that no retry_on rule matches. 1 disables these retries.
backoff :polynomial The delay before each of those retries: :polynomial (attempt**4 + 2 seconds), :exponential (3 * 2**(attempt - 1) seconds), a number of seconds, or ->(attempt, error) { seconds }.
jitter 0.15 A random extra delay, as a fraction of the backoff.
concurrency nil The concurrency limit. See Concurrency limits.
unique nil The uniqueness rule. See Unique jobs.
timeout nil The number of seconds a run can take. After that, the runner raises Mankai::Jobs::JobTimeoutError inside the job and handles it like any other error, so you can match it with retry_on.
record_output false If true, keeps the value of a successful run (Success(value) or a plain return value). The value must be JSON-safe. If it isn't, the runner logs and skips it, and the job still succeeds.
preserve_finished nil If true, keeps the job after it finishes. If false, deletes it. If nil, uses the backend's setting. Failed jobs are always kept.
transactional false If true, runs the job and marks it finished in one database transaction (SQL backend only), so the job's writes and its completion commit or roll back together.

Results

The value that #call returns decides what happens next:

Return value Result
Success(...), or any value that isn't a Result The job succeeds.
discard(reason) The job finishes as discarded. It isn't recorded as failed.
retry_later(reason, wait: seconds) The job runs again after wait seconds, or after the backoff if you omit wait. The retry uses up an attempt from max_attempts.
snooze(seconds) The job runs again after seconds without using up an attempt. Use it for "not yet" rather than "failed", such as a rate limit or a file that's still uploading. envelope.metadata["snoozes"] counts the snoozes.
Any other Failure, or a raised exception The first matching rule retries or discards the job. If no rule matches, the runner retries the job with backoff until it reaches max_attempts, then records it as failed.

The default max_attempts is 1, so a job that returns retry_later fails immediately unless you raise max_attempts.

The runner rescues every exception that a job raises, including ScriptError and SystemExit, and applies the job's rules to it. It doesn't rescue SignalException or NoMemoryError.

Retry and discard rules

A rule matches an exception class, an exception class name as a string (for classes that might not be loaded), or a failure symbol. A symbol matches Failure(:rate_limited) and Failure[:rate_limited, details]. The following methods declare rules:

Method Description
retry_on *errors, attempts: 5, wait: :polynomial, jitter: nil, report: false Retries a matching error until the rule's own attempts are used up, then fails the job. attempts can be :unlimited. Each rule counts its own attempts, separately from max_attempts.
discard_on *errors, report: false Finishes the job as discarded, without recording a failure.

If a rule has report: true, the runner also calls the provider's error_reporter when the rule matches.

The runner checks discard_on rules first, then retry_on rules, then retry_later and max_attempts.

Unique jobs

A unique job blocks duplicates while it's waiting, running, or retrying. Enqueuing a duplicate returns Failure[:duplicate, existing_job_id]. Set config.unique to a hash with the following keys:

Key Default Description
by :args What makes two jobs duplicates: all arguments (:args), one argument name, a list of argument names ([] for none), or a lambda that receives the arguments and returns a value.
queue false If true, jobs on different queues are never duplicates.
period nil A number of seconds. If set, a job that succeeded keeps blocking duplicates until its period ends. Periods are aligned to multiples of period from the Unix epoch, by enqueue time.

The following settings show common uniqueness rules:

config.unique = {}                                # duplicates have equal arguments
config.unique = {by: :user_id}                    # duplicates have the same user_id
config.unique = {by: [:user_id], queue: true}     # ... and the same queue
config.unique = {by: [:report_id], period: 3600}  # ... or succeeded in the same hour-long period

Without period, a job stops blocking duplicates when it succeeds, fails, or is discarded.

In a batch, call_many stores the rest of the batch and returns a Unique::Duplicate in place of each skipped job. The memory, inline, async, and SQL backends all enforce uniqueness.

Concurrency limits

A concurrency limit caps how many jobs that share a key can run at the same time. Only the SQL backend enforces limits; the other backends ignore them. The following settings show three limits:

config.concurrency = {limit: 1, key: :account_id}
config.concurrency = {limit: 3, key: ->(args) { "#{args[:account_id]}-#{args[:kind]}" }, duration: 300}
config.concurrency = {limit: 1, on_conflict: :discard}

config.concurrency takes the following keys:

Key Default Description
limit Required The number of jobs with the same key that can run at the same time.
key nil The key: nil for one key for the whole job, the name of an argument, or ->(args) { string }. The job key is always part of it.
duration 900 The maximum number of seconds that a job holds its slot, its place within the limit. This frees the slot if its release is lost. Pick a value well above the job's normal run time.
on_conflict :block What happens when no slot is free: :block waits for a slot, and :discard drops the job and records it as discarded.

Timeouts and transactions

The timeout setting uses Ruby's Timeout, which interrupts the job wherever it is, even in the middle of a write. Prefer timeouts in the libraries a job calls, such as HTTP clients and database statement timeouts, and use timeout as a backstop.

Transactional jobs can't use resumable steps:, because rolling back a run would undo work that the steps recorded as done.

Callbacks

Each callback takes a method name or a block, and runs on the job instance. The following callbacks are available:

Callback Block arguments Runs
before envelope Before #call. Return a Failure to stop the run with it.
after envelope, result After a successful #call.
around envelope, run Around #call. The block must call run.call and return its result.
after_discard envelope, error After the job is discarded, or fails with no attempts left.
before_enqueue envelope Before the job is stored. Return a Failure to cancel the enqueue, or a changed Envelope to store instead.
after_enqueue envelope After the job is stored.

The following callback logs each run's duration:

include Deps["logger"]

around do |envelope, run|
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  run.call
ensure
  logger.info("#{envelope.job} took #{Process.clock_gettime(Process::CLOCK_MONOTONIC) - started}s")
end

Subclasses inherit settings, rules, and callbacks, so define shared ones on Bookshelf::Job.

Operations as jobs

Mankai::Jobs::Job is Mankai::Jobs::Performable plus a base class. To turn another object into a job, such as a dry-operation, include Performable:

# app/jobs/import_feed.rb
module Bookshelf
  module Jobs
    class ImportFeed < Bookshelf::Operation
      include Mankai::Jobs::Performable
      config.queue = "imports"

      def call(feed_id:)
        feed = step fetch(feed_id)
        step store(feed)
      end
    end
  end
end

The class lives in app/jobs/, so its job key is jobs.import_feed. A dry-operation returns Success or Failure, which the runner treats like any other result.

Resumable jobs

A resumable job splits its work into named steps and records its progress. To receive a Steps object, declare a steps: keyword:

def call(import_id:, steps:)
  steps.step(:download) { download(import_id) }

  steps.step(:process) do |step|
    rows(import_id, after: step.cursor).each do |row|
      process(row)
      step.advance!(row.id) # saves the cursor; pauses here if the worker is stopping
    end
  end

  steps.step(:finish) { notify(import_id) }
end

When the job runs again, it skips completed steps, and an unfinished step resumes from its last cursor, the value that it last passed to advance!. Each call to advance! is a checkpoint. Resumable jobs behave as follows:

  • If the worker is stopping when the job reaches a checkpoint, the job is enqueued again without using up an attempt.
  • If the job is retried after an error, it keeps its progress.
  • Code between checkpoints might run again after an interruption or a crash, so make each unit of work idempotent: running it twice must have the same effect as running it once.

MailerJob

Mankai::Jobs::MailerJob delivers a Hanami mailer in a job. Subclass it in your app:

# app/jobs/deliver_mail.rb
module Bookshelf
  module Jobs
    class DeliverMail < Mankai::Jobs::MailerJob
      def initialize(mailers: Bookshelf::App, **) = super
    end
  end
end

To deliver a mail, enqueue the job with the mailer's key and its input:

enqueuer.call("jobs.deliver_mail", {mailer: "mailers.welcome", input: {name: "Ada", email: "[email protected]"}})

MailerJob behaves as follows:

  • Queue: It runs on the mailers queue. Make sure that a worker serves that queue, or set config.queue in your subclass.
  • Mailers: It can deliver only mailers whose keys start with mailers.. An unknown key makes the job fail.
  • Input: It passes input to #deliver as keywords. Keep input JSON-safe: pass IDs and plain values, and load records inside the mailer.
  • Retries: It retries a delivery whose result isn't successful up to 5 times, with exponential backoff. A raised exception follows max_attempts, which is 1, so the job fails immediately. To retry exceptions, add retry_on rules to your subclass.

Enqueuer

Inject queue.enqueuer and call it with a job key, an arguments hash, and options:

include Deps["queue.enqueuer"]

enqueuer.call("jobs.send_welcome", {user_id: 1})
enqueuer.call("jobs.send_welcome", {user_id: 1}, wait: 60, queue: "low", priority: 5)
enqueuer.call("jobs.send_welcome", {user_id: 1}, at: Time.now + 3600)
enqueuer.call_many([["jobs.send_welcome", {user_id: 1}], ["jobs.send_welcome", {user_id: 2}]])

Pass the job's arguments as a positional hash. The keyword arguments are reserved for the following options:

Option Description
wait: Runs the job no earlier than this many seconds from now.
at: Runs the job no earlier than this Time. You can't combine it with wait:.
queue: Overrides the job's queue setting. The queue_prefix is still added.
priority: Overrides the job's priority setting.

Enqueue results

call returns Success(envelope) or one of the following failures:

Failure Cause
[:unknown_job, message] The key doesn't resolve to a job.
[:invalid_args, errors] The contract rejected the arguments.
[:unserializable_args, message] An argument isn't JSON-safe.
[:invalid_options, message] An enqueue option is invalid, for example both at: and wait:.
[:cancelled, value] A before_enqueue callback or enqueue middleware cancelled the job.
[:duplicate, existing_job_id] A unique job like it is still pending.
[:backend_error, exception] The backend raised an exception, or an inline job failed. See Backends.

call_many enqueues nothing if any request fails. Otherwise, it returns Success with one entry per request.

Arguments

By default, the enqueuer accepts only values that survive a JSON round trip unchanged: strings, integers, finite floats, booleans, nil, arrays, and hashes with string or symbol keys. Any other value fails with :unserializable_args, so pass IDs, not records.

Contracts

A contract is a dry-schema JSON schema for the job's arguments. It runs when the job is enqueued and again before it runs. The following contract requires user_id and allows locale:

contract do
  required(:user_id).filled(:integer)
  optional(:locale).filled(:string)
end

Caution: A job with a contract stores only what the contract returns. The contract drops any key that it doesn't declare, without an error, and coerces values as dry-schema's JSON schemas do. Declare every keyword that #call takes.

Serializers

To accept more argument types, set the serializers provider setting:

config.serializers = [Mankai::Jobs::Serializers::Time, Mankai::Jobs::Serializers::Date]
config.serializers = Mankai::Jobs::Serializers::ALL # Time, Date, BigDecimal, Symbol

A serializer is any object that responds to key, match?(value), dump(value), and load(dumped).

Slices

To give a slice its own enqueuer, register the same provider in the slice:

# slices/admin/config/providers/queue.rb
Admin::Slice.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
  configure { |config| config.backend = Hanami.app["queue.backend"] }
end

The slice's enqueuer stores slice-qualified keys, such as admin:jobs.import. These keys work as follows:

  • Any runner can resolve them, so one set of workers serves the app and its slices.
  • The app can enqueue a slice's job by its slice-qualified key.
  • A slice's enqueuer turns unqualified keys, such as jobs.import, into its own slice's keys. Qualified keys, such as main:jobs.sync, still reach other slices, so the prefix is a convenience, not a boundary.

A slice that shares the app's backend also shares the app's runner. Workers run every job with the app provider's settings. The following table shows where each setting takes effect:

Set on the app's provider Set on each slice's provider
middleware, log_jobs, retry_policy, error_reporter, recurring, and the restoring half of capture_locale enqueue_middleware, queue_prefix, capture_locale, and serializers, which apply when the slice enqueues

Use the same serializers on both providers, so that workers can load what the slice stored.

Middleware

Perform middleware wraps every run. Use it for concerns that all jobs share. A perform middleware is an object with call(envelope, job) that yields to the next layer and returns the result of yield:

class Timing
  def call(envelope, job)
    started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    yield # return the result of yield
  ensure
    Metrics.timing(envelope.job, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
  end
end

config.middleware = [Timing.new]

Enqueue middleware is an object with call(envelope). It returns an Envelope, which it can change, for example to add metadata, or a Failure to cancel the enqueue.

mankai-jobs adds the following built-in middleware:

Middleware Added by Description
Middleware::Logging log_jobs Logs structured, tagged entries with Hanami's logger, and plain lines with a standard Logger.
Middleware::Locale capture_locale Stores the locale when the job is enqueued, and runs the job in i18n.with_locale.

Events

If the container has a notifications bus (dry-monitor, as in Hanami apps), mankai-jobs publishes the following events:

Event Payload
mankai.jobs.enqueue envelope:
mankai.jobs.enqueue_many envelopes:
mankai.jobs.perform envelope:, job:, plus exception: if the job raised one
mankai.jobs.retry, mankai.jobs.snooze, mankai.jobs.discard, mankai.jobs.fail envelope:, outcome:

Backends publish their own events, such as mankai.jobs.sql.claim.

The events are registered when the queue provider starts, and dry-monitor raises an error if you subscribe to an event that isn't registered yet. Subscribe from the provider itself, after it starts:

# config/providers/queue.rb
Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
  configure do |config|
    # ...
  end

  after(:start) do
    target["notifications"].subscribe(:"mankai.jobs.fail") do |event|
      target["logger"].error("Job #{event[:envelope].job} failed: #{event[:outcome].error&.message}")
    end
  end
end

The after(:start) block runs wherever the provider starts: in the web process, in the console when you first use a queue. component, and in hanami jobs start, including with --prepare. To subscribe from another provider, call target.start(:queue) in that provider's start step first.

Recurring tasks

A recurring task enqueues a job on a schedule. Define tasks in the recurring provider setting:

config.recurring = {
  "daily_digest" => {job: "jobs.send_digest", schedule: "0 7 * * *", args: {kind: "daily"}},
  "sweep" => {job: "jobs.sweep", schedule: "every 5 minutes", queue: "low", priority: 10,
              description: "Delete expired drafts"}
}

To read the tasks from a YAML file, use Recurring.load_yaml. A missing file means no tasks:

config.recurring = Mankai::Jobs::Recurring.load_yaml(File.join(Hanami.app.root, "config/recurring.yml"), env: Hanami.env)

The file has one section per environment:

# config/recurring.yml
production:
  daily_digest:
    job: jobs.send_digest
    schedule: "0 7 * * *"
    args:
      kind: daily

Each task takes the following keys:

Key Required Description
job Yes The job key.
schedule Yes A cron line, such as "0 7 * * *", or a phrase, such as "every 5 minutes" or "every day at 7am". Times are UTC unless the schedule names a time zone, as in "0 7 * * * Europe/Berlin".
args No The job's arguments. The default is {}.
queue No Overrides the job's queue.
priority No Overrides the job's priority.
description No A note for people who read the configuration.

Recurring tasks behave as follows:

  • Invalid definitions raise an error at boot.
  • Runs that were due while no scheduler was running are skipped, not backfilled.
  • Only the SQL backend runs recurring tasks. It can also add tasks at runtime.
  • Recurring runs don't go through the enqueuer. The scheduler stores them directly, so before_enqueue and after_enqueue callbacks, enqueue middleware, and the mankai.jobs.enqueue event don't apply. capture_locale stores no locale, so the job runs in the default locale. The contract still checks the arguments.

Testing helpers

Mankai::Jobs::Testing provides RSpec matchers and helpers for the memory backend. To use them, require and include the module:

require "mankai/jobs/testing"

RSpec.configure do |config|
  config.include Mankai::Jobs::Testing
  config.before { jobs_backend.clear }
end

jobs_backend returns Hanami.app["queue.backend"], which must be the memory backend. Override the method if your provider has another name, or to use a slice's backend.

The enqueue_job matcher checks the jobs that a block enqueued. The have_enqueued_job matcher checks every job enqueued since the backend was last cleared:

expect { post "/signup", email: "[email protected]" }
  .to enqueue_job("jobs.send_welcome").with(user_id: 1).on_queue("mailers").once
expect(jobs_backend).to have_enqueued_job("jobs.send_welcome").at(Time.now..Time.now + 60)

Both matchers accept the following chain methods:

Chain method Matches
.with(user_id: 1) Exactly these arguments, as stored. You must give every argument.
.on_queue("mailers") The queue, as stored. With a queue_prefix, give the prefixed name.
.with_priority(5) The priority.
.at(time) The scheduled time, within a millisecond, or a Range of times.
.once, .twice, .exactly(n) The number of matching jobs. Without one of these, at least one.

A job is due when its scheduled time has passed. To run enqueued jobs in a test, use the following helpers:

Helper Description
perform_enqueued_jobs { ... } Runs the jobs that the block enqueued, and the jobs that those jobs enqueue. Returns the outcomes.
perform_enqueued_jobs Runs every due job. Returns the outcomes.
perform_enqueued_jobs(now: time) Runs every job that is due by time.
jobs_backend.drain Runs every due job and returns the outcomes.
jobs_backend.enqueued Returns the envelopes of the jobs that are waiting.
jobs_backend.failed Returns the outcomes of the jobs that failed.

A retry goes back into the backend with its retry time, so a drain runs it only after it's due. To run it sooner, pass a later time as now:.

For Minitest, include Mankai::Jobs::Testing::Assertions, which also includes Mankai::Jobs::Testing. It provides the following assertions:

include Mankai::Jobs::Testing::Assertions

assert_enqueued_job("jobs.send_welcome", {user_id: 1}, queue: "mailers") { post "/signup", email: "[email protected]" }
assert_enqueued_job("jobs.send_welcome", priority: 5, at: Time.now..Time.now + 60, count: 1)
assert_enqueued_jobs(2) { post "/signup", email: "[email protected]" }
assert_enqueued_jobs(1, "jobs.send_welcome") { post "/signup", email: "[email protected]" }
assert_no_enqueued_jobs("jobs.send_welcome") { post "/login", email: "[email protected]" }

Without a block, the assertions check every job enqueued since the backend was last cleared.

A job is a component, so you can unit-test it by calling it: Hanami.app["jobs.send_welcome"].call(user_id: 1).

CLI

The hanami jobs commands are available when the gem is in the Gemfile's :cli group. The commands have the following syntax:

hanami jobs start [--mode={fork|async}] [--only=KINDS] [--prepare] [--provider=NAME]
hanami jobs install [--backend=NAME] [--table-prefix=PREFIX]
hanami jobs clear [--older-than=SECONDS] [--queue=NAME] [--provider=NAME]

hanami jobs start runs the jobs processes: workers, which run jobs, plus any other processes the backend needs. It takes the following options:

Option Default Description
--mode fork Runs each process as a fork (fork), or as threads in one process (async).
--only All kinds A comma-separated list of the process kinds to run: worker, dispatcher, and scheduler.
--prepare Off Prepares the app (lazy loading) and starts only the jobs provider, instead of booting the app. It starts faster, but forks share less memory, and other providers start only when a job uses them.
--provider queue The name of the provider that registers mankai-jobs.

hanami jobs install writes a backend's files. It takes the following options:

Option Default Description
--backend sql The backend whose files to install. For SQL, the files are database migrations.
--table-prefix jobs_ The prefix for the SQL tables.

hanami jobs clear deletes finished jobs. It takes the following options:

Option Default Description
--older-than 86400 Deletes finished jobs older than this many seconds.
--queue All queues Deletes finished jobs only from this queue.
--provider queue The name of the provider that registers mankai-jobs.

start runs until it receives a TERM or INT signal, which stops it gracefully, or a QUIT signal, which stops it immediately. It needs a backend with worker processes, such as the SQL backend.

On Hanami 3.1 or later with code_reloading on (the development default), workers reload changed code between jobs, never during one.

Backend interface

You can write your own backend, for example one that stores jobs in Redis. To write a backend, follow these steps:

  1. Include Mankai::Jobs::Backend in your backend class, and implement the following methods:

    • Required: push(envelope). Backend provides a push_many(envelopes) that calls push for each envelope. Override it to store a batch in one operation.
    • Optional, only if your backend supports them: run(**options), push_recurring(envelope, task_key:, run_at:), clear_finished(older_than:), and close.
    • To enforce unique jobs, return a Unique::Duplicate from push in place of a job that you didn't store. Free the key when a job ends, as envelope.unique.released_by?(status) says. Unique::Locks does this in memory.
    • If you keep finished jobs, store outcome.output, and follow envelope.preserve_finished when it isn't nil.
  2. Run each job with context.runner.call(envelope, interrupted: -> { stopping? }). The runner never touches storage. It returns an Outcome whose status is one of the following:

    • :succeeded
    • :discarded
    • :retry: Run the job again at retry_at. Store metadata, and use up an attempt only if counts_attempt? is true. It's false when retry_reason is :interrupted or :snoozed. Backend.retried(envelope, outcome) builds the next envelope.
    • :failed: The job failed with error.
  3. Expose a factory: any object that responds to call(context), where context is a Mankai::Jobs::Context, and returns your backend. The following module exposes a factory, and the provider setting uses it:

    module Mankai::Jobs::Redis
      def self.backend(**options) = ->(context) { Backend.new(context, **options) }
    end
    
    config.backend = Mankai::Jobs::Redis.backend(url: ENV["REDIS_URL"])
    
  4. Optional: To publish your own events, call context.instrumenter.register(:"redis.claim") when the backend is built, so that apps can subscribe before the first event. Then call context.instrumenter.instrument(:"redis.claim", **payload) to publish mankai.jobs.redis.claim.

Mankai::Jobs::Runtime provides the following storage-neutral building blocks for worker processes:

  • ThreadPool
  • Timer
  • Sleeper: An interruptible sleep that is safe to wake from signal handlers.