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.
data/lib/retcon.rb CHANGED
@@ -1,9 +1,196 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'active_record'
4
+ require 'active_support/concern'
5
+ require 'active_support/notifications'
6
+ require 'securerandom'
7
+ require 'digest'
8
+ require 'json'
9
+ require 'pg'
3
10
  require 'retcon/version'
4
11
 
5
- # VCS-style history for Active Record: field-level versions, changesets, proposals and reverts, with live tables kept
6
- # as a fast projection of history. This release reserves the name; nothing is implemented yet. See README.md.
12
+ # VCS-style history for Active Record on PostgreSQL.
13
+ #
14
+ # Every versioned table gets a history table of immutable field-level versions. Live tables stay where they are and
15
+ # stay as fast as they were: they are a projection of history, written in the same transaction, and can be rebuilt
16
+ # from it. Changes are grouped in changesets with an actor; a proposal is a changeset that hasn't been applied yet.
17
+ #
18
+ # class Venue < ApplicationRecord
19
+ # include Retcon::Model
20
+ # end
21
+ #
22
+ # Retcon.as(current_user) { venue.update!(name: 'The Eagle') } # an applied changeset, attributed
23
+ # proposal = Retcon.propose(actor: member) { |p| p.update(venue, phone: '555-0100') }
24
+ # proposal.apply!(committer: reviewer) # or reject!, amend
25
+ # Retcon.revert_actor(vandal, actor: staff) # drops their changes, keeps later work
26
+ #
27
+ # See README.md and docs/.
7
28
  module Retcon
8
29
  class Error < StandardError; end
30
+ # A model or table isn't set up for Retcon (missing history table or columns).
31
+ class NotVersioned < Error; end
32
+ # A changeset can't move to the state asked for (applying a rejected proposal, say).
33
+ class InvalidState < Error; end
34
+ # The policy refused a change.
35
+ class Denied < Error; end
36
+
37
+ # Fields changed by someone else since the base version the edit started from.
38
+ class Conflict < Error
39
+ attr_reader :conflicts
40
+
41
+ # conflicts: [Retcon::FieldConflict, ...]
42
+ def initialize(conflicts)
43
+ @conflicts = conflicts
44
+ fields = conflicts.map { |c| "#{c.model}##{c.record_id}.#{c.field}" }.join(', ')
45
+ super("changed since the base version: #{fields}")
46
+ end
47
+ end
48
+
49
+ # A record would be invalid after applying a changeset to it.
50
+ class Invalid < Error
51
+ attr_reader :record
52
+
53
+ def initialize(record)
54
+ @record = record
55
+ super("#{record.class.name} #{record.id} is invalid: #{record.errors.full_messages.join(', ')}")
56
+ end
57
+ end
58
+
59
+ # One field that conflicts: what the edit expected (its base), what is there now, and what the edit wanted.
60
+ FieldConflict = Data.define(:model, :record_id, :field, :base_seq, :head_seq, :current, :proposed)
61
+
62
+ autoload :Actor, 'retcon/actor'
63
+ autoload :Bulk, 'retcon/bulk'
64
+ autoload :Changeset, 'retcon/changeset'
65
+ autoload :Config, 'retcon/config'
66
+ autoload :Context, 'retcon/context'
67
+ autoload :Drift, 'retcon/drift'
68
+ autoload :Edge, 'retcon/edge'
69
+ autoload :History, 'retcon/history'
70
+ autoload :Model, 'retcon/model'
71
+ autoload :Projection, 'retcon/projection'
72
+ autoload :Proposal, 'retcon/proposal'
73
+ autoload :Redaction, 'retcon/redaction'
74
+ autoload :Revert, 'retcon/revert'
75
+ autoload :Schema, 'retcon/schema'
76
+ autoload :Value, 'retcon/value'
77
+
78
+ # Columns Retcon keeps on every versioned live table.
79
+ LIVE_COLUMNS = %w[retcon_seq retcon_digest retcon_dirty].freeze
80
+
81
+ class << self
82
+ # Decides whether an edit made with Retcon.edit commits, becomes a proposal or is refused:
83
+ # Retcon.policy = ->(actor, record, changes) { actor.trusted? ? :commit : :propose }
84
+ # changes: {field => [from, to]}. Returns :commit, :propose or :deny. Defaults to :commit.
85
+ attr_writer :policy
86
+
87
+ def policy = @policy || ->(_actor, _record, _changes) { :commit }
88
+
89
+ # Whether saves with no actor set (Retcon.as) are allowed; they are attributed to Actor.system. Defaults to true.
90
+ attr_writer :allow_unattributed
91
+
92
+ def allow_unattributed? = @allow_unattributed.nil? || @allow_unattributed
93
+
94
+ # Runs the block with actor as the author of every change made in it. actor: an Actor, or any record (a User,
95
+ # a device), which gets an Actor of its own. on_behalf_of: who an agent acts for.
96
+ def as(actor, on_behalf_of: nil, &)
97
+ Context.with(actor: Actor.resolve(actor, on_behalf_of:), &)
98
+ end
99
+
100
+ # The actor changes are attributed to right now (nil outside Retcon.as).
101
+ def actor = Context.actor
102
+
103
+ # Groups every change made in the block into one applied changeset, in one database transaction. Returns the
104
+ # Changeset (nil if nothing changed).
105
+ def changeset(actor: nil, message: nil, scope: nil, kind: 'edit', metadata: {}, &)
106
+ Context.changeset(actor: actor && Actor.resolve(actor), message:, scope:, kind:, metadata:, &)
107
+ end
108
+
109
+ # Opens a proposal: the block gets a Proposal::Builder to record updates, creates and destroys without touching
110
+ # live tables. Returns the proposed Changeset.
111
+ def propose(actor: Context.actor, message: nil, scope: nil, metadata: {}, &)
112
+ Proposal.build(actor: Actor.resolve(actor || raise(ArgumentError, 'a proposal needs an actor')),
113
+ message:, scope:, metadata:, &)
114
+ end
115
+
116
+ # Edits a record through the policy: commits, opens a proposal, or raises Denied. Returns the Changeset.
117
+ def edit(record, attributes, actor: Context.actor, message: nil, base: nil)
118
+ actor = Actor.resolve(actor || raise(ArgumentError, 'an edit needs an actor'))
119
+ record.assign_attributes(attributes)
120
+ changes = record.changes_to_save.slice(*record.class.retcon_config.tracked_fields)
121
+ decision = policy.call(actor, record, changes)
122
+ case decision
123
+ when :commit
124
+ record.retcon_base = base if base
125
+ changeset(actor:, message:) { record.save! }
126
+ when :propose
127
+ record.restore_attributes(changes.keys)
128
+ propose(actor:, message:) { |p| p.update(record, changes.transform_values(&:last), base:) }
129
+ when :deny then raise Denied, "#{actor.label} may not change #{record.class.name} #{record.id}"
130
+ else raise ArgumentError, "policy returned #{decision.inspect}, not :commit, :propose or :deny"
131
+ end
132
+ end
133
+
134
+ # Reverts changesets: see Retcon::Revert.
135
+ def revert(changesets, actor:, message: nil)
136
+ Revert.new(Array(changesets), actor: Actor.resolve(actor),
137
+ message:).run
138
+ end
139
+
140
+ # Reverts every applied changeset an actor authored (since a time, in a scope): see Retcon::Revert.
141
+ def revert_actor(target, actor:, since: nil, scope: nil, message: nil)
142
+ target = Actor.resolve(target)
143
+ sets = Changeset.applied.where(author_id: target.id).where.not(kind: %w[revert redaction])
144
+ sets = sets.where(applied_at: since..) if since
145
+ sets = sets.where(scope:) if scope
146
+ revert(sets.to_a, actor:, message: message || "Revert changes by #{target.label}")
147
+ end
148
+
149
+ # Writes in the block skip history (bulk fixes, migrations). The dirty trigger still marks the rows, so the next
150
+ # Retcon::Drift sweep records them as untracked changes; use Retcon::Bulk to keep attribution instead.
151
+ def bypass
152
+ before = Context.state[:bypass]
153
+ Context.state[:bypass] = true
154
+ yield
155
+ ensure
156
+ Context.state[:bypass] = before
157
+ end
158
+
159
+ # Checks that history rebuilds the live rows: compares a sample of live rows' versioned fields with what history
160
+ # says. Returns mismatches as [[record_id, field, live, history], ...]; empty means they agree.
161
+ def verify(model, sample: 100)
162
+ model.unscoped.order(Arel.sql('random()')).limit(sample).flat_map do |record|
163
+ state = model.retcon_state(record.id)
164
+ next [[record.id, nil, 'live', 'no history']] if state.nil? || !state['exists']
165
+
166
+ model.retcon_config.tracked_fields.filter_map do |field|
167
+ live = Value.dump(record.read_attribute(field))
168
+ kept = state['attributes'][field]
169
+ [record.id, field, live, kept] unless Value.same?(live, kept)
170
+ end
171
+ end
172
+ end
173
+
174
+ # Runs the block with model callbacks for side effects told it is a replay (approval, revert, rebuild).
175
+ def replaying? = Context.replaying?
176
+
177
+ # Publishes an event (proposal_opened, changeset_applied, proposal_rejected, revert_conflict, redacted) as
178
+ # "<name>.retcon" through ActiveSupport::Notifications.
179
+ def instrument(name, payload = {}) = ActiveSupport::Notifications.instrument("#{name}.retcon", payload)
180
+
181
+ # Subscribes to a Retcon event: Retcon.on(:proposal_opened) { |changeset| route(changeset) }.
182
+ def on(name, &block)
183
+ ActiveSupport::Notifications.subscribe("#{name}.retcon") { |*, payload| block.call(payload[:changeset]) }
184
+ end
185
+
186
+ # Every model that includes Retcon::Model, by name.
187
+ def models = @models ||= {}
188
+
189
+ def model_for(name) = models[name.to_s] || name.to_s.constantize
190
+
191
+ def connection = ActiveRecord::Base.connection
192
+
193
+ # The next number in Retcon's global order of application.
194
+ def next_seq = connection.select_value("SELECT nextval('retcon_seq')").to_i
195
+ end
9
196
  end
metadata CHANGED
@@ -1,19 +1,47 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: retcon
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Love Wins Media, Inc.
8
8
  bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
- dependencies: []
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activerecord
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: pg
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '1.5'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '1.5'
12
40
  description: 'Field-level version history for Active Record models, kept in per-table
13
41
  history tables with live tables as a fast projection: changesets with full attribution,
14
42
  proposals reviewed before they apply, field-level conflicts, tombstones instead
15
43
  of deletes, reverts of one actor''s changes that keep later good work, and redaction.
16
- Early release: the name is reserved and the design is in review.'
44
+ PostgreSQL.'
17
45
  executables: []
18
46
  extensions: []
19
47
  extra_rdoc_files: []
@@ -21,7 +49,34 @@ files:
21
49
  - CHANGELOG.md
22
50
  - LICENSE.txt
23
51
  - README.md
52
+ - docs/01-getting-started.md
53
+ - docs/02-models.md
54
+ - docs/03-changesets-and-actors.md
55
+ - docs/04-conflicts.md
56
+ - docs/05-proposals.md
57
+ - docs/06-reverts.md
58
+ - docs/07-drift.md
59
+ - docs/08-redaction.md
60
+ - docs/09-edges.md
61
+ - docs/10-schema-evolution.md
62
+ - docs/11-internals.md
63
+ - docs/12-reference.md
24
64
  - lib/retcon.rb
65
+ - lib/retcon/actor.rb
66
+ - lib/retcon/bulk.rb
67
+ - lib/retcon/changeset.rb
68
+ - lib/retcon/config.rb
69
+ - lib/retcon/context.rb
70
+ - lib/retcon/drift.rb
71
+ - lib/retcon/edge.rb
72
+ - lib/retcon/history.rb
73
+ - lib/retcon/model.rb
74
+ - lib/retcon/projection.rb
75
+ - lib/retcon/proposal.rb
76
+ - lib/retcon/redaction.rb
77
+ - lib/retcon/revert.rb
78
+ - lib/retcon/schema.rb
79
+ - lib/retcon/value.rb
25
80
  - lib/retcon/version.rb
26
81
  homepage: https://github.com/lwm-luminx/retcon
27
82
  licenses:
@@ -30,6 +85,7 @@ metadata:
30
85
  rubygems_mfa_required: 'true'
31
86
  source_code_uri: https://github.com/lwm-luminx/retcon
32
87
  changelog_uri: https://github.com/lwm-luminx/retcon/blob/main/CHANGELOG.md
88
+ documentation_uri: https://lwm-luminx.github.io/retcon/
33
89
  bug_tracker_uri: https://github.com/lwm-luminx/retcon/issues
34
90
  rdoc_options: []
35
91
  require_paths: