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,451 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "socket"
5
+
6
+ module Mankai
7
+ module Jobs
8
+ module SQL
9
+ # The long-running processes of the SQL backend.
10
+ #
11
+ # Each registers itself in the processes table, sends heartbeats from a timer thread, and
12
+ # deregisters when it stops (releasing any jobs it still holds). #run blocks; #stop may be
13
+ # called from another thread or a signal handler.
14
+ #
15
+ # @api private
16
+ # @since 0.1.0
17
+ module Processes
18
+ # @api private
19
+ # @since 0.1.0
20
+ class Base
21
+ attr_reader :store, :logger, :id, :name, :supervisor_id
22
+
23
+ # @param hooks [Hash{Symbol => Array<#call>}] called with the process on events such as
24
+ # :worker_start and :worker_stop (see Options::HOOKS)
25
+ #
26
+ # @api private
27
+ # @since 0.1.0
28
+ def initialize(store:, logger:, heartbeat_interval: 60, supervisor_id: nil, hooks: {})
29
+ @store = store
30
+ @logger = logger
31
+ @hooks = hooks
32
+ @heartbeat_interval = heartbeat_interval
33
+ @supervisor_id = supervisor_id
34
+ @name = "#{kind}-#{SecureRandom.hex(6)}"
35
+ @sleeper = Runtime::Sleeper.new
36
+ @stopped = false
37
+ end
38
+
39
+ # @api private
40
+ # @since 0.1.0
41
+ def kind
42
+ self.class.name.split("::").last.downcase
43
+ end
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ def run
48
+ boot
49
+ work
50
+ ensure
51
+ shutdown
52
+ end
53
+
54
+ # Safe to call from a trap handler.
55
+ #
56
+ # @api private
57
+ # @since 0.1.0
58
+ def stop
59
+ @stopped = true
60
+ @sleeper.wake_up
61
+ end
62
+
63
+ # @api private
64
+ # @since 0.1.0
65
+ def stopped?
66
+ @stopped || supervisor_gone?
67
+ end
68
+
69
+ # Called in a forked child: stop when the parent supervisor is gone (e.g. killed), so
70
+ # children never linger as orphans.
71
+ #
72
+ # @api private
73
+ # @since 0.1.0
74
+ def watch_supervisor(pid)
75
+ @supervisor_pid = pid
76
+ end
77
+
78
+ # @api private
79
+ # @since 0.1.0
80
+ def supervisor_gone?
81
+ !@supervisor_pid.nil? && ::Process.ppid != @supervisor_pid
82
+ end
83
+
84
+ # @api private
85
+ # @since 0.1.0
86
+ def metadata
87
+ {}
88
+ end
89
+
90
+ private
91
+
92
+ # @api private
93
+ # @since 0.1.0
94
+ def boot
95
+ @id = store.processes.register(
96
+ kind: kind, name: name, pid: ::Process.pid, hostname: Socket.gethostname,
97
+ supervisor_id: supervisor_id, metadata: metadata
98
+ )
99
+ @heartbeat = Runtime::Timer.new(@heartbeat_interval, on_error: method(:log_error)) {
100
+ # Our row is gone: another process pruned us, and failed our jobs. Stop.
101
+ stop unless store.processes.heartbeat(@id)
102
+ stop if supervisor_gone?
103
+ }.start
104
+ logger.info("[mankai-jobs] #{name} started (pid #{::Process.pid})")
105
+ run_hooks(:start)
106
+ end
107
+
108
+ # @api private
109
+ # @since 0.1.0
110
+ def work
111
+ raise(NotImplementedError)
112
+ end
113
+
114
+ # @api private
115
+ # @since 0.1.0
116
+ def shutdown
117
+ run_hooks(:stop) if @id
118
+ @heartbeat&.stop
119
+ store.processes.deregister(@id) if @id
120
+ logger.info("[mankai-jobs] #{name} stopped")
121
+ rescue StandardError => exception
122
+ log_error(exception)
123
+ end
124
+
125
+ # Hook errors are logged, never raised: a broken hook must not stop job processing.
126
+ #
127
+ # @api private
128
+ # @since 0.1.0
129
+ def run_hooks(event)
130
+ Array(@hooks[:"#{kind}_#{event}"]).each do |hook|
131
+ hook.call(self)
132
+ rescue StandardError => exception
133
+ log_error(exception)
134
+ end
135
+ end
136
+
137
+ # @api private
138
+ # @since 0.1.0
139
+ def log_error(error)
140
+ logger.error("[mankai-jobs] #{name}: #{error.class}: #{error.message}")
141
+ end
142
+ end
143
+
144
+ # Repeats #poll until stopped, sleeping for the number of seconds it returns.
145
+ #
146
+ # @api private
147
+ # @since 0.1.0
148
+ class Poller < Base
149
+ # @api private
150
+ # @since 0.1.0
151
+ def initialize(polling_interval:, **)
152
+ super(**)
153
+ @polling_interval = polling_interval
154
+ end
155
+
156
+ private
157
+
158
+ # @api private
159
+ # @since 0.1.0
160
+ def work
161
+ until stopped?
162
+ delay =
163
+ begin
164
+ poll
165
+ rescue StandardError => exception
166
+ # A database blip should not kill the process; try again after a pause.
167
+ log_error(exception)
168
+ [@polling_interval, 1].max
169
+ end
170
+ @sleeper.sleep(delay)
171
+ end
172
+ end
173
+ end
174
+
175
+ # Claims ready jobs from its queues and runs them on a thread pool.
176
+ #
177
+ # @api private
178
+ # @since 0.1.0
179
+ class Worker < Poller
180
+ # Sleep used while every thread is busy; a finishing job wakes the worker earlier.
181
+ #
182
+ # @api private
183
+ # @since 0.1.0
184
+ BUSY_SLEEP = 600
185
+
186
+ attr_reader :queues
187
+
188
+ # @param reloader [Mankai::Jobs::Reloader, nil] reloads changed code between jobs
189
+ # @param transaction_store [Store, nil] store on the app's connection, used to finish
190
+ # transactional jobs in the same transaction as their own writes
191
+ #
192
+ # @api private
193
+ # @since 0.1.0
194
+ def initialize(queues:, threads:, runner:, shutdown_timeout: 5, reloader: nil, transaction_store: nil, **)
195
+ super(**)
196
+ @reloader = reloader
197
+ @transaction_store = transaction_store
198
+ @queues = Array(queues).map(&:to_s).freeze
199
+ @threads = threads
200
+ @runner = runner
201
+ @shutdown_timeout = shutdown_timeout
202
+ end
203
+
204
+ # @api private
205
+ # @since 0.1.0
206
+ def metadata
207
+ {queues: queues, threads: @threads}
208
+ end
209
+
210
+ private
211
+
212
+ # @api private
213
+ # @since 0.1.0
214
+ def boot
215
+ super
216
+ @pool = Runtime::ThreadPool.new(@threads, on_idle: -> { @sleeper.wake_up }, on_error: method(:log_error))
217
+ end
218
+
219
+ # @api private
220
+ # @since 0.1.0
221
+ def poll
222
+ capacity = @pool.available_capacity
223
+ return BUSY_SLEEP if capacity.zero?
224
+
225
+ # Reload only with no job running, so no job sees half-reloaded code.
226
+ @reloader.call if @reloader && !@pool.busy? && @reloader.changed?
227
+
228
+ store.claim(queues, capacity, id).each { |record| @pool.post { perform(record) } }
229
+ @pool.idle? ? @polling_interval : BUSY_SLEEP
230
+ end
231
+
232
+ # @api private
233
+ # @since 0.1.0
234
+ def perform(record)
235
+ # Resumable jobs pause at their next checkpoint once this worker is stopping.
236
+ envelope = record.to_envelope
237
+ run = -> { @runner.call(envelope, interrupted: -> { stopped? }) }
238
+
239
+ if @transaction_store && @runner.respond_to?(:transactional?) && @runner.transactional?(envelope)
240
+ outcome, finished = @transaction_store.finish_within_transaction(record, &run)
241
+ store.finish(record, outcome) unless finished
242
+ else
243
+ store.finish(record, run.call)
244
+ end
245
+ rescue StandardError => exception
246
+ # The job may have run, but its outcome could not be recorded while this process still
247
+ # holds the claim, so nothing else will recover it. Stop and let the supervisor start
248
+ # a fresh process; deregistering releases the claim so the job runs again.
249
+ log_error(exception)
250
+ stop
251
+ end
252
+
253
+ # @api private
254
+ # @since 0.1.0
255
+ def shutdown
256
+ if @pool
257
+ @pool.shutdown
258
+ @pool.wait_for_termination(@shutdown_timeout)
259
+ end
260
+ super
261
+ end
262
+ end
263
+
264
+ # Moves due scheduled jobs (including retries) to ready, runs concurrency maintenance, and
265
+ # deletes finished jobs past their queue's retention.
266
+ #
267
+ # @api private
268
+ # @since 0.1.0
269
+ class Dispatcher < Poller
270
+ # @api private
271
+ # @since 0.1.0
272
+ def initialize(batch_size: 500, concurrency_maintenance_interval: 600, retention: {},
273
+ retention_interval: 600, **)
274
+ super(**)
275
+ @batch_size = batch_size
276
+ @maintenance_interval = concurrency_maintenance_interval
277
+ @retention = retention
278
+ @retention_interval = retention_interval
279
+ end
280
+
281
+ # @api private
282
+ # @since 0.1.0
283
+ def metadata
284
+ {batch_size: @batch_size}
285
+ end
286
+
287
+ private
288
+
289
+ # @api private
290
+ # @since 0.1.0
291
+ def boot
292
+ super
293
+ @maintenance = Runtime::Timer.new(@maintenance_interval, on_error: method(:log_error)) {
294
+ store.concurrency_maintenance
295
+ }.start
296
+ if @retention.any?
297
+ @cleanup = Runtime::Timer.new(@retention_interval, on_error: method(:log_error)) {
298
+ store.admin.apply_retention(@retention)
299
+ }.start
300
+ end
301
+ end
302
+
303
+ # @api private
304
+ # @since 0.1.0
305
+ def poll
306
+ # A full batch means more may be due: go again right away.
307
+ store.dispatch_scheduled(batch_size: @batch_size) >= @batch_size ? 0 : @polling_interval
308
+ end
309
+
310
+ # @api private
311
+ # @since 0.1.0
312
+ def shutdown
313
+ @maintenance&.stop
314
+ @cleanup&.stop
315
+ super
316
+ end
317
+ end
318
+
319
+ # Enqueues recurring tasks when they are due. Several schedulers may run at once; the
320
+ # recurring_runs table makes sure each run is enqueued once.
321
+ #
322
+ # @api private
323
+ # @since 0.1.0
324
+ class Scheduler < Base
325
+ # Upper bound on one sleep, so clock changes are noticed.
326
+ #
327
+ # @api private
328
+ # @since 0.1.0
329
+ MAX_SLEEP = 60
330
+
331
+ # @param tasks [Array<Recurring::Task>] tasks from configuration
332
+ # @param dynamic [Boolean] also run tasks added at runtime (Store#schedule_recurring),
333
+ # reloaded every `reload_interval` seconds
334
+ #
335
+ # @api private
336
+ # @since 0.1.0
337
+ def initialize(tasks:, builder:, clock: -> { Time.now.utc }, dynamic: false, reload_interval: 5, **)
338
+ super(**)
339
+ @static = tasks
340
+ @builder = builder
341
+ @clock = clock
342
+ @dynamic = dynamic
343
+ @reload_interval = reload_interval
344
+ end
345
+
346
+ # @api private
347
+ # @since 0.1.0
348
+ def metadata
349
+ {tasks: @static.map(&:key), dynamic: @dynamic}
350
+ end
351
+
352
+ private
353
+
354
+ # @api private
355
+ # @since 0.1.0
356
+ def work
357
+ next_runs = {} # task key => [task, next run time]
358
+ reloaded_at = nil
359
+
360
+ until stopped?
361
+ now = @clock.call
362
+ if reloaded_at.nil? || now - reloaded_at >= @reload_interval
363
+ reschedule(next_runs, current_tasks, now)
364
+ reloaded_at = now
365
+ end
366
+
367
+ enqueue_due(next_runs, now)
368
+ sleep_until_next(next_runs, reloaded_at)
369
+ end
370
+ end
371
+
372
+ # New or changed tasks get a fresh next run; removed tasks are forgotten.
373
+ #
374
+ # @api private
375
+ # @since 0.1.0
376
+ def reschedule(next_runs, tasks, now)
377
+ next_runs.select! { |key, (task, _)| tasks[key] && same_task?(tasks[key], task) }
378
+ tasks.each_value { |task| next_runs[task.key] ||= [task, task.next_time(now)] }
379
+ end
380
+
381
+ # @api private
382
+ # @since 0.1.0
383
+ def enqueue_due(next_runs, now)
384
+ next_runs.each do |key, (task, run_at)|
385
+ next if run_at > now
386
+
387
+ enqueue(task, run_at)
388
+ # Runs missed while we were not running are skipped, not backfilled.
389
+ next_runs[key] = [task, task.next_time(now)]
390
+ end
391
+ end
392
+
393
+ # @api private
394
+ # @since 0.1.0
395
+ def sleep_until_next(next_runs, reloaded_at)
396
+ earliest = next_runs.values.map(&:last).min
397
+ wake_at = [earliest, (@dynamic ? reloaded_at + @reload_interval : nil)].compact.min
398
+ @sleeper.sleep(wake_at ? (wake_at - @clock.call).clamp(0.01, MAX_SLEEP) : MAX_SLEEP)
399
+ end
400
+
401
+ # Compares definitions (parsed schedules are compared by their source text).
402
+ #
403
+ # @api private
404
+ # @since 0.1.0
405
+ def same_task?(one, other)
406
+ one.to_h.except(:cron) == other.to_h.except(:cron)
407
+ end
408
+
409
+ # Configured tasks win over runtime tasks with the same key.
410
+ #
411
+ # @api private
412
+ # @since 0.1.0
413
+ def current_tasks
414
+ tasks = @dynamic ? dynamic_tasks : {}
415
+ @static.each { |task| tasks[task.key] = task }
416
+ tasks
417
+ end
418
+
419
+ # @api private
420
+ # @since 0.1.0
421
+ def dynamic_tasks
422
+ store.recurring_tasks.definitions.each_with_object({}) do |(key, definition), tasks|
423
+ tasks[key] = Recurring.build(key => definition).first
424
+ rescue ConfigurationError => exception
425
+ logger.error("[mankai-jobs] skipping recurring task #{key}: #{exception.message}")
426
+ end
427
+ rescue StandardError => exception
428
+ log_error(exception)
429
+ {}
430
+ end
431
+
432
+ # @api private
433
+ # @since 0.1.0
434
+ def enqueue(task, run_at)
435
+ built = @builder.call(task.job, task.args, **task.enqueue_options)
436
+ if built.failure?
437
+ logger.error("[mankai-jobs] recurring task #{task.key} not enqueued: #{built.failure.inspect}")
438
+ return
439
+ end
440
+
441
+ if store.push_recurring(built.value!, task_key: task.key, run_at: run_at)
442
+ logger.info("[mankai-jobs] enqueued recurring task #{task.key} for #{run_at}")
443
+ end
444
+ rescue StandardError => exception
445
+ log_error(exception)
446
+ end
447
+ end
448
+ end
449
+ end
450
+ end
451
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Mankai
6
+ module Jobs
7
+ module SQL
8
+ # A row of the job records table, and what the store asks of it: its locks, the row for an
9
+ # execution table, and the envelope it was stored from.
10
+ #
11
+ # Columns added by later migrations (unique_key, unique_period, preserve_finished, output)
12
+ # read as nil on databases without them.
13
+ #
14
+ # @api private
15
+ # @since 0.1.0
16
+ class Record
17
+ # @api private
18
+ # @since 0.1.0
19
+ COLUMNS = %i[
20
+ id uuid job args queue priority attempts scheduled_at enqueued_at finished_at outcome metadata
21
+ semaphore_id concurrency_key concurrency_limit concurrency_duration concurrency_on_conflict
22
+ unique_key unique_period preserve_finished output
23
+ ].freeze
24
+
25
+ COLUMNS.each do |column|
26
+ # @api private
27
+ # @since 0.1.0
28
+ define_method(column) { @row[column] }
29
+ end
30
+
31
+ # @param row [Hash] as read from the records table
32
+ #
33
+ # @api private
34
+ # @since 0.1.0
35
+ def initialize(row)
36
+ @row = row
37
+ end
38
+
39
+ # @api private
40
+ # @since 0.1.0
41
+ def due?(now)
42
+ scheduled_at.nil? || scheduled_at <= now
43
+ end
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ def concurrency_limited?
48
+ !concurrency_key.nil?
49
+ end
50
+
51
+ # @return [Boolean] whether a job that finds no free slot is discarded (else it waits)
52
+ #
53
+ # @api private
54
+ # @since 0.1.0
55
+ def discard_on_conflict?
56
+ concurrency_on_conflict == "discard"
57
+ end
58
+
59
+ # @return [Concurrency::Lock, nil]
60
+ #
61
+ # @api private
62
+ # @since 0.1.0
63
+ def concurrency_lock
64
+ return unless concurrency_limited?
65
+
66
+ Concurrency::Lock.new(
67
+ key: concurrency_key, limit: concurrency_limit, duration: concurrency_duration,
68
+ on_conflict: concurrency_on_conflict.to_sym
69
+ )
70
+ end
71
+
72
+ # @return [Unique::Lock, nil]
73
+ #
74
+ # @api private
75
+ # @since 0.1.0
76
+ def unique_lock
77
+ return unless unique_key
78
+
79
+ Unique::Lock.new(key: unique_key, period: unique_period)
80
+ end
81
+
82
+ # The column update that frees the unique key, if a job ending with `status` frees it.
83
+ #
84
+ # @api private
85
+ # @since 0.1.0
86
+ def unique_release(status)
87
+ lock = unique_lock
88
+ lock&.released_by?(status) ? {unique_key: nil} : {}
89
+ end
90
+
91
+ # @param default [Boolean] the backend's preserve_finished option
92
+ #
93
+ # @api private
94
+ # @since 0.1.0
95
+ def preserve_finished?(default)
96
+ preserve_finished.nil? ? default : preserve_finished
97
+ end
98
+
99
+ # @return [Hash] a row for the ready, scheduled, claimed or blocked table
100
+ #
101
+ # @api private
102
+ # @since 0.1.0
103
+ def execution_row(now)
104
+ {job_id: id, queue: queue, priority: priority, created_at: now}
105
+ end
106
+
107
+ # @return [Envelope] the envelope this record was stored from
108
+ #
109
+ # @api private
110
+ # @since 0.1.0
111
+ def to_envelope
112
+ Envelope.new(
113
+ id: uuid, job: job, args: JSON.parse(args), queue: queue, priority: priority,
114
+ scheduled_at: scheduled_at, attempts: attempts, enqueued_at: enqueued_at,
115
+ concurrency: concurrency_lock, metadata: JSON.parse(metadata || "{}"), unique: unique_lock,
116
+ preserve_finished: preserve_finished
117
+ )
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Mankai
6
+ module Jobs
7
+ module SQL
8
+ # Turns Envelopes into job record rows, and errors into stored JSON. No database access.
9
+ # Reading a row back is Record's job.
10
+ #
11
+ # @api private
12
+ # @since 0.1.0
13
+ module Records
14
+ # Stored errors and outputs are kept under MySQL's TEXT limit (65,535 bytes), with room
15
+ # to spare.
16
+ #
17
+ # @api private
18
+ # @since 0.1.0
19
+ MAX_BYTES = 60_000
20
+
21
+ # @api private
22
+ # @since 0.1.0
23
+ TRUNCATED = "... [truncated]"
24
+
25
+ module_function
26
+
27
+ # @return [Hash] the job record row for a new envelope
28
+ #
29
+ # @api private
30
+ # @since 0.1.0
31
+ def row(envelope, now)
32
+ concurrency = envelope.concurrency
33
+ {
34
+ uuid: envelope.id,
35
+ job: envelope.job,
36
+ args: JSON.generate(envelope.args),
37
+ queue: envelope.queue,
38
+ priority: envelope.priority,
39
+ attempts: envelope.attempts,
40
+ scheduled_at: envelope.scheduled_at,
41
+ enqueued_at: envelope.enqueued_at,
42
+ concurrency_key: concurrency&.key,
43
+ concurrency_limit: concurrency&.limit,
44
+ concurrency_duration: concurrency&.duration&.ceil,
45
+ concurrency_on_conflict: concurrency&.on_conflict&.to_s,
46
+ metadata: JSON.generate(envelope.metadata),
47
+ created_at: now,
48
+ updated_at: now
49
+ }.merge(newer_columns(envelope))
50
+ end
51
+
52
+ # Columns added by the add_mankai_jobs_controls migration, only when a job uses them, so
53
+ # databases without that migration keep working for jobs that do not.
54
+ #
55
+ # @api private
56
+ # @since 0.1.0
57
+ def newer_columns(envelope)
58
+ columns = {}
59
+ if envelope.unique
60
+ columns[:unique_key] = envelope.unique.key
61
+ columns[:unique_period] = envelope.unique.period&.ceil
62
+ end
63
+ columns[:preserve_finished] = envelope.preserve_finished unless envelope.preserve_finished.nil?
64
+ columns
65
+ end
66
+
67
+ # Drops backtrace lines first, then shortens the message, until the JSON fits MAX_BYTES.
68
+ #
69
+ # @param error [ErrorInfo]
70
+ # @return [String]
71
+ #
72
+ # @api private
73
+ # @since 0.1.0
74
+ def error_json(error) # rubocop:disable Metrics/AbcSize
75
+ data = error.to_h
76
+ json = JSON.generate(data)
77
+ while json.bytesize > MAX_BYTES && data["backtrace"].any?
78
+ data = data.merge("backtrace" => data["backtrace"][0...(data["backtrace"].size / 2)])
79
+ json = JSON.generate(data)
80
+ end
81
+ return json if json.bytesize <= MAX_BYTES
82
+
83
+ # JSON escaping can grow the message, so measure the encoded form.
84
+ overflow = json.bytesize - MAX_BYTES + TRUNCATED.bytesize
85
+ message = data["message"].byteslice(0, [data["message"].bytesize - overflow, 0].max).scrub("")
86
+ JSON.generate(data.merge("message" => message + TRUNCATED))
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end