state_machines-audit_trail 3.0.0 → 4.0.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.
- checksums.yaml +4 -4
- data/README.md +30 -8
- data/Rakefile +35 -5
- data/lib/state_machines/audit_trail/backend/active_record.rb +73 -14
- data/lib/state_machines/audit_trail/backend.rb +53 -65
- data/lib/state_machines/audit_trail/collection_guard.rb +23 -0
- data/lib/state_machines/audit_trail/journal.rb +224 -0
- data/lib/state_machines/audit_trail/owner.rb +122 -0
- data/lib/state_machines/audit_trail/railtie.rb +9 -3
- data/lib/state_machines/audit_trail/save.rb +88 -0
- data/lib/state_machines/audit_trail/transition_auditing.rb +87 -65
- data/lib/state_machines/audit_trail/version.rb +3 -1
- data/lib/state_machines/audit_trail.rb +9 -2
- data/lib/state_machines/audit_trail_generator.rb +27 -22
- data/lib/state_machines-audit_trail.rb +2 -0
- metadata +22 -76
- data/lib/state_machines/audit_trail/backend/mongoid.rb +0 -13
- data/spec/helpers/active_record.rb +0 -289
- data/spec/helpers/mongoid.rb +0 -82
- data/spec/helpers/mongoid.yml +0 -6
- data/spec/lib/state_machines/audit_trail/backend/active_record_spec.rb +0 -288
- data/spec/lib/state_machines/audit_trail/backend/mongoid_spec.rb +0 -98
- data/spec/lib/state_machines/audit_trail_generator_spec.rb +0 -54
- data/spec/lib/state_machines/audit_trail_spec.rb +0 -8
- data/spec/spec_helper.rb +0 -8
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9a9d3c1929b6a67881df6fddd0885a1e5801393d8b2026a895a34dab248f1ecc
|
|
4
|
+
data.tar.gz: 0b59efa7cf9bfc4369981d1e6e2b590e7b8d4c1f409debc7c2b237f6724f568a
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c1ba0dcaf7b33d7abbc0dd08be28c5c76c2ebaef80ca1ca910ffc40aafb43b47448bd77ca7ed25df8ee3f9f82406c4e1925f5589784a687dce86ac8ad92498b5
|
|
7
|
+
data.tar.gz: faed984d56c1404a4532f7fda170e4f1b5f3e2331091f5d9109e79d04e410f8471ab06c0bf01c41a5b110434da701c21c146252309253985c03612f802964bdb
|
data/README.md
CHANGED
|
@@ -18,8 +18,6 @@ For more information read [Why developers should be force-fed state machines](ht
|
|
|
18
18
|
Note: while the state_machines gem integrates with multiple ORMs, this plugin is currently limited to the following ORM backends:
|
|
19
19
|
|
|
20
20
|
* ActiveRecord
|
|
21
|
-
* Mongoid
|
|
22
|
-
|
|
23
21
|
|
|
24
22
|
It should be easy to add new backends by looking at the implementation of the current backends. Pull requests are welcome!
|
|
25
23
|
|
|
@@ -31,11 +29,8 @@ First, make the gem available by adding it to your `Gemfile`, and run `bundle in
|
|
|
31
29
|
# this gem
|
|
32
30
|
gem 'state_machines-audit_trail'
|
|
33
31
|
|
|
34
|
-
# required runtime dependency for your ORM
|
|
32
|
+
# required runtime dependency for your ORM
|
|
35
33
|
gem 'state_machines-activerecord'
|
|
36
|
-
|
|
37
|
-
# OR
|
|
38
|
-
gem 'state_machines-mongoid'
|
|
39
34
|
```
|
|
40
35
|
|
|
41
36
|
## Usage
|
|
@@ -61,7 +56,35 @@ class Subscription < ActiveRecord::Base
|
|
|
61
56
|
```
|
|
62
57
|
|
|
63
58
|
### That's it!
|
|
64
|
-
`audit_trail`
|
|
59
|
+
`audit_trail` logs every transition whose state change the model saves, including the initial state if there is one. An
|
|
60
|
+
audit entry is written by the same `save` that writes the state it records, inside that save's database transaction, so
|
|
61
|
+
the two are written together or not at all:
|
|
62
|
+
|
|
63
|
+
- A transition whose action is `save` (an event method, `state_event` on create or update) is logged by that save. A
|
|
64
|
+
transition generated during the save (e.g. one machine's callback firing another machine's event) is logged by it too.
|
|
65
|
+
- A transition committed without a save (a machine with `action: nil`, `event(false)`) is logged by the next save of the
|
|
66
|
+
record, which is the one that writes its state. So is one made during a save after the row is written (from an
|
|
67
|
+
`after_create` or `after_save`). A transition reloading the record while it runs (`with_lock`, `lock!` in its
|
|
68
|
+
callbacks) is still logged by its save.
|
|
69
|
+
- A transition that is refused, or rolled back, is never logged; once its state change is in place, nothing that runs
|
|
70
|
+
afterwards (a transition's `after:`, an `after_transition` or `around_transition` halting or raising) can drop it.
|
|
71
|
+
- A new record logs `nil => initial state` when it is created, followed by the transitions it went through before or
|
|
72
|
+
while being created: `Subscription.new.start!` logs `nil => waiting`, then `waiting => started`.
|
|
73
|
+
- Entries are written in the order the transitions happened, across all the model's machines.
|
|
74
|
+
- `:if` and `:context` are evaluated when the entry is written. A save that fails or is rolled back (including by an
|
|
75
|
+
enclosing transaction or a savepoint) takes its entries with it, and the next save that writes the state again writes
|
|
76
|
+
them again. Pending transitions belong to the record's attribute set, which is what a save writes: a `clone` or
|
|
77
|
+
`becomes` copy (sharing the attributes) shares them until one of them saves, a `dup` starts without them, and `reload`
|
|
78
|
+
discards them along with the state they set.
|
|
79
|
+
|
|
80
|
+
### Failed audit writes
|
|
81
|
+
|
|
82
|
+
The audit trail is the complete history of a model's state changes, so a state change is never saved without its audit
|
|
83
|
+
entry. If the transition record cannot be written - a validation on your `StateTransition` model, a database constraint -
|
|
84
|
+
the save raises `StateMachines::AuditTrail::RecordNotAudited` (an `ActiveRecord::RecordNotSaved`; `#record` is your
|
|
85
|
+
model, `#audit_record` the invalid transition record), from `save`, `save!` and the event alike. The model's row has
|
|
86
|
+
already been written by then, so the failure has to propagate: it rolls back the save and any transaction enclosing it,
|
|
87
|
+
and the event's state change is rolled back with it.
|
|
65
88
|
|
|
66
89
|
## Upgrading from state_machine-audit_trail
|
|
67
90
|
|
|
@@ -174,7 +197,6 @@ Conversion from the original code to `state_machines` by [AlienFast](http://alie
|
|
|
174
197
|
|
|
175
198
|
### Original Authors
|
|
176
199
|
[The original plugin](https://github.com/wvanbergen/state_machine-audit_trail) was written by Jesse Storimer and Willem van Bergen for Shopify.
|
|
177
|
-
Mongoid support was contributed by [Siddharth](https://github.com/svs).
|
|
178
200
|
|
|
179
201
|
### License
|
|
180
202
|
Released under the MIT license (see LICENSE).
|
data/Rakefile
CHANGED
|
@@ -1,9 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
1
3
|
require 'bundler/gem_tasks'
|
|
2
|
-
require
|
|
4
|
+
require 'rake/testtask'
|
|
5
|
+
require 'shellwords'
|
|
6
|
+
|
|
7
|
+
Rake::TestTask.new(:minitest) do |task|
|
|
8
|
+
task.libs.push 'lib'
|
|
9
|
+
task.libs.push 'test'
|
|
10
|
+
task.pattern = 'test/**/*_test.rb'
|
|
11
|
+
task.verbose = true
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Load Rails tasks from dummy app to get db:test:prepare
|
|
15
|
+
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
|
|
16
|
+
load 'rails/tasks/engine.rake' if File.exist?(APP_RAKEFILE)
|
|
17
|
+
|
|
18
|
+
begin
|
|
19
|
+
# rubocop is only a dependency of the root Gemfile, not of the gemspec or
|
|
20
|
+
# the Appraisal-generated gemfiles/*.gemfile, so it isn't available when
|
|
21
|
+
# running `bundle exec rake` under BUNDLE_GEMFILE=gemfiles/rails_*.gemfile.
|
|
22
|
+
require 'rubocop/rake_task'
|
|
23
|
+
RuboCop::RakeTask.new
|
|
24
|
+
rescue LoadError
|
|
25
|
+
nil
|
|
26
|
+
end
|
|
3
27
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
task
|
|
28
|
+
desc 'Run the test suite (padded_cell on CRuby, plain Minitest elsewhere)'
|
|
29
|
+
if RUBY_ENGINE == 'ruby'
|
|
30
|
+
task :test do
|
|
31
|
+
sh 'padded_cell', *Shellwords.split(ENV.fetch('TESTOPTS', ''))
|
|
32
|
+
end
|
|
33
|
+
else
|
|
34
|
+
task test: :minitest
|
|
7
35
|
end
|
|
8
36
|
|
|
9
|
-
|
|
37
|
+
# rubocop is absent under the Appraisal gemfiles (see above), where the
|
|
38
|
+
# default task is the tests alone
|
|
39
|
+
task default: Rake::Task.task_defined?(:rubocop) ? %i[test rubocop] : :test
|
|
@@ -1,21 +1,80 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
1
3
|
require 'state_machines-activerecord'
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
module StateMachines
|
|
6
|
+
module AuditTrail
|
|
7
|
+
# Raised (from the owner's save, and so from +save+, +save!+ and the event)
|
|
8
|
+
# when an audit row cannot be written. Unlike ActiveRecord::RecordInvalid,
|
|
9
|
+
# which +save+ turns into +false+, it propagates: the owner's row is already
|
|
10
|
+
# written by then, and only a raise rolls back an enclosing transaction the
|
|
11
|
+
# save joined.
|
|
12
|
+
class RecordNotAudited < ::ActiveRecord::RecordNotSaved
|
|
13
|
+
# The audit record that failed its validations
|
|
14
|
+
attr_reader :audit_record
|
|
10
15
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
else
|
|
16
|
-
object.send(@association).create(fields)
|
|
16
|
+
def initialize(owner, audit_record, reason = audit_record.errors.full_messages.to_sentence)
|
|
17
|
+
@audit_record = audit_record
|
|
18
|
+
super("Failed to write the audit trail: #{reason}", owner)
|
|
19
|
+
end
|
|
17
20
|
end
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
class Backend
|
|
23
|
+
class ActiveRecord < StateMachines::AuditTrail::Backend
|
|
24
|
+
def initialize(transition_class, owner_class, options = {})
|
|
25
|
+
super
|
|
26
|
+
@association = transition_class.to_s.tableize.split('/').last.to_sym
|
|
27
|
+
assoc_options = { class_name: transition_class.to_s, dependent: :destroy }.merge(options.slice(:as, :dependent))
|
|
28
|
+
# An STI subclass logs to its base class's transitions (see
|
|
29
|
+
# TransitionAuditing#default_transition_class), keyed like its base
|
|
30
|
+
# class's rows, not by the subclass's name
|
|
31
|
+
assoc_options[:foreign_key] ||= owner_class.base_class.name.foreign_key unless assoc_options[:as]
|
|
32
|
+
owner_class.has_many(@association, **assoc_options) unless owner_class.reflect_on_association(@association)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Inserts the audit record right away; the owner is always persisted by
|
|
36
|
+
# now (TransitionAuditing holds a new record's entries until it is
|
|
37
|
+
# created). The record takes the owner's keys from the association's
|
|
38
|
+
# scope but is never added to the association's target (which
|
|
39
|
+
# +scope.new+ / +build+ would do): a target entry outlives a
|
|
40
|
+
# rolled back owner save as an unsaved record, which the owner's next
|
|
41
|
+
# save would insert with the stale fields. A loaded association is
|
|
42
|
+
# reset so it reads the new row.
|
|
43
|
+
#
|
|
44
|
+
# A record that fails its validations or a database constraint fails
|
|
45
|
+
# the owner's save: the error is reported on the owner and
|
|
46
|
+
# RecordNotAudited raised, rolling back the save and any transaction
|
|
47
|
+
# enclosing it.
|
|
48
|
+
def persist(object, fields)
|
|
49
|
+
fields.delete(:namespace) unless namespace_column_present?(object)
|
|
50
|
+
|
|
51
|
+
association = object.association(@association)
|
|
52
|
+
# Let ActiveRecord manage the timestamp for us so it does the right thing with regards to timezones.
|
|
53
|
+
record = association.klass.new(association.scope.scope_for_create.merge(fields.stringify_keys))
|
|
54
|
+
association.set_inverse_instance(record)
|
|
55
|
+
begin
|
|
56
|
+
saved = record.save
|
|
57
|
+
rescue ::ActiveRecord::StatementInvalid => e
|
|
58
|
+
# A database constraint: raised with the error as its cause
|
|
59
|
+
object.errors.add(@association, :invalid)
|
|
60
|
+
raise RecordNotAudited.new(object, record, e.message)
|
|
61
|
+
end
|
|
62
|
+
unless saved
|
|
63
|
+
object.errors.add(@association, :invalid)
|
|
64
|
+
raise RecordNotAudited.new(object, record)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
association.reset if association.loaded?
|
|
68
|
+
record
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
private
|
|
72
|
+
|
|
73
|
+
# Does the namespace column exist on the transition table for the provided object?
|
|
74
|
+
def namespace_column_present?(object)
|
|
75
|
+
object.class.reflect_on_association(@association).klass.column_names.include?('namespace')
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
20
79
|
end
|
|
21
80
|
end
|
|
@@ -1,77 +1,65 @@
|
|
|
1
|
-
|
|
1
|
+
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
module StateMachines
|
|
4
|
+
module AuditTrail
|
|
5
|
+
Backend = Struct.new(:transition_class, :owner_class, :options) do
|
|
6
|
+
autoload :ActiveRecord, 'state_machines/audit_trail/backend/active_record'
|
|
5
7
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
#
|
|
9
|
+
# Resolve field values and #persist
|
|
10
|
+
# - object: the object being watched by the state_machines observer
|
|
11
|
+
# - transition: state machine transition object that state machine passes to after/before transition callbacks
|
|
12
|
+
#
|
|
13
|
+
def log(object, transition)
|
|
14
|
+
namespace = if transition.machine.presence
|
|
15
|
+
# full transition object
|
|
16
|
+
transition.machine.namespace
|
|
17
|
+
else
|
|
18
|
+
# initial state open struct
|
|
19
|
+
transition.namespace
|
|
20
|
+
end
|
|
21
|
+
fields = { namespace: namespace, event: transition.event&.to_s, from: transition.from,
|
|
22
|
+
to: transition.to }.compact
|
|
23
|
+
[*options[:context]].each do |field|
|
|
24
|
+
fields[field] = resolve_context(object, field, transition)
|
|
25
|
+
end
|
|
12
26
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
namespace = transition.machine.namespace
|
|
16
|
-
else
|
|
17
|
-
# initial state open struct
|
|
18
|
-
namespace = transition.namespace
|
|
19
|
-
end
|
|
20
|
-
fields = {namespace: namespace, event: transition.event ? transition.event.to_s : nil, from: transition.from, to: transition.to}
|
|
21
|
-
[*options[:context]].each { |field|
|
|
22
|
-
fields[field] = resolve_context(object, field, transition)
|
|
23
|
-
}
|
|
27
|
+
persist(object, fields)
|
|
28
|
+
end
|
|
24
29
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
#
|
|
31
|
+
# Creates an instance of the Backend class which does the actual persistence of transition state information.
|
|
32
|
+
# - transition_class: the Class which holds the audit trail
|
|
33
|
+
#
|
|
34
|
+
# To add a new ORM, implement something similar to lib/state_machines/audit_trail/backend/active_record.rb
|
|
35
|
+
# and return from here the appropriate object based on which ORM the transition_class is using
|
|
36
|
+
#
|
|
37
|
+
def self.create_for(transition_class, owner_class, options = {})
|
|
38
|
+
unless Object.const_defined?('ActiveRecord') && transition_class.ancestors.include?(::ActiveRecord::Base)
|
|
39
|
+
raise 'Only ActiveRecord is supported. transition_class must inherit from ActiveRecord::Base.'
|
|
40
|
+
end
|
|
33
41
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
# - transition_class: the Class which holds the audit trail
|
|
37
|
-
#
|
|
38
|
-
# To add a new ORM, implement something similar to lib/state_machines/audit_trail/backend/active_record.rb
|
|
39
|
-
# and return from here the appropriate object based on which ORM the transition_class is using
|
|
40
|
-
#
|
|
41
|
-
def self.create_for(transition_class, owner_class, options = {})
|
|
42
|
-
if Object.const_defined?('ActiveRecord') && transition_class.ancestors.include?(::ActiveRecord::Base)
|
|
43
|
-
return StateMachines::AuditTrail::Backend::ActiveRecord.new(transition_class, owner_class, options)
|
|
44
|
-
elsif Object.const_defined?('Mongoid') && transition_class.ancestors.include?(::Mongoid::Document)
|
|
45
|
-
return StateMachines::AuditTrail::Backend::Mongoid.new(transition_class, owner_class, options)
|
|
46
|
-
else
|
|
47
|
-
raise 'Not implemented. Only support for ActiveRecord and Mongoid is implemented. Pull requests welcome.'
|
|
48
|
-
end
|
|
49
|
-
end
|
|
42
|
+
StateMachines::AuditTrail::Backend::ActiveRecord.new(transition_class, owner_class, options)
|
|
43
|
+
end
|
|
50
44
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
protected
|
|
45
|
+
# Exists in case ORM layer has a different way of answering this question, but works for most.
|
|
46
|
+
def new_record?(object)
|
|
47
|
+
object.new_record?
|
|
48
|
+
end
|
|
57
49
|
|
|
58
|
-
|
|
59
|
-
raise 'Not implemented. Implement in a subclass.'
|
|
60
|
-
end
|
|
50
|
+
protected
|
|
61
51
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
# Don't send params to Rails 5+ associations because it triggers a ton of deprecation messages.
|
|
66
|
-
# @see https://github.com/state-machines/state_machines-audit_trail/issues/6
|
|
67
|
-
# check if activerecord && the context is an association
|
|
68
|
-
skip_args = object.is_a?(::ActiveRecord::Base) && object.class.reflections.keys.include?(context.to_s)
|
|
69
|
-
# ---------------
|
|
52
|
+
def persist(_object, _fields)
|
|
53
|
+
raise 'Not implemented. Implement in a subclass.'
|
|
54
|
+
end
|
|
70
55
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
56
|
+
def resolve_context(object, context, transition)
|
|
57
|
+
if object.method(context).arity.zero?
|
|
58
|
+
object.send(context)
|
|
59
|
+
else
|
|
60
|
+
object.send(context, transition)
|
|
61
|
+
end
|
|
62
|
+
end
|
|
75
63
|
end
|
|
76
64
|
end
|
|
77
65
|
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StateMachines
|
|
4
|
+
module AuditTrail
|
|
5
|
+
# Prepended to StateMachines::TransitionCollection. A transition refused
|
|
6
|
+
# by an exception (e.g. raised from a before callback) gets no refusal and
|
|
7
|
+
# runs no after_failure, so nothing else tells its journal it is over.
|
|
8
|
+
# Once core has unwound the collection, its audited transitions whose
|
|
9
|
+
# state change is not in place are forgotten. Only this collection's
|
|
10
|
+
# transitions: an outer transition whose callback rescues the error is
|
|
11
|
+
# still running and stays noted.
|
|
12
|
+
module CollectionGuard
|
|
13
|
+
def perform(...)
|
|
14
|
+
super
|
|
15
|
+
rescue Exception # rubocop:disable Lint/RescueException -- cleans up, then re-raises whatever it was
|
|
16
|
+
each do |transition|
|
|
17
|
+
Journal.of(transition.object).forget(transition) if transition.machine.audit_trail?
|
|
18
|
+
end
|
|
19
|
+
raise
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StateMachines
|
|
4
|
+
module AuditTrail
|
|
5
|
+
# A record's pending audit entries: every transition started on it (by any
|
|
6
|
+
# audited machine) whose audit row is not committed yet, in the order the
|
|
7
|
+
# transitions started.
|
|
8
|
+
#
|
|
9
|
+
# What a save writes is the record's attribute set (its +@attributes+),
|
|
10
|
+
# and that is what the journal belongs to: it is kept on the attribute set
|
|
11
|
+
# itself, so it lives exactly as long as the set and is shared by every
|
|
12
|
+
# instance holding it - a +clone+, a +becomes+ copy, a record that
|
|
13
|
+
# +reload+ed into the set a find built - while a +dup+ or a freshly built
|
|
14
|
+
# or loaded record gets a set, and so a journal, of its own. Where
|
|
15
|
+
# ActiveRecord gives a record a new set for the same row (see .migrate),
|
|
16
|
+
# the record's entries follow it. A Marshal round trip (e.g. a cache
|
|
17
|
+
# write) drops it.
|
|
18
|
+
class Journal
|
|
19
|
+
# Instance variable holding an attribute set's Journal
|
|
20
|
+
IVAR = :@state_machines_audit_trail
|
|
21
|
+
|
|
22
|
+
# The null => initial entry of a new record
|
|
23
|
+
InitialTransition = Data.define(:namespace, :to) do
|
|
24
|
+
def from = nil
|
|
25
|
+
def event = nil
|
|
26
|
+
def machine = nil
|
|
27
|
+
def args = nil
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# A noted transition, and the database transaction its row was last
|
|
31
|
+
# written in (nil until written)
|
|
32
|
+
class Entry
|
|
33
|
+
attr_reader :transition
|
|
34
|
+
# The database transaction its row was last written in
|
|
35
|
+
attr_accessor :written_in
|
|
36
|
+
|
|
37
|
+
def initialize(transition)
|
|
38
|
+
@transition = transition
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def written?
|
|
42
|
+
!written_in.nil?
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Noted on the record and neither in place nor refused yet
|
|
46
|
+
def running_on?(record)
|
|
47
|
+
transition.object.equal?(record) && !transition.persisted? && transition.refusal.nil?
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Written in a transaction that is still open (neither committed for
|
|
51
|
+
# good nor rolled back)
|
|
52
|
+
def written_row_pending?(transaction_open)
|
|
53
|
+
written? && !written_row_lost? && !written_row_final?(transaction_open)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Whether the transaction its row was written in rolled back (a
|
|
57
|
+
# savepoint's, or one enclosing it), taking the row with it
|
|
58
|
+
def written_row_lost?
|
|
59
|
+
written? && written_in.state.rolledback?
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Whether its row is committed for good: written in a real transaction
|
|
63
|
+
# that committed, or in a savepoint that was released when no
|
|
64
|
+
# transaction is left open (a rollback of an enclosing transaction
|
|
65
|
+
# would have rolled the savepoint back too)
|
|
66
|
+
def written_row_final?(transaction_open)
|
|
67
|
+
return false unless written?
|
|
68
|
+
|
|
69
|
+
state = written_in.state
|
|
70
|
+
state.fully_committed? || (state.committed? && !transaction_open)
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def self.of(record)
|
|
75
|
+
for_attributes(record.instance_variable_get(:@attributes))
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The attribute set a record's attributes live in. Rails main wraps a
|
|
79
|
+
# +becomes+ copy's set in an ActiveModel::ReindexedAttributeSet whose
|
|
80
|
+
# shared side is the original set; the journal is that set's.
|
|
81
|
+
def self.attribute_set(attributes)
|
|
82
|
+
attributes = attributes.instance_variable_get(:@shared) while reindexed?(attributes)
|
|
83
|
+
attributes
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def self.reindexed?(attributes)
|
|
87
|
+
defined?(::ActiveModel::ReindexedAttributeSet) && attributes.is_a?(::ActiveModel::ReindexedAttributeSet)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# A copy of a set (dup, clone - e.g. LazyIndexedAttributeSet#map and
|
|
91
|
+
# #deep_dup on Rails main build theirs with +dup+) is a different set:
|
|
92
|
+
# it must not inherit the journal through its copied instance variables.
|
|
93
|
+
# It gets a fresh, empty one instead, before any freeze: ActiveRecord
|
|
94
|
+
# freezes the clone it gives a destroyed record, and the record's
|
|
95
|
+
# entries must still be able to follow it there (and back, if the
|
|
96
|
+
# destroy rolls back). Prepended to ActiveModel::AttributeSet.
|
|
97
|
+
module CopyGuard
|
|
98
|
+
def initialize_copy(source)
|
|
99
|
+
super
|
|
100
|
+
instance_variable_set(IVAR, Journal.new) if instance_variable_defined?(IVAR)
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def self.guard_copies
|
|
105
|
+
return if ::ActiveModel::AttributeSet <= CopyGuard
|
|
106
|
+
|
|
107
|
+
::ActiveModel::AttributeSet.prepend(CopyGuard)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# A frozen set (a destroyed or frozen record's) cannot take a journal and
|
|
111
|
+
# never writes a transition: it gets a throwaway one
|
|
112
|
+
def self.for_attributes(attributes)
|
|
113
|
+
attributes = attribute_set(attributes)
|
|
114
|
+
attributes.instance_variable_get(IVAR) ||
|
|
115
|
+
(attributes.frozen? ? new : attributes.instance_variable_set(IVAR, new))
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# ActiveRecord replaced the record's attribute set +from+ with +to+ for
|
|
119
|
+
# the same row: in the middle of a save (changes_applied, which runs
|
|
120
|
+
# before the after_save callbacks), on a rollback, on freeze. The
|
|
121
|
+
# entries that are the record's go with it: every state change in place
|
|
122
|
+
# in +from+ (the save under way is writing it, whichever holder ran
|
|
123
|
+
# it), rows already written, and the transitions running on the record
|
|
124
|
+
# itself. Other holders of +from+ (clones) keep only the transitions
|
|
125
|
+
# they are still running; anything they do afterwards is theirs.
|
|
126
|
+
def self.migrate(record, from, to)
|
|
127
|
+
return if from.nil?
|
|
128
|
+
|
|
129
|
+
from = attribute_set(from)
|
|
130
|
+
return if from.equal?(attribute_set(to))
|
|
131
|
+
|
|
132
|
+
old = from.instance_variable_get(IVAR)
|
|
133
|
+
return unless old
|
|
134
|
+
|
|
135
|
+
moving, staying = old.entries.partition do |entry|
|
|
136
|
+
entry.written? || entry.transition.persisted? || entry.transition.object.equal?(record)
|
|
137
|
+
end
|
|
138
|
+
old.entries.replace(staying)
|
|
139
|
+
for_attributes(to).entries.concat(moving)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# A reload gave the record the attribute set a fresh find built, which
|
|
143
|
+
# discards the state changes it had not saved but holds those the
|
|
144
|
+
# database (or a transaction still open) does. The entries that follow
|
|
145
|
+
# it there:
|
|
146
|
+
# * a transition still running on the record (noted, neither in place
|
|
147
|
+
# nor refused yet - e.g. one whose callback takes a lock with
|
|
148
|
+
# +with_lock+ / +lock!+);
|
|
149
|
+
# * one a save under way wrote into its row and still owes a row (a reload
|
|
150
|
+
# from an after_create / after_save running before audit_trail's),
|
|
151
|
+
# including one whose row a nested save wrote and rolled back;
|
|
152
|
+
# * one whose row is written in a transaction still open, which can
|
|
153
|
+
# still roll that row back (and restore the state in memory) - the
|
|
154
|
+
# next save of that state must write it again.
|
|
155
|
+
# Only completed transitions never saved, and rows committed for good
|
|
156
|
+
# (or already lost), stay behind.
|
|
157
|
+
def self.carry_over(record, from, to)
|
|
158
|
+
return if from.nil?
|
|
159
|
+
|
|
160
|
+
from = attribute_set(from)
|
|
161
|
+
return if from.equal?(attribute_set(to))
|
|
162
|
+
|
|
163
|
+
old = from.instance_variable_get(IVAR)
|
|
164
|
+
return unless old
|
|
165
|
+
|
|
166
|
+
saving = Save.owed(record)
|
|
167
|
+
transaction_open = record.class.with_connection(&:transaction_open?)
|
|
168
|
+
running, staying = old.entries.partition do |entry|
|
|
169
|
+
entry.running_on?(record) || saving.include?(entry) || entry.written_row_pending?(transaction_open)
|
|
170
|
+
end
|
|
171
|
+
old.entries.replace(staying)
|
|
172
|
+
for_attributes(to).entries.concat(running)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
attr_reader :entries
|
|
176
|
+
|
|
177
|
+
def initialize
|
|
178
|
+
@entries = []
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# Notes a transition (once, however many copies of the noting callback run)
|
|
182
|
+
def note(transition)
|
|
183
|
+
prune(transition.object.class.with_connection(&:transaction_open?))
|
|
184
|
+
entries << Entry.new(transition) unless entry_for(transition)
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
# Drops the entries that are done: rows committed for good, and
|
|
188
|
+
# transitions core refused (Transition#refusal) whose state change is
|
|
189
|
+
# not in place. A transition still running has no refusal (each perform
|
|
190
|
+
# clears it), so this never drops one that a save happening inside its
|
|
191
|
+
# callbacks would otherwise miss; one refused by an exception is
|
|
192
|
+
# forgotten as the exception leaves its collection (see CollectionGuard).
|
|
193
|
+
def prune(transaction_open)
|
|
194
|
+
entries.reject! do |entry|
|
|
195
|
+
entry.written_row_final?(transaction_open) || (entry.transition.refusal && !entry.transition.persisted?)
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# Drops a refused transition, unless its state change is in place after all
|
|
200
|
+
def forget(transition)
|
|
201
|
+
entries.reject! { |entry| entry.transition.equal?(transition) && !entry.transition.persisted? }
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# The first transition of the named machine whose state change is in place
|
|
205
|
+
def first_persisted(machine_name)
|
|
206
|
+
entries.map(&:transition).find { |transition| transition.machine.name == machine_name && transition.persisted? }
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
def marshal_dump
|
|
210
|
+
nil
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def marshal_load(_)
|
|
214
|
+
@entries = []
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
private
|
|
218
|
+
|
|
219
|
+
def entry_for(transition)
|
|
220
|
+
entries.find { |entry| entry.transition.equal?(transition) }
|
|
221
|
+
end
|
|
222
|
+
end
|
|
223
|
+
end
|
|
224
|
+
end
|