Class: Spree::MaintenanceTask

Inherits:
Object
  • Object
show all
Extended by:
ApiTyped
Includes:
ActiveModel::Attributes, ActiveModel::Model
Defined in:
app/models/spree/maintenance_task.rb

Overview

Base class for the data work an upgrade runs: one step of an upgrade manifest (docs/plans/6.0-maintenance-tasks.md).

A task walks a stable-ordered collection and processes one record at a time. The runner (Spree::MaintenanceTasks::RunJob) supplies batching, checkpointing, cancelling and the audit row, so a task body says only what it does.

class Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets < Spree::MaintenanceTask
supports_dry_run

def collection
  Spree::Order.where(market_id: nil).order(:id)
end

def process(order)
  return tally(:would_update) if dry_run?

  order.update_columns(market_id: order.store.default_market.id)
  tally(:updated)
end
end

A manifest step names its task class, which registers it in Spree.maintenance_tasks; nothing else is runnable.

Defined Under Namespace

Classes: RakeTaskAborted

Constant Summary collapse

RAKE_LOAD_LOCK =

Two threads of one worker must not both find a task undefined and both load its file — the second load would make the task run twice.

Mutex.new
DEFAULT_BATCH_SIZE =
100
MAX_RUN_TIME =

How long one execution may run before the runner checkpoints and re-enqueues itself, so a long step cannot hold a worker indefinitely.

5.minutes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ApiTyped

api_type, api_typed_family, class_name_for, find, registered_class

Instance Attribute Details

#run ⇒ Object

Returns the value of attribute run.



49
50
51
# File 'app/models/spree/maintenance_task.rb', line 49

def run
  @run
end

Class Method Details

.api_type_for(class_name) ⇒ String

A task class name as the API shows it. A task that is no longer registered is shortened the same way rather than loaded by name.

Parameters:

  • class_name (String)

Returns:

  • (String)


91
92
93
# File 'app/models/spree/maintenance_task.rb', line 91

def api_type_for(class_name)
  find_registered(class_name)&.api_type || class_name.to_s.demodulize.underscore
end

.collection_batch_size(size) ⇒ Object



65
66
67
# File 'app/models/spree/maintenance_task.rb', line 65

def collection_batch_size(size)
  self.batch_size = size
end

.find_by_api_type(api_type) ⇒ Class?

The registered task an API caller names. Matches the short name only, so a Ruby class name arriving over the API is an unknown task.

Parameters:

  • api_type (String) —

    e.g. "capture_methods"

Returns:

  • (Class, nil)


100
101
102
# File 'app/models/spree/maintenance_task.rb', line 100

def find_by_api_type(api_type)
  Spree::ApiTyped.find(Spree.maintenance_tasks, api_type)
end

.find_registered(name) ⇒ Class?

Returns nil when the name is not registered — an unregistered task is never runnable, so the runner and the API can treat nil as "no such task" without a second check.

Parameters:

  • name (String) —

    a task class name

Returns:

  • (Class, nil) —

    nil when the name is not registered — an unregistered task is never runnable, so the runner and the API can treat nil as "no such task" without a second check



80
81
82
83
84
# File 'app/models/spree/maintenance_task.rb', line 80

def find_registered(name)
  return nil if name.blank?

  registered_classes.find { |klass| klass.name == name.to_s }
end

.no_collection ⇒ Object

The task performs a single operation instead of iterating; process is called once with no argument.



61
62
63
# File 'app/models/spree/maintenance_task.rb', line 61

def no_collection
  self.collection_kind = :none
end

.registered_classes ⇒ Array<Class>

Returns registered task classes, sorted by name.

Returns:

  • (Array<Class>) —

    registered task classes, sorted by name



70
71
72
73
74
# File 'app/models/spree/maintenance_task.rb', line 70

def registered_classes
  Spree.maintenance_tasks.filter_map do |entry|
    entry.is_a?(Class) ? entry : entry.to_s.safe_constantize
  end.uniq.sort_by(&:name)
end

.supports_dry_run ⇒ Object

Declares that process honors dry_run?. The runner never fakes a dry run by rolling a transaction back, which would silently lie about external calls, enqueued jobs and cache writes.



55
56
57
# File 'app/models/spree/maintenance_task.rb', line 55

def supports_dry_run
  self.dry_run_supported = true
end

Instance Method Details

#after_complete ⇒ Object

Called once the last record has been processed, before the run is marked succeeded — for a summary tally of what the walk left alone.



189
# File 'app/models/spree/maintenance_task.rb', line 189

def after_complete; end

#collection ⇒ ActiveRecord::Relation

The records to walk, ordered by primary key — the cursor is the last id processed, so any other order would resume in the wrong place.

Returns:

  • (ActiveRecord::Relation)

Raises:

  • (NotImplementedError)


109
110
111
# File 'app/models/spree/maintenance_task.rb', line 109

def collection
  raise NotImplementedError, "#{self.class.name} must implement #collection or declare `no_collection`"
end

#count ⇒ Integer?

Total records, for the progress bar. Return nil when counting is more expensive than the work itself — the run then reports ticks only.

Returns:

  • (Integer, nil)


123
124
125
# File 'app/models/spree/maintenance_task.rb', line 123

def count
  collection.count unless no_collection?
end

#dry_run? ⇒ Boolean

Returns:

  • (Boolean)


131
132
133
# File 'app/models/spree/maintenance_task.rb', line 131

def dry_run?
  run&.dry_run? || false
end

#invoke_rake_task(task_name) ⇒ Object

Runs an engine rake task as part of this task.

Rake bodies stop themselves with abort, which raises SystemExit — not an error the runner records. Left alone it would end the whole process from the command line and, in a worker, leave the run marked running with nothing to finish it.

Parameters:

  • task_name (String)

Raises:



155
156
157
158
159
160
161
162
163
# File 'app/models/spree/maintenance_task.rb', line 155

def invoke_rake_task(task_name)
  load_engine_rake_tasks(task_name)

  task = ::Rake::Task[task_name]
  task.reenable
  task.invoke
rescue SystemExit => e
  raise RakeTaskAborted, e.message
end

#no_collection? ⇒ Boolean

Returns:

  • (Boolean)


127
128
129
# File 'app/models/spree/maintenance_task.rb', line 127

def no_collection?
  self.class.collection_kind == :none
end

#process(item = nil) ⇒ Object

Parameters:

  • item (Object) (defaults to: nil) —

    one record from the collection; omitted for no_collection tasks

Raises:

  • (NotImplementedError)


115
116
117
# File 'app/models/spree/maintenance_task.rb', line 115

def process(item = nil)
  raise NotImplementedError, "#{self.class.name} must implement #process"
end

#rake_file_defining(task_name) ⇒ String?

Finds the file that defines a task by reading the files rather than loading them: loading a .rake file to discover whether it is the right one would append its blocks to every task it defines, which is the very duplication this avoids.

Searches every engine and the host application, since a step may ship in an extension gem. When two files define the same task name, the one that also declares the task's namespaces wins.

Returns:

  • (String, nil)


175
176
177
178
179
180
181
182
183
184
185
# File 'app/models/spree/maintenance_task.rb', line 175

def rake_file_defining(task_name)
  *namespaces, leaf = task_name.split(':')
  candidates = rake_files.select do |path|
    File.read(path).match?(/^\s*(?:desc\s.*\n\s*)?task\s+:?["']?#{Regexp.escape(leaf)}["']?\b/)
  end

  candidates.find do |path|
    source = File.read(path)
    namespaces.all? { |name| source.match?(/namespace\s+:?["']?#{Regexp.escape(name)}["']?\b/) }
  end || candidates.first
end

#tallies ⇒ Object



142
143
144
# File 'app/models/spree/maintenance_task.rb', line 142

def tallies
  @tallies ||= Hash.new(0)
end

#tally(key, by = 1) ⇒ Object

Records a counter shown on the run page: what was updated, skipped, or would have changed in a dry run.



137
138
139
140
# File 'app/models/spree/maintenance_task.rb', line 137

def tally(key, by = 1)
  @tallies ||= Hash.new(0)
  @tallies[key.to_s] += by
end