deploy_pin 1.8.7 → 1.10.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.
data/README.md CHANGED
@@ -1,152 +1,448 @@
1
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
2
- [![Gem Version](https://badge.fury.io/rb/deploy_pin.svg)](https://badge.fury.io/rb/deploy_pin)
3
- ![](https://ruby-gem-downloads-badge.herokuapp.com/deploy_pin)
4
- [![Verification](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml/badge.svg)](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml)
5
- [![Publish Gem](https://github.com/skcc321/deploy_pin/actions/workflows/publish.yml/badge.svg)](https://github.com/skcc321/deploy_pin/actions/workflows/publish.yml)
6
-
7
1
  # DeployPin
8
2
 
9
- Deploying applications often involves the need to execute a series of specific commands or tasks either before or after the deployment process. While you might typically turn to migrations for such operations, these tasks aren't always migration-related. Additionally, there are situations where you need to execute code before or after a migration without causing the main thread to block.
10
-
11
- Introducing deploy_pins – your go-to solution for streamlined task management during the deployment process. This Ruby library allows you to seamlessly orchestrate tasks before, after, or independently of migrations, offering the flexibility you need to maintain a smooth and efficient deployment workflow. With deploy_pins, you can take control of your deployment tasks and ensure that your application operates flawlessly in any environment.
3
+ [![Gem Version](https://img.shields.io/gem/v/deploy_pin?color=CC342D)](https://rubygems.org/gems/deploy_pin)
4
+ [![Downloads](https://img.shields.io/gem/dt/deploy_pin)](https://rubygems.org/gems/deploy_pin)
5
+ [![CI](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml/badge.svg)](https://github.com/skcc321/deploy_pin/actions/workflows/verify.yml)
6
+ [![Docs](https://img.shields.io/badge/docs-rubydoc.info-blue)](https://rubydoc.info/gems/deploy_pin)
7
+ [![Ruby](https://img.shields.io/badge/ruby-%E2%89%A5%203.1-CC342D)](#requirements)
8
+ [![Rails](https://img.shields.io/badge/rails-7.0%20%E2%80%93%208.x-CC0000)](#requirements)
9
+ [![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](MIT-LICENSE)
10
+
11
+ **Run one-off and recurring tasks around your deployments — data backfills, cache warm-ups, cleanups — in a defined order, exactly once, with database timeouts and resumable progress.**
12
+
13
+ Migrations are for schema changes. Everything else you need to run during a release (backfill a column, re-index records, call an external API, warm a cache) usually ends up in an ad-hoc rake task that someone has to remember to run. DeployPin keeps these tasks in your repository as plain Ruby files, runs each one once, in the order you define, and remembers what has already run.
14
+
15
+ ## Contents
16
+
17
+ - [Features](#features)
18
+ - [Requirements](#requirements)
19
+ - [Installation](#installation)
20
+ - [Quick start](#quick-start)
21
+ - [How it works](#how-it-works)
22
+ - [Commands](#commands)
23
+ - [Hooking into your deploy](#hooking-into-your-deploy)
24
+ - [Features in depth](#features-in-depth)
25
+ - [Configuration reference](#configuration-reference)
26
+ - [Development](#development)
27
+ - [Contributing](#contributing)
28
+ - [Similar gems](#similar-gems)
29
+ - [License](#license)
30
+
31
+ ## Features
32
+
33
+ - 📌 **Run once:** each task's completion is stored, so it never runs twice. You can still re-run it on purpose.
34
+ - 🗂 **Groups and ordering:** run tasks before or after migrations, or at any other step of your deploy.
35
+ - ⏱ **Statement timeouts:** tasks run under a database statement timeout (PostgreSQL, MySQL, MariaDB).
36
+ - ⚡ **Parallel:** a [Parallel](https://github.com/grosser/parallel) wrapper that applies the timeout in every worker.
37
+ - 🔁 **Resumable:** save progress so a long task continues where it stopped.
38
+ - ♻️ **Recurring tasks:** tasks that run on every deploy.
39
+ - 🚦 **Deployment state:** `DeployPin.ongoing_deployment?` lets your app behave differently while a deploy is in progress.
40
+ - 🍃 **ActiveRecord or Mongoid** storage.
41
+
42
+ ## Requirements
43
+
44
+ | | |
45
+ |---|---|
46
+ | Ruby | ≥ 3.1 (CI runs 3.3, 3.4 and 4.0) |
47
+ | Rails | ≥ 7.0, < 9 (CI runs 8.1) |
48
+ | Storage | ActiveRecord (PostgreSQL, MySQL, MariaDB, …) or Mongoid |
49
+ | Redis | Only for [deployment state](#deployment-state) |
50
+
51
+ Statement timeouts need ActiveRecord with PostgreSQL, MySQL or MariaDB. With other setups, tasks run without a timeout.
12
52
 
13
- ## Usage
53
+ ## Installation
14
54
 
15
- ![DeployPin](deploy_pin.gif)
55
+ Add the gem to your Gemfile and install it:
16
56
 
17
- To generate a new task template file:
18
57
  ```bash
19
- rails g deploy_pin:task some_task_title
20
- # or
21
- rails g deploy_pin:task some_task_title --parallel
58
+ bundle add deploy_pin
22
59
  ```
23
60
 
24
- You can also specify the author:
61
+ Then generate the initializer and the migration, and migrate:
62
+
25
63
  ```bash
26
- rails g deploy_pin:task some_task_title -a author_name
64
+ rails g deploy_pin:install
65
+ rails db:migrate
27
66
  ```
28
67
 
29
- To list all pending tasks:
68
+ <details>
69
+ <summary>Using Mongoid?</summary>
70
+
71
+ Generate the initializer with Mongoid storage (no migration is created), then create the indexes:
72
+
30
73
  ```bash
31
- rake deploy_pin:list
74
+ rails g deploy_pin:install --storage=mongoid
75
+ rails db:mongoid:create_indexes
76
+ ```
77
+
78
+ Mongoid is not a dependency of deploy_pin, so it has to be in your Gemfile. See [Storage](#storage).
79
+
80
+ </details>
81
+
82
+ The generated `config/initializers/deploy_pin.rb` starts like this:
83
+
84
+ ```ruby
85
+ DeployPin.setup do
86
+ tasks_path 'lib/deploy_pin'
87
+ groups %w[pre I II III]
88
+ fallback_group 'III'
89
+ statement_timeout 10.minutes
90
+ # ...formatters and deployment state, see below
91
+ end
32
92
  ```
33
93
 
34
- To run all pending tasks:
94
+ ## Quick start
95
+
35
96
  ```bash
97
+ # 1. Generate a task in a group
98
+ rails g deploy_pin:task backfill_user_names -g I
99
+
100
+ # 2. Write the code in lib/deploy_pin/<timestamp>_backfill_user_names.rb
101
+ # and its test in spec/deploy_pin/<timestamp>_backfill_user_names_spec.rb
102
+
103
+ # 3. See what is pending
104
+ rake deploy_pin:list
105
+
106
+ # 4. Run it (normally from your deploy script)
36
107
  rake deploy_pin:run
37
108
  ```
38
109
 
39
- ## Grouped Tasks
110
+ ## How it works
40
111
 
41
- To define allowed groups, navigate to `config/initializers/deploy_pin.rb`. You can group tasks around the "allowed_group" like this:
42
- ```bash
43
- rails g deploy_pin:task task_title -g allowed_group
44
- # or
45
- rails g deploy_pin:task task_title -g allowed_group --parallel
112
+ ### Task files
113
+
114
+ A task is a Ruby file in `tasks_path`. The generator writes the header for you:
115
+
116
+ ```ruby
117
+ # 20190401135040:I
118
+ # task_title: Backfill user names
119
+ # affected_areas: users
120
+
121
+ # === task code goes down here ===
122
+ User.where(name: nil).find_each { |user| user.update!(name: user.email) }
46
123
  ```
47
124
 
48
- To list all pending tasks within the "allowed_group":
125
+ | Header line | Meaning |
126
+ |---|---|
127
+ | `# 20190401135040:I` | `<identifier>:<group>`. The identifier is a timestamp for one-off tasks. |
128
+ | `# 20190401135040:I:recurring` | A [recurring task](#recurring-tasks) that runs on every deploy |
129
+ | `# task_title:` | Shown by `list` and `run` |
130
+ | `# affected_areas:` | Free text for reviewers: what the task touches |
131
+
132
+ ### Groups and ordering
133
+
134
+ `groups` defines the steps of your deploy, in order. Group names are up to you, and so is the moment each group runs: you choose it by calling `rake 'deploy_pin:run[<group>]'` at that point of your deploy. You can have as many stages as you need. For example:
135
+
136
+ | Group | When you run it | Typical tasks |
137
+ |---|---|---|
138
+ | `pre` | Right before the deploy starts | Pause background jobs, take a snapshot, flip a feature flag |
139
+ | `I`, `II`, … | Around the migrations | Backfill data that the new schema or code needs |
140
+ | `post` | Right after the new release is live | Warm caches, re-enable jobs, notify other services |
141
+
142
+ Tasks are sorted by **group**, then by **identifier**. Negative identifiers run after the other tasks of their group.
143
+
144
+ A non-recurring task runs only once. When it finishes, it is marked done in the storage, and later runs skip it. If two tasks have the same code, only the first one runs.
145
+
146
+ ### Selecting tasks
147
+
148
+ Every command takes an optional, comma-separated list of groups and identifiers:
149
+
150
+ | Argument | Selects |
151
+ |---|---|
152
+ | *(none)* | All pending tasks in all groups |
153
+ | `I` | Pending tasks in group `I` |
154
+ | `20190401135040` | That task, if it is pending |
155
+ | `20190401135040!` or `I!` | Re-run: selects matching tasks even if they are done |
156
+ | `!20190401135040` or `!II` | Skips matching tasks |
157
+
49
158
  ```bash
50
- rake deploy_pin:list[allowed_group]
159
+ rake 'deploy_pin:run[I, II]'
160
+ rake 'deploy_pin:run[20190401135040!]' # re-run one task
161
+ rake 'deploy_pin:run[I, !20190401135040]' # group I except one task
51
162
  ```
52
163
 
53
- To run all pending tasks within the "allowed_group":
164
+ > [!TIP]
165
+ > Quote the task name (`'deploy_pin:run[...]'`). Shells such as zsh treat the square brackets as glob patterns.
166
+
167
+ ## Commands
168
+
169
+ | Command | Description |
170
+ |---|---|
171
+ | `rails g deploy_pin:task <title> -g <group>` | Generate a task and its [test](#testing-tasks). Options: `--parallel`, `--recurring --identifier <n>`, `-a <author>`, `--skip-test`, `--test-framework=rspec` |
172
+ | `rake deploy_pin:list[...]` | List pending tasks, including their code |
173
+ | `rake deploy_pin:short_list[...]` | List pending tasks by group, without the code |
174
+ | `rake deploy_pin:run[...]` | Run pending tasks |
175
+ | `rake deploy_pin:mark_done[...]` | Mark tasks as done without running them. For example, in `db/seeds.rb` for a fresh database, or for a new environment |
176
+
177
+ ## Hooking into your deploy
178
+
179
+ Call `deploy_pin:run` with the right groups at each stage of your deploy. With `groups %w[pre I II III post]`:
180
+
54
181
  ```bash
55
- rake deploy_pin:run[allowed_group]
182
+ # right before the deploy
183
+ bundle exec rake 'deploy_pin:run[pre]'
184
+
185
+ # with the migrations
186
+ bundle exec rake db:migrate 'deploy_pin:run[I, II, III]'
187
+
188
+ # right after the new release is live
189
+ bundle exec rake 'deploy_pin:run[post]'
56
190
  ```
57
191
 
58
- ## Run by Identifier
192
+ ### Example: a search index change in two stages
193
+
194
+ Say the new release searches a new Elasticsearch index, `products_v2`. The index has to exist before the new code goes live, but filling it takes hours. Split the work into a `pre` task and a `post` task:
59
195
 
60
- To execute a specific task using its identifier:
61
196
  ```bash
62
- rake deploy_pin:run['identifier_1, identifier_2']
197
+ rails g deploy_pin:task create_products_v2_index -g pre
198
+ rails g deploy_pin:task backfill_products_v2_index -g post
63
199
  ```
64
200
 
65
- Alternatively, you can combine an identifier and a group:
66
- ```bash
67
- rake deploy_pin:run['identifier, allowed_group']
201
+ The **pre** task creates the mapping and indexes only the data the new release needs right away, so the deploy stays fast:
202
+
203
+ ```ruby
204
+ # 20261124120000:pre
205
+ # task_title: Create products_v2 index and index recent products
206
+ # affected_areas: product search
207
+
208
+ # === task code goes down here ===
209
+ client = Elasticsearch::Client.new(url: ENV.fetch('ELASTICSEARCH_URL'))
210
+
211
+ unless client.indices.exists?(index: 'products_v2')
212
+ client.indices.create(
213
+ index: 'products_v2',
214
+ body: {
215
+ mappings: {
216
+ properties: {
217
+ name: { type: 'text' },
218
+ sku: { type: 'keyword' },
219
+ price: { type: 'scaled_float', scaling_factor: 100 }
220
+ }
221
+ }
222
+ }
223
+ )
224
+ end
225
+
226
+ # Products changed in the last week: enough for search to work after the release
227
+ Product.where(updated_at: 1.week.ago..).find_in_batches(batch_size: 500) do |batch|
228
+ client.bulk(body: batch.flat_map { |product| [{ index: { _index: 'products_v2', _id: product.id } }, product.search_document] })
229
+ end
68
230
  ```
69
231
 
70
- If you wish to rerun a task, add an exclamation mark at the end of the identifier:
232
+ The **post** task indexes everything else after the release is live. It saves its progress, so if it is interrupted, the next `deploy_pin:run[post]` continues where it stopped instead of starting over:
233
+
234
+ ```ruby
235
+ # 20261124120100:post
236
+ # task_title: Index all products into products_v2
237
+ # affected_areas: product search
238
+
239
+ # === task code goes down here ===
240
+ client = Elasticsearch::Client.new(url: ENV.fetch('ELASTICSEARCH_URL'))
241
+
242
+ Product.where('id > ?', progress).find_in_batches(batch_size: 1_000) do |batch|
243
+ client.bulk(body: batch.flat_map { |product| [{ index: { _index: 'products_v2', _id: product.id } }, product.search_document] })
244
+ save_progress!(batch.last.id)
245
+ end
246
+ ```
247
+
248
+ Both tasks run once. The next deploy skips them because they are marked done.
249
+
250
+ ### Deploy tool examples
251
+
252
+ The examples below use the same stages. Adjust them to your own groups.
253
+
254
+ <details>
255
+ <summary>Heroku</summary>
256
+
257
+ The release phase runs before the new release goes live:
258
+
259
+ ```
260
+ # Procfile
261
+ release: bundle exec rake 'deploy_pin:run[pre]' db:migrate 'deploy_pin:run[I, II, III]'
262
+ ```
263
+
264
+ Heroku has no hook after the release is live, so run `post` as a one-off dyno from your deploy pipeline:
265
+
71
266
  ```bash
72
- rake deploy_pin:run['identifier_1!, identifier_2!']
267
+ heroku run "bundle exec rake 'deploy_pin:run[post]'"
73
268
  ```
74
269
 
75
- ## Installation
270
+ </details>
76
271
 
77
- Add this line to your application's Gemfile:
272
+ <details>
273
+ <summary>Capistrano</summary>
78
274
 
79
275
  ```ruby
80
- gem 'deploy_pin'
276
+ # lib/capistrano/tasks/deploy_pin.rake
277
+ namespace :deploy_pin do
278
+ { pre: 'pre', migrate: 'I, II, III', post: 'post' }.each do |stage, groups|
279
+ task stage do
280
+ on primary(:db) do
281
+ within release_path do
282
+ with rails_env: fetch(:rails_env) do
283
+ execute :rake, "'deploy_pin:run[#{groups}]'"
284
+ end
285
+ end
286
+ end
287
+ end
288
+ end
289
+ end
290
+
291
+ # config/deploy.rb
292
+ before 'deploy:migrate', 'deploy_pin:pre'
293
+ after 'deploy:migrate', 'deploy_pin:migrate'
294
+ after 'deploy:published', 'deploy_pin:post'
81
295
  ```
82
296
 
83
- Then execute:
297
+ </details>
298
+
299
+ <details>
300
+ <summary>Kamal</summary>
301
+
302
+ Use [Kamal hooks](https://kamal-deploy.org/docs/hooks/overview/). They run on your machine, so each one calls `kamal app exec` (remember to make them executable):
303
+
84
304
  ```bash
85
- $ bundle
305
+ # .kamal/hooks/pre-deploy: the new image is pushed, the old version still serves traffic
306
+ kamal app exec --primary --version "$KAMAL_VERSION" "bin/rails 'deploy_pin:run[pre]'"
307
+
308
+ # .kamal/hooks/post-deploy: the new version is live
309
+ kamal app exec --primary --reuse "bin/rails 'deploy_pin:run[I, II, III]' 'deploy_pin:run[post]'"
86
310
  ```
87
311
 
88
- You can also install it manually with:
89
- ```bash
90
- $ gem install deploy_pin
312
+ The default Rails entrypoint runs `db:prepare` when the container boots, so here the migration groups run in the post-deploy hook.
313
+
314
+ </details>
315
+
316
+ ## Features in depth
317
+
318
+ ### Database timeout
319
+
320
+ Tasks run under `statement_timeout` from the initializer. To use a different timeout, wrap the code in `DeployPin::Database.execute_with_timeout`. The default timeout is then not applied to that task.
321
+
322
+ ```ruby
323
+ # === task code goes down here ===
324
+ DeployPin::Database.execute_with_timeout 30.minutes do
325
+ ActiveRecord::Base.connection.execute('UPDATE shipments SET ...')
326
+ end
91
327
  ```
92
328
 
93
- Afterward, generate the configuration file:
94
- ```bash
95
- rails g deploy_pin:install
329
+ It also accepts `connected_to:`, to run against a replica or another database. See the [`DeployPin::Database` docs](https://rubydoc.info/gems/deploy_pin/DeployPin/Database).
330
+
331
+ ### Parallel
332
+
333
+ Generate the task with `--parallel`. Inside it, prefix any [Parallel](https://github.com/grosser/parallel) method with `parallel_`. Each block call gets its own connection and runs under the timeout:
334
+
335
+ ```ruby
336
+ parallel_each(User.ids.each_slice(1_000).to_a, in_processes: 4, timeout: 5.minutes) do |ids|
337
+ User.where(id: ids).update_all(active: true)
338
+ end
96
339
  ```
97
340
 
98
- Finally, run the migration:
341
+ See the [`DeployPin::ParallelWrapper` docs](https://rubydoc.info/gems/deploy_pin/DeployPin/ParallelWrapper) for passing timeout options.
342
+
343
+ ### Resumable tasks
344
+
345
+ Long tasks can save progress in their record and pick up from there on the next run. Use `progress`, `save_progress!(value)` and `increment_progress!(by)`:
346
+
347
+ ```ruby
348
+ # === task code goes down here ===
349
+ User.where('id > ?', progress).find_each do |user|
350
+ user.recalculate_stats!
351
+ save_progress!(user.id) # resume after the last processed id
352
+ end
353
+ ```
354
+
355
+ ### Recurring tasks
356
+
357
+ Recurring tasks run on every deploy and are never marked done. Their identifier is a number you choose, which sets their order within the group:
358
+
99
359
  ```bash
100
- rake db:migrate
360
+ rails g deploy_pin:task warm_caches -g III --recurring --identifier 5
101
361
  ```
102
362
 
103
- ## Database Timeout
363
+ > [!NOTE]
364
+ > Identifiers `0` and `-10` are used by the built-in [deployment state](#deployment-state) tasks. Don't use them.
365
+
366
+ ### Deployment state
104
367
 
105
- By default, deploy_pin runs all non-parallel tasks under a database statement timeout. To set a default value, you should define it in the deploy_pin initializer, for example:
368
+ DeployPin can store in Redis whether a deploy is in progress, so your code can check it:
106
369
 
107
370
  ```ruby
108
- # config/initializers/deploy_pin.rb
109
371
  DeployPin.setup do
110
- statement_timeout 0.2.seconds # 200 ms
372
+ groups %w[I II III post rollback]
373
+ deployment_state_transition({
374
+ ongoing: %w[I III], # "ongoing" from the start of I until the end of III
375
+ pending: 'rollback', # "pending" from the start of rollback
376
+ ttl: 20.seconds, # how long to cache the state in memory
377
+ redis_url: 'redis://localhost:6379'
378
+ })
111
379
  end
380
+
381
+ DeployPin.ongoing_deployment? # => true while groups I..III run
382
+ DeployPin.pending_deployment? # => true after rollback started
112
383
  ```
113
384
 
114
- If you want to use a different value than the default, you need to specify it explicitly in the task, as shown below:
385
+ ### Continue on error
115
386
 
116
- ```ruby
117
- # Some deploy_pin task
118
- # 20190401135040:I
119
- # task_title: Execute some query with timeout
120
- # affected_areas: none
387
+ By default, a failing task stops the run. With `continue_on_error`, the error is logged, the task is marked done, and the run continues. This can be useful in CI, where external services may be unavailable:
121
388
 
122
- # === task code goes down here ===
123
- DeployPin::Database::execute_with_timeout do
124
- ActiveRecord::Base.connection.execute("select * from shipments;")
389
+ ```ruby
390
+ DeployPin.setup do
391
+ continue_on_error ENV.fetch('DEPLOY_PIN_CONTINUE_ON_ERROR', 'false') == 'true'
125
392
  end
126
393
  ```
127
394
 
128
- For more information about the parameters, please refer to the documentation [here](lib/deploy_pin/database.rb).
395
+ ### Storage
396
+
397
+ Task records are kept by a storage provider, set with `storage`:
398
+
399
+ | Provider | Model | Where |
400
+ |---|---|---|
401
+ | `:active_record` (default) | `DeployPin::Record` | `deploy_pins` table |
402
+ | `:mongoid` | `DeployPin::MongoidRecord` | `deploy_pins` collection |
129
403
 
130
- ## Parallel
404
+ `DeployPin::Storage.record_class` returns the model of the configured provider. Statement timeouts and the parallel timeout rely on ActiveRecord. Without it, tasks run without a timeout.
131
405
 
132
- To run parallel tasks using a timeout, you need to use the parallel wrapper, which mimics the parallel interface but adds the timeout option. In a deploy_pin task, instead of using `Parallel.each(1..2, in_processes: 2)`, use:
406
+ ### Testing tasks
407
+
408
+ `rails g deploy_pin:task` also creates a spec for the task, at `spec/deploy_pin/<task file>_spec.rb`. The directory is created if it doesn't exist. The spec runs the task end to end, the same way a deploy does, through `rake 'deploy_pin:run[<identifier>]'`. It checks that the task runs without errors and is marked as done. Add your own expectations for what the task changes:
133
409
 
134
410
  ```ruby
135
- parallel_each(1..2, in_processes: 2, timeout: 0.3.seconds) do |i|
136
- # ActiveRecord::Base.connection_pool.with_connection is already included in the parallel wrapper.
137
- puts "Item: #{i}, Worker: #{Parallel.worker_number}"
138
- ActiveRecord::Base.connection.execute("<some db query>")
411
+ # spec/deploy_pin/20261124120000_backfill_user_names_spec.rb (generated)
412
+ RSpec.describe 'DeployPin task 20261124120000_backfill_user_names' do
413
+ subject(:run_task) { Rake::Task['deploy_pin:run'].invoke('20261124120000') }
414
+
415
+ # ...
416
+
417
+ it 'backfills user names' do
418
+ user = User.create!(email: 'user@example.com', name: nil)
419
+
420
+ expect { run_task }.to change { user.reload.name }.to('user@example.com')
421
+ end
139
422
  end
140
423
  ```
141
424
 
142
- Check the documentation [here](lib/deploy_pin/parallel_wrapper.rb) for more details.
425
+ The spec turns off `continue_on_error`, so a failing task always fails its spec.
426
+
427
+ RSpec is the only supported framework for now. It is detected automatically when the `RSpec` constant is loaded, which is the case when `rspec-rails` is in the `:development` group, as rspec-rails recommends. If nothing is detected, the generator skips the test and says so. Set the framework and the directory, or turn test generation off, in the initializer:
428
+
429
+ ```ruby
430
+ DeployPin.setup do
431
+ test_framework :rspec # detected by default; `false` to not generate tests
432
+ tests_path 'spec/deploy_pin' # default for RSpec
433
+ end
434
+ ```
143
435
 
144
- ## Formatting
436
+ For a single task, pass `--skip-test` or `--test-framework=rspec` to the generator.
145
437
 
146
- `run_formatter` is used to format the output of a `run` task, `list_formatter` for the `list` task and `short_list_formatter` is used to format the output of a `short_list` task. To set a default value, you should define it in the deploy_pin initializer:
438
+ ### Output formatting
439
+
440
+ `run_formatter`, `list_formatter` and `short_list_formatter` control what the rake tasks print. The install generator writes working defaults into the initializer.
441
+
442
+ <details>
443
+ <summary>Default formatters</summary>
147
444
 
148
445
  ```ruby
149
- # config/initializers/deploy_pin.rb
150
446
  DeployPin.setup do
151
447
  run_formatter(
152
448
  lambda do |index, task_count, task, executable, start, duration = nil|
@@ -162,158 +458,105 @@ DeployPin.setup do
162
458
  list_formatter(
163
459
  lambda do |index, task|
164
460
  puts("======= Task ##{index} ========".blue.bold)
165
-
166
- # Print details
167
- task.details.each do |key, value|
168
- puts("#{key}:\t\t#{value}")
169
- end
170
-
461
+ task.details.each { |key, value| puts("#{key}:\t\t#{value}") }
171
462
  puts("\n<<<\n#{task.script.strip.green}\n>>>\n\n")
172
463
  end
173
464
  )
174
465
  short_list_formatter(
175
466
  lambda do |group, tasks, start_index|
176
- puts(" Group: #{group} ".center(38, "=").light_cyan.bold)
177
- puts("\n")
178
-
467
+ puts(" Group: #{group} ".center(38, '=').light_cyan.bold)
179
468
  tasks.each.with_index(start_index) do |task, index|
180
- puts(" Task ##{index} ".center(38, "=").blue.bold)
181
- # print details
182
- task.details.each do |key, value|
183
- key_aligned = "#{key}:".ljust(20)
184
- puts("#{key_aligned}#{value}")
185
- end
186
-
187
- puts("\n")
469
+ puts(" Task ##{index} ".center(38, '=').blue.bold)
470
+ task.details.each { |key, value| puts("#{key}:".ljust(20) + value.to_s) }
471
+ puts
188
472
  end
189
473
  end
190
474
  )
191
475
  end
192
476
  ```
193
477
 
194
- To use a different formatting value than the default, you need to specify it explicitly in the task, similar to the database timeout configuration.
478
+ </details>
195
479
 
196
- ## Resumable Tasks
480
+ ## Configuration reference
197
481
 
198
- When working with long-running code that processes a large dataset, it makes sense to store progress in the database to allow resuming the task later. You can do this by using the `DeployPin::Task` instance methods: `#progress`, `#save_progress!(num)` and `#increment_progress!(num)`.
482
+ All options are set in `DeployPin.setup`. See the [API docs](https://rubydoc.info/gems/deploy_pin/DeployPin) for details.
199
483
 
200
- Here is an example of how to use these methods:
484
+ | Option | Default | Description |
485
+ |---|---|---|
486
+ | `tasks_path` | — | Directory with task files (`'lib/deploy_pin'` in the generated initializer) |
487
+ | `groups` | — | Ordered list of groups |
488
+ | `fallback_group` | — | Group for `deploy_pin:task` when `-g` is not given |
489
+ | `statement_timeout` | — | Default database statement timeout |
490
+ | `storage` | `:active_record` | `:active_record` or `:mongoid` |
491
+ | `continue_on_error` | `false` | Log failed tasks and continue instead of stopping |
492
+ | `test_framework` | detected (`:rspec` if `RSpec` is loaded) | Test framework for generated task tests; `false` to skip them. See [Testing tasks](#testing-tasks) |
493
+ | `tests_path` | `'spec/deploy_pin'` | Directory for generated task tests |
494
+ | `task_wrapper` | runs the task | `->(task, task_runner) { ... }` around every task, e.g. for logging or error reporting |
495
+ | `deployment_state_transition` | off | See [Deployment state](#deployment-state) |
496
+ | `run_formatter`, `list_formatter`, `short_list_formatter` | — | See [Output formatting](#output-formatting) |
201
497
 
202
- ```ruby
203
- # Some DeployPin task
204
- ...
205
- # === task code goes here ===
206
-
207
- # The progress is 0 by default
208
- Users.where(id: progress..).find_each do |user|
209
- # Do some work
210
- increment_progress!(1) # Increment progress by 1 and store it in the database so you can resume the task from this point
211
- # or save_progress!(user.id) # Save the progress as the user id
212
- end
213
- ```
498
+ ## Development
214
499
 
215
- This allows your task to resume from where it left off, minimizing the risk of repeating work.
216
-
217
-
218
- ## Recurring Tasks
219
- If you want to generate a recurring task, you can use the `--recurring` option. Make sure to set a correct `--identifier`, which should be a numeric value. Positive and negative numbers are possible here. The identifier affects the order of task execution, allowing you to customize the sequence as desired.
220
-
221
- Please note that two identifiers, 0 and -10, are already reserved for deployment state tracking. Avoid using these identifiers.
500
+ You need Ruby (see [`.ruby-version`](.ruby-version)) and Docker. The `pg` and `mysql2` gems compile against the PostgreSQL and MySQL client libraries, so install those first (on macOS: `brew install libpq mysql-client`, then make sure `pg_config` and `mysql_config` are on your `PATH`).
222
501
 
223
502
  ```bash
224
- rails g deploy_pin:task some_task_title --recurring --identifier 5
225
- # or
226
- rails g deploy_pin:task some_task_title --parallel --recurring --identifier 5
503
+ git clone https://github.com/skcc321/deploy_pin.git && cd deploy_pin
504
+ bundle install
505
+
506
+ # Start the databases (credentials come from .env)
507
+ docker compose up -d
508
+ set -a; source .env; set +a
509
+ export RAILS_ENV=test
227
510
  ```
228
511
 
229
- ## Mark Tasks as Done
512
+ Run the tests against one database at a time. `DB_ROLE` is `pg`, `mysql`, `mariadb` or `mongodb`:
230
513
 
231
514
  ```bash
232
- rake deploy_pin:mark_done['identifier_1, identifier_2'] # marks specific tasks as done
233
- rake deploy_pin:mark_done # marks all tasks as done. useful in seed file
515
+ DB_ROLE=pg bin/rails db:prepare # not needed for mongodb
516
+ DB_ROLE=pg bin/test
517
+ DB_ROLE=pg bin/test test/lib/deploy_pin/task_test.rb # a single file
234
518
  ```
235
519
 
236
- ## DeploymentStateTrack
237
- In the initializer
238
- ```ruby
239
- DeployPin.setup do
240
- groups %w[I II III post rollback]
241
- ...
242
- deployment_state_transition({
243
- ongoing: %w[I III],
244
- pending: "rollback", # enters to pending step before "rollback"
245
- ttl: 20.second, # memoize the state to avoid Redis spam
246
- redis_url: "redis://localhost:6379"
247
- })
248
- end
249
-
250
- # enabled next methods
251
- DeployPin.ongoing_deployment?
252
- DeployPin.pending_deployment?
253
- ```
520
+ Linting and docs, also checked on CI:
254
521
 
255
- Around the deployment
256
522
  ```bash
257
- bundle exec rake deploy_pin:run[I, II, III] - # enters to ongoing state before "I" and leaves it after "III" so all tasks in I, II, III have DeployPin.ongoing_deployment? == true
258
- bundle exec rake deploy_pin:run[rollback] - # enters "pending state"
523
+ bundle exec rubocop
524
+ gem install reek && reek lib
525
+ bundle exec rake yard # builds doc/, must stay 100% documented
259
526
  ```
260
- ## Continue on Error
261
527
 
262
- By default, if a task raises an error, the entire deploy pin run is aborted. You can configure `continue_on_error` to rescue failures, log them, and still mark the task as done. This is useful in CI environments where external services may be unavailable.
528
+ <details>
529
+ <summary>Run the CI workflow locally with <code>act</code></summary>
263
530
 
264
- ```ruby
265
- # config/initializers/deploy_pin.rb
266
- DeployPin.setup do
267
- continue_on_error true
268
- end
269
- ```
531
+ With [`act`](https://nektosact.com/installation/index.html) and Docker:
270
532
 
271
- Or conditionally via environment variable:
272
-
273
- ```ruby
274
- DeployPin.setup do
275
- continue_on_error ENV.fetch("DEPLOY_PIN_CONTINUE_ON_ERROR", "false") == "true"
276
- end
533
+ ```bash
534
+ act pull_request --secret-file .env --container-architecture linux/amd64 -W .github/workflows -j test
277
535
  ```
278
536
 
279
- When enabled, failed tasks will log the error and continue to the next task without halting execution.
280
-
281
- ## Similar Gems
282
- - https://github.com/ilyakatz/data-migrate
283
- - https://github.com/Shopify/maintenance_tasks
284
- - https://github.com/theSteveMitchell/after_party
537
+ </details>
285
538
 
286
539
  ## Contributing
287
- Contribution directions go here.
288
-
289
- ### Running Tests Locally
290
-
291
- To ensure your changes meet the required standards and pass all tests before submitting a pull request, you can simulate the GitHub Actions workflow locally using the [`act`](https://github.com/nektos/act) tool.
292
-
293
- #### Prerequisites
294
540
 
295
- 1. **Install `act`**
296
- Follow the installation guide provided in the official [`act` documentation](https://nektosact.com/installation/index.html).
541
+ Bug reports and pull requests are welcome.
297
542
 
298
- 2. **Docker**
299
- Ensure Docker is installed and running on your machine.
543
+ 1. For bigger changes, open an [issue](https://github.com/skcc321/deploy_pin/issues) first to discuss them.
544
+ 2. Fork the repo and create a branch from `master`.
545
+ 3. Add tests, and run them on at least one SQL database and on `mongodb` if you touch storage.
546
+ 4. Make sure `rubocop` passes and new public methods have YARD docs.
547
+ 5. Add a line under `# Unreleased` in [CHANGELOG.md](CHANGELOG.md).
548
+ 6. Open a pull request. The template asks what changed, why, and how you tested it.
300
549
 
301
- #### Running the Workflow
550
+ Please report security issues privately. See [SECURITY.md](SECURITY.md).
302
551
 
303
- Use the following command to simulate the workflow locally:
552
+ ## Similar gems
304
553
 
305
- ```bash
306
- act pull_request --secret-file .env --container-architecture linux/amd64 -W .github/workflows -j test
307
- ```
554
+ - [data-migrate](https://github.com/ilyakatz/data-migrate): data migrations that run alongside schema migrations.
555
+ - [maintenance_tasks](https://github.com/Shopify/maintenance_tasks): a Rails engine with a web UI for running data tasks on demand.
556
+ - [after_party](https://github.com/theSteveMitchell/after_party): one-off post-deploy rake tasks.
308
557
 
309
- This command does the following:
310
- - `pull_request`: Runs the pull_request workflow defined in your .github/workflows directory.
311
- - `--secret-file .env`: Uses the .env file provided in the repository to load environment variables.
312
- - `--container-architecture linux/amd64`: Ensures compatibility with GitHub Actions runners.
313
- - `-W .github/workflows`: Specifies the directory containing the workflow files.
314
- - `-j rspec`: Runs the `rspec` job defined in the workflow.
315
-
316
- For more details on customizing this command, refer to the [act documentation](https://nektosact.com/).
558
+ DeployPin sits between them: tasks are tied to the steps of your deploy (groups), with statement timeouts, parallel helpers and deployment state.
317
559
 
318
560
  ## License
319
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
561
+
562
+ Released under the [MIT License](MIT-LICENSE).