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,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Writes history into live tables: when a proposal is applied, a changeset reverted, a record revived or rebuilt.
5
+ # Records are validated first (Retcon::Invalid if they would be invalid), then written with SQL, so model callbacks
6
+ # with side effects (pushes, emails, geocoding) don't run for changes that are old or reviewed. Subscribe to
7
+ # Retcon's changeset_applied event for side effects that should follow these writes.
8
+ module Projection
9
+ module_function
10
+
11
+ # The digest a live row's versioned fields should have.
12
+ def digest(record)
13
+ fields = record.class.retcon_config.tracked_fields
14
+ Value.digest(fields.to_h { |f| [f, Value.dump(record.read_attribute(f))] })
15
+ end
16
+
17
+ # Sets attributes on a live row. Returns the record.
18
+ def update(model, record_id, attributes, seq:, validate: true)
19
+ record = model.unscoped.find_by(model.primary_key => record_id) or
20
+ raise ActiveRecord::RecordNotFound, "#{model.name} #{record_id} isn't live"
21
+ attributes.each { |field, value| record[field] = Value.load(model, field, value) }
22
+ check!(record) if validate
23
+ Context.writing do
24
+ values = attributes.keys.to_h { |f| [f, record.read_attribute(f)] }
25
+ model.unscoped.where(model.primary_key => record_id)
26
+ .update_all(values.merge(retcon_seq: seq, retcon_digest: digest(record), retcon_dirty: false))
27
+ end
28
+ record
29
+ end
30
+
31
+ # Puts a row back (or in for the first time) with its id. attributes: every column to set.
32
+ def insert(model, record_id, attributes, seq:, validate: true)
33
+ record = model.new
34
+ attributes.each { |field, value| record[field] = Value.load(model, field, value) if model.has_attribute?(field) }
35
+ record[model.primary_key] = record_id
36
+ check!(record) if validate
37
+ values = record.attributes.compact.merge('retcon_seq' => seq, 'retcon_digest' => digest(record),
38
+ 'retcon_dirty' => false)
39
+ Context.writing { model.insert!(values) }
40
+ record
41
+ end
42
+
43
+ def delete(model, record_id)
44
+ Context.writing { model.unscoped.where(model.primary_key => record_id).delete_all }
45
+ end
46
+
47
+ def check!(record)
48
+ Context.replaying { raise Invalid, record unless record.valid? }
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,224 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Proposals: changesets recorded against base versions and applied later, like pull requests.
5
+ #
6
+ # proposal = Retcon.propose(actor: member, message: 'New hours') do |p|
7
+ # p.update(venue, hours: 'Tue–Sun 4pm–2am') # base: the version venue was loaded at
8
+ # p.create(Event, venue_id: venue.id, name: 'Drag Bingo') # id chosen now
9
+ # p.destroy(old_event)
10
+ # end
11
+ # proposal.apply!(committer: reviewer) # Retcon::Conflict if a field moved on
12
+ # proposal.apply!(committer: reviewer, on_conflict: :skip) # applies the rest, returns conflicts
13
+ #
14
+ # A proposal touches no live table until it is applied. Fields conflict only when someone else changed that same
15
+ # field since the proposal's base, to a different value.
16
+ module Proposal
17
+ # Records a proposal's changes.
18
+ class Builder
19
+ attr_reader :rows
20
+
21
+ def initialize
22
+ @rows = Hash.new { |h, model| h[model] = [] }
23
+ end
24
+
25
+ # Proposes new values for record's fields. base: the seq (or {field => seq}) the proposer saw; defaults to
26
+ # the version the record was loaded at. Fields go as a Hash or as keywords: p.update(venue, phone: '555').
27
+ def update(record, attributes = nil, base: nil, **fields)
28
+ attributes ||= fields
29
+ model = record.class
30
+ fields = model.retcon_config.tracked_fields
31
+ attributes.each do |field, value|
32
+ field = field.to_s
33
+ raise ArgumentError, "#{model.name}.#{field} isn't versioned" unless fields.include?(field)
34
+
35
+ rows[model] << { record_id: record.id, op: 'set', field:, value: Value.dump(value),
36
+ base_seq: base_for(record, field, base) }
37
+ end
38
+ record
39
+ end
40
+
41
+ # Proposes a new record, with its id chosen now. Returns the (unsaved) record.
42
+ def create(model, attributes = nil, **fields)
43
+ record = model.new(attributes || fields)
44
+ record[model.primary_key] ||= Proposal.new_id(model)
45
+ rows[model] << { record_id: record.id, op: 'create', field: nil, value: nil, base_seq: nil }
46
+ model.retcon_config.tracked_fields.each do |field|
47
+ value = record.read_attribute(field)
48
+ unless value.nil?
49
+ rows[model] << { record_id: record.id, op: 'set', field:, value: Value.dump(value),
50
+ base_seq: nil }
51
+ end
52
+ end
53
+ record
54
+ end
55
+
56
+ # Proposes deleting a record (a tombstone, applied later).
57
+ def destroy(record)
58
+ rows[record.class] << { record_id: record.id, op: 'tombstone', field: nil, value: nil,
59
+ base_seq: record.attribute_in_database('retcon_seq') }
60
+ record
61
+ end
62
+
63
+ private
64
+
65
+ def base_for(record, field, base)
66
+ case base
67
+ when Hash then base[field] || base[field.to_sym]
68
+ when Integer then base
69
+ else record.attribute_in_database('retcon_seq')
70
+ end
71
+ end
72
+ end
73
+
74
+ module_function
75
+
76
+ def build(actor:, message:, scope:, metadata:, parent: nil, author: actor, committer: nil)
77
+ builder = Builder.new
78
+ yield builder
79
+ raise ArgumentError, 'the proposal changes nothing' if builder.rows.values.all?(&:empty?)
80
+
81
+ ActiveRecord::Base.transaction(requires_new: true) do
82
+ changeset = Changeset.create!(author:, committer:, parent:, kind: 'proposal', state: 'proposed', message:,
83
+ scope:, metadata:)
84
+ builder.rows.each { |model, rows| write_proposed(model, changeset, rows) }
85
+ Retcon.instrument(:proposal_opened, changeset:)
86
+ changeset
87
+ end
88
+ end
89
+
90
+ def write_proposed(model, changeset, rows)
91
+ # Values are already dumped; History.write dumps again, which leaves dumped values as they are.
92
+ model.retcon_history.write(changeset, rows, applied: false)
93
+ end
94
+
95
+ def amend(original, by:, message:)
96
+ raise InvalidState, "changeset #{original.id} is #{original.state}, not proposed" unless original.proposed?
97
+
98
+ builder = Builder.new
99
+ original.versions.each do |v|
100
+ builder.rows[v.live_model] << { record_id: v.record_id, op: v.op, field: v.field, value: v.raw_value,
101
+ base_seq: v.base_seq }
102
+ end
103
+ yield builder if block_given?
104
+ ActiveRecord::Base.transaction(requires_new: true) do
105
+ amended = Changeset.create!(author: original.author, committer: by, parent: original, kind: 'proposal',
106
+ state: 'proposed', message:, scope: original.scope, metadata: original.metadata)
107
+ builder.rows.each { |model, rows| write_proposed(model, amended, dedupe(rows)) }
108
+ original.update!(state: 'amended', committer: by, decided_at: Time.current)
109
+ Retcon.instrument(:proposal_opened, changeset: amended)
110
+ amended
111
+ end
112
+ end
113
+
114
+ # The last row for each (record, op, field) wins: an amendment's own update replaces the original's.
115
+ def dedupe(rows) = rows.reverse.uniq { |r| [r[:record_id], r[:op], r[:field]] }.reverse
116
+
117
+ # Applies a proposed changeset. Returns { changeset:, conflicts: [FieldConflict] }.
118
+ def apply(changeset, committer:, on_conflict:)
119
+ ActiveRecord::Base.transaction(requires_new: true) do
120
+ changeset.lock!
121
+ raise InvalidState, "changeset #{changeset.id} is #{changeset.state}, not proposed" unless changeset.proposed?
122
+
123
+ plan = plan(changeset)
124
+ conflicts = plan.flat_map { |step| step[:conflicts] }
125
+ raise Conflict, conflicts if conflicts.any? && on_conflict == :raise
126
+
127
+ seq = Retcon.next_seq
128
+ changeset.update!(state: 'applied', committer:, applied_seq: seq, applied_at: Time.current,
129
+ decided_at: Time.current)
130
+ plan.each { |step| apply_step(changeset, step, seq) }
131
+ changeset.update!(metadata: changeset.metadata.merge('skipped' => conflicts.map(&:to_h))) if conflicts.any?
132
+ Retcon.instrument(:changeset_applied, changeset:)
133
+ { changeset:, conflicts: }
134
+ end
135
+ end
136
+
137
+ # What applying does to each record: [{model:, record_id:, rows:, conflicts:}].
138
+ def plan(changeset)
139
+ changeset.versions.group_by { |v| [v.live_model, v.record_id] }.map do |(model, record_id), rows|
140
+ rows.sort_by!(&:id)
141
+ if model.unscoped.exists?(model.primary_key => record_id)
142
+ Drift.lock_and_catch_up(model.unscoped.find(record_id))
143
+ end
144
+ heads = model.retcon_history.heads(record_id)
145
+ conflicts = []
146
+ merged = {}
147
+ rows.each do |v|
148
+ next unless v.op == 'set'
149
+
150
+ head = heads[v.field]
151
+ next if head.nil? || v.base_seq.nil? || head.seq <= v.base_seq || Value.same?(head.value, v.raw_value)
152
+
153
+ if (value = merge_value(model, v.field, head.value, v.raw_value))
154
+ merged[v.field] = value
155
+ next
156
+ end
157
+
158
+ conflicts << FieldConflict.new(model: model.name, record_id:, field: v.field, base_seq: v.base_seq,
159
+ head_seq: head.seq, current: head.value, proposed: v.raw_value)
160
+ end
161
+ { model:, record_id:, rows:, conflicts:, heads:, merged: }
162
+ end
163
+ end
164
+
165
+ # The value a field merges to instead of conflicting, per its merge strategy (nil: it conflicts). :set_union keeps
166
+ # every element either side has, so two people tagging a venue both get their tags.
167
+ def merge_value(model, field, current, proposed)
168
+ return unless model.retcon_config.merges[field] == :set_union && current.is_a?(Array) && proposed.is_a?(Array)
169
+
170
+ current | proposed
171
+ end
172
+
173
+ def apply_step(changeset, step, seq)
174
+ model = step[:model]
175
+ record_id = step[:record_id]
176
+ skipped = step[:conflicts].map(&:field)
177
+ rows = step[:rows].reject { |v| v.op == 'set' && skipped.include?(v.field) }
178
+ ops = rows.map(&:op)
179
+ sets = rows.select { |v| v.op == 'set' }.to_h { |v| [v.field, v.raw_value] }.merge(step[:merged])
180
+
181
+ if ops.include?('tombstone')
182
+ apply_tombstone(model, record_id, rows.find { |v| v.op == 'tombstone' })
183
+ elsif ops.include?('create')
184
+ Projection.insert(model, record_id, sets, seq:)
185
+ elsif sets.any?
186
+ Projection.update(model, record_id, sets, seq:)
187
+ end
188
+ model.retcon_history.where(id: rows.map(&:id)).update_all(applied: true, seq:)
189
+ # Skipped fields stay unapplied in the applied changeset, so history shows what was proposed and not taken.
190
+ write_merged(changeset, step)
191
+ end
192
+
193
+ # Deletes the live row and keeps it, as it is now, in the tombstone row's snapshot.
194
+ def apply_tombstone(model, record_id, tombstone)
195
+ record = model.unscoped.find_by(model.primary_key => record_id)
196
+ snapshot = record ? record.attributes.except(*LIVE_COLUMNS).transform_values { |v| Value.dump(v) } : {}
197
+ Projection.delete(model, record_id)
198
+ model.retcon_history.where(id: tombstone.id).update_all(value: snapshot)
199
+ end
200
+
201
+ # A merged field gets one more version, after the proposed one, holding what live now has.
202
+ def write_merged(changeset, step)
203
+ rows = step[:merged].map do |field, value|
204
+ { record_id: step[:record_id], op: 'set', field:, value:, base_seq: step[:heads][field]&.seq }
205
+ end
206
+ step[:model].retcon_history.write(changeset, rows, applied: true)
207
+ changeset
208
+ end
209
+
210
+ # An id for a record that doesn't exist yet: a UUID, or the table's sequence.
211
+ def new_id(model)
212
+ column = model.columns_hash[model.primary_key]
213
+ return SecureRandom.uuid if column.type == :uuid
214
+
215
+ sequence = model.connection.select_value(
216
+ "SELECT pg_get_serial_sequence(#{model.connection.quote(model.table_name)}, " \
217
+ "#{model.connection.quote(model.primary_key)})"
218
+ )
219
+ raise Error, "#{model.name} has no id sequence to propose a new record with" unless sequence
220
+
221
+ model.connection.select_value("SELECT nextval(#{model.connection.quote(sequence)})").to_i
222
+ end
223
+ end
224
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Removing what history must not keep (privacy requests, DMCA, the right to be forgotten). The one place Retcon
5
+ # changes history rows: it deletes their value and salt and keeps the commitment, so history still verifies but the
6
+ # value is gone and a short one (a phone number) can't be guessed back from the commitment.
7
+ #
8
+ # Retcon::Redaction.field(venue, :phone, actor: staff, reason: 'privacy request', remedy: nil)
9
+ # Retcon::Redaction.editor(actor, by: staff, reason: 'account deleted')
10
+ # Retcon::Redaction.erase(actor, by: deletion_job, reason: 'deletion request')
11
+ #
12
+ # Every redaction is a changeset (kind redaction) recording who, when, why and which rows: never what.
13
+ module Redaction
14
+ KEEP = Object.new.freeze
15
+
16
+ module_function
17
+
18
+ # Scrubs a field's values from every version (applied or proposed) of a record and from its tombstone
19
+ # snapshots. value: only versions holding this value (default: every version). remedy: the live value afterwards
20
+ # (written as a new version, so a rebuild lands on it); Redaction::KEEP leaves live alone (when the live value
21
+ # is already clean). Returns the redaction changeset.
22
+ def field(record, field, actor:, reason:, value: KEEP, remedy: nil)
23
+ model = record.class
24
+ field = field.to_s
25
+ Retcon.changeset(actor:, kind: 'redaction', message: 'Redaction') do
26
+ changeset = Context.open.changeset(scope: model.retcon_config.scope_for(record))
27
+ history = model.retcon_history
28
+ rows = history.where(record_id: record.id, field:, op: 'set', redacted_by_id: nil)
29
+ rows = rows.to_a.select { |r| Value.same?(r.raw_value, value) } unless value.equal?(KEEP)
30
+ ids = rows.map(&:id)
31
+ history.where(id: ids).update_all(value: nil, salt: nil, redacted_by_id: changeset.id)
32
+ snapshots = history.where(record_id: record.id, op: 'tombstone').where('value ? :f', f: field)
33
+ snapshots.update_all(['value = value - ?', field])
34
+ unless remedy.equal?(KEEP)
35
+ heads = history.heads(record.id)
36
+ if model.unscoped.exists?(model.primary_key => record.id)
37
+ Projection.update(model, record.id, { field => remedy }, seq: changeset.applied_seq, validate: false)
38
+ end
39
+ history.write(changeset, [{ record_id: record.id, op: 'set', field:, value: remedy,
40
+ base_seq: heads[field]&.seq }], applied: true)
41
+ end
42
+ changeset.update!(metadata: { 'reason' => reason, 'table' => model.table_name, 'record_id' => record.id,
43
+ 'field' => field, 'version_ids' => ids, 'snapshots' => snapshots.count })
44
+ Retcon.instrument(:redacted, changeset:)
45
+ end
46
+ end
47
+
48
+ # Replaces an editor's identity with a pseudonym. Their edits stay, grouped under the pseudonym for audit and
49
+ # revert.
50
+ def editor(target, by:, reason:)
51
+ target = Actor.resolve(target)
52
+ Retcon.changeset(actor: by, kind: 'redaction', message: 'Editor redaction',
53
+ metadata: { 'reason' => reason, 'actor_id' => target.id }) do
54
+ Context.open.changeset
55
+ target.pseudonymize!
56
+ end
57
+ end
58
+
59
+ # An automated personal deletion request: reverts the requester's own changes, scrubs the values they wrote,
60
+ # and pseudonymizes them. Anything else that may hold their data (later edits by others to the same fields)
61
+ # comes back as a review proposal instead of being touched: a request can't wipe other people's work.
62
+ # Returns the Revert::Result with the redaction changeset added: { revert:, review:, flagged:, redaction: }.
63
+ def erase(target, by:, reason:)
64
+ target = Actor.resolve(target)
65
+ ActiveRecord::Base.transaction(requires_new: true) do
66
+ result = Retcon.revert_actor(target, actor: by, message: 'Revert for deletion request')
67
+ redaction = Retcon.changeset(actor: by, kind: 'redaction', message: 'Deletion request',
68
+ metadata: { 'reason' => reason, 'actor_id' => target.id }) do
69
+ changeset = Context.open.changeset
70
+ authored = Changeset.where(author_id: target.id).select(:id)
71
+ Retcon.models.each_value do |model|
72
+ model.retcon_history.where(changeset_id: authored, op: 'set', redacted_by_id: nil)
73
+ .update_all(value: nil, salt: nil, redacted_by_id: changeset.id)
74
+ end
75
+ target.pseudonymize!
76
+ end
77
+ result.to_h.merge(redaction:)
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Reverts changesets the way an interactive rebase drops commits, without rewriting history: one new revert
5
+ # changeset puts back what the dropped changesets replaced, and later work by others stays.
6
+ #
7
+ # For each field the dropped changesets set:
8
+ # - if a dropped changeset wrote its current value, it goes back to the newest value nobody dropped wrote (nil if
9
+ # none);
10
+ # - if someone else changed it afterwards, their value stays, and a proposal to restore the earlier value goes to
11
+ # review (same-field overlap).
12
+ # Records the dropped changesets created are tombstoned, records they tombstoned are revived. Committers who
13
+ # applied a dropped changeset someone else wrote are flagged, for whoever cleans up.
14
+ #
15
+ # result = Retcon.revert_actor(vandal, actor: staff)
16
+ # result.revert # the applied revert changeset (nil if nothing to undo)
17
+ # result.review # a proposal with the overlaps (nil if none)
18
+ # result.flagged # [Actor] who approved the vandal's proposals
19
+ class Revert
20
+ Result = Data.define(:revert, :review, :flagged)
21
+
22
+ def initialize(changesets, actor:, message: nil)
23
+ @targets = changesets.select(&:applied?)
24
+ @ids = @targets.map(&:id)
25
+ @actor = actor
26
+ @message = message || "Revert #{@ids.map { |i| "##{i}" }.join(', ')}"
27
+ end
28
+
29
+ def run
30
+ return Result.new(revert: nil, review: nil, flagged: []) if @targets.empty?
31
+
32
+ review_rows = Hash.new { |h, k| h[k] = [] }
33
+ revert = Retcon.changeset(actor: @actor, message: @message, kind: 'revert',
34
+ metadata: { 'reverts' => @ids }) do
35
+ Retcon.models.each_value { |model| revert_model(model, review_rows) }
36
+ end
37
+ review = review_proposal(revert, review_rows)
38
+ Retcon.instrument(:revert_conflict, changeset: review) if review
39
+ Result.new(revert:, review:, flagged:)
40
+ end
41
+
42
+ # Puts a tombstoned record back into its live table, inside changeset.
43
+ def self.revive(model, record_id, changeset)
44
+ raise Error, "#{model.name} #{record_id} is live" if model.unscoped.exists?(model.primary_key => record_id)
45
+
46
+ history = model.retcon_history
47
+ tomb = history.applied.where(record_id:, op: 'tombstone').order(seq: :desc, id: :desc).first or
48
+ raise Error, "#{model.name} #{record_id} was never tombstoned"
49
+ attributes = (tomb.value || {}).merge(history.heads(record_id).transform_values(&:value))
50
+ Projection.insert(model, record_id, attributes, seq: changeset.applied_seq)
51
+ history.write(changeset, [{ record_id:, op: 'revive', field: nil, value: nil, base_seq: tomb.seq }],
52
+ applied: true)
53
+ end
54
+
55
+ private
56
+
57
+ def revert_model(model, review_rows)
58
+ history = model.retcon_history
59
+ touched = history.applied.where(changeset_id: @ids).distinct.pluck(:record_id)
60
+ touched.each { |record_id| revert_record(model, record_id, review_rows) }
61
+ end
62
+
63
+ def revert_record(model, record_id, review_rows)
64
+ history = model.retcon_history
65
+ changeset = Context.open.changeset
66
+ rows = history.applied.where(record_id:).order(:seq, :id).to_a
67
+ life = rows.select { |r| History::LIFECYCLE.include?(r.op) }.last
68
+
69
+ if life && @ids.include?(life.changeset_id)
70
+ case life.op
71
+ when 'create', 'revive'
72
+ return tombstone(model, record_id, changeset) if model.unscoped.exists?(model.primary_key => record_id)
73
+ when 'tombstone'
74
+ Revert.revive(model, record_id, changeset)
75
+ end
76
+ end
77
+ return unless model.unscoped.exists?(model.primary_key => record_id)
78
+
79
+ restore_fields(model, record_id, rows, changeset, review_rows)
80
+ end
81
+
82
+ def restore_fields(model, record_id, rows, changeset, review_rows)
83
+ sets = rows.select { |r| r.op == 'set' }.group_by(&:field)
84
+ restore = {}
85
+ sets.each do |field, versions|
86
+ dropped = versions.select { |v| @ids.include?(v.changeset_id) }
87
+ next if dropped.empty?
88
+
89
+ kept = versions.reject { |v| @ids.include?(v.changeset_id) }
90
+ head = versions.last
91
+ if @ids.include?(head.changeset_id)
92
+ restore[field] = kept.last&.raw_value
93
+ else
94
+ earlier = kept.select { |v| v.seq < dropped.first.seq }.last&.raw_value
95
+ next if Value.same?(earlier, head.raw_value)
96
+
97
+ review_rows[model] << { record_id:, op: 'set', field:, value: earlier, base_seq: head.seq }
98
+ end
99
+ end
100
+ return if restore.empty?
101
+
102
+ heads = model.retcon_history.heads(record_id)
103
+ Projection.update(model, record_id, restore, seq: changeset.applied_seq, validate: false)
104
+ model.retcon_history.write(changeset, restore.map do |field, value|
105
+ { record_id:, op: 'set', field:, value:, base_seq: heads[field]&.seq }
106
+ end, applied: true)
107
+ end
108
+
109
+ def tombstone(model, record_id, changeset)
110
+ record = model.unscoped.find(record_id)
111
+ snapshot = record.attributes.except(*LIVE_COLUMNS).transform_values { |v| Value.dump(v) }
112
+ Projection.delete(model, record_id)
113
+ model.retcon_history.write(changeset, [{ record_id:, op: 'tombstone', field: nil, value: snapshot,
114
+ base_seq: record.retcon_seq }], applied: true)
115
+ end
116
+
117
+ def review_proposal(revert, review_rows)
118
+ return nil if review_rows.values.all?(&:empty?)
119
+
120
+ Proposal.build(actor: @actor, message: "Review overlaps left by #{revert ? "revert ##{revert.id}" : 'a revert'}",
121
+ scope: nil, metadata: { 'reverts' => @ids, 'revert_id' => revert&.id }, parent: revert) do |b|
122
+ review_rows.each { |model, rows| b.rows[model].concat(rows) }
123
+ end
124
+ end
125
+
126
+ def flagged
127
+ @targets.select { |c| c.committer_id && c.committer_id != c.author_id }.map(&:committer).uniq
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # Migration helpers, available in migrations as Retcon::Schema methods (include it, or call
5
+ # Retcon::Schema.install(self)):
6
+ #
7
+ # class InstallRetcon < ActiveRecord::Migration[8.0]
8
+ # include Retcon::Schema
9
+ #
10
+ # def change
11
+ # create_retcon_tables # retcon_actors, retcon_changesets, the retcon_seq sequence
12
+ # version_table :venues # retcon_venues history + live columns + the dirty trigger
13
+ # end
14
+ # end
15
+ module Schema
16
+ # The history table for a live table.
17
+ def self.history_table(table) = "retcon_#{table}"
18
+
19
+ def create_retcon_tables
20
+ reversible do |dir|
21
+ dir.up { execute 'CREATE SEQUENCE IF NOT EXISTS retcon_seq' }
22
+ dir.down { execute 'DROP SEQUENCE IF EXISTS retcon_seq' }
23
+ end
24
+
25
+ create_table :retcon_actors do |t|
26
+ t.string :kind, null: false, comment: 'user, device, import, research, system, untracked or agent'
27
+ t.string :ref_type, comment: 'The record this actor stands for (User, a device grant); null once redacted'
28
+ t.string :ref_id
29
+ t.string :name, comment: 'A display name, for imports and systems; null once redacted'
30
+ t.string :pseudonym, comment: 'Shown instead of the actor once redacted'
31
+ t.references :on_behalf_of, foreign_key: { to_table: :retcon_actors }, comment: 'Who an agent acts for'
32
+ t.datetime :redacted_at
33
+ t.timestamps
34
+ end
35
+ add_index :retcon_actors, %i[kind ref_type ref_id name on_behalf_of_id], unique: true, nulls_not_distinct: true,
36
+ where: 'redacted_at IS NULL',
37
+ name: 'index_retcon_actors_identity'
38
+
39
+ create_table :retcon_changesets do |t|
40
+ t.string :kind, null: false, default: 'edit',
41
+ comment: 'edit, proposal, genesis, catch_up, revert, redaction, merge or import'
42
+ t.string :state, null: false, default: 'applied',
43
+ comment: 'applied, proposed, rejected, withdrawn, amended or superseded'
44
+ t.string :scope, comment: 'The tenant it belongs to (an audience, say); policy decides what it means'
45
+ t.references :author, null: false, foreign_key: { to_table: :retcon_actors }
46
+ t.references :committer, foreign_key: { to_table: :retcon_actors }, comment: 'Who applied or decided it'
47
+ t.references :parent, foreign_key: { to_table: :retcon_changesets }, comment: 'Amended or grouped under'
48
+ t.bigint :applied_seq, comment: 'Its place in the order of application (retcon_seq)'
49
+ t.text :message
50
+ t.jsonb :metadata, null: false, default: {}
51
+ t.datetime :applied_at
52
+ t.datetime :decided_at
53
+ t.timestamps
54
+ end
55
+ add_index :retcon_changesets, :applied_seq, unique: true
56
+ add_index :retcon_changesets, %i[state scope]
57
+ end
58
+
59
+ # Versions a live table: creates its history table, adds the live columns Retcon keeps, and installs the trigger
60
+ # that marks rows written outside Retcon as dirty. id_type: the live table's primary key type.
61
+ def version_table(table, id_type: nil)
62
+ id_type ||= primary_key_type(table)
63
+ history = Schema.history_table(table)
64
+ create_table history do |t|
65
+ t.bigint :changeset_id, null: false
66
+ t.column :record_id, id_type, null: false
67
+ t.string :op, null: false, comment: 'set, create, tombstone or revive'
68
+ t.string :field, comment: 'For set: the field'
69
+ t.jsonb :value, comment: 'set: {"v": value}; tombstone: the row as it was; null once redacted'
70
+ t.string :salt, comment: 'Random salt of the commitment; null once redacted'
71
+ t.string :commitment, comment: 'SHA-256 of salt and value, kept after redaction'
72
+ t.boolean :applied, null: false, default: false
73
+ t.bigint :seq, comment: 'retcon_seq when applied'
74
+ t.bigint :base_seq, comment: 'The field head the change was made against'
75
+ t.integer :schema_version, null: false, default: 1
76
+ t.bigint :redacted_by_id, comment: 'The redaction changeset that scrubbed this value'
77
+ t.datetime :created_at, null: false
78
+ end
79
+ add_foreign_key history, :retcon_changesets, column: :changeset_id
80
+ add_index history, %i[record_id field seq], name: "index_#{history}_head"
81
+ add_index history, :changeset_id
82
+ add_index history, :value, using: :gin, opclass: :jsonb_path_ops, where: "op = 'tombstone'",
83
+ name: "index_#{history}_tombstones"
84
+
85
+ add_column table, :retcon_seq, :bigint
86
+ add_column table, :retcon_digest, :string
87
+ add_column table, :retcon_dirty, :boolean, null: false, default: false
88
+ add_index table, :retcon_dirty, where: 'retcon_dirty'
89
+ add_retcon_dirty_trigger(table)
90
+ end
91
+
92
+ # A trigger that sets retcon_dirty on rows inserted or updated without Retcon (insert_all, update_all, SQL, the
93
+ # console), so Retcon::Drift only has to look at those rows.
94
+ def add_retcon_dirty_trigger(table)
95
+ function = "retcon_mark_dirty_#{table}"
96
+ reversible do |dir|
97
+ dir.up do
98
+ execute <<~SQL.squish
99
+ CREATE OR REPLACE FUNCTION #{function}() RETURNS trigger AS $$
100
+ BEGIN
101
+ IF current_setting('retcon.writing', true) IS DISTINCT FROM 'on' THEN
102
+ NEW.retcon_dirty := true;
103
+ END IF;
104
+ RETURN NEW;
105
+ END $$ LANGUAGE plpgsql
106
+ SQL
107
+ execute "CREATE TRIGGER #{function} BEFORE INSERT OR UPDATE ON #{quote_table_name(table)} " \
108
+ "FOR EACH ROW EXECUTE FUNCTION #{function}()"
109
+ end
110
+ dir.down do
111
+ execute "DROP TRIGGER IF EXISTS #{function} ON #{quote_table_name(table)}"
112
+ execute "DROP FUNCTION IF EXISTS #{function}()"
113
+ end
114
+ end
115
+ end
116
+
117
+ private
118
+
119
+ def primary_key_type(table)
120
+ pk = connection.primary_key(table) || 'id'
121
+ column = connection.columns(table).find { |c| c.name == pk }
122
+ column&.type || :bigint
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Retcon
4
+ # How field values are kept in history: as JSON (dates, times and decimals as strings, geometries as WKT), read back
5
+ # through the attribute's type. Also the salted commitments that survive redaction and the row digest drift checks
6
+ # compare.
7
+ module Value
8
+ module_function
9
+
10
+ # A value as history keeps it.
11
+ def dump(value)
12
+ case value
13
+ when nil, true, false, String, Integer, Float then value
14
+ when BigDecimal then value.to_s
15
+ when Hash then value.transform_keys(&:to_s).transform_values { |v| dump(v) }
16
+ when Array then value.map { |v| dump(v) }
17
+ else value.respond_to?(:as_text) ? value.as_text : value.as_json
18
+ end
19
+ end
20
+
21
+ # A kept value read back for an attribute of model.
22
+ def load(model, field, dumped) = model.type_for_attribute(field.to_s).cast(dumped)
23
+
24
+ def same?(left, right) = canonical(left) == canonical(right)
25
+
26
+ def canonical(value) = JSON.generate(sort(dump(value)))
27
+
28
+ def salt = SecureRandom.hex(16)
29
+
30
+ # The commitment to a value: SHA-256 over the salt and the value's canonical JSON. Redaction deletes value and
31
+ # salt and keeps this, so history still verifies but short values can't be guessed from it.
32
+ def commit(salt, value) = Digest::SHA256.hexdigest("#{salt}:#{canonical(value)}")
33
+
34
+ # A digest of a live row's versioned fields, for drift checks: no salt, cheap to compute.
35
+ def digest(fields) = Digest::SHA256.hexdigest(canonical(fields.sort.to_h))[0, 32]
36
+
37
+ def sort(value)
38
+ case value
39
+ when Hash then value.sort.to_h { |k, v| [k, sort(v)] }
40
+ when Array then value.map { |v| sort(v) }
41
+ else value
42
+ end
43
+ end
44
+ end
45
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Retcon
4
- VERSION = '0.0.1'
4
+ VERSION = '0.1.0'
5
5
  end