deploy_pin 1.8.7 → 1.9.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,415 @@
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:
25
- ```bash
26
- rails g deploy_pin:task some_task_title -a author_name
27
- ```
61
+ Then generate the initializer and the migration, and migrate:
28
62
 
29
- To list all pending tasks:
30
63
  ```bash
31
- rake deploy_pin:list
64
+ rails g deploy_pin:install
65
+ rails db:migrate
32
66
  ```
33
67
 
34
- To run 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
+
35
73
  ```bash
36
- rake deploy_pin:run
74
+ rails g deploy_pin:install --storage=mongoid
75
+ rails db:mongoid:create_indexes
37
76
  ```
38
77
 
39
- ## Grouped Tasks
78
+ Mongoid is not a dependency of deploy_pin, so it has to be in your Gemfile. See [Storage](#storage).
40
79
 
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
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
46
92
  ```
47
93
 
48
- To list all pending tasks within the "allowed_group":
94
+ ## Quick start
95
+
49
96
  ```bash
50
- rake deploy_pin:list[allowed_group]
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
+
102
+ # 3. See what is pending
103
+ rake deploy_pin:list
104
+
105
+ # 4. Run it (normally from your deploy script)
106
+ rake deploy_pin:run
51
107
  ```
52
108
 
53
- To run all pending tasks within the "allowed_group":
54
- ```bash
55
- rake deploy_pin:run[allowed_group]
109
+ ## How it works
110
+
111
+ ### Task files
112
+
113
+ A task is a Ruby file in `tasks_path`. The generator writes the header for you:
114
+
115
+ ```ruby
116
+ # 20190401135040:I
117
+ # task_title: Backfill user names
118
+ # affected_areas: users
119
+
120
+ # === task code goes down here ===
121
+ User.where(name: nil).find_each { |user| user.update!(name: user.email) }
56
122
  ```
57
123
 
58
- ## Run by Identifier
124
+ | Header line | Meaning |
125
+ |---|---|
126
+ | `# 20190401135040:I` | `<identifier>:<group>`. The identifier is a timestamp for one-off tasks. |
127
+ | `# 20190401135040:I:recurring` | A [recurring task](#recurring-tasks) that runs on every deploy |
128
+ | `# task_title:` | Shown by `list` and `run` |
129
+ | `# affected_areas:` | Free text for reviewers: what the task touches |
130
+
131
+ ### Groups and ordering
132
+
133
+ `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:
134
+
135
+ | Group | When you run it | Typical tasks |
136
+ |---|---|---|
137
+ | `pre` | Right before the deploy starts | Pause background jobs, take a snapshot, flip a feature flag |
138
+ | `I`, `II`, … | Around the migrations | Backfill data that the new schema or code needs |
139
+ | `post` | Right after the new release is live | Warm caches, re-enable jobs, notify other services |
140
+
141
+ Tasks are sorted by **group**, then by **identifier**. Negative identifiers run after the other tasks of their group.
142
+
143
+ 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.
144
+
145
+ ### Selecting tasks
146
+
147
+ Every command takes an optional, comma-separated list of groups and identifiers:
148
+
149
+ | Argument | Selects |
150
+ |---|---|
151
+ | *(none)* | All pending tasks in all groups |
152
+ | `I` | Pending tasks in group `I` |
153
+ | `20190401135040` | That task, if it is pending |
154
+ | `20190401135040!` or `I!` | Re-run: selects matching tasks even if they are done |
155
+ | `!20190401135040` or `!II` | Skips matching tasks |
59
156
 
60
- To execute a specific task using its identifier:
61
157
  ```bash
62
- rake deploy_pin:run['identifier_1, identifier_2']
158
+ rake 'deploy_pin:run[I, II]'
159
+ rake 'deploy_pin:run[20190401135040!]' # re-run one task
160
+ rake 'deploy_pin:run[I, !20190401135040]' # group I except one task
63
161
  ```
64
162
 
65
- Alternatively, you can combine an identifier and a group:
163
+ > [!TIP]
164
+ > Quote the task name (`'deploy_pin:run[...]'`). Shells such as zsh treat the square brackets as glob patterns.
165
+
166
+ ## Commands
167
+
168
+ | Command | Description |
169
+ |---|---|
170
+ | `rails g deploy_pin:task <title> -g <group>` | Generate a task. Options: `--parallel`, `--recurring --identifier <n>`, `-a <author>` |
171
+ | `rake deploy_pin:list[...]` | List pending tasks, including their code |
172
+ | `rake deploy_pin:short_list[...]` | List pending tasks by group, without the code |
173
+ | `rake deploy_pin:run[...]` | Run pending tasks |
174
+ | `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 |
175
+
176
+ ## Hooking into your deploy
177
+
178
+ Call `deploy_pin:run` with the right groups at each stage of your deploy. With `groups %w[pre I II III post]`:
179
+
66
180
  ```bash
67
- rake deploy_pin:run['identifier, allowed_group']
181
+ # right before the deploy
182
+ bundle exec rake 'deploy_pin:run[pre]'
183
+
184
+ # with the migrations
185
+ bundle exec rake db:migrate 'deploy_pin:run[I, II, III]'
186
+
187
+ # right after the new release is live
188
+ bundle exec rake 'deploy_pin:run[post]'
68
189
  ```
69
190
 
70
- If you wish to rerun a task, add an exclamation mark at the end of the identifier:
191
+ ### Example: a search index change in two stages
192
+
193
+ 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:
194
+
71
195
  ```bash
72
- rake deploy_pin:run['identifier_1!, identifier_2!']
196
+ rails g deploy_pin:task create_products_v2_index -g pre
197
+ rails g deploy_pin:task backfill_products_v2_index -g post
73
198
  ```
74
199
 
75
- ## Installation
200
+ The **pre** task creates the mapping and indexes only the data the new release needs right away, so the deploy stays fast:
201
+
202
+ ```ruby
203
+ # 20261124120000:pre
204
+ # task_title: Create products_v2 index and index recent products
205
+ # affected_areas: product search
76
206
 
77
- Add this line to your application's Gemfile:
207
+ # === task code goes down here ===
208
+ client = Elasticsearch::Client.new(url: ENV.fetch('ELASTICSEARCH_URL'))
209
+
210
+ unless client.indices.exists?(index: 'products_v2')
211
+ client.indices.create(
212
+ index: 'products_v2',
213
+ body: {
214
+ mappings: {
215
+ properties: {
216
+ name: { type: 'text' },
217
+ sku: { type: 'keyword' },
218
+ price: { type: 'scaled_float', scaling_factor: 100 }
219
+ }
220
+ }
221
+ }
222
+ )
223
+ end
224
+
225
+ # Products changed in the last week: enough for search to work after the release
226
+ Product.where(updated_at: 1.week.ago..).find_in_batches(batch_size: 500) do |batch|
227
+ client.bulk(body: batch.flat_map { |product| [{ index: { _index: 'products_v2', _id: product.id } }, product.search_document] })
228
+ end
229
+ ```
230
+
231
+ 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:
78
232
 
79
233
  ```ruby
80
- gem 'deploy_pin'
234
+ # 20261124120100:post
235
+ # task_title: Index all products into products_v2
236
+ # affected_areas: product search
237
+
238
+ # === task code goes down here ===
239
+ client = Elasticsearch::Client.new(url: ENV.fetch('ELASTICSEARCH_URL'))
240
+
241
+ Product.where('id > ?', progress).find_in_batches(batch_size: 1_000) do |batch|
242
+ client.bulk(body: batch.flat_map { |product| [{ index: { _index: 'products_v2', _id: product.id } }, product.search_document] })
243
+ save_progress!(batch.last.id)
244
+ end
81
245
  ```
82
246
 
83
- Then execute:
84
- ```bash
85
- $ bundle
247
+ Both tasks run once. The next deploy skips them because they are marked done.
248
+
249
+ ### Deploy tool examples
250
+
251
+ The examples below use the same stages. Adjust them to your own groups.
252
+
253
+ <details>
254
+ <summary>Heroku</summary>
255
+
256
+ The release phase runs before the new release goes live:
257
+
258
+ ```
259
+ # Procfile
260
+ release: bundle exec rake 'deploy_pin:run[pre]' db:migrate 'deploy_pin:run[I, II, III]'
86
261
  ```
87
262
 
88
- You can also install it manually with:
263
+ Heroku has no hook after the release is live, so run `post` as a one-off dyno from your deploy pipeline:
264
+
89
265
  ```bash
90
- $ gem install deploy_pin
266
+ heroku run "bundle exec rake 'deploy_pin:run[post]'"
91
267
  ```
92
268
 
93
- Afterward, generate the configuration file:
94
- ```bash
95
- rails g deploy_pin:install
269
+ </details>
270
+
271
+ <details>
272
+ <summary>Capistrano</summary>
273
+
274
+ ```ruby
275
+ # lib/capistrano/tasks/deploy_pin.rake
276
+ namespace :deploy_pin do
277
+ { pre: 'pre', migrate: 'I, II, III', post: 'post' }.each do |stage, groups|
278
+ task stage do
279
+ on primary(:db) do
280
+ within release_path do
281
+ with rails_env: fetch(:rails_env) do
282
+ execute :rake, "'deploy_pin:run[#{groups}]'"
283
+ end
284
+ end
285
+ end
286
+ end
287
+ end
288
+ end
289
+
290
+ # config/deploy.rb
291
+ before 'deploy:migrate', 'deploy_pin:pre'
292
+ after 'deploy:migrate', 'deploy_pin:migrate'
293
+ after 'deploy:published', 'deploy_pin:post'
96
294
  ```
97
295
 
98
- Finally, run the migration:
296
+ </details>
297
+
298
+ <details>
299
+ <summary>Kamal</summary>
300
+
301
+ 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):
302
+
99
303
  ```bash
100
- rake db:migrate
304
+ # .kamal/hooks/pre-deploy: the new image is pushed, the old version still serves traffic
305
+ kamal app exec --primary --version "$KAMAL_VERSION" "bin/rails 'deploy_pin:run[pre]'"
306
+
307
+ # .kamal/hooks/post-deploy: the new version is live
308
+ kamal app exec --primary --reuse "bin/rails 'deploy_pin:run[I, II, III]' 'deploy_pin:run[post]'"
101
309
  ```
102
310
 
103
- ## Database Timeout
311
+ The default Rails entrypoint runs `db:prepare` when the container boots, so here the migration groups run in the post-deploy hook.
312
+
313
+ </details>
104
314
 
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:
315
+ ## Features in depth
316
+
317
+ ### Database timeout
318
+
319
+ 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.
106
320
 
107
321
  ```ruby
108
- # config/initializers/deploy_pin.rb
109
- DeployPin.setup do
110
- statement_timeout 0.2.seconds # 200 ms
322
+ # === task code goes down here ===
323
+ DeployPin::Database.execute_with_timeout 30.minutes do
324
+ ActiveRecord::Base.connection.execute('UPDATE shipments SET ...')
111
325
  end
112
326
  ```
113
327
 
114
- If you want to use a different value than the default, you need to specify it explicitly in the task, as shown below:
328
+ 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).
329
+
330
+ ### Parallel
331
+
332
+ 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:
115
333
 
116
334
  ```ruby
117
- # Some deploy_pin task
118
- # 20190401135040:I
119
- # task_title: Execute some query with timeout
120
- # affected_areas: none
335
+ parallel_each(User.ids.each_slice(1_000).to_a, in_processes: 4, timeout: 5.minutes) do |ids|
336
+ User.where(id: ids).update_all(active: true)
337
+ end
338
+ ```
339
+
340
+ See the [`DeployPin::ParallelWrapper` docs](https://rubydoc.info/gems/deploy_pin/DeployPin/ParallelWrapper) for passing timeout options.
121
341
 
342
+ ### Resumable tasks
343
+
344
+ 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)`:
345
+
346
+ ```ruby
122
347
  # === task code goes down here ===
123
- DeployPin::Database::execute_with_timeout do
124
- ActiveRecord::Base.connection.execute("select * from shipments;")
348
+ User.where('id > ?', progress).find_each do |user|
349
+ user.recalculate_stats!
350
+ save_progress!(user.id) # resume after the last processed id
125
351
  end
126
352
  ```
127
353
 
128
- For more information about the parameters, please refer to the documentation [here](lib/deploy_pin/database.rb).
354
+ ### Recurring tasks
355
+
356
+ 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:
357
+
358
+ ```bash
359
+ rails g deploy_pin:task warm_caches -g III --recurring --identifier 5
360
+ ```
361
+
362
+ > [!NOTE]
363
+ > Identifiers `0` and `-10` are used by the built-in [deployment state](#deployment-state) tasks. Don't use them.
364
+
365
+ ### Deployment state
366
+
367
+ DeployPin can store in Redis whether a deploy is in progress, so your code can check it:
368
+
369
+ ```ruby
370
+ DeployPin.setup do
371
+ groups %w[I II III post rollback]
372
+ deployment_state_transition({
373
+ ongoing: %w[I III], # "ongoing" from the start of I until the end of III
374
+ pending: 'rollback', # "pending" from the start of rollback
375
+ ttl: 20.seconds, # how long to cache the state in memory
376
+ redis_url: 'redis://localhost:6379'
377
+ })
378
+ end
379
+
380
+ DeployPin.ongoing_deployment? # => true while groups I..III run
381
+ DeployPin.pending_deployment? # => true after rollback started
382
+ ```
129
383
 
130
- ## Parallel
384
+ ### Continue on error
131
385
 
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:
386
+ 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:
133
387
 
134
388
  ```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>")
389
+ DeployPin.setup do
390
+ continue_on_error ENV.fetch('DEPLOY_PIN_CONTINUE_ON_ERROR', 'false') == 'true'
139
391
  end
140
392
  ```
141
393
 
142
- Check the documentation [here](lib/deploy_pin/parallel_wrapper.rb) for more details.
394
+ ### Storage
143
395
 
144
- ## Formatting
396
+ Task records are kept by a storage provider, set with `storage`:
145
397
 
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:
398
+ | Provider | Model | Where |
399
+ |---|---|---|
400
+ | `:active_record` (default) | `DeployPin::Record` | `deploy_pins` table |
401
+ | `:mongoid` | `DeployPin::MongoidRecord` | `deploy_pins` collection |
402
+
403
+ `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.
404
+
405
+ ### Output formatting
406
+
407
+ `run_formatter`, `list_formatter` and `short_list_formatter` control what the rake tasks print. The install generator writes working defaults into the initializer.
408
+
409
+ <details>
410
+ <summary>Default formatters</summary>
147
411
 
148
412
  ```ruby
149
- # config/initializers/deploy_pin.rb
150
413
  DeployPin.setup do
151
414
  run_formatter(
152
415
  lambda do |index, task_count, task, executable, start, duration = nil|
@@ -162,158 +425,103 @@ DeployPin.setup do
162
425
  list_formatter(
163
426
  lambda do |index, task|
164
427
  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
-
428
+ task.details.each { |key, value| puts("#{key}:\t\t#{value}") }
171
429
  puts("\n<<<\n#{task.script.strip.green}\n>>>\n\n")
172
430
  end
173
431
  )
174
432
  short_list_formatter(
175
433
  lambda do |group, tasks, start_index|
176
- puts(" Group: #{group} ".center(38, "=").light_cyan.bold)
177
- puts("\n")
178
-
434
+ puts(" Group: #{group} ".center(38, '=').light_cyan.bold)
179
435
  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")
436
+ puts(" Task ##{index} ".center(38, '=').blue.bold)
437
+ task.details.each { |key, value| puts("#{key}:".ljust(20) + value.to_s) }
438
+ puts
188
439
  end
189
440
  end
190
441
  )
191
442
  end
192
443
  ```
193
444
 
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.
445
+ </details>
195
446
 
196
- ## Resumable Tasks
197
-
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)`.
199
-
200
- Here is an example of how to use these methods:
201
-
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
- ```
447
+ ## Configuration reference
214
448
 
215
- This allows your task to resume from where it left off, minimizing the risk of repeating work.
449
+ All options are set in `DeployPin.setup`. See the [API docs](https://rubydoc.info/gems/deploy_pin/DeployPin) for details.
216
450
 
451
+ | Option | Default | Description |
452
+ |---|---|---|
453
+ | `tasks_path` | — | Directory with task files (`'lib/deploy_pin'` in the generated initializer) |
454
+ | `groups` | — | Ordered list of groups |
455
+ | `fallback_group` | — | Group for `deploy_pin:task` when `-g` is not given |
456
+ | `statement_timeout` | — | Default database statement timeout |
457
+ | `storage` | `:active_record` | `:active_record` or `:mongoid` |
458
+ | `continue_on_error` | `false` | Log failed tasks and continue instead of stopping |
459
+ | `task_wrapper` | runs the task | `->(task, task_runner) { ... }` around every task, e.g. for logging or error reporting |
460
+ | `deployment_state_transition` | off | See [Deployment state](#deployment-state) |
461
+ | `run_formatter`, `list_formatter`, `short_list_formatter` | — | See [Output formatting](#output-formatting) |
217
462
 
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.
463
+ ## Development
220
464
 
221
- Please note that two identifiers, 0 and -10, are already reserved for deployment state tracking. Avoid using these identifiers.
465
+ 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
466
 
223
467
  ```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
468
+ git clone https://github.com/skcc321/deploy_pin.git && cd deploy_pin
469
+ bundle install
470
+
471
+ # Start the databases (credentials come from .env)
472
+ docker compose up -d
473
+ set -a; source .env; set +a
474
+ export RAILS_ENV=test
227
475
  ```
228
476
 
229
- ## Mark Tasks as Done
477
+ Run the tests against one database at a time. `DB_ROLE` is `pg`, `mysql`, `mariadb` or `mongodb`:
230
478
 
231
479
  ```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
480
+ DB_ROLE=pg bin/rails db:prepare # not needed for mongodb
481
+ DB_ROLE=pg bin/test
482
+ DB_ROLE=pg bin/test test/lib/deploy_pin/task_test.rb # a single file
234
483
  ```
235
484
 
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
- ```
485
+ Linting and docs, also checked on CI:
254
486
 
255
- Around the deployment
256
487
  ```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"
488
+ bundle exec rubocop
489
+ gem install reek && reek lib
490
+ bundle exec rake yard # builds doc/, must stay 100% documented
259
491
  ```
260
- ## Continue on Error
261
492
 
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.
493
+ <details>
494
+ <summary>Run the CI workflow locally with <code>act</code></summary>
263
495
 
264
- ```ruby
265
- # config/initializers/deploy_pin.rb
266
- DeployPin.setup do
267
- continue_on_error true
268
- end
269
- ```
270
-
271
- Or conditionally via environment variable:
496
+ With [`act`](https://nektosact.com/installation/index.html) and Docker:
272
497
 
273
- ```ruby
274
- DeployPin.setup do
275
- continue_on_error ENV.fetch("DEPLOY_PIN_CONTINUE_ON_ERROR", "false") == "true"
276
- end
498
+ ```bash
499
+ act pull_request --secret-file .env --container-architecture linux/amd64 -W .github/workflows -j test
277
500
  ```
278
501
 
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
502
+ </details>
285
503
 
286
504
  ## Contributing
287
- Contribution directions go here.
288
-
289
- ### Running Tests Locally
290
505
 
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.
506
+ Bug reports and pull requests are welcome.
292
507
 
293
- #### Prerequisites
508
+ 1. For bigger changes, open an [issue](https://github.com/skcc321/deploy_pin/issues) first to discuss them.
509
+ 2. Fork the repo and create a branch from `master`.
510
+ 3. Add tests, and run them on at least one SQL database and on `mongodb` if you touch storage.
511
+ 4. Make sure `rubocop` passes and new public methods have YARD docs.
512
+ 5. Add a line under `# Unreleased` in [CHANGELOG.md](CHANGELOG.md).
513
+ 6. Open a pull request. The template asks what changed, why, and how you tested it.
294
514
 
295
- 1. **Install `act`**
296
- Follow the installation guide provided in the official [`act` documentation](https://nektosact.com/installation/index.html).
515
+ Please report security issues privately. See [SECURITY.md](SECURITY.md).
297
516
 
298
- 2. **Docker**
299
- Ensure Docker is installed and running on your machine.
517
+ ## Similar gems
300
518
 
301
- #### Running the Workflow
519
+ - [data-migrate](https://github.com/ilyakatz/data-migrate): data migrations that run alongside schema migrations.
520
+ - [maintenance_tasks](https://github.com/Shopify/maintenance_tasks): a Rails engine with a web UI for running data tasks on demand.
521
+ - [after_party](https://github.com/theSteveMitchell/after_party): one-off post-deploy rake tasks.
302
522
 
303
- Use the following command to simulate the workflow locally:
304
-
305
- ```bash
306
- act pull_request --secret-file .env --container-architecture linux/amd64 -W .github/workflows -j test
307
- ```
308
-
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/).
523
+ DeployPin sits between them: tasks are tied to the steps of your deploy (groups), with statement timeouts, parallel helpers and deployment state.
317
524
 
318
525
  ## License
319
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
526
+
527
+ Released under the [MIT License](MIT-LICENSE).