mankai-jobs-sql 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,558 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+ require "json"
5
+
6
+ module Mankai
7
+ module Jobs
8
+ module SQL
9
+ # The job state machine of mankai-jobs-sql: enqueuing, claiming, finishing and dispatching
10
+ # jobs. Processes and the backend call this, and the classes it hands out for the rest:
11
+ # #processes (the process registry), #admin (inspecting and managing jobs and queues) and
12
+ # #recurring_tasks (recurring tasks added at runtime).
13
+ #
14
+ # A job's state is the execution table its row is in (ready, scheduled, claimed, blocked,
15
+ # failed), or finished_at on the record. Moving a job is "delete from one, insert into
16
+ # another" inside a transaction, which keeps the table workers poll small.
17
+ #
18
+ # @api private
19
+ # @since 0.1.0
20
+ class Store
21
+ extend Forwardable
22
+
23
+ # What to do when enqueuing while the caller has a transaction open on the same database.
24
+ #
25
+ # @api private
26
+ # @since 0.1.0
27
+ IN_TRANSACTION_MODES = %i[join after_commit raise].freeze
28
+
29
+ attr_reader :database, :semaphores, :processes, :admin, :recurring_tasks
30
+
31
+ def_delegators :database, :db, :tables, :clock, :instrumenter, :table, :transaction
32
+
33
+ # @param instrumenter [Mankai::Jobs::Instrumenter] receives "mankai.jobs.sql.*" events
34
+ #
35
+ # @api private
36
+ # @since 0.1.0
37
+ def initialize(db:, tables: Tables.new, clock: -> { Time.now.utc }, preserve_finished: true,
38
+ in_transaction: :join, instrumenter: Instrumenter::NULL)
39
+ unless IN_TRANSACTION_MODES.include?(in_transaction)
40
+ raise ConfigurationError, "in_transaction must be one of #{IN_TRANSACTION_MODES.inspect}"
41
+ end
42
+
43
+ @database = Database.new(db: db, tables: tables, clock: clock, instrumenter: instrumenter)
44
+ @preserve_finished = preserve_finished
45
+ @in_transaction = in_transaction
46
+ @semaphores = Semaphores.new(db: db, table: tables[:semaphores], clock: clock)
47
+ @processes = ProcessRegistry.new(database: database, store: self)
48
+ @admin = Admin.new(database: database, store: self)
49
+ @recurring_tasks = RecurringTasks.new(database: database)
50
+ end
51
+
52
+ # -- Enqueuing ----------------------------------------------------------------------------
53
+
54
+ # Stores envelopes and makes each ready, scheduled or blocked.
55
+ #
56
+ # If the caller already has a transaction open on this database:
57
+ # - :join (default): the jobs commit or roll back with the caller's transaction
58
+ # - :after_commit: the jobs are written after the caller's transaction commits (and are
59
+ # lost if the process dies in between)
60
+ # - :raise: raise, to catch code that would silently depend on either behaviour
61
+ #
62
+ # A unique job whose key is taken is not stored; it comes back as a Unique::Duplicate.
63
+ # (With :after_commit, duplicates are found only after the commit, and dropped silently.)
64
+ #
65
+ # @api private
66
+ # @since 0.1.0
67
+ def push_many(envelopes)
68
+ return envelopes if envelopes.empty?
69
+
70
+ if db.in_transaction?
71
+ case @in_transaction
72
+ when :raise
73
+ raise Error, "enqueuing inside an open transaction (in_transaction: :raise)"
74
+ when :after_commit
75
+ db.after_commit { write(envelopes) }
76
+ return envelopes
77
+ end
78
+ end
79
+
80
+ _, duplicates = write(envelopes)
81
+ envelopes.map do |envelope|
82
+ if duplicates.key?(envelope.id)
83
+ Unique::Duplicate.new(envelope: envelope,
84
+ existing_id: duplicates[envelope.id])
85
+ else
86
+ envelope
87
+ end
88
+ end
89
+ end
90
+
91
+ # Stores a recurring task's job unless that task already ran for run_at.
92
+ #
93
+ # @return [Boolean] false if another scheduler already enqueued this run
94
+ #
95
+ # @api private
96
+ # @since 0.1.0
97
+ def push_recurring(envelope, task_key:, run_at:)
98
+ transaction do
99
+ job_ids, = write([envelope])
100
+ table(:recurring_runs).insert(task_key: task_key, run_at: run_at, job_id: job_ids.first, created_at: now)
101
+ end
102
+ event(:enqueue_recurring, task: task_key, run_at: run_at, enqueued: true)
103
+ true
104
+ rescue Sequel::UniqueConstraintViolation
105
+ event(:enqueue_recurring, task: task_key, run_at: run_at, enqueued: false)
106
+ false
107
+ end
108
+
109
+ # -- Claiming and finishing ---------------------------------------------------------------
110
+
111
+ # Claims up to `limit` ready jobs for a worker process, in queue order, then priority.
112
+ #
113
+ # `queues` entries are exact names, prefixes ending in "*", or "*" for all queues.
114
+ # Paused queues are skipped.
115
+ #
116
+ # @return [Array<Record>] claimed job records
117
+ #
118
+ # @api private
119
+ # @since 0.1.0
120
+ def claim(queues, limit, process_id)
121
+ return [] if limit <= 0
122
+
123
+ job_ids = []
124
+ ready_datasets(queues).each do |dataset|
125
+ break if limit <= 0
126
+
127
+ claimed = claim_from(dataset, limit, process_id)
128
+ limit -= claimed.size
129
+ job_ids.concat(claimed)
130
+ end
131
+ return [] if job_ids.empty?
132
+
133
+ event(:claim, process_id: process_id, size: job_ids.size)
134
+ # Keep claim order (queue order, then priority).
135
+ position = job_ids.each_with_index.to_h
136
+ records(table(:records).where(id: job_ids)).sort_by { |record| position.fetch(record.id) }
137
+ end
138
+
139
+ # Records how a claimed job ended. Only the holder of the claim can finish a job: if the
140
+ # claim is gone (released or failed by another process), this does nothing.
141
+ #
142
+ # @param record [Record] the job record, as returned by #claim
143
+ # @param outcome [Mankai::Jobs::Outcome]
144
+ # @return [Boolean] whether this call finished the job
145
+ #
146
+ # @api private
147
+ # @since 0.1.0
148
+ def finish(record, outcome)
149
+ finished = transaction do
150
+ claim = table(:claimed).where(job_id: record.id).for_update.first
151
+ next false unless claim
152
+
153
+ table(:claimed).where(id: claim[:id]).delete
154
+ apply_outcome(record, outcome)
155
+ true
156
+ end
157
+
158
+ # Outside the transaction above, so a failure here cannot undo a finished job.
159
+ release_concurrency(record) if finished
160
+ finished
161
+ end
162
+
163
+ # Runs a transactional job (the block, which returns its Outcome) and, if it succeeded,
164
+ # marks it finished in the same transaction, so the job's own writes on this database and
165
+ # its completion commit together. Anything else rolls the job's writes back and leaves
166
+ # the claim for the caller to finish with #finish.
167
+ #
168
+ # @return [Array(Outcome, Boolean)] the outcome, and whether the job was finished here
169
+ #
170
+ # @api private
171
+ # @since 0.1.0
172
+ def finish_within_transaction(record)
173
+ outcome = nil
174
+ # Never retried: the block runs the job.
175
+ finished = transaction(retriable: false) do
176
+ outcome = yield
177
+ raise Sequel::Rollback unless outcome.succeeded?
178
+
179
+ claim = table(:claimed).where(job_id: record.id).for_update.first
180
+ # The claim was taken away (the process was pruned): undo the run, it is not ours.
181
+ raise Sequel::Rollback unless claim
182
+
183
+ table(:claimed).where(id: claim[:id]).delete
184
+ apply_outcome(record, outcome)
185
+ true
186
+ end
187
+
188
+ release_concurrency(record) if finished
189
+ [outcome, finished == true]
190
+ end
191
+
192
+ # Puts a process's claimed jobs back in ready, keeping their concurrency slots. Used when a
193
+ # process stops gracefully; the jobs will run again.
194
+ #
195
+ # @return [Integer] how many jobs were released
196
+ #
197
+ # @api private
198
+ # @since 0.1.0
199
+ def release_claims(process_id)
200
+ released = table(:claimed).where(process_id: process_id).select_map(:job_id).count do |job_id|
201
+ transaction do
202
+ claim = table(:claimed).where(job_id: job_id).for_update.first
203
+ next false unless claim
204
+
205
+ record = find_record(job_id)
206
+ table(:claimed).where(id: claim[:id]).delete
207
+ table(:ready).insert(record.execution_row(now))
208
+ true
209
+ end
210
+ end
211
+ event(:release_claims, process_id: process_id, size: released) if released.positive?
212
+ released
213
+ end
214
+
215
+ # Marks claimed jobs as failed, for processes that died without releasing them. These
216
+ # errors are recorded by another process; the job's own code never sees them.
217
+ #
218
+ # @param scope [Sequel::Dataset] claimed rows to fail
219
+ # @return [Integer] how many jobs were failed
220
+ #
221
+ # @api private
222
+ # @since 0.1.0
223
+ def fail_claims(scope, error)
224
+ info = ErrorInfo.from_exception(error)
225
+ failed = scope.select_map(:job_id).count do |job_id|
226
+ record = find_record(job_id)
227
+ record && finish(record, Outcome.failed(nil, info))
228
+ end
229
+ event(:fail_claims, size: failed, error: error.class.name) if failed.positive?
230
+ failed
231
+ end
232
+
233
+ # @api private
234
+ # @since 0.1.0
235
+ def fail_claims_of(process_id, error)
236
+ fail_claims(table(:claimed).where(process_id: process_id), error)
237
+ end
238
+
239
+ # Fails claims whose process row no longer exists.
240
+ #
241
+ # @api private
242
+ # @since 0.1.0
243
+ def fail_orphaned_claims
244
+ live = table(:processes).select(:id)
245
+ orphans = table(:claimed).where(Sequel.|({process_id: nil}, Sequel.~(process_id: live)))
246
+ fail_claims(orphans, ProcessMissingError.new("claimed by a process that no longer exists"))
247
+ end
248
+
249
+ # -- Dispatching scheduled and blocked jobs -----------------------------------------------
250
+
251
+ # Moves due scheduled jobs to ready (or blocked).
252
+ #
253
+ # @return [Integer] how many jobs were dispatched
254
+ #
255
+ # @api private
256
+ # @since 0.1.0
257
+ def dispatch_scheduled(batch_size: 500) # rubocop:disable Metrics/AbcSize
258
+ transaction do
259
+ current = now
260
+ rows = skip_locked(
261
+ table(:scheduled).where(Sequel[:scheduled_at] <= current)
262
+ .order(:scheduled_at, :priority, :job_id).limit(batch_size).select(:id, :job_id)
263
+ ).all
264
+ next 0 if rows.empty?
265
+
266
+ table(:scheduled).where(id: rows.map { |row| row[:id] }).delete
267
+ dispatch(records(table(:records).where(id: rows.map { |row| row[:job_id] })), now: current)
268
+ rows.size
269
+ end.tap { |size| event(:dispatch_scheduled, size: size) if size.positive? }
270
+ end
271
+
272
+ # Moves the next blocked job for a key to ready, if a slot is free.
273
+ #
274
+ # @return [Boolean]
275
+ #
276
+ # @api private
277
+ # @since 0.1.0
278
+ def unblock_next(concurrency_key)
279
+ transaction do
280
+ blocked = skip_locked(
281
+ table(:blocked).where(concurrency_key: concurrency_key).order(:priority, :job_id).limit(1)
282
+ ).first
283
+ next false unless blocked
284
+
285
+ record = find_record(blocked[:job_id])
286
+ semaphore_id = acquire_slot(record)
287
+ next false unless semaphore_id
288
+
289
+ table(:records).where(id: record.id).update(semaphore_id: semaphore_id, updated_at: now)
290
+ table(:blocked).where(id: blocked[:id]).delete
291
+ table(:ready).insert(record.execution_row(now))
292
+ true
293
+ end
294
+ end
295
+
296
+ # Safety net for lost releases: deletes expired semaphores and retries keys whose blocked
297
+ # jobs have waited past their expiry.
298
+ #
299
+ # @return [Integer] how many jobs were unblocked
300
+ #
301
+ # @api private
302
+ # @since 0.1.0
303
+ def concurrency_maintenance
304
+ semaphores.delete_expired
305
+ keys = table(:blocked).where(Sequel[:expires_at] < now).distinct.select_map(:concurrency_key)
306
+ keys.count { |key| unblock_next(key) }
307
+ end
308
+
309
+ # Queues whose jobs are not claimed.
310
+ #
311
+ # @api private
312
+ # @since 0.1.0
313
+ def paused_queues
314
+ table(:pauses).select_order_map(:queue)
315
+ end
316
+
317
+ # Puts records into scheduled, ready or blocked. Call inside a transaction.
318
+ #
319
+ # @api private
320
+ # @since 0.1.0
321
+ def dispatch(records, now: self.now)
322
+ due, later = records.partition { |record| record.due?(now) }
323
+ limited, free = due.partition(&:concurrency_limited?)
324
+
325
+ table(:scheduled).multi_insert(later.map { |record|
326
+ record.execution_row(now).merge(scheduled_at: record.scheduled_at)
327
+ })
328
+ table(:ready).multi_insert(free.map { |record| record.execution_row(now) })
329
+
330
+ # Sorted so concurrent dispatchers take semaphore row locks in the same order and
331
+ # cannot deadlock each other.
332
+ limited.sort_by { |record|
333
+ [record.concurrency_key, record.id]
334
+ }.each { |record| dispatch_limited(record, now) }
335
+ end
336
+
337
+ # Frees a finished or deleted job's concurrency slot and unblocks the next job for its key.
338
+ #
339
+ # @api private
340
+ # @since 0.1.0
341
+ def release_concurrency(record)
342
+ return unless record.concurrency_limited?
343
+
344
+ if record.semaphore_id
345
+ semaphores.release(
346
+ id: record.semaphore_id, limit: record.concurrency_limit, duration: record.concurrency_duration
347
+ )
348
+ end
349
+ unblock_next(record.concurrency_key)
350
+ end
351
+
352
+ private
353
+
354
+ def_delegators :database, :now, :event, :skip_locked
355
+ private :now, :event, :skip_locked
356
+
357
+ # @api private
358
+ # @since 0.1.0
359
+ def records(dataset)
360
+ dataset.all.map { |row| Record.new(row) }
361
+ end
362
+
363
+ # @api private
364
+ # @since 0.1.0
365
+ def find_record(id)
366
+ row = table(:records).where(id: id).first
367
+ row && Record.new(row)
368
+ end
369
+
370
+ # @return [Integer, nil] the semaphore id, or nil if the record's key has no free slot
371
+ #
372
+ # @api private
373
+ # @since 0.1.0
374
+ def acquire_slot(record)
375
+ semaphores.acquire(
376
+ key: record.concurrency_key, limit: record.concurrency_limit, duration: record.concurrency_duration
377
+ )
378
+ end
379
+
380
+ # @return [Array(Array<Integer, nil>, Hash)] ids of the stored records in envelope order
381
+ # (nil for duplicates), and {duplicate envelope id => existing job id}
382
+ #
383
+ # @api private
384
+ # @since 0.1.0
385
+ def write(envelopes) # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
386
+ transaction do
387
+ current = now
388
+ rows = envelopes.map { |envelope| Records.row(envelope, current) }
389
+ unique, plain = rows.partition { |row| row[:unique_key] }
390
+ # Rows only carry the newer columns they use, so group rows by their columns.
391
+ plain.group_by(&:keys).each_value { |group| table(:records).multi_insert(group) }
392
+ duplicates = insert_unique(unique)
393
+
394
+ stored = envelopes.map(&:id) - duplicates.keys
395
+ records = stored.empty? ? [] : records(table(:records).where(uuid: stored))
396
+ dispatch(records, now: current)
397
+ by_uuid = records.to_h { |record| [record.uuid, record.id] }
398
+ [envelopes.map { |envelope| by_uuid[envelope.id] }, duplicates]
399
+ end
400
+ end
401
+
402
+ # Inserts rows of unique jobs one by one, skipping those whose key is taken.
403
+ #
404
+ # @return [Hash] {duplicate envelope id => id of the job holding the key}
405
+ #
406
+ # @api private
407
+ # @since 0.1.0
408
+ def insert_unique(rows)
409
+ duplicates = {}
410
+ # In key order, so concurrent batches wait on each other's keys in the same order
411
+ # and cannot deadlock (an insert waits for an uncommitted row with the same key).
412
+ rows.sort_by { |row| row[:unique_key] }.each do |row|
413
+ # A savepoint, so a taken key fails this insert without aborting the transaction.
414
+ db.transaction(savepoint: true) { table(:records).insert(row) }
415
+ rescue Sequel::UniqueConstraintViolation
416
+ duplicates[row[:uuid]] = table(:records).where(unique_key: row[:unique_key]).get(:uuid)
417
+ end
418
+ duplicates
419
+ end
420
+
421
+ # @api private
422
+ # @since 0.1.0
423
+ def dispatch_limited(record, now)
424
+ semaphore_id = acquire_slot(record)
425
+
426
+ if semaphore_id
427
+ table(:records).where(id: record.id).update(semaphore_id: semaphore_id, updated_at: now)
428
+ table(:ready).insert(record.execution_row(now))
429
+ elsif record.discard_on_conflict?
430
+ mark_finished(record, :discarded, now)
431
+ else
432
+ table(:blocked).insert(
433
+ record.execution_row(now).merge(
434
+ concurrency_key: record.concurrency_key, expires_at: now + record.concurrency_duration
435
+ )
436
+ )
437
+ end
438
+ end
439
+
440
+ # @api private
441
+ # @since 0.1.0
442
+ def apply_outcome(record, outcome)
443
+ current = now
444
+ case outcome.status
445
+ when :succeeded, :discarded
446
+ mark_finished(record, outcome.status, current, output: outcome.output)
447
+ when :retry then schedule_retry(record, outcome, current)
448
+ when :failed then record_failure(record, outcome, current)
449
+ else raise Error, "unknown outcome status #{outcome.status.inspect}"
450
+ end
451
+ end
452
+
453
+ # @api private
454
+ # @since 0.1.0
455
+ def schedule_retry(record, outcome, now)
456
+ table(:records).where(id: record.id).update(
457
+ attempts: Sequel[:attempts] + (outcome.counts_attempt? ? 1 : 0), scheduled_at: outcome.retry_at,
458
+ semaphore_id: nil, updated_at: now, **metadata_update(outcome)
459
+ )
460
+ table(:scheduled).insert(record.execution_row(now).merge(scheduled_at: outcome.retry_at))
461
+ end
462
+
463
+ # @api private
464
+ # @since 0.1.0
465
+ def record_failure(record, outcome, now)
466
+ table(:records).where(id: record.id).update(
467
+ attempts: Sequel[:attempts] + 1, updated_at: now,
468
+ **metadata_update(outcome), **record.unique_release(:failed)
469
+ )
470
+ table(:failed).insert(job_id: record.id, error: Records.error_json(outcome.error), created_at: now)
471
+ end
472
+
473
+ # @api private
474
+ # @since 0.1.0
475
+ def metadata_update(outcome)
476
+ outcome.metadata ? {metadata: JSON.generate(outcome.metadata)} : {}
477
+ end
478
+
479
+ # @api private
480
+ # @since 0.1.0
481
+ def mark_finished(record, status, now, output: nil)
482
+ unless record.preserve_finished?(@preserve_finished)
483
+ table(:records).where(id: record.id).delete
484
+ return
485
+ end
486
+
487
+ table(:records).where(id: record.id).update(
488
+ attempts: Sequel[:attempts] + 1, finished_at: now, outcome: status.to_s, updated_at: now,
489
+ **output_update(record, output), **record.unique_release(status)
490
+ )
491
+ end
492
+
493
+ # Recorded output, unless it is too large to store.
494
+ #
495
+ # @api private
496
+ # @since 0.1.0
497
+ def output_update(record, output)
498
+ return {} if output.nil?
499
+
500
+ json = JSON.generate(output)
501
+ return {output: json} if json.bytesize <= Records::MAX_BYTES
502
+
503
+ event(:output_dropped, job: record.job, id: record.uuid, bytes: json.bytesize)
504
+ {}
505
+ end
506
+
507
+ # @api private
508
+ # @since 0.1.0
509
+ def claim_from(dataset, limit, process_id)
510
+ transaction do
511
+ rows = skip_locked(dataset.order(:priority, :job_id).limit(limit).select(:id, :job_id)).all
512
+ next [] if rows.empty?
513
+
514
+ current = now
515
+ claims = rows.map { |row| {job_id: row[:job_id], process_id: process_id, created_at: current} }
516
+ table(:claimed).multi_insert(claims)
517
+ table(:ready).where(id: rows.map { |row| row[:id] }).delete
518
+ rows.map { |row| row[:job_id] }
519
+ end
520
+ end
521
+
522
+ # One dataset per queue, in the order the worker lists them.
523
+ #
524
+ # @api private
525
+ # @since 0.1.0
526
+ def ready_datasets(queues)
527
+ ready = table(:ready)
528
+ patterns = Array(queues).map(&:to_s)
529
+ patterns = ["*"] if patterns.empty?
530
+ paused = paused_queues
531
+ return [ready] if patterns.include?("*") && paused.empty?
532
+
533
+ names = patterns.include?("*") ? ready.distinct.select_order_map(:queue) : queue_names(ready, patterns)
534
+ (names - paused).map { |name| ready.where(queue: name) }
535
+ end
536
+
537
+ # Exact names as given, and names of ready queues matching each "prefix*", in pattern order.
538
+ #
539
+ # @api private
540
+ # @since 0.1.0
541
+ def queue_names(ready, patterns) # rubocop:disable Metrics/PerceivedComplexity
542
+ prefixes = patterns.select { |pattern| pattern.end_with?("*") }.map { |pattern| pattern.delete_suffix("*") }
543
+ found =
544
+ if prefixes.empty?
545
+ []
546
+ else
547
+ ready.where(Sequel.|(*prefixes.map { |prefix| Sequel.like(:queue, "#{ready.escape_like(prefix)}%") }))
548
+ .distinct.select_order_map(:queue)
549
+ end
550
+
551
+ patterns.flat_map { |pattern|
552
+ pattern.end_with?("*") ? found.select { |queue| queue.start_with?(pattern.delete_suffix("*")) } : [pattern]
553
+ }.uniq
554
+ end
555
+ end
556
+ end
557
+ end
558
+ end