append_transitions 0.1.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.
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ class CurrentScope
5
+ include ForeignKey
6
+
7
+ def initialize(class_name:, attr_name:, foreign_key:, order:)
8
+ @class_name = class_name
9
+ @attr_name = attr_name
10
+ @foreign_key = foreign_key
11
+ @order = order
12
+ @hydrator = Hydrator.new(class_name:, attr_name:)
13
+ end
14
+
15
+ def call(base)
16
+ subquery = subquery_for(base)
17
+
18
+ base
19
+ .select(base.arel_table[Arel.star], *aliased_columns)
20
+ .joins("LEFT JOIN LATERAL (#{subquery.to_sql}) #{quoted_alias} ON true")
21
+ .extending(@hydrator, CountAll)
22
+ end
23
+
24
+ private
25
+
26
+ def subquery_for(base)
27
+ klass
28
+ .where(join_condition(base))
29
+ .order(@order)
30
+ .limit(1)
31
+ end
32
+
33
+ # Arel quotes the names and uses the base's real primary key
34
+ def join_condition(base)
35
+ foreign_key = klass.arel_table[fk_for(base)]
36
+ primary_key = base.arel_table[base.primary_key]
37
+
38
+ foreign_key.eq(primary_key)
39
+ end
40
+
41
+ # Quoted, so mixed-case column names keep their case. The hydrator
42
+ # reads them back as current_status_<column>.
43
+ def aliased_columns
44
+ klass.column_names.map do |column|
45
+ "#{quoted_alias}.#{quote(column)} AS #{quote("#{@attr_name}_#{column}")}"
46
+ end
47
+ end
48
+
49
+ def quoted_alias
50
+ quote(@attr_name)
51
+ end
52
+
53
+ def quote(name)
54
+ klass.connection.quote_column_name(name)
55
+ end
56
+
57
+ def klass
58
+ @klass ||= @class_name.constantize
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Resolves the configured @foreign_key, or infers it from the owner
5
+ # class the same way Rails does for has_many (User => user_id). Uses
6
+ # base_class so STI subclasses (Admin < User) still resolve to user_id.
7
+ module ForeignKey
8
+ private
9
+
10
+ def fk_for(owner)
11
+ @foreign_key || owner.base_class.model_name.to_s.foreign_key
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Defines, for base name :status:
5
+ #
6
+ # user.current_status # cached latest UserStatus, or nil
7
+ # user.transition_status(:new) # appends a row under a row lock,
8
+ # # clears @current_status
9
+ # user.reload # also clears @current_status
10
+ # User.with_current_status # LATERAL join, hydrates @current_status
11
+ class HasCurrent < Module
12
+ DEFAULT_ORDER = {created_at: :desc, id: :desc}.freeze
13
+
14
+ def initialize(
15
+ base_name, class_name:, initial_state:, transitions: {}, foreign_key: nil,
16
+ state_column: :status, order: DEFAULT_ORDER
17
+ )
18
+ super()
19
+
20
+ validate_order!(order)
21
+
22
+ @base_name = base_name
23
+ base_args = {class_name:, foreign_key:}
24
+ attr_name = :"current_#{base_name}"
25
+ ivar = :"@#{attr_name}"
26
+
27
+ current_query = CurrentQuery.new(**base_args, order:)
28
+ transition_map = TransitionMap.new(initial_state:, transitions:)
29
+ transitioner = Transitioner.new(**base_args, state_column:, transition_map:, current_query:)
30
+ current_scope = CurrentScope.new(**base_args, attr_name:, order:)
31
+ index_validator = IndexValidator.new(**base_args, state_column:, order:)
32
+
33
+ # Drops the cached value, so the next read queries again
34
+ clear_current = proc do
35
+ instance_variable_defined?(ivar) && remove_instance_variable(ivar)
36
+ end
37
+
38
+ # def current_status
39
+ #
40
+ # Caches the result, including nil, like Rails associations do.
41
+ define_method(attr_name) do
42
+ if instance_variable_defined?(ivar)
43
+ instance_variable_get(ivar)
44
+ else
45
+ index_validator.validate!(self.class)
46
+ instance_variable_set(ivar, current_query.call(self))
47
+ end
48
+ end
49
+
50
+ # def transition_status(new_state, &block)
51
+ define_method(:"transition_#{base_name}") do |new_state, &block|
52
+ transitioner.call(self, new_state, &block).tap do
53
+ instance_exec(&clear_current)
54
+ end
55
+ end
56
+
57
+ # def reload(*args)
58
+ define_method(:reload) do |*args|
59
+ instance_exec(&clear_current)
60
+ super(*args)
61
+ end
62
+
63
+ @class_methods = Module.new do
64
+ # def self.with_current_status
65
+ define_method(:"with_#{attr_name}") do
66
+ index_validator.validate!(self)
67
+ current_scope.call(self)
68
+ end
69
+ end
70
+ end
71
+
72
+ def included(base)
73
+ super
74
+
75
+ base.extend(@class_methods)
76
+ end
77
+
78
+ def inspect
79
+ "HasCurrent(:#{@base_name})"
80
+ end
81
+
82
+ private
83
+
84
+ # The recommended index and the missing index check are built from
85
+ # the order's columns, so it can't be raw SQL.
86
+ def validate_order!(order)
87
+ unless order.is_a?(Hash)
88
+ raise ArgumentError, "order must be a Hash of columns to directions, got #{order.inspect}"
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Hooks into ActiveRecord::Relation#load via .extending to turn flat
5
+ # lateral join rows into hydrated AR objects on each parent record.
6
+ #
7
+ # #<User id: 1, current_status_id: 42, current_status_status: "approved">
8
+ # => user.@current_status = #<UserStatus id: 42, status: "approved">
9
+ #
10
+ # Uses @records (AR::Relation internal, stable since Rails 3, same
11
+ # approach as the Goldiloader and Bullet gems).
12
+ class Hydrator < Module
13
+ def initialize(class_name:, attr_name:)
14
+ super()
15
+
16
+ klass_name = class_name
17
+ name = attr_name
18
+ ivar = :"@#{attr_name}"
19
+
20
+ # Forwards the block, which the preloader uses to set inverses
21
+ define_method(:load) do |&block|
22
+ # Hydrates only when this call runs the query. Records of an
23
+ # already loaded relation may have moved on, e.g. a transition
24
+ # cleared their state.
25
+ return super(&block) if loaded?
26
+
27
+ super(&block).tap do
28
+ klass = klass_name.constantize
29
+
30
+ @records.each do |record|
31
+ # Without the selected columns (e.g. after reselect), the state
32
+ # is left to be queried on first read, one query per record
33
+ next unless record.has_attribute?("#{name}_id")
34
+
35
+ attrs = klass.column_names.each_with_object({}) do |col, h|
36
+ h[col] = record.read_attribute("#{name}_#{col}")
37
+ end
38
+
39
+ # Sets nil explicitly, so a row without a status counts as loaded
40
+ obj = attrs["id"].presence && klass.instantiate(attrs.stringify_keys)
41
+ record.instance_variable_set(ivar, obj)
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Checks that the child table has an index starting with the
5
+ # RecommendedIndex columns (foreign key, then the order columns).
6
+ # Without one, each lookup scans or sorts the parent's rows. Order
7
+ # directions and INCLUDE aren't checked: PostgreSQL can scan an index
8
+ # backward, and the index works without INCLUDE, only slower.
9
+ class IndexValidator
10
+ include ForeignKey
11
+
12
+ def initialize(class_name:, foreign_key:, state_column:, order:)
13
+ @class_name = class_name
14
+ @foreign_key = foreign_key
15
+ @state_column = state_column
16
+ @order = order
17
+ @validated = false
18
+ end
19
+
20
+ def validate!(owner)
21
+ # Concurrent calls may both pass this guard, which is harmless
22
+ # in practice. It's a brief window and the check is a read-only
23
+ # catalog lookup.
24
+ return if @validated
25
+
26
+ klass = @class_name.constantize
27
+ table_name = klass.table_name
28
+ index = recommended_index(table_name, fk_for(owner))
29
+
30
+ unless index_exists?(klass.connection, table_name, index)
31
+ report_missing_index(table_name, index)
32
+ end
33
+
34
+ @validated = true
35
+ end
36
+
37
+ private
38
+
39
+ def recommended_index(table_name, fk)
40
+ RecommendedIndex.new(
41
+ table_name:, foreign_key: fk, order: @order, state_column: @state_column
42
+ )
43
+ end
44
+
45
+ def index_exists?(connection, table_name, index)
46
+ columns = index.columns.map(&:to_s)
47
+
48
+ connection.indexes(table_name).any? do |existing|
49
+ covers?(existing, columns)
50
+ end
51
+ end
52
+
53
+ # Expression indexes report their columns as a String, and partial
54
+ # indexes leave rows out, so neither counts.
55
+ def covers?(existing, columns)
56
+ existing.columns.is_a?(Array) &&
57
+ existing.where.nil? &&
58
+ existing.columns.first(columns.size) == columns
59
+ end
60
+
61
+ def report_missing_index(table_name, index)
62
+ message = message_for(table_name, index)
63
+
64
+ case AppendTransitions.configuration.on_missing_index
65
+ when :raise
66
+ raise MissingIndexError, message
67
+ when :warn
68
+ warn message
69
+ end
70
+ end
71
+
72
+ def message_for(table_name, index)
73
+ <<~MSG.squish
74
+ AppendTransitions: no index on "#{table_name}" starting with
75
+ (#{index.columns.join(", ")}).
76
+ Lookups of the current state will slow down as history grows.
77
+ Add to a migration: #{index.lines.join(" ")}
78
+ MSG
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # The index current_* and with_current_* read through: the foreign key,
5
+ # then the order columns. IndexValidator checks for it, and both the
6
+ # missing index message and the generator write it out.
7
+ class RecommendedIndex
8
+ # PostgreSQL's limit on identifier length
9
+ MAX_NAME_LENGTH = 63
10
+
11
+ def initialize(table_name:, foreign_key:, order:, state_column:)
12
+ @table_name = table_name
13
+ @foreign_key = foreign_key
14
+ @order = order
15
+ @state_column = state_column
16
+ end
17
+
18
+ # The add_index call for this index, as an array with one argument
19
+ # per string and a trailing comma on all but the last:
20
+ #
21
+ # ["add_index :user_statuses, [:user_id, :created_at, :id],",
22
+ # "order: {created_at: :desc, id: :desc},",
23
+ # "include: :status"]
24
+ #
25
+ # Callers join it to fit their output: with spaces for the one-line
26
+ # missing index message, with indented newlines for the generated
27
+ # migration.
28
+ #
29
+ # Before ActiveRecord 7.1, include isn't supported, so it's left out,
30
+ # and long index names aren't shortened, so a short name is added
31
+ # when the default would be too long.
32
+ def lines
33
+ arguments = [columns_argument, order_argument]
34
+ include_supported? && arguments << include_argument
35
+ name_required? && arguments << name_argument
36
+
37
+ arguments[...-1].map { |argument| "#{argument}," } << arguments.last
38
+ end
39
+
40
+ def columns
41
+ [@foreign_key, *@order.keys].map(&:to_sym)
42
+ end
43
+
44
+ private
45
+
46
+ def columns_argument
47
+ "add_index #{@table_name.to_sym.inspect}, #{columns.inspect}"
48
+ end
49
+
50
+ def order_argument
51
+ pairs = @order.map { |column, direction| "#{column}: #{direction.to_sym.inspect}" }
52
+
53
+ "order: {#{pairs.join(", ")}}"
54
+ end
55
+
56
+ def include_supported?
57
+ active_record_7_1_or_later?
58
+ end
59
+
60
+ def include_argument
61
+ "include: #{@state_column.to_sym.inspect}"
62
+ end
63
+
64
+ def name_required?
65
+ !active_record_7_1_or_later? && default_name.length > MAX_NAME_LENGTH
66
+ end
67
+
68
+ def name_argument
69
+ "name: #{"index_#{@table_name}_current".inspect}"
70
+ end
71
+
72
+ # The name ActiveRecord 7.0 gives the index
73
+ def default_name
74
+ "index_#{@table_name}_on_#{columns.join("_and_")}"
75
+ end
76
+
77
+ def active_record_7_1_or_later?
78
+ ActiveRecord.version >= Gem::Version.new("7.1")
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ class TransitionMap
5
+ def initialize(initial_state:, transitions:)
6
+ unless initial_state.is_a?(Symbol) || initial_state.is_a?(String)
7
+ raise ArgumentError, "initial_state must be a single state, got #{initial_state.inspect}"
8
+ end
9
+
10
+ if transitions.key?(nil)
11
+ raise ArgumentError, "transitions cannot have a nil key, use initial_state instead"
12
+ end
13
+
14
+ # Normalize to symbols so string states (e.g. from YAML) match.
15
+ @transitions = {nil => initial_state, **transitions}
16
+ .to_h { |from, to| [from&.to_sym, Array(to).map(&:to_sym)] }
17
+ end
18
+
19
+ def valid?(from:, to:)
20
+ possible_states(from).include?(to)
21
+ end
22
+
23
+ private
24
+
25
+ def possible_states(state)
26
+ @transitions.fetch(state, [])
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ # Inserts a new state record under a SELECT FOR UPDATE lock on the
5
+ # parent row. Validates the transition against the TransitionMap,
6
+ # creates the row, and yields the inserted record to an optional block.
7
+ # The entire operation runs in one transaction, so concurrent
8
+ # transitions on the same parent are serialized.
9
+ class Transitioner
10
+ include ForeignKey
11
+
12
+ def initialize(class_name:, foreign_key:, state_column:, transition_map:, current_query:)
13
+ @class_name = class_name
14
+ @foreign_key = foreign_key
15
+ @state_column = state_column
16
+ @transition_map = transition_map
17
+ @current_query = current_query
18
+ end
19
+
20
+ def call(record, new_state, &block)
21
+ ensure_saved(record)
22
+
23
+ record.transaction do
24
+ lock(record)
25
+ current = @current_query.call(record)
26
+ new_state = validate_transition(current, new_state)
27
+ state_record = create_transition(record, new_state, current)
28
+ block&.call(state_record)
29
+ state_record
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ # A new record has no row to lock, and no id to reference
36
+ def ensure_saved(record)
37
+ return unless record.new_record?
38
+
39
+ message = "Cannot transition a new record, save it first"
40
+ raise ActiveRecord::RecordNotSaved.new(message, record)
41
+ end
42
+
43
+ # Not with_lock: it reloads the record and refuses records with
44
+ # unsaved changes, and a transition shouldn't touch the parent's
45
+ # attributes. unscoped keeps a default scope on the parent (e.g. a
46
+ # soft-delete filter) from hiding the row being locked.
47
+ def lock(record)
48
+ record.class.unscoped.lock.find(record.id)
49
+ end
50
+
51
+ def validate_transition(current, new_state)
52
+ from = current&.public_send(@state_column)&.to_sym
53
+
54
+ new_state&.to_sym.tap do |to|
55
+ unless @transition_map.valid?(from:, to:)
56
+ message = "Cannot transition from #{from || "nil"} to #{to || "nil"}"
57
+ raise InvalidTransition, message
58
+ end
59
+ end
60
+ end
61
+
62
+ def create_transition(record, new_state, current)
63
+ klass.create!(
64
+ fk_for(record.class) => record.id,
65
+ @state_column => new_state,
66
+ **timestamps_after(current)
67
+ )
68
+ end
69
+
70
+ # created_at comes from this process's clock, which may be behind the
71
+ # one that wrote the current row. Rows are ordered by it, so keep it
72
+ # after the current row's.
73
+ def timestamps_after(current)
74
+ if current&.has_attribute?(:created_at)
75
+ {created_at: [Time.current, current.created_at + 1.0e-6].max}
76
+ else
77
+ {}
78
+ end
79
+ end
80
+
81
+ def klass
82
+ @klass ||= @class_name.constantize
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AppendTransitions
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "append_transitions/version"
4
+ require_relative "append_transitions/configuration"
5
+ require_relative "append_transitions/foreign_key"
6
+ require_relative "append_transitions/transition_map"
7
+ require_relative "append_transitions/current_query"
8
+ require_relative "append_transitions/transitioner"
9
+ require_relative "append_transitions/hydrator"
10
+ require_relative "append_transitions/count_all"
11
+ require_relative "append_transitions/current_scope"
12
+ require_relative "append_transitions/recommended_index"
13
+ require_relative "append_transitions/index_validator"
14
+ require_relative "append_transitions/has_current"
15
+
16
+ module AppendTransitions
17
+ class Error < StandardError; end
18
+ class InvalidTransition < Error; end
19
+ class MissingIndexError < Error; end
20
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/active_record"
5
+ require "append_transitions"
6
+
7
+ module AppendTransitions
8
+ module Generators
9
+ # bin/rails generate append_transitions:state User status
10
+ #
11
+ # Creates the user_statuses migration, with the index current_status
12
+ # reads through, and a read-only UserStatus model.
13
+ class StateGenerator < Rails::Generators::NamedBase
14
+ include ActiveRecord::Generators::Migration
15
+
16
+ DEFAULT_STATE_COLUMN = "status"
17
+
18
+ source_root Pathname(__dir__).join("templates")
19
+
20
+ argument :base_name, type: :string, banner: "base_name"
21
+
22
+ class_option :state_column, type: :string, default: DEFAULT_STATE_COLUMN,
23
+ desc: "The state table's column holding the state"
24
+ class_option :primary_key_type, type: :string,
25
+ desc: "The type for primary key"
26
+ class_option :database, type: :string, aliases: %i[--db],
27
+ desc: "The database for the migration"
28
+
29
+ def create_migration_file
30
+ migration_template "migration.rb.tt",
31
+ Pathname(db_migrate_path).join("create_#{state_table_name}.rb")
32
+ end
33
+
34
+ def create_model_file
35
+ template "model.rb.tt", Pathname("app/models").join("#{state_file_name}.rb")
36
+ end
37
+
38
+ # Like Rails' model generator, creates the abstract class the model
39
+ # inherits from with --database, unless it already exists
40
+ def create_database_abstract_class
41
+ return unless options[:database]
42
+
43
+ path = Pathname("app/models").join("#{options[:database].underscore}_record.rb")
44
+ return if Pathname(destination_root).join(path).exist?
45
+
46
+ template "abstract_class.rb.tt", path
47
+ end
48
+
49
+ def show_has_current
50
+ say ""
51
+ say "Add to app/models/#{file_path}.rb, with your own states:"
52
+ say ""
53
+ say has_current_lines.map { |line| " #{line}" }.join("\n")
54
+ end
55
+
56
+ private
57
+
58
+ def has_current_lines
59
+ [
60
+ "include AppendTransitions::HasCurrent.new(",
61
+ " :#{base_name},",
62
+ " class_name: #{state_class_name.inspect},",
63
+ *state_column_lines,
64
+ " initial_state: :pending,",
65
+ " transitions: {pending: [:approved, :denied]}",
66
+ ")"
67
+ ]
68
+ end
69
+
70
+ def state_column_lines
71
+ if state_column == DEFAULT_STATE_COLUMN
72
+ []
73
+ else
74
+ [" state_column: :#{state_column},"]
75
+ end
76
+ end
77
+
78
+ def state_column
79
+ options[:state_column]
80
+ end
81
+
82
+ def state_class_name
83
+ "#{class_name}#{base_name.camelize}"
84
+ end
85
+
86
+ # Admin::UserStatus => admin_user_statuses, like Rails names the
87
+ # table for a namespaced model
88
+ def state_table_name
89
+ state_class_name.tableize.tr("/", "_")
90
+ end
91
+
92
+ def state_file_name
93
+ state_class_name.underscore
94
+ end
95
+
96
+ # ActiveRecord's helpers of the same name only read the option.
97
+ # Rails' own generators also get the app's default from
98
+ # config.generators, under a namespace this generator doesn't share.
99
+ def primary_key_type
100
+ key_type && ", id: :#{key_type}"
101
+ end
102
+
103
+ def foreign_key_type
104
+ key_type && ", type: :#{key_type}"
105
+ end
106
+
107
+ def key_type
108
+ options[:primary_key_type] ||
109
+ Rails::Generators.options.dig(:active_record, :primary_key_type)
110
+ end
111
+
112
+ # A namespaced parent's table (admin_users) can't be inferred from
113
+ # the reference name (user)
114
+ def foreign_key_option
115
+ if class_path.empty?
116
+ "true"
117
+ else
118
+ "{to_table: :#{table_name}}"
119
+ end
120
+ end
121
+
122
+ def parent_class_name
123
+ if options[:database]
124
+ database_class_name
125
+ else
126
+ "ApplicationRecord"
127
+ end
128
+ end
129
+
130
+ def database_class_name
131
+ "#{options[:database].camelize}Record"
132
+ end
133
+
134
+ def index_lines
135
+ RecommendedIndex.new(
136
+ table_name: state_table_name,
137
+ foreign_key: "#{singular_name}_id",
138
+ order: HasCurrent::DEFAULT_ORDER,
139
+ state_column:
140
+ ).lines
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,5 @@
1
+ class <%= database_class_name %> < ApplicationRecord
2
+ self.abstract_class = true
3
+
4
+ connects_to database: { <%= ActiveRecord.writing_role %>: :<%= options[:database] %> }
5
+ end
@@ -0,0 +1,11 @@
1
+ class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
2
+ def change
3
+ create_table :<%= state_table_name %><%= primary_key_type %> do |t|
4
+ t.references :<%= singular_name %>, null: false, foreign_key: <%= foreign_key_option %>, index: false<%= foreign_key_type %>
5
+ t.string :<%= state_column %>, null: false
6
+ t.timestamps
7
+ end
8
+
9
+ <%= index_lines.join("\n ") %>
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ class <%= state_class_name %> < <%= parent_class_name %>
2
+ belongs_to :<%= singular_name %>
3
+
4
+ def readonly? = super || (persisted? && !destroyed_by_association)
5
+ end