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/Rakefile CHANGED
@@ -3,5 +3,8 @@
3
3
  require 'bundler/setup'
4
4
 
5
5
  require 'bundler/gem_tasks'
6
+ require 'yard'
6
7
 
7
8
  import 'test/dummy/Rakefile'
9
+
10
+ YARD::Rake::YardocTask.new(:yard)
@@ -1,14 +1,26 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # executes tasks
4
3
  module DeployPin
4
+ # Loads the task files and the deployment state tasks, selects the ones
5
+ # matching the identifiers, sorts them by group and identifier, and runs or
6
+ # lists them.
5
7
  class Collector
6
- attr_reader :identifiers, :formatter
8
+ # @return [Array<String, Integer>] the identifiers tasks are selected by
9
+ attr_reader :identifiers
10
+ # @return [nil] always nil; kept for backward compatibility
11
+ attr_reader :formatter
7
12
 
13
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
14
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
8
15
  def initialize(identifiers:)
9
16
  @identifiers = identifiers
10
17
  end
11
18
 
19
+ # Runs the selected tasks through {DeployPin.task_wrapper}. A task whose
20
+ # script duplicates an earlier one is marked done but not run.
21
+ #
22
+ # @return [void]
23
+ # @raise [StandardError] a task's error, unless {DeployPin.continue_on_error} is set
12
24
  # :reek:TooManyStatements
13
25
  def run
14
26
  tasks = init_tasks
@@ -18,6 +30,9 @@ module DeployPin
18
30
  end
19
31
  # :reek:TooManyStatements
20
32
 
33
+ # Prints each selected task with {DeployPin.list_formatter}.
34
+ #
35
+ # @return [void]
21
36
  def list
22
37
  tasks = init_tasks
23
38
  tasks.each_with_index do |task, index|
@@ -25,6 +40,9 @@ module DeployPin
25
40
  end
26
41
  end
27
42
 
43
+ # Prints the selected tasks group by group with {DeployPin.short_list_formatter}.
44
+ #
45
+ # @return [void]
28
46
  def short_list
29
47
  groups_tasks = init_tasks.group_by(&:group).to_a
30
48
  groups_tasks.inject(0) do |offset, (group, tasks)|
@@ -33,6 +51,9 @@ module DeployPin
33
51
  end
34
52
  end
35
53
 
54
+ # Marks the selected tasks as done without running them.
55
+ #
56
+ # @return [void]
36
57
  # :reek:FeatureEnvy
37
58
  def mark_done
38
59
  tasks = init_tasks
@@ -43,6 +64,9 @@ module DeployPin
43
64
  end
44
65
  # :reek:FeatureEnvy
45
66
 
67
+ # The selected tasks without duplicates (tasks whose script is the same as an earlier task's).
68
+ #
69
+ # @return [Array<Task>]
46
70
  def executable
47
71
  tasks = init_tasks
48
72
  tasks.map.with_index do |task, index|
@@ -50,6 +74,7 @@ module DeployPin
50
74
  end.compact
51
75
  end
52
76
 
77
+ # @return [Integer] number of selected tasks
53
78
  def tasks_count
54
79
  init_tasks.count
55
80
  end
@@ -107,7 +132,7 @@ module DeployPin
107
132
 
108
133
  # :reek:UtilityFunction and :reek:ControlParameter
109
134
  def run_with_timeout(task, &block)
110
- return yield unless task.under_timeout?
135
+ return yield unless task.under_timeout? && DeployPin::Database.available?
111
136
 
112
137
  DeployPin::Database.execute_with_timeout(DeployPin.statement_timeout, **{}, &block)
113
138
  end
@@ -1,48 +1,46 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # Runs database queries under a statement timeout (PostgreSQL, MySQL and MariaDB).
4
5
  module Database
5
6
  extend self
6
7
 
7
- # Run a block under a sql maximum timeout.
8
+ # Runs a block under a database statement timeout.
8
9
  #
9
- # A default timeout will be get from DeployPin.setup
10
- #
11
- # # config/initializers/deploy_pin.rb
12
- # DeployPin.setup do
13
- # statement_timeout 0.2.second # 200 ms
14
- # end
15
- #
16
- # # <app root>/deploy_pin/20190401135040_task.rb
10
+ # @example Use the default {DeployPin.statement_timeout}
17
11
  # # 20190401135040:I
18
12
  # # task_title: Execute some query with timeout
19
13
  # # affected_areas: none
20
14
  #
21
15
  # # === task code goes down here ===
22
- # DeployPin::Database::execute_with_timeout do
16
+ # DeployPin::Database.execute_with_timeout do
23
17
  # ActiveRecord::Base.connection.execute("select * from shipments;")
24
18
  # end
25
19
  #
26
- # A timeout can be passed as param as well:
27
- #
28
- # DeployPin::Database::execute_with_timeout 10.minutes do
20
+ # @example Pass a timeout
21
+ # DeployPin::Database.execute_with_timeout 10.minutes do
29
22
  # ActiveRecord::Base.connection.execute("select * from shipments;")
30
23
  # end
31
24
  #
32
- # In order to connect to multiple databases, pass the +connected_to+ keyword into the params.
33
- # The +connected_to+ will use the +ActiveRecord::Base.connected_to+.
34
- # To connect to a replica database, for example:
35
- #
36
- # DeployPin::Database::execute_with_timeout 1.seconds, connected_to: { role: :reading } do
37
- # Shipment.all # Get all record from replica
25
+ # @example Run against a replica, through `ApplicationRecord.connected_to`
26
+ # DeployPin::Database.execute_with_timeout 1.second, connected_to: { role: :reading } do
27
+ # Shipment.all
38
28
  # end
39
29
  #
40
- # Or a specific database:
41
- #
42
- # DeployPin::Database.execute_with_timeout 30.second, connected_to: { database: :test_mysql } do
30
+ # @example Run against another database, through `ActiveRecord::Base.connected_to`
31
+ # DeployPin::Database.execute_with_timeout 30.seconds, connected_to: { database: :test_mysql } do
43
32
  # ActiveRecord::Base.connection.execute("<some mysql query>")
44
33
  # end
34
+ #
35
+ # @param timeout [ActiveSupport::Duration, Numeric] timeout, in seconds when numeric
36
+ # @param params [Hash] options
37
+ # @option params [Hash] :connected_to arguments passed to `connected_to`
38
+ # @yield the code to run under the timeout
39
+ # @return [Object] the result of the block
40
+ # @raise [NotImplementedError] if ActiveRecord is not loaded
41
+ # @raise [ArgumentError] if the timeout is not greater than zero
45
42
  def execute_with_timeout(timeout = DeployPin.statement_timeout, **params, &blk)
43
+ raise NotImplementedError, 'statement timeout requires ActiveRecord' unless available?
46
44
  raise ArgumentError, 'timeout must be greater than zero' if timeout.to_f <= 0
47
45
 
48
46
  return call_block_under_timeout(timeout, &blk) unless params.key? :connected_to
@@ -53,6 +51,13 @@ module DeployPin
53
51
  end
54
52
  end
55
53
 
54
+ # Statement timeouts are implemented on top of ActiveRecord connections only.
55
+ #
56
+ # @return [Boolean] whether ActiveRecord is loaded
57
+ def available?
58
+ defined?(::ActiveRecord::Base) ? true : false
59
+ end
60
+
56
61
  private
57
62
 
58
63
  def call_block_under_timeout(timeout)
@@ -1,31 +1,40 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
- # This class is used to detect used database engine and managing specific
5
- # differences between them.
4
+ # Detects the database engine behind an ActiveRecord connection, to pick
5
+ # the right statement timeout SQL.
6
6
  class DatabaseEngine
7
+ # PostgreSQL settings.
7
8
  module PostgreSQL
9
+ # SQL that sets the timeout, in milliseconds.
8
10
  TIMEOUT_STATEMENT = 'SET statement_timeout TO %s'
9
11
  end
10
12
 
13
+ # MySQL settings.
11
14
  module MySQL
15
+ # SQL that sets the timeout, in milliseconds.
12
16
  TIMEOUT_STATEMENT = 'SET max_execution_time = %s'
13
17
  end
14
18
 
19
+ # MariaDB settings.
15
20
  module MariaDB
21
+ # SQL that sets the timeout, in milliseconds.
16
22
  TIMEOUT_STATEMENT = 'SET SESSION max_statement_time = %s'
17
23
  end
18
24
 
25
+ # Engine modules by key.
19
26
  DB_ENGINES_MAPPING = {
20
27
  mariadb: MariaDB,
21
28
  mysql: MySQL,
22
29
  pg: PostgreSQL
23
30
  }.freeze
24
31
 
32
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter]
25
33
  def initialize(connection)
26
34
  @connection = connection
27
35
  end
28
36
 
37
+ # @return [Module, nil] {PostgreSQL}, {MySQL} or {MariaDB}; nil for other engines
29
38
  def detect
30
39
  db_engine_symbol =
31
40
  case connection.adapter_name
@@ -3,15 +3,27 @@
3
3
  require 'connection_pool'
4
4
  require 'redis'
5
5
 
6
- # This module is used to track the state of a deployment.
6
+ # Extended with {DeployPin::DeploymentState}.
7
7
  module DeployPin
8
- # The mixin that extends DeployPin module with
9
- # @ongoing_deployment? & @pending_deployment? methods
8
+ # Tracks whether a deployment is in progress, so application code can
9
+ # behave differently while it runs. It is enabled by
10
+ # {DeployPin.deployment_state_transition} and extends {DeployPin}.
11
+ #
12
+ # The state is stored in Redis by built-in recurring tasks that run with
13
+ # the configured groups, and cached in memory for the configured `ttl`.
14
+ #
15
+ # @example
16
+ # DeployPin.ongoing_deployment? # => true between the "ongoing" groups
17
+ # DeployPin.pending_deployment? # => true after the "pending" group
10
18
  module DeploymentState
19
+ # Redis key that holds the state.
11
20
  STORE_KEY = 'deploy_pin:deployment'
21
+ # State between the start and end groups of `ongoing`.
12
22
  ONGOING = 'ongoing'
23
+ # State after the `pending` group.
13
24
  PENDING = 'pending'
14
25
 
26
+ # Source of the task that clears the state.
15
27
  DEPLOYMENT_OVER_TASK = %(
16
28
  # no_file_task
17
29
  # -10:%<group>s:recurring
@@ -20,6 +32,7 @@ module DeployPin
20
32
  DeployPin.send(:deployment_over!)
21
33
  ).strip
22
34
 
35
+ # Source of the task that sets the state to {ONGOING}.
23
36
  DEPLOYMENT_ONGOING_TASK = %(
24
37
  # no_file_task
25
38
  # 0:%<group>s:recurring
@@ -28,6 +41,7 @@ module DeployPin
28
41
  DeployPin.send(:deployment_ongoing!)
29
42
  ).strip
30
43
 
44
+ # Source of the task that sets the state to {PENDING}.
31
45
  DEPLOYMENT_PENDING_TASK = %(
32
46
  # no_file_task
33
47
  # 0:%<group>s:recurring
@@ -36,14 +50,18 @@ module DeployPin
36
50
  DeployPin.send(:deployment_pending!)
37
51
  ).strip
38
52
 
53
+ # @return [Boolean] whether a deployment is running
39
54
  def ongoing_deployment?
40
55
  deployment_state == ONGOING
41
56
  end
42
57
 
58
+ # @return [Boolean] whether a deployment has entered the pending step
43
59
  def pending_deployment?
44
60
  deployment_state == PENDING
45
61
  end
46
62
 
63
+ # @return [Array<String>] sources of the built-in state tasks; empty unless
64
+ # {DeployPin.deployment_state_transition} is set
47
65
  def deployment_tasks_code
48
66
  return [] unless DeployPin.enabled?(:deployment_state_transition)
49
67
 
@@ -59,15 +77,21 @@ module DeployPin
59
77
 
60
78
  protected
61
79
 
80
+ # Clears the state. Called by the built-in task.
81
+ # @return [void]
62
82
  def deployment_over!
63
83
  in_memory_store.delete(:deployment)
64
84
  persistent_store.del(STORE_KEY)
65
85
  end
66
86
 
87
+ # Sets the state to {ONGOING}. Called by the built-in task.
88
+ # @return [void]
67
89
  def deployment_ongoing!
68
90
  persistent_store.set(STORE_KEY, ONGOING)
69
91
  end
70
92
 
93
+ # Sets the state to {PENDING}. Called by the built-in task.
94
+ # @return [void]
71
95
  def deployment_pending!
72
96
  persistent_store.set(STORE_KEY, PENDING)
73
97
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # Rails engine that loads the `deploy_pin:*` rake tasks.
4
5
  class Engine < ::Rails::Engine
5
6
  isolate_namespace DeployPin
6
7
  end
@@ -1,25 +1,35 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
- # Parallel wrapper to run parallel tasks using database statement timeout.
5
- # This wrapper keeps parallel interface, but running the processes under db statement timeout.
4
+ # Runs the methods of the [Parallel](https://github.com/grosser/parallel)
5
+ # gem with each block call under a database statement timeout. Prefix any
6
+ # Parallel method with `parallel_` inside a task.
6
7
  #
7
- # In order to use this wrapper, just use call parallel methods with `parallel_`. Ex.:
8
+ # The `timeout:` option sets the timeout; it defaults to
9
+ # {DeployPin.statement_timeout}. Pass an array to give
10
+ # {Database.execute_with_timeout} options too.
11
+ #
12
+ # @example
8
13
  # parallel_each(1..2, in_processes: 2, timeout: 0.3.seconds) do |i|
9
14
  # puts "Item: #{i}, Worker: #{Parallel.worker_number}"
10
15
  # ActiveRecord::Base.connection.execute("<some db query>")
11
16
  # end
12
17
  #
13
- # In order to pass more `timeout` options, it requires to pass an array, like:
18
+ # @example With timeout options
14
19
  # parallel_each(1..2, in_processes: 2, timeout: [0.3.seconds, { connected_to: { role: :reading } }]) do |i|
15
- # puts "Item: #{i}, Worker: #{Parallel.worker_number}"
16
20
  # ActiveRecord::Base.connection.execute("<some db query>")
17
21
  # end
18
22
  module ParallelWrapper
23
+ # Prefix that maps a method to its Parallel counterpart.
19
24
  PARALLEL_PREFIX = 'parallel_'
20
25
 
26
+ # Runs one `parallel_*` call.
21
27
  # :reek:TooManyInstanceVariables
22
28
  class ParallelRunner
29
+ # @param method_name [Symbol] the `parallel_*` method that was called
30
+ # @param args [Array] arguments for the Parallel method; a trailing hash
31
+ # with `:timeout` is used for the timeout
32
+ # @yield the block to run for each item
23
33
  def initialize(method_name, *args, &db_block)
24
34
  @method_name = method_name
25
35
  @db_block = db_block
@@ -32,15 +42,13 @@ module DeployPin
32
42
  @parallel_args = args
33
43
  end
34
44
 
45
+ # @return [Object] the result of the Parallel method
46
+ # @raise [RuntimeError] if no arguments were given
35
47
  def run
36
48
  raise 'You must provide at least one argument for parallel methods' if parallel_args.empty?
37
49
 
38
50
  Parallel.send(parallel_method_name, *parallel_args) do |*block_args|
39
- ActiveRecord::Base.connection_pool.with_connection do
40
- DeployPin::Database.execute_with_timeout(timeout, **timeout_params) do
41
- db_block.call(*block_args)
42
- end
43
- end
51
+ with_database_timeout { db_block.call(*block_args) }
44
52
  end
45
53
  end
46
54
 
@@ -48,6 +56,14 @@ module DeployPin
48
56
 
49
57
  attr_accessor :method_name, :parallel_args, :db_block
50
58
 
59
+ def with_database_timeout(&block)
60
+ return yield unless DeployPin::Database.available?
61
+
62
+ ActiveRecord::Base.connection_pool.with_connection do
63
+ DeployPin::Database.execute_with_timeout(timeout, **timeout_params, &block)
64
+ end
65
+ end
66
+
51
67
  def prepare_timeout_args
52
68
  timeout = @timeout_args[:timeout]
53
69
  if timeout.is_a?(Array)
@@ -71,12 +87,16 @@ module DeployPin
71
87
  end
72
88
  end
73
89
 
90
+ # Handles `parallel_*` calls.
91
+ #
92
+ # @return [Object] the result of the Parallel method
74
93
  def method_missing(name, *args, &block)
75
94
  return super unless respond_to_missing?(name)
76
95
 
77
96
  ParallelRunner.new(name, *args, &block).run
78
97
  end
79
98
 
99
+ # @return [Boolean] true for `parallel_*` names of existing Parallel methods
80
100
  # :reek:ManualDispatch and :reek:BooleanParameter
81
101
  def respond_to_missing?(method_name, include_private = false)
82
102
  return super unless parallel_prefix_pattern.match? method_name
@@ -1,30 +1,63 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # executes tasks
4
3
  module DeployPin
4
+ # Entry point used by the `deploy_pin:*` rake tasks.
5
+ #
6
+ # @example Run all pending tasks of groups I and II
7
+ # DeployPin::Runner.run(identifiers: %w[I II])
5
8
  module Runner
9
+ # Runs the selected tasks that have not been done yet.
10
+ #
11
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
12
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
13
+ # @return [void]
14
+ # @raise [StandardError] a task's error, unless {DeployPin.continue_on_error} is set
6
15
  def self.run(identifiers:)
7
16
  DeployPin::Collector.new(identifiers:).run
8
17
  end
9
18
 
19
+ # Prints each selected task, including its script, with {DeployPin.list_formatter}.
20
+ #
21
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
22
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
23
+ # @return [void]
10
24
  def self.list(identifiers:)
11
25
  DeployPin::Collector.new(identifiers:).list
12
26
  end
13
27
 
28
+ # Prints the selected tasks grouped by group, with {DeployPin.short_list_formatter}.
29
+ #
30
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
31
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
32
+ # @return [void]
14
33
  def self.short_list(identifiers:)
15
34
  DeployPin::Collector.new(identifiers:).short_list
16
35
  end
17
36
 
37
+ # Marks the selected tasks as done without running them.
38
+ #
39
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
40
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
41
+ # @return [void]
18
42
  def self.mark_done(identifiers:)
19
43
  DeployPin::Collector.new(identifiers:).mark_done
20
44
  end
21
45
 
46
+ # Prints how many tasks are selected.
47
+ #
48
+ # @param identifiers [Array<String, Integer>] groups and task identifiers to select;
49
+ # see {TaskCriteria} for the `!` prefix and suffix syntax
50
+ # @return [void]
22
51
  def self.summary(identifiers:)
23
52
  # print summary
24
53
  self.print('======= Summary ========')
25
54
  self.print("Tasks number: #{DeployPin::Collector.new(identifiers:).tasks_count}")
26
55
  end
27
56
 
57
+ # Prints a message, except in the test environment.
58
+ #
59
+ # @param msg [String]
60
+ # @return [void]
28
61
  def self.print(msg)
29
62
  puts(msg) unless Rails.env.test?
30
63
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # Base class for DeployPin's ActiveRecord models.
4
5
  class ApplicationRecord < ActiveRecord::Base
5
6
  self.abstract_class = true
6
7
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DeployPin
4
+ # ActiveRecord storage for task records (the default), in the `deploy_pins` table.
4
5
  class Record < DeployPin::ApplicationRecord
5
6
  self.table_name = 'deploy_pins'
6
7
  end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeployPin
4
+ # Mongoid storage for task records, enabled with `storage :mongoid`.
5
+ # :reek:MissingSafeMethod - increment! mirrors the ActiveRecord API used by DeployPin::Task.
6
+ class MongoidRecord
7
+ include ::Mongoid::Document
8
+ include ::Mongoid::Timestamps
9
+
10
+ store_in collection: 'deploy_pins'
11
+
12
+ field :uuid, type: String
13
+ field :progress, type: Integer, default: 0
14
+ field :completed_at, type: Time
15
+
16
+ index({ uuid: 1 }, { unique: true })
17
+
18
+ # Same semantics as ActiveRecord: nil when missing (Mongoid raises by default).
19
+ #
20
+ # @param uuid [Integer, String] the task identifier
21
+ # @return [MongoidRecord, nil]
22
+ def self.find_by(uuid:)
23
+ where(uuid: uuid&.to_s).first
24
+ end
25
+
26
+ # Atomic, like ActiveRecord's increment!.
27
+ #
28
+ # @param attribute [Symbol]
29
+ # @param by [Integer]
30
+ # @return [void]
31
+ def increment!(attribute, by = 1)
32
+ inc(attribute => by)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeployPin
4
+ # Resolves the model used to persist task records, based on the configured storage provider.
5
+ #
6
+ # @example
7
+ # DeployPin.setup do
8
+ # storage :active_record # default, or :mongoid
9
+ # end
10
+ #
11
+ # A record class must respond to `.find_by(uuid:)` (returning a record or
12
+ # nil) and `.create(uuid:)`. Its instances must respond to `#progress`,
13
+ # `#completed_at`, `#update(attributes)` and `#increment!(attribute, by)`.
14
+ module Storage
15
+ # Record classes by storage name. They are resolved lazily, so only the
16
+ # configured ORM has to be installed.
17
+ PROVIDERS = {
18
+ active_record: -> { DeployPin::Record },
19
+ mongoid: -> { DeployPin::MongoidRecord }
20
+ }.freeze
21
+
22
+ # @return [Class] {Record} or {MongoidRecord}
23
+ # @raise [ArgumentError] if {DeployPin.storage} is not one of {PROVIDERS}
24
+ def self.record_class
25
+ PROVIDERS.fetch(DeployPin.storage.to_sym) do
26
+ raise ArgumentError,
27
+ "Unknown DeployPin storage #{DeployPin.storage.inspect}. Supported: #{PROVIDERS.keys.join(', ')}"
28
+ end.call
29
+ end
30
+ end
31
+ end