|
| 1 | +module River |
| 2 | + MAX_ATTEMPTS_DEFAULT = 25 |
| 3 | + PRIORITY_DEFAULT = 1 |
| 4 | + QUEUE_DEFAULT = "default" |
| 5 | + |
| 6 | + # Provides a client for River that inserts jobs. Unlike the Go version of the |
| 7 | + # River client, this one can insert jobs only. Jobs can only be worked from Go |
| 8 | + # code, so job arg kinds and JSON encoding details must be shared between Ruby |
| 9 | + # and Go code. |
| 10 | + # |
| 11 | + # Used in conjunction with a River driver like: |
| 12 | + # |
| 13 | + # DB = Sequel.connect(...) |
| 14 | + # client = River::Client.new(River::Driver::Sequel.new(DB)) |
| 15 | + # |
| 16 | + # River drivers are found in separate gems like `riverqueue-sequel` to help |
| 17 | + # minimize transient dependencies. |
| 18 | + class Client |
| 19 | + def initialize(driver) |
| 20 | + @driver = driver |
| 21 | + end |
| 22 | + |
| 23 | + # Inserts a new job for work given a job args implementation and insertion |
| 24 | + # options (which may be omitted). |
| 25 | + # |
| 26 | + # Job arg implementations are expected to respond to: |
| 27 | + # |
| 28 | + # * `#kind`: A string that uniquely identifies the job in the database. |
| 29 | + # * `#to_json`: Encodes the args to JSON for persistence in the database. |
| 30 | + # Must match encoding an args struct on the Go side to be workable. |
| 31 | + # |
| 32 | + # They may also respond to `#insert_opts` which is expected to return an |
| 33 | + # `InsertOpts` that contains options that will apply to all jobs of this |
| 34 | + # kind. Insertion options provided as an argument to `#insert` override |
| 35 | + # those returned by job args. |
| 36 | + def insert(args, insert_opts: InsertOpts.new) |
| 37 | + raise "args should respond to `#kind`" if !args.respond_to?(:kind) |
| 38 | + raise "args should respond to `#to_json`" if !args.respond_to?(:to_json) |
| 39 | + |
| 40 | + args_insert_opts = args.respond_to?(:insert_opts) ? args.insert_opts : InsertOpts.new |
| 41 | + |
| 42 | + scheduled_at = insert_opts.scheduled_at || args_insert_opts.scheduled_at |
| 43 | + |
| 44 | + @driver.insert(Internal::JobInsertParams.new( |
| 45 | + encoded_args: args.to_json, |
| 46 | + kind: args.kind, |
| 47 | + max_attempts: insert_opts.max_attempts || args_insert_opts.max_attempts || MAX_ATTEMPTS_DEFAULT, |
| 48 | + priority: insert_opts.priority || args_insert_opts.priority || PRIORITY_DEFAULT, |
| 49 | + queue: insert_opts.queue || args_insert_opts.queue || QUEUE_DEFAULT, |
| 50 | + scheduled_at: scheduled_at, # database default to now |
| 51 | + state: scheduled_at ? JOB_STATE_SCHEDULED : JOB_STATE_AVAILABLE, |
| 52 | + tags: insert_opts.tags || args_insert_opts.tags |
| 53 | + )) |
| 54 | + end |
| 55 | + end |
| 56 | +end |
0 commit comments