Skip to content

Document that concurrency key procs receive all job arguments - #840

Open
wintan1418 wants to merge 1 commit into
rails:mainfrom
wintan1418:document-concurrency-key-arguments
Open

wintan1418 wants to merge 1 commit into
rails:mainfrom
wintan1418:document-concurrency-key-arguments

Conversation

@wintan1418

Copy link
Copy Markdown
Contributor

The concurrency key is computed with instance_exec(*arguments, &key), so the proc gets every argument the job is enqueued with. A lambda checks how many arguments it gets, so a key like ->(contact) { contact } works until the job is enqueued with one more argument, and then perform_later raises:

class DeliverAnnouncementJob < ApplicationJob
  limits_concurrency key: ->(contact) { contact }

  def perform(contact, notify = true)
  end
end

DeliverAnnouncementJob.perform_later(contact)        # enqueued
DeliverAnnouncementJob.perform_later(contact, false) # ArgumentError: wrong number of arguments (given 2, expected 1)

The same happens with keyword arguments: perform_later(contact, notify: false) passes the keywords as a second argument to the lambda. I ran into this in production with a job that is usually enqueued with one argument and sometimes with two. The error comes from instance_exec in concurrency_controls.rb and doesn't name the job or the key, so it took a while to find.

The README says the proc "receives the job arguments as parameters", and the first example uses ->(arg1, arg2, *), but the examples below it are one-argument lambdas for one-argument jobs, so the * is easy to miss. This adds a note to the key option saying that the proc gets all the arguments, including optional and keyword ones, and that a lambda needs to accept them, e.g. ->(contact, *) { contact }. That's the same thing the test jobs do with ->(job_result, **).

The key is computed with instance_exec(*arguments, &key), so a lambda
that takes fewer parameters than the arguments the job is enqueued with
raises ArgumentError when enqueuing. This is easy to miss when the job
has optional or keyword arguments, as the lambda works until the job is
enqueued with them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant