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,236 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Jobs
5
+ module SQL
6
+ # The SQL backend: stores jobs through a Store and runs them with a Supervisor.
7
+ #
8
+ # Besides the Backend contract it exposes admin operations (queues, pause/resume, retry or
9
+ # discard failed jobs, runtime recurring tasks, counts) for consoles, dashboards and tasks.
10
+ #
11
+ # Those admin methods only forward to Store, Admin and RecurringTasks. That is on purpose:
12
+ # this class is the public entry point, and the classes behind it are private, so they can
13
+ # change without breaking apps.
14
+ #
15
+ # @api public
16
+ # @since 0.1.0
17
+ class Backend
18
+ include Jobs::Backend
19
+
20
+ attr_reader :store, :process_store, :options
21
+
22
+ # @param store [Store] used to enqueue and for admin; shares the app's connection, so
23
+ # enqueuing can join the caller's transaction
24
+ # @param process_store [Store] used by worker processes; may use a separate connection
25
+ # pool (e.g. one that does not log polling queries)
26
+ #
27
+ # @api public
28
+ # @since 0.1.0
29
+ def initialize(store:, runner:, builder:, logger:, process_store: store, recurring: [], clock: -> {
30
+ Time.now.utc
31
+ }, options: Options.call({}))
32
+ @store = store
33
+ @process_store = process_store
34
+ @runner = runner
35
+ @builder = builder
36
+ @recurring = recurring
37
+ @logger = logger
38
+ @clock = clock
39
+ @options = options
40
+ end
41
+
42
+ # @api public
43
+ # @since 0.1.0
44
+ def push(envelope)
45
+ push_many([envelope]).first
46
+ end
47
+
48
+ # @api public
49
+ # @since 0.1.0
50
+ def push_many(envelopes)
51
+ store.push_many(envelopes)
52
+ end
53
+
54
+ # @api public
55
+ # @since 0.1.0
56
+ def push_recurring(envelope, task_key:, run_at:)
57
+ store.push_recurring(envelope, task_key: task_key, run_at: run_at)
58
+ end
59
+
60
+ # Runs the configured processes until a signal stops them. Blocks.
61
+ #
62
+ # @param mode [:fork, :async]
63
+ # @param only [Array<Symbol>, nil] process kinds to run (:worker, :dispatcher, :scheduler)
64
+ # @param reloader [Mankai::Jobs::Reloader, nil] reloads changed code in workers (development)
65
+ #
66
+ # @api public
67
+ # @since 0.1.0
68
+ def run(mode: :fork, only: nil, reloader: nil)
69
+ supervisor(mode: mode, only: only, reloader: reloader).run_with_signals
70
+ end
71
+
72
+ # Builds a supervisor without starting it (call #run, and #stop from another thread).
73
+ #
74
+ # @api public
75
+ # @since 0.1.0
76
+ def supervisor(mode: :async, only: nil, reloader: nil)
77
+ build = ->(spec, supervisor_id:) { build_process(spec, supervisor_id: supervisor_id, reloader: reloader) }
78
+ Supervisor.new(
79
+ specs: specs(only), build: build, mode: mode,
80
+ shutdown_timeout: options[:shutdown_timeout], alive_threshold: options[:alive_threshold],
81
+ fork_boot_timeout: options[:fork_boot_timeout],
82
+ store: process_store, logger: @logger, heartbeat_interval: options[:heartbeat_interval],
83
+ hooks: options[:hooks]
84
+ )
85
+ end
86
+
87
+ # @param queue [String, nil] only this queue
88
+ #
89
+ # @api public
90
+ # @since 0.1.0
91
+ def clear_finished(older_than:, queue: nil, batch_size: 500)
92
+ store.admin.clear_finished(older_than: older_than, queue: queue, batch_size: batch_size)
93
+ end
94
+
95
+ # Deletes finished jobs older than each queue's retention (the `retention` option).
96
+ # Dispatchers do this every `retention_interval` seconds.
97
+ #
98
+ # @api public
99
+ # @since 0.1.0
100
+ def apply_retention
101
+ store.admin.apply_retention(options[:retention])
102
+ end
103
+
104
+ # One job by id, whatever its state, with its recorded output or error.
105
+ #
106
+ # @api public
107
+ # @since 0.1.0
108
+ def job(id)
109
+ store.admin.job(id)
110
+ end
111
+
112
+ # @return [Array<Hash>] {name:, size:, latency:, paused:} per queue
113
+ #
114
+ # @api public
115
+ # @since 0.1.0
116
+ def queues
117
+ store.admin.queues
118
+ end
119
+
120
+ # @api public
121
+ # @since 0.1.0
122
+ def clear_queue(queue)
123
+ store.admin.clear_queue(queue)
124
+ end
125
+
126
+ # @api public
127
+ # @since 0.1.0
128
+ def pause(queue)
129
+ store.admin.pause(queue)
130
+ end
131
+
132
+ # @api public
133
+ # @since 0.1.0
134
+ def resume(queue)
135
+ store.admin.resume(queue)
136
+ end
137
+
138
+ # @api public
139
+ # @since 0.1.0
140
+ def failed_jobs(limit: 100)
141
+ store.admin.failed_jobs(limit: limit)
142
+ end
143
+
144
+ # Retries failed jobs. Pass job ids: the UUIDs that `job(id)` takes and `failed_jobs`
145
+ # returns as :uuid. Record ids (Integers, :id in `failed_jobs`) work too.
146
+ #
147
+ # @return [Integer] how many jobs were retried
148
+ #
149
+ # @api public
150
+ # @since 0.1.0
151
+ def retry_failed(*job_ids)
152
+ store.admin.retry_failed(job_ids.flatten)
153
+ end
154
+
155
+ # Deletes failed jobs. Takes the same ids as #retry_failed.
156
+ #
157
+ # @return [Integer] how many jobs were deleted
158
+ #
159
+ # @api public
160
+ # @since 0.1.0
161
+ def discard_failed(*job_ids)
162
+ store.admin.discard_failed(job_ids.flatten)
163
+ end
164
+
165
+ # Recurring tasks added at runtime (needs `dynamic_recurring_tasks: true` to run).
166
+ #
167
+ # @api public
168
+ # @since 0.1.0
169
+ def schedule_recurring(key, **definition)
170
+ store.recurring_tasks.add(Recurring.build(key.to_s => definition).first)
171
+ end
172
+
173
+ # @api public
174
+ # @since 0.1.0
175
+ def unschedule_recurring(key)
176
+ store.recurring_tasks.remove(key)
177
+ end
178
+
179
+ # @api public
180
+ # @since 0.1.0
181
+ def counts
182
+ store.admin.counts
183
+ end
184
+
185
+ # @api public
186
+ # @since 0.1.0
187
+ def close
188
+ # The app's connection belongs to its db provider; only a pool of our own is ours to close.
189
+ process_store.db.disconnect unless process_store.db.equal?(store.db)
190
+ end
191
+
192
+ private
193
+
194
+ # @api public
195
+ # @since 0.1.0
196
+ def specs(only)
197
+ specs = []
198
+ options[:workers].each do |worker|
199
+ worker[:processes].times { specs << Supervisor::Spec.new(:worker, worker.except(:processes)) }
200
+ end
201
+ options[:dispatchers].each { |dispatcher| specs << Supervisor::Spec.new(:dispatcher, dispatcher) }
202
+ scheduler = options[:scheduler] && (@recurring.any? || options[:dynamic_recurring_tasks])
203
+ specs << Supervisor::Spec.new(:scheduler, {}) if scheduler
204
+ only ? specs.select { |spec| only.include?(spec.kind) } : specs
205
+ end
206
+
207
+ # @api public
208
+ # @since 0.1.0
209
+ def build_process(spec, supervisor_id:, reloader:)
210
+ common = {
211
+ store: process_store, logger: @logger, heartbeat_interval: options[:heartbeat_interval],
212
+ supervisor_id: supervisor_id, hooks: options[:hooks]
213
+ }
214
+ case spec.kind
215
+ when :worker
216
+ Processes::Worker.new(
217
+ **common, **spec.options,
218
+ runner: @runner, shutdown_timeout: options[:shutdown_timeout], reloader: reloader,
219
+ # Transactional jobs finish on the app's own connection, which their writes use.
220
+ transaction_store: store
221
+ )
222
+ when :dispatcher
223
+ Processes::Dispatcher.new(
224
+ **common, **spec.options, retention: options[:retention], retention_interval: options[:retention_interval]
225
+ )
226
+ when :scheduler
227
+ Processes::Scheduler.new(
228
+ **common, tasks: @recurring, builder: @builder, clock: @clock,
229
+ dynamic: options[:dynamic_recurring_tasks], reload_interval: options[:recurring_reload_interval]
230
+ )
231
+ end
232
+ end
233
+ end
234
+ end
235
+ end
236
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Jobs
5
+ module SQL
6
+ # The connection, table names, clock and instrumenter shared by Store and the classes that
7
+ # work beside it (ProcessRegistry, Admin, RecurringTasks), with the transaction rules every
8
+ # write follows.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ class Database
13
+ # Deadlocks (common with MySQL/MariaDB gap locks under concurrent inserts) roll back the
14
+ # whole transaction, so it is safe to run it again, after a short random pause.
15
+ #
16
+ # @api private
17
+ # @since 0.1.0
18
+ RETRY = {
19
+ retry_on: [Sequel::SerializationFailure], num_retries: 5,
20
+ before_retry: ->(attempt, _error) { sleep(rand * 0.02 * attempt) }
21
+ }.freeze
22
+
23
+ # The events this backend publishes, each "mankai.jobs.sql.<name>". They are registered
24
+ # when the backend is built, so subscribers can find them before they first fire.
25
+ #
26
+ # @api private
27
+ # @since 0.1.0
28
+ EVENTS = %i[
29
+ claim release_claims fail_claims dispatch_scheduled prune_processes enqueue_recurring apply_retention
30
+ output_dropped
31
+ ].map { |name| :"sql.#{name}" }.freeze
32
+
33
+ attr_reader :db, :tables, :clock, :instrumenter
34
+
35
+ # @api private
36
+ # @since 0.1.0
37
+ def initialize(db:, tables:, clock:, instrumenter:)
38
+ @db = db
39
+ @tables = tables
40
+ @clock = clock
41
+ @instrumenter = instrumenter.register(*EVENTS)
42
+ @transaction_options = transaction_options_for(db)
43
+ end
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ def table(name)
48
+ db[tables[name]]
49
+ end
50
+
51
+ # @api private
52
+ # @since 0.1.0
53
+ def now
54
+ clock.call
55
+ end
56
+
57
+ # Retried after a deadlock or serialization failure (the database rolled it back), unless
58
+ # it is nested in a transaction of the caller's, which only the caller can retry. Pass
59
+ # `retriable: false` for blocks with effects outside the database.
60
+ #
61
+ # @api private
62
+ # @since 0.1.0
63
+ def transaction(retriable: true, &)
64
+ options = @transaction_options
65
+ options = options.merge(RETRY) if retriable && !db.in_transaction?
66
+ db.transaction(**options, &)
67
+ end
68
+
69
+ # Locks the rows of `dataset`, skipping rows other transactions hold where supported.
70
+ #
71
+ # @api private
72
+ # @since 0.1.0
73
+ def skip_locked(dataset)
74
+ dataset = dataset.for_update
75
+ dataset.supports_skip_locked? ? dataset.skip_locked : dataset
76
+ end
77
+
78
+ # Instruments "mankai.jobs.sql.<name>".
79
+ #
80
+ # @api private
81
+ # @since 0.1.0
82
+ def event(name, **payload)
83
+ instrumenter.instrument(:"sql.#{name}", **payload)
84
+ end
85
+
86
+ private
87
+
88
+ # @api private
89
+ # @since 0.1.0
90
+ def transaction_options_for(db)
91
+ case db.database_type
92
+ # SQLite has no row locks: take the write lock up front so concurrent claims serialize
93
+ # instead of failing on lock upgrade.
94
+ when :sqlite then {mode: :immediate}
95
+ # Under REPEATABLE READ, InnoDB gap locks can deadlock enqueues against claims.
96
+ when :mysql then {isolation: :committed}
97
+ else {}
98
+ end
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Jobs
5
+ module SQL
6
+ # Explanations for the error page of Hanami 3.1+ (experimental Hanami diagnostics API).
7
+ # Registered by `lib/mankai/jobs/sql/hanami_diagnostics.rb`, which Hanami loads in
8
+ # development through this gem's `hanami_diagnostics` metadata.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ module Diagnostics
13
+ # A query hit a mankai-jobs table that does not exist yet.
14
+ #
15
+ # @api private
16
+ # @since 0.1.0
17
+ class MissingTables
18
+ # @api private
19
+ # @since 0.1.0
20
+ PATTERNS = [
21
+ /no such table: (?<table>\w*jobs_\w+)/, # SQLite
22
+ /relation "(?<table>\w*jobs_\w+)" does not exist/, # PostgreSQL
23
+ /Table '[^.']*\.?(?<table>\w*jobs_\w+)' doesn't exist/ # MySQL
24
+ ].freeze
25
+
26
+ # @api private
27
+ # @since 0.1.0
28
+ def initialize(exception, _context = nil)
29
+ @exception = exception
30
+ end
31
+
32
+ # @api private
33
+ # @since 0.1.0
34
+ def applies?
35
+ !table.nil?
36
+ end
37
+
38
+ # @api private
39
+ # @since 0.1.0
40
+ def title
41
+ "mankai-jobs tables are missing"
42
+ end
43
+
44
+ # @api private
45
+ # @since 0.1.0
46
+ def explanation
47
+ "The table `#{table}` doesn't exist. mankai-jobs-sql keeps jobs in your database, and its " \
48
+ "migration hasn't been installed or run yet."
49
+ end
50
+
51
+ # @api private
52
+ # @since 0.1.0
53
+ def fix
54
+ {
55
+ name: "Install and run the migration",
56
+ text: "Run `bundle exec hanami jobs install`, then `bundle exec hanami db migrate`."
57
+ }
58
+ end
59
+
60
+ # @api private
61
+ # @since 0.1.0
62
+ def run_fix
63
+ ["bundle exec hanami jobs install", "bundle exec hanami db migrate"].map { |command|
64
+ output = `#{command} 2>&1`
65
+ raise "`#{command}` failed:\n#{output}" unless $?.success?
66
+
67
+ output
68
+ }.join
69
+ end
70
+
71
+ private
72
+
73
+ # @api private
74
+ # @since 0.1.0
75
+ def table
76
+ messages = []
77
+ error = @exception
78
+ while error
79
+ messages << error.message
80
+ error = error.cause
81
+ end
82
+ PATTERNS.each do |pattern|
83
+ messages.each { |message| (match = pattern.match(message)) and return match[:table] }
84
+ end
85
+ nil
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Jobs
5
+ module SQL
6
+ # Builds the SQL backend from the provider's context and the options given to
7
+ # Mankai::Jobs::SQL.backend(...).
8
+ #
9
+ # `gateway:` may be a container key (default "db.gateway"; use "db.gateways.jobs" for a
10
+ # separate database), a ROM gateway, or a Sequel::Database.
11
+ #
12
+ # @api private
13
+ # @since 0.1.0
14
+ module Factory
15
+ # Makes a SQLite connection wait for locks without holding Ruby's global lock, so other
16
+ # threads keep running while it waits. Pass it as the connection's `after_connect`.
17
+ #
18
+ # @api private
19
+ # @since 0.1.0
20
+ SQLITE_BUSY_HANDLER = ->(connection) { connection.busy_handler_timeout = 5000 }
21
+
22
+ module_function
23
+
24
+ # @api private
25
+ # @since 0.1.0
26
+ def call(context, **raw_options)
27
+ options = Options.call(raw_options)
28
+ db = resolve_database(options[:gateway], context.container)
29
+ warn_about_database(db, options, context.logger)
30
+
31
+ store_options = {
32
+ tables: Tables.new(options[:table_prefix]),
33
+ clock: context.clock,
34
+ preserve_finished: options[:preserve_finished],
35
+ in_transaction: options[:in_transaction],
36
+ instrumenter: context.instrumenter
37
+ }
38
+ store = Store.new(db: db, **store_options)
39
+ process_store = options[:silence_polling] ? Store.new(db: quiet_copy(db), **store_options) : store
40
+
41
+ Backend.new(
42
+ store: store, process_store: process_store, runner: context.runner, builder: context.builder,
43
+ recurring: context.recurring, logger: context.logger, clock: context.clock, options: options
44
+ )
45
+ end
46
+
47
+ # Backs `hanami jobs install`.
48
+ #
49
+ # @api private
50
+ # @since 0.1.0
51
+ def install(root:, out:, table_prefix: "jobs_")
52
+ Migration.install(root: root, out: out, table_prefix: table_prefix)
53
+ end
54
+
55
+ # @api private
56
+ # @since 0.1.0
57
+ def resolve_database(gateway, container)
58
+ gateway = container[gateway] if gateway.is_a?(String) && container
59
+ gateway = gateway.connection if gateway.respond_to?(:connection) && !gateway.is_a?(Sequel::Database)
60
+ return gateway if gateway.is_a?(Sequel::Database)
61
+
62
+ raise ConfigurationError,
63
+ "gateway must be a container key, a ROM gateway or a Sequel::Database, got #{gateway.inspect}"
64
+ end
65
+
66
+ # A second connection pool to the same database, without the app's loggers and query
67
+ # instrumentation, so the constant polling of worker processes stays out of the logs.
68
+ # Falls back to the app's connection for in-memory SQLite, which cannot be shared.
69
+ #
70
+ # @api private
71
+ # @since 0.1.0
72
+ def quiet_copy(db)
73
+ return db if db.database_type == :sqlite && [nil, "", ":memory:"].include?(db.opts[:database])
74
+
75
+ options = db.opts.except(:loggers, :logger, :orig_opts).merge(logger: nil, test: false)
76
+ # This pool is ours, so it can wait for locks the way warn_about_sqlite_locking asks the
77
+ # app to.
78
+ options[:after_connect] ||= SQLITE_BUSY_HANDLER if db.database_type == :sqlite
79
+ Sequel.connect(options)
80
+ end
81
+
82
+ # MySQL and MariaDB keep whole seconds unless Sequel is told to send fractions, so jobs
83
+ # scheduled for "in 0.2 seconds" could run up to a second off.
84
+ #
85
+ # @api private
86
+ # @since 0.1.0
87
+ def warn_about_time_precision(db, logger)
88
+ return unless db.database_type == :mysql && !db.supports_timestamp_usecs?
89
+
90
+ logger.warn(
91
+ "[mankai-jobs] this MySQL/MariaDB connection stores times in whole seconds. Add " \
92
+ "fractional_seconds=true to the database URL (before running mankai-jobs' migrations)."
93
+ )
94
+ end
95
+
96
+ # Settings of the app's connection that mankai-jobs cannot change itself.
97
+ #
98
+ # @api private
99
+ # @since 0.1.0
100
+ def warn_about_database(db, options, logger)
101
+ warn_about_pool_size(db, options, logger)
102
+ warn_about_time_precision(db, logger)
103
+ warn_about_sqlite_locking(db, logger)
104
+ end
105
+
106
+ # By default, a SQLite connection waiting for a lock holds Ruby's global lock, so every
107
+ # other thread in the process (other jobs, heartbeats, web requests) stops for up to 5
108
+ # seconds, including the thread holding the lock. The connection belongs to the app, so
109
+ # say how to fix it rather than change it. Any `after_connect` counts as handled.
110
+ #
111
+ # @api private
112
+ # @since 0.1.0
113
+ def warn_about_sqlite_locking(db, logger)
114
+ return unless db.database_type == :sqlite && db.opts[:after_connect].nil?
115
+
116
+ logger.warn(
117
+ "[mankai-jobs] SQLite connections hold Ruby's global lock while waiting for a database lock, " \
118
+ "stalling worker threads. Add after_connect: ->(conn) { conn.busy_handler_timeout = 5000 } to the " \
119
+ "database's connection options (see the mankai-jobs-sql README)."
120
+ )
121
+ end
122
+
123
+ # Each worker needs one connection per thread, plus polling and heartbeats.
124
+ #
125
+ # @api private
126
+ # @since 0.1.0
127
+ def warn_about_pool_size(db, options, logger)
128
+ needed = options[:workers].map { |worker| worker[:threads] + 2 }.max || 0
129
+ size = db.pool.respond_to?(:max_size) ? db.pool.max_size : nil
130
+ return unless size && size < needed
131
+
132
+ logger.warn(
133
+ "[mankai-jobs] database pool size #{size} is smaller than the #{needed} connections a worker " \
134
+ "process needs (threads + 2). Raise max_connections on the database URL."
135
+ )
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loaded by Hanami webconsole (3.1+) in development, through this gem's `hanami_diagnostics`
4
+ # gemspec metadata. It may load before the gem itself, so it registers by class name, and only
5
+ # autoloads the (dependency-free) diagnostic class for when an error needs it.
6
+ module Mankai
7
+ module Jobs
8
+ module SQL
9
+ autoload :Diagnostics, File.expand_path("diagnostics", __dir__)
10
+ end
11
+ end
12
+ end
13
+
14
+ Hanami::Diagnostics.register "Sequel::DatabaseError", "Mankai::Jobs::SQL::Diagnostics::MissingTables"
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
4
+ require "fileutils"
5
+
6
+ module Mankai
7
+ module Jobs
8
+ module SQL
9
+ # Renders mankai-jobs-sql's migrations, and installs them into an app.
10
+ #
11
+ # Migrations are versioned: a newer release adds a migration rather than changing an old
12
+ # one, and `hanami jobs install` writes the ones an app does not have yet.
13
+ #
14
+ # @api public
15
+ # @since 0.1.0
16
+ module Migration
17
+ # @api private
18
+ # @since 0.1.0
19
+ Step = Data.define(:name, :template)
20
+
21
+ # @api private
22
+ # @since 0.1.0
23
+ STEPS = [
24
+ Step.new("create_mankai_jobs_tables", "create_jobs_tables.rb.erb"),
25
+ Step.new("add_mankai_jobs_controls", "add_jobs_controls.rb.erb")
26
+ ].freeze
27
+
28
+ module_function
29
+
30
+ # @param migration_dsl ["ROM::SQL", "Sequel"] the object whose .migration builds it.
31
+ # Hanami apps use ROM::SQL; plain Sequel projects use Sequel.
32
+ # @param step [Step] which migration (the first by default)
33
+ #
34
+ # @api public
35
+ # @since 0.1.0
36
+ def render(table_prefix: "jobs_", migration_dsl: "ROM::SQL", step: STEPS.first)
37
+ t = Tables.new(table_prefix)
38
+ ERB.new(File.read(template_path(step)), trim_mode: "-").result(binding)
39
+ end
40
+
41
+ # Writes the migrations the app does not have yet into config/db/migrate.
42
+ #
43
+ # @return [Array<String>] paths of all the migrations, existing or new
44
+ #
45
+ # @api public
46
+ # @since 0.1.0
47
+ def install(root:, out: $stdout, table_prefix: "jobs_", now: Time.now.utc)
48
+ dir = File.join(root.to_s, "config", "db", "migrate")
49
+ created = []
50
+ paths = STEPS.each_with_index.map do |step, index|
51
+ existing(dir, step, out) || write_step(dir, step, now + index, table_prefix).tap { |path| created << path }
52
+ end
53
+
54
+ if created.empty?
55
+ out.puts "Migrations already exist: #{paths.join(", ")}"
56
+ else
57
+ created.each { |path| out.puts "Created #{path}" }
58
+ out.puts "Run `hanami db migrate` to update the tables."
59
+ end
60
+ paths
61
+ end
62
+
63
+ # @return [String, nil] the app's copy of a migration, noting duplicate copies
64
+ #
65
+ # @api public
66
+ # @since 0.1.0
67
+ def existing(dir, step, out)
68
+ copies = Dir.glob(File.join(dir, "*_#{step.name}.rb")).sort
69
+ if copies.size > 1
70
+ out.puts "Note: #{step.name} exists #{copies.size} times (#{copies.join(", ")}). " \
71
+ "It is idempotent, so this is harmless, but you can delete all but the first."
72
+ end
73
+ copies.first
74
+ end
75
+
76
+ # @api public
77
+ # @since 0.1.0
78
+ def write_step(dir, step, time, table_prefix)
79
+ FileUtils.mkdir_p(dir)
80
+ path = File.join(dir, "#{time.strftime("%Y%m%d%H%M%S")}_#{step.name}.rb")
81
+ File.write(path, render(table_prefix: table_prefix, step: step))
82
+ path
83
+ end
84
+
85
+ # Applies the migrations directly to a Sequel database. For tests and non-Hanami use.
86
+ #
87
+ # @api public
88
+ # @since 0.1.0
89
+ def apply(db, direction = :up, table_prefix: "jobs_")
90
+ Sequel.extension :migration
91
+ steps = direction == :up ? STEPS : STEPS.reverse
92
+ steps.each do |step|
93
+ source = render(table_prefix: table_prefix, migration_dsl: "Sequel", step: step)
94
+ migration = eval(source, TOPLEVEL_BINDING, template_path(step)) # rubocop:disable Security/Eval
95
+ migration.apply(db, direction)
96
+ end
97
+ end
98
+
99
+ # @api public
100
+ # @since 0.1.0
101
+ def template_path(step)
102
+ File.join(__dir__, "templates", step.template)
103
+ end
104
+ end
105
+ end
106
+ end
107
+ end