retcon 0.0.1 → 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,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Per-thread (per-fiber, through ActiveSupport::IsolatedExecutionState) state: the actor, the changeset being
5
+ # written, and whether Retcon is replaying history into live tables.
6
+ module Context
7
+ # An open changeset: created on the first write, so a block that changes nothing leaves no changeset behind.
8
+ class Open
9
+ attr_reader :actor, :message, :scope, :kind, :metadata
10
+
11
+ def initialize(actor:, message:, scope:, kind:, metadata:)
12
+ @actor = actor
13
+ @message = message
14
+ @scope = scope
15
+ @kind = kind
16
+ @metadata = metadata
17
+ end
18
+
19
+ def changeset(scope: nil)
20
+ @changeset ||= Changeset.create!(author: actor, kind:, message:, scope: @scope || scope, metadata:,
21
+ state: 'applied', applied_seq: Retcon.next_seq, applied_at: Time.current)
22
+ end
23
+
24
+ def created = @changeset
25
+
26
+ def seq = changeset.applied_seq
27
+ end
28
+
29
+ module_function
30
+
31
+ def state = ActiveSupport::IsolatedExecutionState[:retcon] ||= {}
32
+
33
+ def actor = state[:actor]
34
+
35
+ def with(actor:)
36
+ before = state[:actor]
37
+ state[:actor] = actor
38
+ yield
39
+ ensure
40
+ state[:actor] = before
41
+ end
42
+
43
+ def open = state[:open]
44
+
45
+ # Runs the block in a transaction with an open changeset (joining the one already open, if any). Returns the
46
+ # Changeset written, or nil.
47
+ def changeset(actor:, message:, scope:, kind:, metadata:, &)
48
+ run(actor:, message:, scope:, kind:, metadata:, &).last
49
+ end
50
+
51
+ # The changeset a save writes into: the open one, or a new one around the block. Returns the block's value, so
52
+ # save, save! and destroy keep returning what Active Record returns.
53
+ def implicit(&)
54
+ return yield if open
55
+
56
+ run(actor: nil, message: nil, scope: nil, kind: 'edit', metadata: {}, &).first
57
+ end
58
+
59
+ # [block's value, Changeset written or nil].
60
+ def run(actor:, message:, scope:, kind:, metadata:)
61
+ return [yield, open.created] if open
62
+
63
+ actor ||= self.actor || fallback_actor
64
+ opened = Open.new(actor:, message:, scope:, kind:, metadata:)
65
+ result = nil
66
+ ActiveRecord::Base.transaction(requires_new: true) do
67
+ state[:open] = opened
68
+ result = yield
69
+ ensure
70
+ state[:open] = nil
71
+ end
72
+ [result, opened.created]
73
+ end
74
+
75
+ def fallback_actor
76
+ raise Error, 'no actor: wrap changes in Retcon.as(actor) { ... }' unless Retcon.allow_unattributed?
77
+
78
+ Actor.system
79
+ end
80
+
81
+ def replaying? = state[:replaying] == true
82
+
83
+ def replaying
84
+ before = state[:replaying]
85
+ state[:replaying] = true
86
+ yield
87
+ ensure
88
+ state[:replaying] = before
89
+ end
90
+
91
+ # Tells the dirty trigger that the writes in the block are Retcon's own.
92
+ def writing(connection = Retcon.connection)
93
+ connection.execute("SELECT set_config('retcon.writing', 'on', true)")
94
+ yield
95
+ ensure
96
+ begin
97
+ connection.execute("SELECT set_config('retcon.writing', 'off', true)") if connection.transaction_open?
98
+ rescue ActiveRecord::StatementInvalid
99
+ nil # the transaction is failing anyway; the setting ends with it
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Finds live rows written outside Retcon (insert_all, update_all, update_column, raw SQL, the console) and writes
5
+ # them into history as catch-up changesets attributed to Actor.untracked, so nothing builds on a change history
6
+ # doesn't know. Rows are found three ways: the dirty flag the trigger sets (cheap, the default), a digest of every
7
+ # row's versioned fields (full: true), and history that says a row exists when the live table has none (a delete
8
+ # outside Retcon). Rows with no history at all are pre-Retcon data: they get genesis changesets instead.
9
+ module Drift
10
+ module_function
11
+
12
+ # Locks the live row for the rest of the transaction and catches it up if it was written outside Retcon. Called
13
+ # before every update and destroy.
14
+ def lock_and_catch_up(record)
15
+ model = record.class
16
+ seq, dirty = model.unscoped.lock.where(model.primary_key => record.id).pick(:retcon_seq, :retcon_dirty)
17
+ return unless dirty || seq.nil?
18
+
19
+ catch_up(model, [record.id])
20
+ end
21
+
22
+ # Writes what changed outside Retcon for these ids in one changeset (genesis for rows history hasn't seen).
23
+ # Returns the changesets written.
24
+ def catch_up(model, ids, actor: Actor.untracked)
25
+ live = model.unscoped.where(model.primary_key => ids).index_by(&:id)
26
+ fresh, known = ids.partition { |id| model.retcon_history.state(id).nil? }
27
+ written = []
28
+ written << write(model, fresh.filter_map { |id| live[id] }, kind: 'genesis',
29
+ actor: Actor.named('import', 'genesis'))
30
+ written << write(model, known.filter_map { |id| live[id] }, kind: 'catch_up', actor:)
31
+ gone = known.reject { |id| live.key?(id) }
32
+ written << tombstone_missing(model, gone, actor:) if gone.any?
33
+ written.compact.tap { renumber_open(written.compact) }
34
+ end
35
+
36
+ # Catches up every dirty row (or, with full, every row whose digest differs) and every row deleted outside
37
+ # Retcon. Returns the number of rows caught up.
38
+ def sweep(model, full: false, batch_size: 500)
39
+ count = 0
40
+ scope = model.unscoped.where(retcon_dirty: true).or(model.unscoped.where(retcon_seq: nil))
41
+ scope.in_batches(of: batch_size) do |batch|
42
+ ids = batch.pluck(model.primary_key)
43
+ model.transaction { catch_up(model, ids) }
44
+ count += ids.size
45
+ end
46
+ count += sweep_digests(model, batch_size) if full
47
+ count + sweep_deleted(model)
48
+ end
49
+
50
+ # Writes genesis changesets for rows with no history, a batch per changeset.
51
+ def genesis(model, batch_size:, actor:)
52
+ count = 0
53
+ model.unscoped.where(retcon_seq: nil).in_batches(of: batch_size) do |batch|
54
+ model.transaction { write(model, batch.to_a, kind: 'genesis', actor:) }
55
+ count += batch.size
56
+ end
57
+ count
58
+ end
59
+
60
+ def sweep_digests(model, batch_size)
61
+ count = 0
62
+ model.unscoped.find_in_batches(batch_size:) do |records|
63
+ drifted = records.reject { |r| r.retcon_digest == Projection.digest(r) }
64
+ next if drifted.empty?
65
+
66
+ model.transaction { catch_up(model, drifted.map(&:id)) }
67
+ count += drifted.size
68
+ end
69
+ count
70
+ end
71
+
72
+ def sweep_deleted(model)
73
+ history = model.retcon_history
74
+ alive = history.applied.where(op: History::LIFECYCLE)
75
+ .select('DISTINCT ON (record_id) record_id, op')
76
+ .order(:record_id, seq: :desc, id: :desc)
77
+ ids = history.connection.select_values("SELECT record_id FROM (#{alive.to_sql}) l WHERE op <> 'tombstone'")
78
+ ids = ids.map { |id| model.type_for_attribute(model.primary_key).cast(id) }
79
+ gone = ids - model.unscoped.where(model.primary_key => ids).pluck(model.primary_key)
80
+ return 0 if gone.empty?
81
+
82
+ model.transaction { tombstone_missing(model, gone, actor: Actor.untracked) }
83
+ gone.size
84
+ end
85
+
86
+ # One changeset with set rows for the fields of records that differ from history (every field, for genesis),
87
+ # and the live rows' Retcon columns brought up to date.
88
+ def write(model, records, kind:, actor:)
89
+ return nil if records.empty?
90
+
91
+ changeset = Changeset.create!(author: actor, kind:, state: 'applied', applied_seq: Retcon.next_seq,
92
+ applied_at: Time.current, message: kind == 'genesis' ? 'Genesis' : 'Untracked')
93
+ fields = model.retcon_config.tracked_fields
94
+ rows = records.flat_map { |record| rows_for(model, record, fields, kind) }
95
+ model.retcon_history.write(changeset, rows, applied: true)
96
+ records.each do |record|
97
+ Context.writing do
98
+ model.unscoped.where(model.primary_key => record.id)
99
+ .update_all(retcon_seq: changeset.applied_seq, retcon_digest: Projection.digest(record),
100
+ retcon_dirty: false)
101
+ end
102
+ end
103
+ changeset
104
+ end
105
+
106
+ def rows_for(model, record, fields, kind)
107
+ state = kind == 'genesis' ? nil : model.retcon_history.state(record.id)
108
+ rows = []
109
+ if state.nil?
110
+ rows << { record_id: record.id, op: 'create', field: nil, value: nil, base_seq: nil }
111
+ elsif !state['exists']
112
+ rows << { record_id: record.id, op: 'revive', field: nil, value: nil, base_seq: state['seq'] }
113
+ end
114
+ heads = state ? model.retcon_history.heads(record.id) : {}
115
+ fields.each do |field|
116
+ value = record.read_attribute(field)
117
+ next if state.nil? && value.nil?
118
+ next if state && Value.same?(heads[field]&.value, value)
119
+
120
+ rows << { record_id: record.id, op: 'set', field:, value:, base_seq: heads[field]&.seq }
121
+ end
122
+ rows
123
+ end
124
+
125
+ def tombstone_missing(model, ids, actor:)
126
+ changeset = Changeset.create!(author: actor, kind: 'catch_up', state: 'applied', applied_seq: Retcon.next_seq,
127
+ applied_at: Time.current, message: 'Deleted outside Retcon')
128
+ rows = ids.map do |id|
129
+ attributes = model.retcon_history.state(id)&.dig('attributes') || {}
130
+ { record_id: id, op: 'tombstone', field: nil, value: attributes, base_seq: nil }
131
+ end
132
+ model.retcon_history.write(changeset, rows, applied: true)
133
+ changeset
134
+ end
135
+
136
+ # A changeset already open in this transaction was given its seq before the catch-up; move it after, so history
137
+ # orders the catch-up before the edit that follows it.
138
+ def renumber_open(written)
139
+ changeset = Context.open&.created
140
+ return if written.empty? || changeset.nil?
141
+
142
+ old = changeset.applied_seq
143
+ seq = Retcon.next_seq
144
+ changeset.update_columns(applied_seq: seq)
145
+ Retcon.models.each_value do |m|
146
+ m.retcon_history.where(changeset_id: changeset.id).update_all(seq:)
147
+ Context.writing { m.unscoped.where(retcon_seq: old).update_all(retcon_seq: seq) }
148
+ end
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Edges as versioned rows: semantic triples (subject, predicate, object) whose identity is the triple, kept unique
5
+ # by an index. Removing an edge tombstones it like any record; linking the same triple again revives that row, with
6
+ # its id and its whole history, instead of starting a new one.
7
+ #
8
+ # class EntityLink < ApplicationRecord
9
+ # include Retcon::Edge
10
+ # retcon_triple subject: %i[item_type item_id], predicate: :predicate, object: %i[target_type target_id],
11
+ # discriminator: :slot # optional: lets one triple appear more than once
12
+ # end
13
+ #
14
+ # EntityLink.link!(episode, :recorded_at, event, status: 'linked') # creates, updates or revives
15
+ # EntityLink.unlink!(episode, :recorded_at, event) # tombstones
16
+ #
17
+ # Because removed edges leave the live table, graph_query (and any other reader) walks only live edges.
18
+ module Edge
19
+ extend ActiveSupport::Concern
20
+
21
+ included do
22
+ include Retcon::Model
23
+ end
24
+
25
+ class_methods do
26
+ # Names the columns that hold the subject, predicate and object. A polymorphic end is [type_column, id_column];
27
+ # a plain end is an id column (its records' class is then taken as given).
28
+ def retcon_triple(subject:, predicate:, object:, discriminator: nil)
29
+ @retcon_triple = { subject: Array(subject).map(&:to_s), predicate: predicate.to_s,
30
+ object: Array(object).map(&:to_s), discriminator: discriminator&.to_s }
31
+ end
32
+
33
+ def retcon_triple_columns
34
+ @retcon_triple or raise Error, "#{name} has no retcon_triple"
35
+ end
36
+
37
+ # The identifying attributes of a triple: { 'item_type' => 'MediaEpisode', 'item_id' => ..., ... }.
38
+ def retcon_identity(subject, predicate, object, discriminator: nil)
39
+ cols = retcon_triple_columns
40
+ attrs = end_attributes(cols[:subject], subject).merge(cols[:predicate] => predicate.to_s)
41
+ .merge(end_attributes(cols[:object], object))
42
+ attrs[cols[:discriminator]] = discriminator if cols[:discriminator]
43
+ attrs.to_h { |col, value| [col, type_for_attribute(col).cast(value)] }
44
+ end
45
+
46
+ # Makes sure the edge exists with these attributes: updates a live one, revives a removed one (keeping its id
47
+ # and history), or creates it. Attributes go as a Hash or as keywords. Returns the record.
48
+ def link!(subject, predicate, object, attributes = nil, discriminator: nil, **fields)
49
+ attributes ||= fields
50
+ identity = retcon_identity(subject, predicate, object, discriminator:)
51
+ Context.implicit do
52
+ record = unscoped.find_by(identity)
53
+ unless record
54
+ tomb = retcon_history.tombstone_matching(identity)
55
+ record = tomb ? retcon_revive!(tomb.record_id) : new(identity)
56
+ end
57
+ record.assign_attributes(attributes)
58
+ record.save! if record.new_record? || record.changed?
59
+ record
60
+ end
61
+ end
62
+
63
+ # Removes the edge (a tombstone). Returns the removed record, or nil when there was none.
64
+ def unlink!(subject, predicate, object, discriminator: nil)
65
+ record = unscoped.find_by(retcon_identity(subject, predicate, object, discriminator:))
66
+ record&.destroy!
67
+ end
68
+
69
+ private
70
+
71
+ def end_attributes(columns, node)
72
+ if columns.size == 2
73
+ { columns[0] => node.class.polymorphic_name, columns[1] => node.id }
74
+ else
75
+ { columns[0] => node.respond_to?(:id) ? node.id : node }
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # A versioned table's history: immutable rows, one per field set (op 'set') or lifecycle step ('create',
5
+ # 'tombstone', 'revive'), each in a changeset. Rows of applied changesets carry seq, their place in Retcon's global
6
+ # order of application; a proposal's rows wait with applied false until it is applied. Only redaction ever changes a
7
+ # row, and only to scrub its value and salt.
8
+ module History
9
+ LIFECYCLE = %w[create tombstone revive].freeze
10
+
11
+ # The current value of a field: its newest applied version.
12
+ Head = Data.define(:field, :seq, :value, :redacted, :row_id)
13
+
14
+ # The class for a model's history table (retcon_<table>).
15
+ def self.for(model)
16
+ table = Schema.history_table(model.table_name)
17
+ klass = Class.new(Base) do
18
+ self.table_name = table
19
+ @live_model = model
20
+ end
21
+ model.const_set(:RetconHistory, klass)
22
+ end
23
+
24
+ # Shared behavior of every history class.
25
+ class Base < ActiveRecord::Base
26
+ self.abstract_class = true
27
+
28
+ belongs_to :changeset, class_name: 'Retcon::Changeset'
29
+
30
+ scope :applied, -> { where(applied: true) }
31
+ scope :in_order, -> { order(:seq, :id) }
32
+
33
+ class << self
34
+ attr_reader :live_model
35
+
36
+ def config = live_model.retcon_config
37
+
38
+ # Writes version rows: [{record_id:, op:, field:, value:, base_seq:}, ...] into changeset. applied rows get
39
+ # the changeset's seq.
40
+ def write(changeset, rows, applied:)
41
+ return if rows.empty?
42
+
43
+ now = Time.current
44
+ version = config.schema_version
45
+ insert_all!(rows.map do |row|
46
+ salt = row[:op] == 'set' ? Value.salt : nil
47
+ value = row[:op] == 'set' ? { 'v' => Value.dump(row[:value]) } : row[:value]
48
+ { changeset_id: changeset.id, record_id: row[:record_id], op: row[:op], field: row[:field], value:,
49
+ salt:, commitment: salt && Value.commit(salt, value['v']), applied:,
50
+ seq: applied ? changeset.applied_seq : nil, base_seq: row[:base_seq], schema_version: version,
51
+ created_at: now }
52
+ end)
53
+ end
54
+
55
+ # {field => Head} for a record, upcast to the current schema. Only applied rows count.
56
+ def heads(record_id)
57
+ rows = applied.where(record_id:, op: 'set')
58
+ .select('DISTINCT ON (field) id, op, field, value, seq, schema_version, redacted_by_id')
59
+ .order(:field, seq: :desc, id: :desc).to_a
60
+ heads = {}
61
+ rows.each do |row|
62
+ row.current_pairs.each do |field, value|
63
+ next if heads[field] && heads[field].seq > row.seq
64
+
65
+ heads[field] = Head.new(field:, seq: row.seq, value:, redacted: row.redacted?, row_id: row.id)
66
+ end
67
+ end
68
+ heads
69
+ end
70
+
71
+ # The newest applied lifecycle row (create, tombstone or revive), or nil.
72
+ def lifecycle(record_id)
73
+ applied.where(record_id:, op: LIFECYCLE).order(seq: :desc, id: :desc).first
74
+ end
75
+
76
+ # Whether history says the record exists (created or revived, and not since tombstoned).
77
+ def alive?(record_id) = %w[create revive].include?(lifecycle(record_id)&.op)
78
+
79
+ # The record as history says it is: { 'exists' => bool, 'seq' => newest seq, 'attributes' => {...} }, or nil
80
+ # when history has never seen it.
81
+ def state(record_id)
82
+ life = lifecycle(record_id)
83
+ heads = heads(record_id)
84
+ return nil if life.nil? && heads.empty?
85
+
86
+ fields = heads.slice(*config.tracked_fields).transform_values(&:value)
87
+ seq = [life&.seq, *heads.values.map(&:seq)].compact.max
88
+ { 'exists' => life.nil? || life.op != 'tombstone', 'seq' => seq, 'attributes' => fields }
89
+ end
90
+
91
+ # The newest tombstone whose snapshot contains these attributes (for reviving an edge by its triple).
92
+ def tombstone_matching(attributes)
93
+ applied.where(op: 'tombstone').where('value @> ?', Value.dump(attributes).to_json)
94
+ .order(seq: :desc, id: :desc).first
95
+ end
96
+ end
97
+
98
+ def live_model = self.class.live_model
99
+
100
+ def redacted? = redacted_by_id.present?
101
+
102
+ # This row's value as written (nil once redacted).
103
+ def raw_value = op == 'set' ? value&.fetch('v', nil) : value
104
+
105
+ # [[field, value], ...] under the current schema (an upcaster may rename, split or drop the field).
106
+ def current_pairs
107
+ return [[field, raw_value]] if schema_version >= self.class.config.schema_version
108
+
109
+ self.class.config.upcast_value(field, raw_value, schema_version)
110
+ end
111
+
112
+ def current_value = current_pairs.first&.last
113
+
114
+ # Whether the stored commitment matches the value (always true once redacted: nothing left to check).
115
+ def verified?
116
+ return true if redacted? || op != 'set'
117
+
118
+ Value.commit(salt, raw_value) == commitment
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Versions an Active Record model. Every save and destroy writes history in the same transaction as the live row,
5
+ # into the open changeset (Retcon.changeset) or one of its own, attributed to Retcon.as's actor.
6
+ #
7
+ # class Venue < ApplicationRecord
8
+ # include Retcon::Model
9
+ # versioned { ignore :view_count }
10
+ # end
11
+ #
12
+ # Before an update, Retcon locks the live row, catches up any change written outside Retcon (Retcon::Drift), then
13
+ # checks each changed field against the version the record was loaded at (or retcon_base): a field someone else
14
+ # changed since raises Retcon::Conflict, or with retcon_on_conflict = :skip is left out and listed in
15
+ # retcon_conflicts. Destroys write a tombstone with the row as it was; the live row is deleted, so reads never see
16
+ # it, and Model.retcon_revive! brings it back with its id and history.
17
+ module Model
18
+ extend ActiveSupport::Concern
19
+
20
+ # Wraps whole saves and destroys, so autosaved and dependent records join the same changeset.
21
+ module Grouping
22
+ %i[save save! destroy destroy!].each do |name|
23
+ define_method(name) do |*args, **kwargs, &block|
24
+ return super(*args, **kwargs, &block) if Context.replaying? || Context.state[:bypass]
25
+
26
+ Context.implicit { super(*args, **kwargs, &block) }
27
+ end
28
+ end
29
+ end
30
+
31
+ included do
32
+ prepend Grouping
33
+
34
+ Retcon.models[name] = self if name
35
+
36
+ # Per-field base versions for the next save: {field => seq}, or one seq for every field.
37
+ attr_writer :retcon_base
38
+ # :raise (the default) or :skip, for fields that conflict on the next save.
39
+ attr_writer :retcon_on_conflict
40
+ # The FieldConflicts left out of the last save (with retcon_on_conflict = :skip).
41
+ attr_reader :retcon_conflicts
42
+
43
+ around_save :retcon_around_save
44
+ around_destroy :retcon_around_destroy
45
+ end
46
+
47
+ class_methods do
48
+ def retcon_config = @retcon_config ||= Config.new(self)
49
+
50
+ # Sets versioning options: see Retcon::Config.
51
+ def versioned(&)
52
+ retcon_config.instance_eval(&)
53
+ retcon_config.reset!
54
+ self
55
+ end
56
+
57
+ def retcon_history = @retcon_history ||= History.for(self)
58
+
59
+ # The record as history says it is (see History.state).
60
+ def retcon_state(record_id) = retcon_history.state(record_id)
61
+
62
+ # Brings back a tombstoned record with its id: the row as it was, with each field's newest version. Returns
63
+ # the record. Done as a changeset of its own (or in the open one).
64
+ def retcon_revive!(record_id, actor: Retcon.actor, message: nil)
65
+ Retcon.changeset(actor:, message: message || "Revive #{name} #{record_id}") do
66
+ Revert.revive(self, record_id, Context.open.changeset(scope: nil))
67
+ end
68
+ unscoped.find(record_id)
69
+ end
70
+
71
+ # Rewrites a live row from history (inserting, updating or deleting it). Returns what history says.
72
+ def retcon_rebuild!(record_id)
73
+ state = retcon_state(record_id) or raise Error, "#{name} #{record_id} has no history"
74
+ live = unscoped.exists?(primary_key => record_id)
75
+ if !state['exists']
76
+ Projection.delete(self, record_id) if live
77
+ elsif live
78
+ Projection.update(self, record_id, state['attributes'], seq: state['seq'], validate: false)
79
+ else
80
+ snapshot = retcon_history.applied.where(record_id:, op: 'tombstone').order(seq: :desc).first&.value || {}
81
+ Projection.insert(self, record_id, snapshot.merge(state['attributes']), seq: state['seq'], validate: false)
82
+ end
83
+ state
84
+ end
85
+
86
+ # Rows written outside Retcon, caught up into history: see Retcon::Drift.
87
+ def retcon_sweep!(full: false, batch_size: 500) = Drift.sweep(self, full:, batch_size:)
88
+
89
+ # Writes Retcon columns without history for rows that have none (run before the first sweep, or let the sweep
90
+ # do it as genesis changesets).
91
+ def retcon_genesis!(batch_size: 500, actor: Actor.named('import', 'genesis'))
92
+ Drift.genesis(self, batch_size:, actor:)
93
+ end
94
+ end
95
+
96
+ # Every version row of this record, oldest first (proposals included; check #applied).
97
+ def retcon_versions = self.class.retcon_history.where(record_id: id).order(Arel.sql('seq NULLS LAST'), :id)
98
+
99
+ # {field => Head} with the newest applied version of each field: who changed it last and when (blame).
100
+ def retcon_heads = self.class.retcon_history.heads(id)
101
+
102
+ # Whether the live row's versioned fields differ from what Retcon last wrote (a write outside Retcon).
103
+ def retcon_drifted?
104
+ row = self.class.unscoped.where(self.class.primary_key => id).pick(:retcon_dirty, :retcon_digest)
105
+ row.nil? || row[0] || row[1] != Projection.digest(self.class.unscoped.find(id))
106
+ end
107
+
108
+ def retcon_base = @retcon_base
109
+
110
+ def retcon_on_conflict = @retcon_on_conflict || :raise
111
+
112
+ private
113
+
114
+ def retcon_skip? = Context.replaying? || Context.state[:bypass]
115
+
116
+ def retcon_around_save(&)
117
+ return yield if retcon_skip?
118
+
119
+ new_record? ? retcon_create(&) : retcon_update(&)
120
+ end
121
+
122
+ def retcon_create(&)
123
+ changeset = Context.open.changeset(scope: self.class.retcon_config.scope_for(self))
124
+ self.retcon_seq = changeset.applied_seq
125
+ self.retcon_digest = Projection.digest(self)
126
+ self.retcon_dirty = false
127
+ result = Context.writing(&)
128
+ fields = self.class.retcon_config.tracked_fields
129
+ rows = [{ record_id: id, op: 'create', field: nil, value: nil, base_seq: nil }]
130
+ fields.each do |field|
131
+ value = read_attribute(field)
132
+ rows << { record_id: id, op: 'set', field:, value:, base_seq: nil } unless value.nil?
133
+ end
134
+ self.class.retcon_history.write(changeset, rows, applied: true)
135
+ retcon_fix_digest
136
+ result
137
+ end
138
+
139
+ def retcon_update(&)
140
+ tracked = self.class.retcon_config.tracked_fields
141
+ return yield if changes_to_save.slice(*tracked).empty?
142
+
143
+ Drift.lock_and_catch_up(self)
144
+ heads = self.class.retcon_history.heads(id)
145
+ retcon_check_conflicts(heads, tracked)
146
+ changed = changes_to_save.slice(*tracked)
147
+ return yield if changed.empty?
148
+
149
+ changeset = Context.open.changeset(scope: self.class.retcon_config.scope_for(self))
150
+ self.retcon_seq = changeset.applied_seq
151
+ self.retcon_digest = Projection.digest(self)
152
+ self.retcon_dirty = false
153
+ result = Context.writing(&)
154
+ rows = saved_changes.slice(*tracked).map do |field, (_from, to)|
155
+ { record_id: id, op: 'set', field:, value: to, base_seq: heads[field]&.seq }
156
+ end
157
+ self.class.retcon_history.write(changeset, rows, applied: true)
158
+ retcon_fix_digest
159
+ @retcon_base = nil
160
+ result
161
+ end
162
+
163
+ def retcon_around_destroy(&)
164
+ return yield if retcon_skip?
165
+
166
+ Drift.lock_and_catch_up(self)
167
+ snapshot = attributes.except(*LIVE_COLUMNS).transform_values { |v| Value.dump(v) }
168
+ row = { record_id: id, op: 'tombstone', field: nil, value: snapshot, base_seq: retcon_seq_in_database }
169
+ changeset = Context.open.changeset(scope: self.class.retcon_config.scope_for(self))
170
+ result = Context.writing(&)
171
+ self.class.retcon_history.write(changeset, [row], applied: true)
172
+ result
173
+ end
174
+
175
+ # Fields changed since this record's base: raise, or (on_conflict :skip) put them back and list them.
176
+ def retcon_check_conflicts(heads, tracked)
177
+ @retcon_conflicts = []
178
+ changes_to_save.slice(*tracked).each do |field, (_from, to)|
179
+ head = heads[field]
180
+ base = retcon_base_for(field)
181
+ next if head.nil? || base.nil? || head.seq <= base || Value.same?(head.value, Value.dump(to))
182
+ # Without an explicit base, an editor who loaded the row after the change saw it: nothing of theirs is lost.
183
+ next if @retcon_base.nil? && Value.same?(head.value, Value.dump(attribute_in_database(field)))
184
+
185
+ @retcon_conflicts << FieldConflict.new(model: self.class.name, record_id: id, field:, base_seq: base,
186
+ head_seq: head.seq, current: head.value, proposed: Value.dump(to))
187
+ end
188
+ return if @retcon_conflicts.empty?
189
+ raise Conflict, @retcon_conflicts unless retcon_on_conflict == :skip
190
+
191
+ @retcon_conflicts.each { |c| restore_attributes([c.field]) }
192
+ end
193
+
194
+ def retcon_base_for(field)
195
+ case @retcon_base
196
+ when Hash then @retcon_base[field] || @retcon_base[field.to_sym] || attribute_in_database('retcon_seq')
197
+ when Integer then @retcon_base
198
+ else attribute_in_database('retcon_seq')
199
+ end
200
+ end
201
+
202
+ # App callbacks inside the save may have changed versioned fields after the digest was taken.
203
+ def retcon_fix_digest
204
+ digest = Projection.digest(self)
205
+ return if digest == retcon_digest
206
+
207
+ Context.writing { update_columns(retcon_digest: digest) }
208
+ end
209
+ end
210
+ end