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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +18 -0
- data/README.md +67 -21
- data/docs/01-getting-started.md +94 -0
- data/docs/02-models.md +104 -0
- data/docs/03-changesets-and-actors.md +97 -0
- data/docs/04-conflicts.md +72 -0
- data/docs/05-proposals.md +86 -0
- data/docs/06-reverts.md +62 -0
- data/docs/07-drift.md +47 -0
- data/docs/08-redaction.md +60 -0
- data/docs/09-edges.md +42 -0
- data/docs/10-schema-evolution.md +51 -0
- data/docs/11-internals.md +51 -0
- data/docs/12-reference.md +64 -0
- data/lib/retcon/actor.rb +86 -0
- data/lib/retcon/bulk.rb +60 -0
- data/lib/retcon/changeset.rb +76 -0
- data/lib/retcon/config.rb +94 -0
- data/lib/retcon/context.rb +103 -0
- data/lib/retcon/drift.rb +151 -0
- data/lib/retcon/edge.rb +80 -0
- data/lib/retcon/history.rb +122 -0
- data/lib/retcon/model.rb +210 -0
- data/lib/retcon/projection.rb +51 -0
- data/lib/retcon/proposal.rb +224 -0
- data/lib/retcon/redaction.rb +81 -0
- data/lib/retcon/revert.rb +130 -0
- data/lib/retcon/schema.rb +125 -0
- data/lib/retcon/value.rb +45 -0
- data/lib/retcon/version.rb +1 -1
- data/lib/retcon.rb +189 -2
- metadata +59 -3
data/docs/07-drift.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Drift and bulk writes
|
|
2
|
+
|
|
3
|
+
Not every write goes through a model save. `update_all`, `insert_all`, `update_column`, raw SQL and console fixes all
|
|
4
|
+
write live rows without history. retcon finds them and records them before anything builds on them, attributed to
|
|
5
|
+
`Retcon::Actor.untracked`, so history never silently disagrees with the live table.
|
|
6
|
+
|
|
7
|
+
## How drift is found
|
|
8
|
+
|
|
9
|
+
`version_table` installs a trigger on the live table that sets `retcon_dirty` on any insert or update retcon didn't
|
|
10
|
+
make. retcon's own writes set the `retcon.writing` setting for the transaction, so the trigger leaves them alone.
|
|
11
|
+
|
|
12
|
+
Drift is caught three ways:
|
|
13
|
+
|
|
14
|
+
- **On write.** Before every update and destroy, retcon locks the row and, if it is dirty, writes a `catch_up`
|
|
15
|
+
changeset with what changed. Your edit then goes in after it, in order.
|
|
16
|
+
- **Sweeps.** `Venue.retcon_sweep!` catches up every dirty row in batches, and records rows deleted outside retcon
|
|
17
|
+
(history says they exist, the live table has none) as tombstones. Run it from a scheduled job.
|
|
18
|
+
- **Full sweeps.** `Venue.retcon_sweep!(full: true)` also compares every row's digest of its versioned fields with the
|
|
19
|
+
one retcon wrote. That catches writes made with the trigger disabled. It reads the whole table, so run it rarely.
|
|
20
|
+
|
|
21
|
+
Rows with no history at all are pre-retcon data and get `genesis` changesets instead.
|
|
22
|
+
|
|
23
|
+
```ruby
|
|
24
|
+
Venue.retcon_sweep! # => number of rows caught up
|
|
25
|
+
venue.retcon_drifted? # one row
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Skipping history on purpose
|
|
29
|
+
|
|
30
|
+
```ruby
|
|
31
|
+
Retcon.bypass { Venue.where(audience_id: old).update_all(audience_id: new) }
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Writes in a bypass block skip history, but the trigger still marks the rows dirty, so the next sweep records them as
|
|
35
|
+
untracked changes. Use bypass for migrations and repairs where attribution doesn't matter.
|
|
36
|
+
|
|
37
|
+
## Bulk writes with attribution
|
|
38
|
+
|
|
39
|
+
Imports and syncs that would use `upsert_all` can keep attribution with `Retcon::Bulk.upsert`:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
Retcon::Bulk.upsert(Venue, rows, unique_by: :external_key, actor: Retcon::Actor.named('import', 'facebook'))
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Rows are matched to live rows by `unique_by` (one column or several). New rows are created, matched rows get only the
|
|
46
|
+
fields that differ, and everything lands in one changeset of kind `import`. Like `upsert_all`, validations and
|
|
47
|
+
callbacks don't run. It returns the changeset, or nil when nothing changed.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Redaction
|
|
2
|
+
|
|
3
|
+
Some things history must not keep: a phone number posted by mistake, a privacy or right-to-be-forgotten request, a
|
|
4
|
+
takedown. Redaction is the one place retcon changes history rows, and it changes them only to delete a value.
|
|
5
|
+
|
|
6
|
+
## Commitments
|
|
7
|
+
|
|
8
|
+
Every version row holds its value, a random salt, and a **commitment**: SHA-256 over the salt and the value's
|
|
9
|
+
canonical JSON. Redaction deletes the value and the salt and keeps the commitment. History still verifies (each row
|
|
10
|
+
proves a value existed, and which changeset wrote it), but the value is gone, and because the salt is gone too, a short
|
|
11
|
+
value like a phone number can't be guessed back by hashing candidates.
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
row.verified? # the commitment matches the value (true once redacted: nothing left to check)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Scrubbing a field
|
|
18
|
+
|
|
19
|
+
```ruby
|
|
20
|
+
Retcon::Redaction.field(venue, :phone, actor: staff, reason: 'privacy request')
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
This scrubs the field from every version of the record, applied or proposed, and removes it from the record's
|
|
24
|
+
tombstone snapshots. Options:
|
|
25
|
+
|
|
26
|
+
- `value:` scrub only versions holding this value, leaving the field's other history alone.
|
|
27
|
+
- `remedy:` the live value afterwards (nil by default), written as a new version so a rebuild lands on it. Pass
|
|
28
|
+
`Retcon::Redaction::KEEP` to leave the live value alone when it is already clean.
|
|
29
|
+
|
|
30
|
+
```ruby
|
|
31
|
+
Retcon::Redaction.field(venue, :phone, actor: staff, reason: 'posted by mistake', value: '555-0100',
|
|
32
|
+
remedy: Retcon::Redaction::KEEP)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Every redaction is a changeset of kind `redaction` recording who, when, why and which version rows, never what was
|
|
36
|
+
removed. It fires the `redacted` event.
|
|
37
|
+
|
|
38
|
+
## Pseudonymizing an editor
|
|
39
|
+
|
|
40
|
+
```ruby
|
|
41
|
+
Retcon::Redaction.editor(user, by: staff, reason: 'account deleted')
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
History stores actor ids, so this rewrites one actor row: their identity is replaced with a stable pseudonym such as
|
|
45
|
+
`editor-3f9a1c2b`. Their edits stay, grouped under the pseudonym, so they can still be audited and reverted.
|
|
46
|
+
|
|
47
|
+
## Deletion requests
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
result = Retcon::Redaction.erase(user, by: deletion_job, reason: 'deletion request')
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
For an automated personal deletion request, `erase` does three things in one transaction:
|
|
54
|
+
|
|
55
|
+
1. reverts everything the person authored (see [Reverts](#reverts));
|
|
56
|
+
2. scrubs every value they wrote from history;
|
|
57
|
+
3. pseudonymizes them.
|
|
58
|
+
|
|
59
|
+
Later edits by other people to the same fields are not touched: they come back in `result[:review]` as a proposal,
|
|
60
|
+
because a deletion request can't wipe other people's work. The result is `{ revert:, review:, flagged:, redaction: }`.
|
data/docs/09-edges.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Edges
|
|
2
|
+
|
|
3
|
+
Relationships between records (an episode recorded at an event, a person hosting a night) are often rows in a link
|
|
4
|
+
table whose identity is the triple **subject, predicate, object**. `Retcon::Edge` versions them like any record and
|
|
5
|
+
adds two rules: linking the same triple again revives the row it had, and removed edges leave the live table.
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
class EntityLink < ApplicationRecord
|
|
9
|
+
include Retcon::Edge
|
|
10
|
+
|
|
11
|
+
retcon_triple subject: %i[item_type item_id], predicate: :predicate, object: %i[target_type target_id]
|
|
12
|
+
end
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
A polymorphic end is `[type_column, id_column]`; a plain end is one id column. Give the table a unique index on the
|
|
16
|
+
triple. `discriminator:` names one more identifying column, for a triple that may appear more than once (two slots
|
|
17
|
+
on the same night, say).
|
|
18
|
+
|
|
19
|
+
## Linking and unlinking
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
EntityLink.link!(episode, :recorded_at, event, status: 'linked') # creates, updates or revives
|
|
23
|
+
EntityLink.unlink!(episode, :recorded_at, event) # tombstones; nil when there was no edge
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`link!` updates a live edge in place, writing a version only for attributes that changed. If the triple was linked
|
|
27
|
+
before and removed, it revives that row, keeping its id and its whole history, instead of starting a new one. It
|
|
28
|
+
finds the old row through the tombstone snapshots, with a jsonb containment query on the history table's GIN index.
|
|
29
|
+
|
|
30
|
+
## Walking the graph
|
|
31
|
+
|
|
32
|
+
Removed edges leave the live table, so anything that reads the live table, including
|
|
33
|
+
[graph_query](https://lwm-luminx.github.io/graph_query/), walks only live edges with no extra filter:
|
|
34
|
+
|
|
35
|
+
```ruby
|
|
36
|
+
class MediaEpisode < ApplicationRecord
|
|
37
|
+
graph_edge :recorded_at, to: Event, through: EntityLink, source: :item_id, target: :target_id,
|
|
38
|
+
where: { item_type: 'MediaEpisode', predicate: 'recorded_at', target_type: 'Event' }
|
|
39
|
+
end
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
graph_query sees only the links that exist now. Who linked or unlinked an edge, and when, is in its history like any other record.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Schema evolution
|
|
2
|
+
|
|
3
|
+
History outlives your schema. A column renamed today still has years of versions under its old name. retcon stamps
|
|
4
|
+
every version row with the model's **schema version** and reads old rows through **upcasters**, so history never has
|
|
5
|
+
to be rewritten when a column changes.
|
|
6
|
+
|
|
7
|
+
## Versions and upcasters
|
|
8
|
+
|
|
9
|
+
Bump `schema_version` in the same deploy as the migration, and say how older rows read:
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
class Venue < ApplicationRecord
|
|
13
|
+
include Retcon::Model
|
|
14
|
+
|
|
15
|
+
versioned do
|
|
16
|
+
schema_version 3
|
|
17
|
+
rename_field :hours_text, :hours, before: 2 # rows written under version 1
|
|
18
|
+
upcast(before: 3) do |field, value| # rows written under versions 1 and 2
|
|
19
|
+
next [] if field == 'legacy_rating' # dropped
|
|
20
|
+
next [['city', value['city']], ['region', value['region']]] if field == 'location' # split
|
|
21
|
+
|
|
22
|
+
[[field, value]]
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
An upcaster takes `(field, value)` and returns `[[field, value], ...]`: one pair to keep or rename, none to drop,
|
|
29
|
+
several to split. Upcasters run in order of `before:`, and only on rows written under an older version, so a row
|
|
30
|
+
from version 1 goes through both of the upcasters above.
|
|
31
|
+
|
|
32
|
+
Heads, state, conflict checks and rebuilds all read through upcasters. The rows themselves keep what was
|
|
33
|
+
written, and `row.raw_value` returns it.
|
|
34
|
+
|
|
35
|
+
## Changing columns
|
|
36
|
+
|
|
37
|
+
- **Adding a versioned column:** nothing to do. Existing records have no versions for it until it changes. If the
|
|
38
|
+
migration backfills it with SQL, the trigger marks those rows dirty and `Venue.retcon_sweep!` records the values.
|
|
39
|
+
- **Removing a column:** add an upcaster that drops it, or `ignore` it first and remove it later.
|
|
40
|
+
- **Renaming:** `rename_field` with the new schema version.
|
|
41
|
+
- **Changing a type:** history keeps JSON values; an upcaster can convert old ones.
|
|
42
|
+
|
|
43
|
+
## Live columns
|
|
44
|
+
|
|
45
|
+
`version_table` adds three columns to the live table. Keep them out of your forms and serializers:
|
|
46
|
+
|
|
47
|
+
| Column | Holds |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `retcon_seq` | the seq of the last changeset that wrote the row: its base version |
|
|
50
|
+
| `retcon_digest` | a digest of the versioned fields as retcon last wrote them |
|
|
51
|
+
| `retcon_dirty` | set by the trigger when the row is written outside retcon |
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Internals
|
|
2
|
+
|
|
3
|
+
## Tables
|
|
4
|
+
|
|
5
|
+
`create_retcon_tables` makes:
|
|
6
|
+
|
|
7
|
+
- the sequence `retcon_seq`, retcon's global order of application;
|
|
8
|
+
- `retcon_actors`: kind, the record an actor stands for (`ref_type`, `ref_id`), a name, `on_behalf_of_id` for
|
|
9
|
+
agents, and the pseudonym and `redacted_at` once redacted;
|
|
10
|
+
- `retcon_changesets`: kind, state, author, committer, parent, scope, message, metadata, `applied_seq`, and when it
|
|
11
|
+
was applied and decided.
|
|
12
|
+
|
|
13
|
+
`version_table :venues` makes `retcon_venues`, with one row per field change or lifecycle step:
|
|
14
|
+
|
|
15
|
+
| Column | Holds |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `changeset_id` | the changeset the row belongs to |
|
|
18
|
+
| `record_id` | the live row's id, in the live table's key type |
|
|
19
|
+
| `op` | `set`, or a lifecycle step: `create`, `tombstone`, `revive` |
|
|
20
|
+
| `field`, `value` | for `set`: the field and `{"v": value}`; for a tombstone, the row as it was |
|
|
21
|
+
| `salt`, `commitment` | for `set`: the salted SHA-256 commitment that survives redaction |
|
|
22
|
+
| `applied`, `seq` | whether the changeset is applied, and its seq |
|
|
23
|
+
| `base_seq` | the version the change was made against |
|
|
24
|
+
| `schema_version` | the model's schema version when written |
|
|
25
|
+
| `redacted_by_id` | the redaction changeset that scrubbed the value |
|
|
26
|
+
|
|
27
|
+
History rows are inserted, never updated or deleted, except when a proposal is applied (`applied`, `seq`) and when
|
|
28
|
+
redaction scrubs a value and salt.
|
|
29
|
+
|
|
30
|
+
## One transaction
|
|
31
|
+
|
|
32
|
+
A save writes the changeset, the live row and the history rows in one transaction, in that order:
|
|
33
|
+
|
|
34
|
+
1. lock the live row and catch up drift;
|
|
35
|
+
2. check conflicts against the base;
|
|
36
|
+
3. take the changeset's seq (on its first write), set the live row's `retcon_seq`, digest and dirty flag, and save;
|
|
37
|
+
4. write the history rows for the fields that changed.
|
|
38
|
+
|
|
39
|
+
If anything raises, the transaction rolls back and neither history nor the live row changes. A catch-up that happens
|
|
40
|
+
inside an open changeset renumbers that changeset after itself, so history orders the catch-up first.
|
|
41
|
+
|
|
42
|
+
## Replaying
|
|
43
|
+
|
|
44
|
+
When retcon writes live rows from history (applying, reverting, reviving, rebuilding), it runs validations with
|
|
45
|
+
`Retcon.replaying?` true and writes with SQL, so callbacks don't fire for changes that are old or were reviewed.
|
|
46
|
+
Subscribe to `changeset_applied` for side effects that should follow these writes.
|
|
47
|
+
|
|
48
|
+
## Cost
|
|
49
|
+
|
|
50
|
+
A save of N changed fields adds one changeset insert (per changeset, not per record), one multi-row history insert,
|
|
51
|
+
one row lock and one `DISTINCT ON` query for the record's field heads. Reads of live tables are unchanged.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Reference
|
|
2
|
+
|
|
3
|
+
## Retcon
|
|
4
|
+
|
|
5
|
+
| Method | Does |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| `Retcon.as(actor, on_behalf_of: nil) { }` | attributes every change in the block |
|
|
8
|
+
| `Retcon.actor` | the current actor, or nil |
|
|
9
|
+
| `Retcon.changeset(actor:, message:, scope:, kind:, metadata:) { }` | one applied changeset, one transaction; returns it |
|
|
10
|
+
| `Retcon.propose(actor:, message:, scope:, metadata:) { \|p\| }` | opens a proposal; returns it |
|
|
11
|
+
| `Retcon.edit(record, attributes, actor:, message:, base:)` | commits, proposes or denies through the policy |
|
|
12
|
+
| `Retcon.policy = ->(actor, record, changes) { }` | returns `:commit`, `:propose` or `:deny` |
|
|
13
|
+
| `Retcon.revert(changesets, actor:, message:)` | returns a `Revert::Result` |
|
|
14
|
+
| `Retcon.revert_actor(actor, actor:, since:, scope:, message:)` | reverts what an actor authored |
|
|
15
|
+
| `Retcon.bypass { }` | writes skip history (and are swept later) |
|
|
16
|
+
| `Retcon.verify(model, sample: 100)` | live rows that disagree with history |
|
|
17
|
+
| `Retcon.replaying?` | true while retcon writes live rows from history |
|
|
18
|
+
| `Retcon.on(event) { \|changeset\| }` | subscribes to an event |
|
|
19
|
+
| `Retcon.allow_unattributed = false` | saves with no actor raise |
|
|
20
|
+
|
|
21
|
+
## Retcon::Changeset
|
|
22
|
+
|
|
23
|
+
`versions`, `records`, `changes`, `apply!(committer:, on_conflict: :raise)`, `reject!(by:, reason:)`,
|
|
24
|
+
`withdraw!(by:)`, `amend!(by:, message:) { |p| }`, `revert!(actor:, message:)`. Scopes: `applied`, `proposed`.
|
|
25
|
+
|
|
26
|
+
## Retcon::Proposal::Builder
|
|
27
|
+
|
|
28
|
+
`update(record, fields, base: nil)`, `create(model, attributes)`, `destroy(record)`.
|
|
29
|
+
|
|
30
|
+
## Retcon::Actor
|
|
31
|
+
|
|
32
|
+
`Actor.resolve(thing, on_behalf_of: nil)`, `Actor.named(kind, name)`, `Actor.system`, `Actor.untracked`,
|
|
33
|
+
`Actor.kinds = {}`, `#record`, `#label`, `#redacted?`, `#pseudonymize!`.
|
|
34
|
+
|
|
35
|
+
## Retcon::Redaction
|
|
36
|
+
|
|
37
|
+
`field(record, field, actor:, reason:, value: KEEP, remedy: nil)`, `editor(actor, by:, reason:)`,
|
|
38
|
+
`erase(actor, by:, reason:)`.
|
|
39
|
+
|
|
40
|
+
## Retcon::Bulk
|
|
41
|
+
|
|
42
|
+
`upsert(model, rows, unique_by:, actor:, message: nil)`.
|
|
43
|
+
|
|
44
|
+
## Retcon::Edge
|
|
45
|
+
|
|
46
|
+
`retcon_triple(subject:, predicate:, object:, discriminator: nil)`, `link!(subject, predicate, object, attributes)`,
|
|
47
|
+
`unlink!(subject, predicate, object)`, `retcon_identity(subject, predicate, object)`.
|
|
48
|
+
|
|
49
|
+
## Retcon::Schema (migrations)
|
|
50
|
+
|
|
51
|
+
`create_retcon_tables`, `version_table(table, id_type: nil)`, `add_retcon_dirty_trigger(table)`.
|
|
52
|
+
|
|
53
|
+
## Errors
|
|
54
|
+
|
|
55
|
+
| Error | Raised when |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| `Retcon::Conflict` | fields changed since the base; `#conflicts` lists `FieldConflict`s |
|
|
58
|
+
| `Retcon::Invalid` | a record would be invalid after applying history to it; `#record` |
|
|
59
|
+
| `Retcon::InvalidState` | a changeset can't move to the state asked for |
|
|
60
|
+
| `Retcon::Denied` | the policy refused an edit |
|
|
61
|
+
| `Retcon::NotVersioned` | a model or table isn't set up for retcon |
|
|
62
|
+
| `Retcon::Error` | the base class, and other misuse |
|
|
63
|
+
|
|
64
|
+
`Retcon::FieldConflict` has `model`, `record_id`, `field`, `base_seq`, `head_seq`, `current` and `proposed`.
|
data/lib/retcon/actor.rb
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Retcon
|
|
4
|
+
# Who made a change. History stores only actor ids, so pseudonymizing an editor rewrites one row here and nothing in
|
|
5
|
+
# history. An actor stands for a record (a User, a device grant), or is named (an import, a system job), and an agent
|
|
6
|
+
# can act on behalf of another actor.
|
|
7
|
+
class Actor < ActiveRecord::Base
|
|
8
|
+
self.table_name = 'retcon_actors'
|
|
9
|
+
|
|
10
|
+
KINDS = %w[user device import research system untracked agent].freeze
|
|
11
|
+
|
|
12
|
+
belongs_to :on_behalf_of, class_name: 'Retcon::Actor', optional: true
|
|
13
|
+
has_many :changesets, class_name: 'Retcon::Changeset', foreign_key: :author_id, inverse_of: :author,
|
|
14
|
+
dependent: :restrict_with_exception
|
|
15
|
+
|
|
16
|
+
validates :kind, inclusion: { in: KINDS }
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
# An Actor for anything: an Actor, a record (found or created by type and id), or a String naming a system.
|
|
20
|
+
# kind: overrides the kind given to a new record actor (user by default, or what Retcon.kind_for says).
|
|
21
|
+
def resolve(thing, on_behalf_of: nil, kind: nil)
|
|
22
|
+
on_behalf_of &&= resolve(on_behalf_of)
|
|
23
|
+
actor = case thing
|
|
24
|
+
when Actor then thing
|
|
25
|
+
when nil then return nil
|
|
26
|
+
when String, Symbol then named('system', thing.to_s)
|
|
27
|
+
when ActiveRecord::Base then for_record(thing, kind:)
|
|
28
|
+
else raise ArgumentError, "can't attribute changes to #{thing.inspect}"
|
|
29
|
+
end
|
|
30
|
+
return actor unless on_behalf_of
|
|
31
|
+
|
|
32
|
+
identity(kind: 'agent', ref_type: actor.ref_type, ref_id: actor.ref_id, name: actor.name,
|
|
33
|
+
on_behalf_of_id: on_behalf_of.id)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def for_record(record, kind: nil)
|
|
37
|
+
identity(kind: kind || kind_for(record), ref_type: record.class.polymorphic_name, ref_id: record.id.to_s)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# A named actor of a kind: Actor.named('import', 'facebook sync').
|
|
41
|
+
def named(kind, name) = identity(kind:, name:)
|
|
42
|
+
|
|
43
|
+
# Changes no one claims: saves made with no actor set, when Retcon.allow_unattributed is on.
|
|
44
|
+
def system = named('system', 'unattributed')
|
|
45
|
+
|
|
46
|
+
# Writes Retcon found but didn't make (Retcon::Drift).
|
|
47
|
+
def untracked = named('untracked', 'untracked change')
|
|
48
|
+
|
|
49
|
+
# Kind for a new record actor: set Retcon::Actor.kinds = { 'VenueDeviceGrant' => 'device' }.
|
|
50
|
+
attr_writer :kinds
|
|
51
|
+
|
|
52
|
+
def kinds = @kinds ||= {}
|
|
53
|
+
|
|
54
|
+
def kind_for(record) = kinds.fetch(record.class.polymorphic_name, 'user')
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
def identity(kind:, ref_type: nil, ref_id: nil, name: nil, on_behalf_of_id: nil)
|
|
59
|
+
attrs = { kind:, ref_type:, ref_id:, on_behalf_of_id: }
|
|
60
|
+
attrs[:name] = name if ref_type.nil?
|
|
61
|
+
live = where(redacted_at: nil)
|
|
62
|
+
live.find_by(attrs) || transaction(requires_new: true) { create!(attrs.merge(name:)) }
|
|
63
|
+
rescue ActiveRecord::RecordNotUnique
|
|
64
|
+
live.find_by!(attrs)
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# The record this actor stands for, if it still does.
|
|
69
|
+
def record = ref_type && ref_id && ref_type.safe_constantize&.find_by(id: ref_id)
|
|
70
|
+
|
|
71
|
+
def redacted? = redacted_at.present?
|
|
72
|
+
|
|
73
|
+
# How to show this actor: its pseudonym once redacted.
|
|
74
|
+
def label
|
|
75
|
+
return pseudonym if redacted?
|
|
76
|
+
|
|
77
|
+
base = name || "#{ref_type} #{ref_id}"
|
|
78
|
+
on_behalf_of ? "#{base} for #{on_behalf_of.label}" : base
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Replaces identity with a stable pseudonym; every edit stays and stays grouped under this actor.
|
|
82
|
+
def pseudonymize!(pseudonym: "editor-#{SecureRandom.hex(4)}")
|
|
83
|
+
update!(ref_type: nil, ref_id: nil, name: nil, pseudonym:, redacted_at: Time.current)
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
data/lib/retcon/bulk.rb
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Retcon
|
|
4
|
+
# Bulk writes with history: imports and syncs that would otherwise use upsert_all and leave untracked changes.
|
|
5
|
+
# One changeset per call, attributed to the import.
|
|
6
|
+
#
|
|
7
|
+
# Retcon::Bulk.upsert(Venue, rows, unique_by: :external_key, actor: Retcon::Actor.named('import', 'facebook'))
|
|
8
|
+
#
|
|
9
|
+
# Rows are matched to live rows by unique_by; new rows are created, matched rows get only the fields that differ.
|
|
10
|
+
# Validations and callbacks don't run (as with upsert_all). Returns the Changeset, or nil when nothing changed.
|
|
11
|
+
module Bulk
|
|
12
|
+
module_function
|
|
13
|
+
|
|
14
|
+
def upsert(model, rows, unique_by:, actor:, message: nil)
|
|
15
|
+
keys = Array(unique_by).map(&:to_s)
|
|
16
|
+
rows = rows.map { |r| r.transform_keys(&:to_s) }
|
|
17
|
+
Retcon.changeset(actor:, kind: 'import', message: message || "Import into #{model.table_name}") do
|
|
18
|
+
existing = match(model, keys, rows)
|
|
19
|
+
fields = model.retcon_config.tracked_fields
|
|
20
|
+
changeset = nil
|
|
21
|
+
rows.each do |row|
|
|
22
|
+
record = existing[row.values_at(*keys)]
|
|
23
|
+
changeset ||= Context.open.changeset
|
|
24
|
+
record ? update(model, record, row, fields, changeset) : create(model, row, fields, changeset)
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def match(model, keys, rows)
|
|
30
|
+
conditions = keys.to_h { |k| [k, rows.map { |r| r[k] }.uniq] }
|
|
31
|
+
model.unscoped.where(conditions).index_by { |rec| keys.map { |k| rec.read_attribute(k) } }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def create(model, row, fields, changeset)
|
|
35
|
+
id = row[model.primary_key] || Proposal.new_id(model)
|
|
36
|
+
record = Projection.insert(model, id, row, seq: changeset.applied_seq, validate: false)
|
|
37
|
+
history_rows = [{ record_id: id, op: 'create', field: nil, value: nil, base_seq: nil }]
|
|
38
|
+
fields.each do |field|
|
|
39
|
+
value = record.read_attribute(field)
|
|
40
|
+
history_rows << { record_id: id, op: 'set', field:, value:, base_seq: nil } unless value.nil?
|
|
41
|
+
end
|
|
42
|
+
model.retcon_history.write(changeset, history_rows, applied: true)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def update(model, record, row, fields, changeset)
|
|
46
|
+
Drift.lock_and_catch_up(record)
|
|
47
|
+
changed = row.slice(*fields).reject do |f, v|
|
|
48
|
+
Value.same?(record.read_attribute(f), model.type_for_attribute(f).cast(v))
|
|
49
|
+
end
|
|
50
|
+
return if changed.empty?
|
|
51
|
+
|
|
52
|
+
heads = model.retcon_history.heads(record.id)
|
|
53
|
+
Projection.update(model, record.id, changed, seq: changeset.applied_seq, validate: false)
|
|
54
|
+
model.retcon_history.write(changeset, changed.map do |field, value|
|
|
55
|
+
{ record_id: record.id, op: 'set', field:, value: model.type_for_attribute(field).cast(value),
|
|
56
|
+
base_seq: heads[field]&.seq }
|
|
57
|
+
end, applied: true)
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Retcon
|
|
4
|
+
# One logical change: version rows across any number of records and tables, with an author and (once someone
|
|
5
|
+
# applies or decides it) a committer. A direct edit is an applied changeset; a proposal is a proposed one, applied
|
|
6
|
+
# later through #apply!. Changesets are never deleted; reverts and redactions are changesets too.
|
|
7
|
+
class Changeset < ActiveRecord::Base
|
|
8
|
+
self.table_name = 'retcon_changesets'
|
|
9
|
+
|
|
10
|
+
KINDS = %w[edit proposal genesis catch_up revert redaction merge import].freeze
|
|
11
|
+
STATES = %w[applied proposed rejected withdrawn amended superseded].freeze
|
|
12
|
+
|
|
13
|
+
belongs_to :author, class_name: 'Retcon::Actor'
|
|
14
|
+
belongs_to :committer, class_name: 'Retcon::Actor', optional: true
|
|
15
|
+
belongs_to :parent, class_name: 'Retcon::Changeset', optional: true
|
|
16
|
+
has_many :children, class_name: 'Retcon::Changeset', foreign_key: :parent_id, inverse_of: :parent,
|
|
17
|
+
dependent: :restrict_with_exception
|
|
18
|
+
|
|
19
|
+
validates :kind, inclusion: { in: KINDS }
|
|
20
|
+
validates :state, inclusion: { in: STATES }
|
|
21
|
+
|
|
22
|
+
scope :applied, -> { where(state: 'applied') }
|
|
23
|
+
scope :proposed, -> { where(state: 'proposed') }
|
|
24
|
+
scope :in_order, -> { order(:applied_seq) }
|
|
25
|
+
|
|
26
|
+
STATES.each { |state| define_method(:"#{state}?") { self.state == state } }
|
|
27
|
+
|
|
28
|
+
# Every version row in this changeset, across all versioned tables: [History row, ...] in write order.
|
|
29
|
+
def versions
|
|
30
|
+
Retcon.models.values.flat_map { |model| model.retcon_history.where(changeset_id: id).order(:id).to_a }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# The records this changeset touched: [[model, record_id], ...].
|
|
34
|
+
def records
|
|
35
|
+
Retcon.models.values.flat_map do |model|
|
|
36
|
+
model.retcon_history.where(changeset_id: id).distinct.pluck(:record_id).map { |rid| [model, rid] }
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# {[model, record_id] => {field => value}} that this changeset sets, for showing a diff.
|
|
41
|
+
def changes
|
|
42
|
+
versions.select { |v| v.op == 'set' }.group_by { |v| [v.class.live_model, v.record_id] }
|
|
43
|
+
.transform_values { |rows| rows.to_h { |v| [v.field, v.current_value] } }
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Applies a proposal: checks every field against its base, writes live rows (validated, without callbacks) and
|
|
47
|
+
# marks the version rows applied, all in one transaction. on_conflict: :raise (Retcon::Conflict, nothing
|
|
48
|
+
# applied) or :skip (applies the fields that don't conflict and returns the conflicts).
|
|
49
|
+
def apply!(committer:, on_conflict: :raise)
|
|
50
|
+
Proposal.apply(self, committer: Actor.resolve(committer),
|
|
51
|
+
on_conflict:)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Rejects a proposal. reason goes to metadata.
|
|
55
|
+
def reject!(by:, reason: nil) = decide!('rejected', by:, reason:, event: :proposal_rejected)
|
|
56
|
+
|
|
57
|
+
# The author takes the proposal back.
|
|
58
|
+
def withdraw!(by: author) = decide!('withdrawn', by:)
|
|
59
|
+
|
|
60
|
+
# Replaces a proposal with an amended one: the block gets a Proposal::Builder pre-filled with this proposal's
|
|
61
|
+
# changes. The new proposal keeps this author, names by as committer and points here as its parent.
|
|
62
|
+
def amend!(by:, message: self.message, &) = Proposal.amend(self, by: Actor.resolve(by), message:, &)
|
|
63
|
+
|
|
64
|
+
# Undoes this changeset (see Retcon::Revert).
|
|
65
|
+
def revert!(actor:, message: nil) = Retcon.revert(self, actor:, message:)
|
|
66
|
+
|
|
67
|
+
def decide!(state, by:, reason: nil, event: nil)
|
|
68
|
+
raise InvalidState, "changeset #{id} is #{self.state}, not proposed" unless proposed?
|
|
69
|
+
|
|
70
|
+
update!(state:, committer: Actor.resolve(by), decided_at: Time.current,
|
|
71
|
+
metadata: reason ? metadata.merge('reason' => reason) : metadata)
|
|
72
|
+
Retcon.instrument(event, changeset: self) if event
|
|
73
|
+
self
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Retcon
|
|
4
|
+
# A model's versioning settings, set in a `versioned do ... end` block:
|
|
5
|
+
#
|
|
6
|
+
# class Venue < ApplicationRecord
|
|
7
|
+
# include Retcon::Model
|
|
8
|
+
#
|
|
9
|
+
# versioned do
|
|
10
|
+
# ignore :view_count, :search_vector # not versioned (timestamps and *_count already aren't)
|
|
11
|
+
# only :name, :address, :phone # or name the versioned fields outright
|
|
12
|
+
# merge :tags, :set_union # merge strategy for proposals that touch the same field
|
|
13
|
+
# scope { |venue| venue.audience_id } # the scope changesets about this record get
|
|
14
|
+
# schema_version 2
|
|
15
|
+
# rename_field :hours_text, :hours, before: 2 # upcaster for history written under version 1
|
|
16
|
+
# upcast(before: 2) { |field, value| [[field, value]] }
|
|
17
|
+
# end
|
|
18
|
+
# end
|
|
19
|
+
class Config
|
|
20
|
+
DEFAULT_IGNORED = %w[created_at updated_at lock_version].freeze
|
|
21
|
+
MERGES = %i[replace set_union].freeze
|
|
22
|
+
|
|
23
|
+
attr_reader :model, :merges, :upcasters
|
|
24
|
+
|
|
25
|
+
def initialize(model)
|
|
26
|
+
@model = model
|
|
27
|
+
@ignored = []
|
|
28
|
+
@only = nil
|
|
29
|
+
@merges = {}
|
|
30
|
+
@scope = nil
|
|
31
|
+
@schema_version = 1
|
|
32
|
+
@upcasters = []
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def ignore(*fields) = @ignored.concat(fields.map(&:to_s))
|
|
36
|
+
|
|
37
|
+
def only(*fields)
|
|
38
|
+
@only = fields.map(&:to_s)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def merge(field, strategy)
|
|
42
|
+
raise ArgumentError, "merge strategy must be one of #{MERGES.join(', ')}" unless MERGES.include?(strategy)
|
|
43
|
+
|
|
44
|
+
@merges[field.to_s] = strategy
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def scope(&block)
|
|
48
|
+
@scope = block
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def schema_version(version = nil)
|
|
52
|
+
return @schema_version if version.nil?
|
|
53
|
+
|
|
54
|
+
@schema_version = Integer(version)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Converts history written under schema versions below before: the block takes (field, value) and returns
|
|
58
|
+
# [[field, value], ...]: none to drop a field, several to split one.
|
|
59
|
+
def upcast(before:, &block)
|
|
60
|
+
@upcasters << [Integer(before), block]
|
|
61
|
+
@upcasters.sort_by!(&:first)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def rename_field(from, to, before:)
|
|
65
|
+
from = from.to_s
|
|
66
|
+
upcast(before:) { |field, value| field == from ? [[to.to_s, value]] : [[field, value]] }
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The fields Retcon versions: every column but the primary key, Retcon's own, timestamps, lock_version, counter
|
|
70
|
+
# caches (*_count) and the ones ignored; or the ones named with only.
|
|
71
|
+
def tracked_fields
|
|
72
|
+
@tracked_fields ||= begin
|
|
73
|
+
columns = model.column_names - [model.primary_key] - LIVE_COLUMNS
|
|
74
|
+
fields = @only || (columns.reject { |c| c.end_with?('_count') } - DEFAULT_IGNORED)
|
|
75
|
+
fields - @ignored
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def reset! = @tracked_fields = nil
|
|
80
|
+
|
|
81
|
+
def scope_for(record) = @scope&.call(record)&.to_s
|
|
82
|
+
|
|
83
|
+
# A field and value written under schema_version, as they read under the current one: [[field, value], ...].
|
|
84
|
+
def upcast_value(field, value, from_version)
|
|
85
|
+
pairs = [[field, value]]
|
|
86
|
+
upcasters.each do |before, block|
|
|
87
|
+
next unless from_version < before
|
|
88
|
+
|
|
89
|
+
pairs = pairs.flat_map { |f, v| block.call(f, v) }
|
|
90
|
+
end
|
|
91
|
+
pairs
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|