deploy_pin 1.7.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.
@@ -1,23 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Task wrapper
4
3
  module DeployPin
4
+ # A task loaded from a file in {DeployPin.tasks_path}.
5
+ #
6
+ # The file starts with a header, followed by the code to run:
7
+ #
8
+ # # 20190401135040:I
9
+ # # task_title: Backfill user names
10
+ # # affected_areas: users
11
+ #
12
+ # # === task code goes down here ===
13
+ # User.where(name: nil).find_each { |user| user.update!(name: user.email) }
14
+ #
15
+ # The first line is `# <identifier>:<group>`, or `# <identifier>:<group>:recurring`
16
+ # for a task that runs on every deployment. Negative identifiers sort after
17
+ # the other tasks of their group.
18
+ #
19
+ # The code is evaluated in the context of the task, so it can call the
20
+ # {ParallelWrapper} `parallel_*` methods and {#increment_progress!}.
21
+ #
22
+ # Tasks run under {DeployPin.statement_timeout}, unless their code calls
23
+ # {Database.execute_with_timeout} or uses Parallel.
5
24
  # :reek:TooManyMethods
6
25
  class Task # rubocop:disable Metrics/ClassLength
7
26
  extend ::DeployPin::ParallelWrapper
8
27
  include ::DeployPin::ParallelWrapper
9
28
 
10
- attr_reader :file,
11
- :identifier,
12
- :group,
13
- :title,
14
- :affected_areas,
15
- :script,
16
- :recurring,
17
- :explicit_timeout
18
-
29
+ # @return [String] path of the task file, or the task source for built-in tasks
30
+ attr_reader :file
31
+ # @return [Integer, nil] the identifier from the header, usually a timestamp
32
+ attr_reader :identifier
33
+ # @return [String, nil] the group from the header, one of {DeployPin.groups}
34
+ attr_reader :group
35
+ # @return [String] the `task_title` from the header
36
+ attr_reader :title
37
+ # @return [String] the `affected_areas` from the header
38
+ attr_reader :affected_areas
39
+ # @return [String] the code to run
40
+ attr_reader :script
41
+ # @return [String, nil] `"recurring"` for a task that runs on every deployment
42
+ attr_reader :recurring
43
+ # @return [Boolean] whether the code calls {Database.execute_with_timeout} itself
44
+ attr_reader :explicit_timeout
45
+
46
+ # @!method progress
47
+ # @return [Integer] the progress saved with {#increment_progress!} or {#save_progress!}
19
48
  delegate :progress, to: :record
20
49
 
50
+ # @param file [String] path of a task file, or task source starting with
51
+ # `# no_file_task`. Call {#parse} to load it.
21
52
  def initialize(file)
22
53
  @file = file
23
54
  @identifier = nil
@@ -29,21 +60,31 @@ module DeployPin
29
60
  @parallel = false
30
61
  end
31
62
 
63
+ # Evaluates the task code.
64
+ #
65
+ # @return [Object] the result of the code
32
66
  def run
33
67
  # eval script
34
68
  eval(script)
35
69
  end
36
70
 
71
+ # @return [Object, nil] the stored record for this task (see {Storage}), or nil
37
72
  def record
38
- DeployPin::Record.find_by(uuid: identifier)
73
+ DeployPin::Storage.record_class.find_by(uuid: identifier)
39
74
  end
40
75
 
76
+ # Creates the stored record for a non-recurring task if it does not exist yet.
77
+ #
78
+ # @return [void]
41
79
  def prepare
42
80
  return if recurring
43
81
 
44
- DeployPin::Record.create(uuid: identifier) unless record
82
+ DeployPin::Storage.record_class.create(uuid: identifier) unless record
45
83
  end
46
84
 
85
+ # Stores the completion time of a non-recurring task.
86
+ #
87
+ # @return [void]
47
88
  def mark
48
89
  return if recurring
49
90
 
@@ -51,18 +92,35 @@ module DeployPin
51
92
  record.update(completed_at: Time.current)
52
93
  end
53
94
 
95
+ # Adds to the saved progress, so a long task can resume where it stopped.
96
+ #
97
+ # @example In a task file
98
+ # User.where('id > ?', progress).find_each do |user|
99
+ # user.touch
100
+ # increment_progress!(1)
101
+ # end
102
+ # @param incrementor [Integer]
103
+ # @return [void]
104
+ # @raise [NotImplementedError] for recurring tasks
54
105
  def increment_progress!(incrementor)
55
106
  raise NotImplementedError, 'Recurring tasks do not support progress yet.' if recurring
56
107
 
57
108
  record.increment!(:progress, incrementor)
58
109
  end
59
110
 
111
+ # Overwrites the saved progress.
112
+ #
113
+ # @param value [Integer]
114
+ # @return [void]
115
+ # @raise [NotImplementedError] for recurring tasks
60
116
  def save_progress!(value)
61
117
  raise NotImplementedError, 'Recurring tasks do not support progress yet.' if recurring
62
118
 
63
119
  record.update(progress: value)
64
120
  end
65
121
 
122
+ # @return [Boolean, nil] whether the task has been completed; nil for
123
+ # recurring tasks and tasks that have not started
66
124
  def done?
67
125
  return if recurring
68
126
  return unless record
@@ -70,10 +128,14 @@ module DeployPin
70
128
  record.completed_at.present?
71
129
  end
72
130
 
131
+ # @return [Boolean] whether the task should run under {DeployPin.statement_timeout}
73
132
  def under_timeout?
74
133
  !explicit_timeout? && !parallel?
75
134
  end
76
135
 
136
+ # Reads the header and the code from {#file}.
137
+ #
138
+ # @return [void]
77
139
  # :reek:TooManyStatements
78
140
  def parse # rubocop:disable Metrics/MethodLength
79
141
  each_line do |line|
@@ -96,6 +158,8 @@ module DeployPin
96
158
  end
97
159
  # :reek:TooManyStatements
98
160
 
161
+ # @yieldparam line [String] each line of the task source
162
+ # @return [void]
99
163
  def each_line(&block)
100
164
  if file.starts_with?('# no_file_task')
101
165
  file.each_line(&block)
@@ -104,6 +168,7 @@ module DeployPin
104
168
  end
105
169
  end
106
170
 
171
+ # @return [Hash{Symbol => Object}] identifier, group, title and affected areas, for formatters
107
172
  def details
108
173
  {
109
174
  identifier:,
@@ -113,15 +178,21 @@ module DeployPin
113
178
  }
114
179
  end
115
180
 
181
+ # Whether another task has the same code but a different identifier.
182
+ #
183
+ # @param other [Task]
184
+ # @return [Boolean]
116
185
  def eql?(other)
117
186
  # same script & different identifier
118
187
  script == other.script && identifier != other.identifier
119
188
  end
120
189
 
190
+ # @return [Integer] a timestamp a year ahead, used to sort negative identifiers last
121
191
  def unreachable_future
122
192
  1.year.from_now.to_date.strftime('%Y%m%d%H%M%S').to_i
123
193
  end
124
194
 
195
+ # @return [Array(Integer, Integer)] group position and identifier, used for sorting
125
196
  def sorting_key
126
197
  if identifier.to_i.negative?
127
198
  [group_index, unreachable_future + identifier]
@@ -130,13 +201,17 @@ module DeployPin
130
201
  end
131
202
  end
132
203
 
133
- # for sorting
204
+ # Orders tasks by group position, then identifier.
205
+ #
206
+ # @param other [Task]
207
+ # @return [Integer, nil]
134
208
  def <=>(other)
135
209
  sorting_key <=> other.sorting_key
136
210
  end
137
211
 
138
212
  protected
139
213
 
214
+ # @return [Integer, nil] position of {#group} in {DeployPin.groups}
140
215
  def group_index
141
216
  DeployPin.groups.index(group)
142
217
  end
@@ -1,18 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # check task criteria
4
3
  module DeployPin
4
+ # Decides whether a task is selected by a list of identifiers. Each
5
+ # identifier is a group name or a task identifier:
6
+ #
7
+ # * `"I"` or `"20190401135040"` selects matching tasks that are not done yet;
8
+ # * `"I!"` or `"20190401135040!"` selects matching tasks even if they are done;
9
+ # * `"!I"` or `"!20190401135040"` excludes matching tasks.
10
+ #
11
+ # @example Re-run one task and skip group II
12
+ # DeployPin::TaskCriteria.new(identifiers: %w[I 20190401135040! !II]).suitable?(task)
5
13
  class TaskCriteria
6
- SKIP_REGEXEP = /\A!(.+[^!])\z/
7
- FORCE_REGEXP = /\A([^!].+)!\z/
14
+ # Matches an identifier that excludes tasks (`!I`).
15
+ SKIP_REGEXEP = /\A!([^!]+)\z/
16
+ # Matches an identifier that forces tasks to run again (`I!`).
17
+ FORCE_REGEXP = /\A([^!]+)!\z/
18
+ # Matches a plain identifier (`I`).
8
19
  COMMON_REGEXP = /(^[^!]?.+[^!]?$)/
9
20
 
21
+ # @return [Array<String, Integer>]
10
22
  attr_reader :identifiers
11
23
 
24
+ # @param identifiers [Array<String, Integer>] groups and task identifiers
12
25
  def initialize(identifiers:)
13
26
  @identifiers = identifiers
14
27
  end
15
28
 
29
+ # @param task [Task] a parsed task
30
+ # @return [Boolean] whether the task is selected
16
31
  def suitable?(task)
17
32
  task_cover = lambda { |task, regexp|
18
33
  items = identifiers.flat_map { |x| x.to_s.scan(regexp) }.flatten
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
- VERSION = '1.7.7'
4
+ # The gem version.
5
+ VERSION = '1.9.0'
5
6
  end
data/lib/deploy_pin.rb CHANGED
@@ -9,11 +9,108 @@ require 'deploy_pin/task_criteria'
9
9
  require 'deploy_pin/engine'
10
10
  require 'deploy_pin/database'
11
11
  require 'deploy_pin/database_engine'
12
+ require 'deploy_pin/storage'
12
13
  require 'parallel'
13
14
  require 'ruby-progressbar'
14
15
  require 'colorize'
15
16
 
17
+ # DeployPin runs one-off and recurring tasks around a deployment
18
+ # (for example, data migrations before or after the code is released).
19
+ #
20
+ # Tasks are plain Ruby files kept in {DeployPin.tasks_path}. Each one has a
21
+ # header with an identifier, a group and a title. Tasks run in group order,
22
+ # and each non-recurring task runs only once: its completion is stored in
23
+ # the configured {DeployPin.storage}.
24
+ #
25
+ # Configure it in an initializer generated by `rails g deploy_pin:install`.
26
+ #
27
+ # @example config/initializers/deploy_pin.rb
28
+ # DeployPin.setup do
29
+ # tasks_path 'lib/deploy_pin'
30
+ # groups %w[pre I II III]
31
+ # fallback_group 'III'
32
+ # statement_timeout 10.minutes
33
+ # end
34
+ #
35
+ # @!method self.continue_on_error(val = nil)
36
+ # When true, a failing task is logged and the run moves on to the next task
37
+ # instead of raising. Defaults to `false`.
38
+ # @param val [Boolean, nil] new value; omit to read the current one
39
+ # @return [Boolean]
40
+ #
41
+ # @!method self.deployment_state_transition(val = nil)
42
+ # Enables tracking of the deployment state in Redis, exposed through
43
+ # {DeploymentState#ongoing_deployment?} and {DeploymentState#pending_deployment?}.
44
+ # @example
45
+ # deployment_state_transition({
46
+ # ongoing: %w[I III], # groups that start and end the "ongoing" state
47
+ # pending: 'rollback', # group that sets the "pending" state
48
+ # ttl: 20.seconds, # how long to cache the state in memory
49
+ # redis_url: 'redis://localhost:6379'
50
+ # })
51
+ # @param val [Hash, nil] new value; omit to read the current one
52
+ # @return [Hash, nil]
53
+ #
54
+ # @!method self.fallback_group(val = nil)
55
+ # Default group for `rails g deploy_pin:task` when `--group` is not given.
56
+ # @param val [String, nil] new value; omit to read the current one
57
+ # @return [String, nil]
58
+ #
59
+ # @!method self.groups(val = nil)
60
+ # Ordered list of task groups. Tasks run in this group order, and a task's
61
+ # group must be one of these.
62
+ # @param val [Array<String>, nil] new value; omit to read the current one
63
+ # @return [Array<String>, nil]
64
+ #
65
+ # @!method self.list_formatter(val = nil)
66
+ # Prints a task for `rake deploy_pin:list`.
67
+ # @param val [Proc, nil] `->(index, task) { ... }`; omit to read the current one
68
+ # @return [Proc, nil]
69
+ #
70
+ # @!method self.short_list_formatter(val = nil)
71
+ # Prints a group of tasks for `rake deploy_pin:short_list`.
72
+ # @param val [Proc, nil] `->(group, tasks, start_index) { ... }`; omit to read the current one
73
+ # @return [Proc, nil]
74
+ #
75
+ # @!method self.run_formatter(val = nil)
76
+ # Prints progress for `rake deploy_pin:run`. It is called once before a task
77
+ # starts (`start` is true) and, for executable tasks, once after it finishes
78
+ # with its `duration` in seconds.
79
+ # @param val [Proc, nil] `->(index, task_count, task, executable, start, duration = nil) { ... }`;
80
+ # omit to read the current one
81
+ # @return [Proc, nil]
82
+ #
83
+ # @!method self.statement_timeout(val = nil)
84
+ # Default database statement timeout for tasks and for
85
+ # {Database.execute_with_timeout}. Requires ActiveRecord.
86
+ # @param val [ActiveSupport::Duration, Numeric, nil] new value; omit to read the current one
87
+ # @return [ActiveSupport::Duration, Numeric, nil]
88
+ #
89
+ # @!method self.storage(val = nil)
90
+ # Where task records are stored: `:active_record` (default) or `:mongoid`.
91
+ # @see Storage
92
+ # @param val [Symbol, nil] new value; omit to read the current one
93
+ # @return [Symbol]
94
+ #
95
+ # @!method self.task_wrapper(val = nil)
96
+ # Wraps the execution of every task, for example to add logging or error
97
+ # reporting. It must call `task_runner.call` to run the task.
98
+ # @example
99
+ # task_wrapper ->(task, task_runner) { Rails.logger.tagged(task.identifier) { task_runner.call } }
100
+ # @param val [Proc, nil] `->(task, task_runner) { ... }`; omit to read the current one
101
+ # @return [Proc]
102
+ #
103
+ # @!method self.tasks_path(val = nil)
104
+ # Directory that holds task files.
105
+ # @param val [String, nil] new value; omit to read the current one
106
+ # @return [String, nil]
16
107
  module DeployPin
108
+ # Storage models are loaded lazily, so only the configured ORM has to be present.
109
+ autoload :ApplicationRecord, 'deploy_pin/storage/active_record/application_record'
110
+ autoload :Record, 'deploy_pin/storage/active_record/record'
111
+ autoload :MongoidRecord, 'deploy_pin/storage/mongoid_record'
112
+
113
+ # Names of the configuration options. Each one is a reader/writer method on {DeployPin}.
17
114
  OPTIONS = %i[
18
115
  continue_on_error
19
116
  deployment_state_transition
@@ -23,12 +120,15 @@ module DeployPin
23
120
  short_list_formatter
24
121
  run_formatter
25
122
  statement_timeout
123
+ storage
26
124
  task_wrapper
27
125
  tasks_path
28
126
  ].freeze
29
127
 
128
+ # Values the options are reset to by {setup_defaults!}.
30
129
  DEFAULTS = {
31
130
  continue_on_error: false,
131
+ storage: :active_record,
32
132
  task_wrapper: ->(_task, task_runner) { task_runner.call }
33
133
  }.freeze
34
134
 
@@ -42,10 +142,22 @@ module DeployPin
42
142
  }, __FILE__, __LINE__ - 6
43
143
  end
44
144
 
145
+ # Configures DeployPin. The block is evaluated on the {DeployPin} module, so
146
+ # every option can be called without a receiver.
147
+ #
148
+ # @example
149
+ # DeployPin.setup do
150
+ # groups %w[I II III]
151
+ # end
152
+ # @yield the configuration block
153
+ # @return [void]
45
154
  def self.setup(&block)
46
155
  instance_eval(&block)
47
156
  end
48
157
 
158
+ # Resets the options listed in {DEFAULTS} to their default values.
159
+ #
160
+ # @return [void]
49
161
  def self.setup_defaults!
50
162
  DEFAULTS.each do |option, value|
51
163
  instance_variable_set(:"@#{option}", value)
@@ -54,6 +166,10 @@ module DeployPin
54
166
 
55
167
  setup_defaults!
56
168
 
169
+ # Whether an option has been set, even to `nil`.
170
+ #
171
+ # @param option [Symbol] one of {OPTIONS}
172
+ # @return [Boolean]
57
173
  def self.enabled?(option)
58
174
  instance_variable_defined?("@#{option}")
59
175
  end
@@ -1,31 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # `rails g deploy_pin:install [--storage=mongoid]`: creates the initializer
5
+ # and, for ActiveRecord, the `deploy_pins` migration.
4
6
  class InstallGenerator < Rails::Generators::Base
5
7
  include Rails::Generators::Migration
6
8
 
7
9
  source_root File.expand_path('templates', __dir__)
8
10
  desc 'Add the migration & initializer for DeployPin'
9
11
 
12
+ class_option :storage, type: :string, default: 'active_record', enum: %w[active_record mongoid],
13
+ desc: 'Storage provider for task records'
14
+
15
+ # @param path [String] migrations directory
16
+ # @return [String] the next migration timestamp
10
17
  def self.next_migration_number(path)
11
18
  next_migration_number = current_migration_number(path) + 1
12
19
  ActiveRecord::Migration.next_migration_number(next_migration_number)
13
20
  end
14
21
 
22
+ # Creates the `deploy_pins` migration, unless the storage is Mongoid.
23
+ # @return [void]
15
24
  def copy_migrations
25
+ return if mongoid?
26
+
16
27
  migration_template 'create_deploy_pins.rb', 'db/migrate/create_deploy_pins.rb'
17
28
  end
18
29
 
30
+ # Creates `config/initializers/deploy_pin.rb`.
31
+ # @return [void]
19
32
  def copy_initializer
20
33
  template 'deploy_pin.rb', 'config/initializers/deploy_pin.rb'
21
34
  end
22
35
 
23
- def activerecord_migration_class
24
- if ::ActiveRecord::Migration.respond_to?(:current_version)
36
+ # Reminds Mongoid users to create the indexes.
37
+ # @return [void]
38
+ def mongoid_indexes_hint
39
+ say 'Run `rails db:mongoid:create_indexes` to create the DeployPin indexes.' if mongoid?
40
+ end
41
+
42
+ private
43
+
44
+ # Used by the migration template.
45
+ # :reek:UtilityFunction
46
+ def activerecord_migration_class
25
47
  "ActiveRecord::Migration[#{::ActiveRecord::Migration.current_version}]"
26
- else
27
- 'ActiveRecord::Migration'
28
48
  end
29
- end
49
+
50
+ def mongoid?
51
+ options[:storage] == 'mongoid'
52
+ end
30
53
  end
31
54
  end
@@ -1,6 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  DeployPin.setup do
4
+ <% if options[:storage] != 'active_record' -%>
5
+ storage :<%= options[:storage] %>
6
+ <% end -%>
4
7
  tasks_path 'lib/deploy_pin'
5
8
  groups %w[pre I II III]
6
9
  fallback_group 'III'
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # `rails g deploy_pin:task <title> --group <group> [--parallel] [--recurring --identifier <id>]`:
5
+ # creates a task file in {DeployPin.tasks_path}.
4
6
  class TaskGenerator < Rails::Generators::Base
5
7
  class_option :parallel, type: :boolean, aliases: '-p'
6
8
  class_option :recurring, type: :boolean, aliases: '-r'
@@ -19,6 +21,8 @@ module DeployPin
19
21
  validate
20
22
  end
21
23
 
24
+ # Writes the task file, named after its identifier and title.
25
+ # @return [void]
22
26
  def create_task_file
23
27
  template_file = if options[:parallel]
24
28
  'parallel_task.rb.erb'
@@ -34,6 +38,8 @@ module DeployPin
34
38
  template template_file, "#{DeployPin.tasks_path}/#{filename}"
35
39
  end
36
40
 
41
+ # @return [void]
42
+ # @raise [Thor::Error] if the group is missing or not in {DeployPin.groups}
37
43
  def validate
38
44
  raise Thor::Error, set_color('Missing required option: --group', :red) if options[:group].blank?
39
45
 
@@ -8,11 +8,15 @@ module DeployPin
8
8
  source_root File.expand_path('templates', __dir__)
9
9
  desc 'Add the upgrade migration for DeployPin.'
10
10
 
11
+ # @param path [String] migrations directory
12
+ # @return [String] the next migration timestamp
11
13
  def self.next_migration_number(path)
12
14
  next_migration_number = current_migration_number(path) + 1
13
15
  ActiveRecord::Migration.next_migration_number(next_migration_number)
14
16
  end
15
17
 
18
+ # Creates the migration that upgrades the `deploy_pins` table.
19
+ # @return [void]
16
20
  def copy_migrations
17
21
  migration_template 'upgrade_deploy_pins.rb', 'db/migrate/upgrade_deploy_pins.rb'
18
22
  end