Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions .github/workflows/testing-and-standardization.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,25 @@ concurrency:
on:
pull_request:
branches:
- core
- main
push:
branches:
- core
- main
workflow_dispatch:

jobs:
checking:
name: Unit Tests
name: Unit Tests (Ruby ${{ matrix.ruby }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby: ["3.4", "4.0"]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Rubocop check
run: |
Expand All @@ -30,4 +35,4 @@ jobs:
--fail-level warning \
lib/
- name: Run tests
run: bundle exec rspec --backtrace --profile 10 lib/**/*_spec.rb
run: bundle exec rake spec
2 changes: 1 addition & 1 deletion .ruby-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.4.7
4.0.10
2 changes: 1 addition & 1 deletion .tool-versions
Original file line number Diff line number Diff line change
@@ -1 +1 @@
ruby 3.4.7
ruby 4.0.10
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
# Changelog

## 2.0.0

- Requires paper_trail 17
- Replaces ar_after_transaction with an `after_commit` on the record's current transaction, so only a rollback on the record's own database drops the job. Remove any `ActiveRecord::Base.normally_open_transactions` setup; `with_versioning` no longer takes `expected_open_transactions:`
- `PaperTrail::Background::Job` sets `enqueue_after_transaction_commit = false` on the class that includes it. With the setting on, Active Job would wait for every open transaction on every database, and a rollback on another database would drop the job
- `with_versioning` needs each example to run in a non-joinable transaction, as Rails transactional fixtures and DatabaseCleaner's `:transaction` strategy do. Inside a plain `ActiveRecord::Base.transaction` wrapper the example's rollback drops the job before it writes a version
- A record created inside a savepoint that rolls back no longer enqueues a version job
- Inside `transaction(joinable: false)` the gem enqueues the job when the record's savepoint is released, the same moment Rails runs `after_commit` callbacks. If the outer transaction then rolls back, the job still writes a version for a row that never committed. 1.x waited for the outer commit
- `paper_trail.update_columns` on an async model no longer raises `NameError`
- Update versions take `created_at` from the record's `updated_at`, as create versions already did. Destroy and `update_columns` versions take it from the time the job is enqueued
- `record_update` merges `data_for_update` instead of `data_for_update_columns`
- The job payload carries `item_id` and `item_type` instead of the record, so a version is still written when the record is deleted before the job runs
- A model with `versions: { dependent: :destroy }`, `:delete_all` or `:destroy_async` gets no create or update version from a job that runs after the record is gone, because destroying the record purges its versions. Destroy versions are still written
- Known gap: the purge check is best effort. A create or update job that runs before the destroy transaction commits finds the record and writes a version that outlives the purge. 1.x had the same window
- Known gap: the purge check reads the `versions: { dependent: }` option from the class in `item_type`, which for STI is the base class. When only a subclass purges its versions, or base and subclass set different options, the job follows the base class. A late create or update job can then write a version for a subclass record whose versions were purged
- Known gap: on a model that purges its versions, `record.delete` and `Model.delete_all` skip the purge, yet the job still reads the missing row as purged and drops the record's pending create and update versions. Sync paper_trail 17 keeps them, and 1.x lost them as well
- Known gap: when version jobs run out of order, on parallel workers or after a retry, a later event can get a lower id. `record.versions` orders by `created_at`, while `Version#previous`, `#next` and `#index` go by id, so the two disagree. Run `VersionJob` on a single-threaded queue if that matters
- Known gap: a per-model `has_paper_trail limit:` does not apply to an async version whose record is gone when the job runs, which includes every async destroy version. paper_trail then falls back to the global `PaperTrail.config.version_limit`, so without a global limit the older versions of a destroyed record are never pruned. Sync paper_trail 17 prunes them
- Known gap: pending jobs honour `versions: { dependent: }` only for `:destroy`, `:delete_all` and `:destroy_async`. `dependent: :nullify`, `:restrict_with_error`, `:restrict_with_exception`, horizontally sharded models and `store_full_class_name = false` are unsupported. Keep those models on `async: false` (see the README)
- With `opt_in` unset, create and destroy go through the job too, as update already did
- An explicit `async:` on `has_paper_trail` wins over `opt_in`. With `async: false` a model stays synchronous even when `opt_in` is unset, updates included
- Async versions take `item_type` from `polymorphic_name`, as sync versions do, so a model that overrides it finds them in `record.versions`

## 1.2.0

- When async is false we want to fall back to the original logic (#11 thanks @erf530)
Expand Down
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ gemspec
# Git. Remember to move these dependencies to your gemspec before releasing
# your gem to rubygems.org.

gem "activejob"
gem "bundler"
gem "rake"
gem "rspec"
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ class VersionJob < ApplicationJob
end
```

`include PaperTrail::Background::Job` sets `enqueue_after_transaction_commit = false` on `VersionJob`, even when `ApplicationJob` turns it on. The gem already enqueues the job once the record's transaction commits. With the setting on, Active Job would also wait for every open transaction on every database, and a rollback on another database would drop the job.

## Configuration
In an initializer, you can specify whether you want to opt into this behavior on a per-model basis:

Expand All @@ -26,6 +28,8 @@ PaperTrail::Background::Config.configure do |config|
end
```

With `opt_in` unset (the default), every `has_paper_trail` model without an explicit `async:` writes its create, update, `update_columns` and destroy versions through `VersionJob`, so `record.versions` stays empty until the job runs.

If opt-in behavior is set to `true`, you can enable async paper trails by specifying `async: true` in a given model's paper trail options:

``` ruby
Expand All @@ -34,6 +38,14 @@ class SomeModel < ActiveRecord::Base
end
```

An explicit `async:` option takes precedence over `opt_in`. A model with `has_paper_trail async: false` stays synchronous even when `opt_in` is unset.

Async versions don't record [paper_trail-association_tracking](https://github.com/westonganger/paper_trail-association_tracking) associations. Keep a model synchronous with `async: false` if you need them.

Version jobs for the same record can run out of order, on parallel workers or when a job is retried. Each version keeps the time of its event in `created_at`, so `record.versions` stays in event order. Ids follow the order the jobs ran in, and `Version#previous`, `#next` and `#index` go by id. Run `VersionJob` on a single-threaded queue if you rely on them.

Pending jobs honour `has_paper_trail versions: { dependent: }` only for `:destroy`, `:delete_all` and `:destroy_async`. A create or update job that runs after such a record is gone writes nothing, because destroying the record purged its versions. Keep a model on `async: false` in four other setups. With `dependent: :nullify`, a pending version keeps the destroyed record's `item_id` and `item_type`. With `:restrict_with_error` or `:restrict_with_exception`, a record whose create version is still queued has no versions yet, so it can be destroyed. On a horizontal shard, the job runs on the worker's current shard, so it can write the version to the wrong shard, or drop it on a model that purges its versions. With `ActiveRecord::Base.store_full_class_name = false`, `item_type` drops the namespace, so the job can check the wrong class and drop a live record's version.

## Installing

Run this command in your project:
Expand Down
2 changes: 0 additions & 2 deletions lib/paper_trail-background/rspec.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# frozen_string_literal: true

require "ar_after_transaction"

require_relative "../paper_trail/background/rspec_helpers"

RSpec.configure do |config|
Expand Down
56 changes: 31 additions & 25 deletions lib/paper_trail/background.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# frozen_string_literal: true

require "paper_trail/record_trail"
require "ar_after_transaction"

module PaperTrail
require_relative "background/config"
Expand All @@ -10,12 +9,9 @@ module PaperTrail

module Background
# @api private
# @return - The created version object, so that plugins can use it, e.g.
# paper_trail-association_tracking
def record_create
return unless enabled?

return super if @record.paper_trail_options[:async].blank?
return super unless async?
Comment thread
filippoliverani marked this conversation as resolved.
Resolved

event = PaperTrail::Events::Create.new(@record, true)

Expand All @@ -29,11 +25,9 @@ def record_create
# `recording_order` is "after" or "before". See ModelConfig#on_destroy.
#
# @api private
# @return - The created version object, so that plugins can use it, e.g.
# paper_trail-association_tracking
def record_destroy(recording_order)
return unless enabled?
return super if @record.paper_trail_options[:async].blank?
return super unless async?
return if @record.new_record?

in_after_callback = recording_order == "after"
Expand All @@ -48,33 +42,35 @@ def record_destroy(recording_order)
end

# @api private
# @return - The created version object, so that plugins can use it, e.g.
# paper_trail-association_tracking
def record_update(force:, in_after_callback:, is_touch:)
return unless enabled?
return super if Config.configuration.opt_in && @record.paper_trail_options[:async].blank?
return super unless async?

event = PaperTrail::Events::Update.new(@record, in_after_callback, is_touch, nil)

return unless force || event.changed_notably?

data = event.data

# Same rule as `RecordTrail#build_version_on_update`.
if @record.respond_to?(:updated_at) &&
@record.paper_trail_options[:synchronize_version_creation_timestamp] != false
data[:created_at] = @record.updated_at
end

# Merge data from `Event` with data from PT-AT. We no longer use
# `data_for_update_columns` but PT-AT still does.
data = event.data.merge(data_for_update_columns)
# `data_for_update` but PT-AT still does.
data.merge!(data_for_update)

trigger_write(@record, data, :update)
end

# @api private
# @return - The created version object, so that plugins can use it, e.g.
# paper_trail-association_tracking
def record_update_columns(changes)
return unless enabled?
return super if Config.configuration.opt_in && @record.paper_trail_options[:async].blank?
return super unless async?

event = Events::Update.new(@record, false, false, changes)

return unless force || event.changed_notably?
event = PaperTrail::Events::Update.new(@record, false, false, changes)
Comment thread
filippoliverani marked this conversation as resolved.
Resolved

# Merge data from `Event` with data from PT-AT. We no longer use
# `data_for_update_columns` but PT-AT still does.
Expand All @@ -83,14 +79,24 @@ def record_update_columns(changes)
trigger_write(@record, data, :update)
end

private def async?
@record.paper_trail_options.fetch(:async) { !Config.configuration.opt_in }.present?
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
end
Comment thread
filippoliverani marked this conversation as resolved.
Resolved

private def trigger_write(record, data, event)
record.class.after_transaction do
VersionJob.perform_later(
record.class.paper_trail.version_class.name,
data,
event
)
item = data.delete(:item)
if item
data[:item_id] = item.id
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
data[:item_type] = item.class.polymorphic_name
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
end
data[:created_at] ||= Time.current
version_class_name = record.class.paper_trail.version_class.name
Comment thread
filippoliverani marked this conversation as resolved.
Resolved

record.class.current_transaction.after_commit do
VersionJob.perform_later(version_class_name, data, event)
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
end

nil
end
end
end
Expand Down
27 changes: 26 additions & 1 deletion lib/paper_trail/background/job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,34 @@
module PaperTrail
module Background
module Job
def perform(version_class, attributes, _event)
PURGING_DEPENDENTS = %i[destroy delete_all destroy_async].freeze

def self.included(base)
return unless base.respond_to?(:enqueue_after_transaction_commit=)

base.enqueue_after_transaction_commit = false
end

def perform(version_class, attributes, event)
return if purged_with_item?(attributes, event)

version_class.constantize.create!(attributes)
end

private def purged_with_item?(attributes, event)
return false if event.to_s == "destroy"
return false unless (item_class = attributes[:item_type]&.safe_constantize)
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
return false unless purges_versions?(item_class)
Comment thread
filippoliverani marked this conversation as resolved.
Resolved

!item_class.unscoped.exists?(attributes[:item_id])
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
Comment thread
filippoliverani marked this conversation as resolved.
Resolved
end

private def purges_versions?(item_class)
return false unless item_class.respond_to?(:versions_association_name)

dependent = item_class.reflect_on_association(item_class.versions_association_name).options[:dependent]
PURGING_DEPENDENTS.include?(dependent)
end
end
end
end
Loading