diff --git a/.github/workflows/testing-and-standardization.yml b/.github/workflows/testing-and-standardization.yml index 09def3b..22d8d70 100644 --- a/.github/workflows/testing-and-standardization.yml +++ b/.github/workflows/testing-and-standardization.yml @@ -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: | @@ -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 diff --git a/.ruby-version b/.ruby-version index 81f1b89..4d5826d 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.4.7 \ No newline at end of file +4.0.10 \ No newline at end of file diff --git a/.tool-versions b/.tool-versions index 3f03c7a..09b5e24 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1 @@ -ruby 3.4.7 +ruby 4.0.10 diff --git a/CHANGELOG.md b/CHANGELOG.md index 351ea88..4c37247 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/Gemfile b/Gemfile index 6652ecd..5f6bf51 100644 --- a/Gemfile +++ b/Gemfile @@ -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" diff --git a/README.md b/README.md index f637da7..06c2542 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 @@ -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: diff --git a/lib/paper_trail-background/rspec.rb b/lib/paper_trail-background/rspec.rb index ae571b5..4633e8e 100644 --- a/lib/paper_trail-background/rspec.rb +++ b/lib/paper_trail-background/rspec.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require "ar_after_transaction" - require_relative "../paper_trail/background/rspec_helpers" RSpec.configure do |config| diff --git a/lib/paper_trail/background.rb b/lib/paper_trail/background.rb index 282e367..b95a06f 100644 --- a/lib/paper_trail/background.rb +++ b/lib/paper_trail/background.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require "paper_trail/record_trail" -require "ar_after_transaction" module PaperTrail require_relative "background/config" @@ -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? event = PaperTrail::Events::Create.new(@record, true) @@ -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" @@ -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) # Merge data from `Event` with data from PT-AT. We no longer use # `data_for_update_columns` but PT-AT still does. @@ -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? + end + 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 + data[:item_type] = item.class.polymorphic_name end + data[:created_at] ||= Time.current + version_class_name = record.class.paper_trail.version_class.name + + record.class.current_transaction.after_commit do + VersionJob.perform_later(version_class_name, data, event) + end + + nil end end end diff --git a/lib/paper_trail/background/job.rb b/lib/paper_trail/background/job.rb index 8f07513..4ab3eac 100644 --- a/lib/paper_trail/background/job.rb +++ b/lib/paper_trail/background/job.rb @@ -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) + return false unless purges_versions?(item_class) + + !item_class.unscoped.exists?(attributes[:item_id]) + 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 diff --git a/lib/paper_trail/background/parity_spec.rb b/lib/paper_trail/background/parity_spec.rb new file mode 100644 index 0000000..852468e --- /dev/null +++ b/lib/paper_trail/background/parity_spec.rb @@ -0,0 +1,275 @@ +# frozen_string_literal: true + +require "spec_helper" +require "active_support/all" +require "active_support/testing/time_helpers" +require "active_job" + +RSpec.describe PaperTrail::Background, "parity" do + include ActiveSupport::Testing::TimeHelpers + + before(:all) do # rubocop:disable RSpec/BeforeAfterAll -- one in-memory sqlite schema for the whole group + ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") + ActiveRecord::Schema.verbose = false + ActiveRecord::Schema.define do + create_table(:widgets) do |t| + t.string :name + t.timestamps + end + create_table(:versions) do |t| + t.string :item_type, null: false + t.bigint :item_id, null: false + t.string :event, null: false + t.string :whodunnit + t.json :object + t.json :object_changes + t.datetime :created_at + end + end + ActiveJob::Base.logger = nil + end + + after(:all) { ActiveRecord::Base.remove_connection } # rubocop:disable RSpec/BeforeAfterAll -- drops the connection the before(:all) opened + + let(:async_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail async: true + end + end + let(:plain_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail + end + end + let(:sync_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail async: false + end + end + let(:purging_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail async: true, on: %i[create update], versions: { dependent: :destroy } + end + end + let(:renamed_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail async: true + + def self.polymorphic_name = "Gadget" + end + end + let(:unsynchronized_widget) do + Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + has_paper_trail async: true, synchronize_version_creation_timestamp: false + end + end + let(:jobs) { ActiveJob::Base.queue_adapter.enqueued_jobs } + + before do + stub_const("AsyncWidget", async_widget) + stub_const("PlainWidget", plain_widget) + stub_const("PurgingWidget", purging_widget) + stub_const("RenamedWidget", renamed_widget) + stub_const("SyncWidget", sync_widget) + stub_const("UnsynchronizedWidget", unsynchronized_widget) + stub_const("VersionJob", Class.new(ActiveJob::Base) { include PaperTrail::Background::Job }) + ActiveJob::Base.queue_adapter = :test + PaperTrail::Background::Config.configure { |config| config.opt_in = true } + PaperTrail::Version.delete_all + end + + def perform_jobs + jobs.shift(jobs.size).each { |job| ActiveJob::Base.execute(job) } + end + + def created_widget + AsyncWidget.create!(name: "a").tap { perform_jobs } + end + + it "writes the create version from the job" do + widget = AsyncWidget.create!(name: "a") + + expect { perform_jobs }.to change { widget.versions.pluck(:event, :created_at) } + .from([]).to([["create", widget.updated_at]]) + end + + it "still writes the version when the record is gone before the job runs" do + widget = AsyncWidget.create!(name: "a") + AsyncWidget.where(id: widget.id).delete_all + + perform_jobs + + expect(PaperTrail::Version.where(item_type: "AsyncWidget", item_id: widget.id).count).to eq(1) + end + + it "writes nothing when the record and its versions are destroyed before the job runs" do + widget = PurgingWidget.create!(name: "a").tap { perform_jobs } + widget.update!(name: "b") + widget.destroy! + + perform_jobs + + expect(PaperTrail::Version.where(item_type: "PurgingWidget", item_id: widget.id)).to be_empty + end + + it "still writes the version of a live record that its default scope hides from the job" do + stub_const("ScopedPurgingWidget", Class.new(ActiveRecord::Base) do + self.table_name = "widgets" + default_scope { where(name: "visible") } + has_paper_trail async: true, versions: { dependent: :destroy } + end) + widget = ScopedPurgingWidget.create!(name: "visible").tap { perform_jobs } + widget.update!(name: "hidden") + + perform_jobs + + expect(PaperTrail::Version.where(item_type: "ScopedPurgingWidget", item_id: widget.id).pluck(:event)) + .to eq(%w[create update]) + end + + it "writes the version of a job queued by 1.x, whose payload carries the record instead of item_type" do + widget = created_widget + + expect { VersionJob.perform_now("PaperTrail::Version", { item: widget, event: "update" }, "update") } + .to change { widget.versions.pluck(:event) }.from(%w[create]).to(%w[create update]) + end + + it "stamps an update version with the record's updated_at, however late the job runs" do + widget = created_widget + widget.update!(name: "b") + + travel(1.hour) { perform_jobs } + + expect(widget.versions.last).to have_attributes(event: "update", created_at: widget.updated_at) + end + + it "stamps an update version with the time of the write when the creation timestamp is not synchronized" do + widget = UnsynchronizedWidget.create!(name: "a") + written_at = Time.current + widget.update!(name: "b", updated_at: 1.day.ago) + + travel(1.hour) { perform_jobs } + + expect(widget.versions.find_by(event: "update").created_at).to be_within(60).of(written_at) + end + + it "records the changes of paper_trail.update_columns" do + widget = created_widget + widget.paper_trail.update_columns(name: "c") + + perform_jobs + + expect(widget.versions.last.object_changes).to eq("name" => %w[a c]) + end + + it "stamps a destroy version with the time of the destroy, not of the job" do + widget = created_widget + destroyed_at = Time.current + widget.destroy! + + travel(1.hour) { perform_jobs } + + expect(PaperTrail::Version.find_by(event: "destroy").created_at).to be_within(60).of(destroyed_at) + end + + it "enqueues only after the outermost transaction commits" do + AsyncWidget.transaction do + AsyncWidget.create!(name: "a") + expect(jobs).to be_empty + end + + expect(jobs.size).to eq(1) + end + + it "enqueues nothing for a rolled back savepoint" do + AsyncWidget.transaction do + AsyncWidget.transaction(requires_new: true) do + AsyncWidget.create!(name: "a") + raise ActiveRecord::Rollback + end + end + + expect(jobs).to be_empty + end + + it "enqueues once the record's database commits, even when another database rolls back" do + stub_const("OtherDatabaseRecord", Class.new(ActiveRecord::Base) { self.abstract_class = true }) + OtherDatabaseRecord.establish_connection(adapter: "sqlite3", database: ":memory:") + + OtherDatabaseRecord.transaction do + AsyncWidget.create!(name: "a") + raise ActiveRecord::Rollback + end + + expect(jobs.size).to eq(1) + ensure + OtherDatabaseRecord.remove_connection + end + + it "enqueues once the record's database commits, even when the job defers enqueuing to every transaction's commit" do + stub_const("VersionJob", Class.new(ActiveJob::Base) do + include ActiveJob::EnqueueAfterTransactionCommit + + self.enqueue_after_transaction_commit = true + include PaperTrail::Background::Job + end) + stub_const("OtherDatabaseRecord", Class.new(ActiveRecord::Base) { self.abstract_class = true }) + OtherDatabaseRecord.establish_connection(adapter: "sqlite3", database: ":memory:") + + OtherDatabaseRecord.transaction do + AsyncWidget.create!(name: "a") + raise ActiveRecord::Rollback + end + + expect(jobs.size).to eq(1) + ensure + OtherDatabaseRecord.remove_connection + end + + it "enqueues inside a non-joinable transaction, as transactional tests open" do + AsyncWidget.lease_connection.transaction(joinable: false) do + AsyncWidget.create!(name: "a") + expect(jobs.size).to eq(1) + end + end + + it "writes synchronously for a model without async when opt_in is on" do + expect { PlainWidget.create!(name: "a") }.to change(PaperTrail::Version, :count).by(1) + expect(jobs).to be_empty + end + + it "goes through the job for every model when opt_in is off" do + PaperTrail::Background::Config.configure { |config| config.opt_in = false } + + widget = PlainWidget.create!(name: "a") + widget.destroy! + + expect(jobs.size).to eq(2) + expect { perform_jobs }.to change { widget.versions.pluck(:event) }.from([]).to(%w[create destroy]) + end + + it "writes every event synchronously for a model with async: false when opt_in is off" do + PaperTrail::Background::Config.configure { |config| config.opt_in = false } + + widget = SyncWidget.create!(name: "a") + widget.update!(name: "b") + widget.paper_trail.update_columns(name: "c") + widget.destroy! + + expect(jobs).to be_empty + expect(widget.versions.pluck(:event)).to eq(%w[create update update destroy]) + end + + it "files the version under the model's polymorphic name" do + stub_const("Gadget", RenamedWidget) + widget = RenamedWidget.create!(name: "a") + + expect { perform_jobs }.to change { widget.versions.count }.from(0).to(1) + end +end diff --git a/lib/paper_trail/background/rspec_helpers.rb b/lib/paper_trail/background/rspec_helpers.rb index a51b08d..4e7228e 100644 --- a/lib/paper_trail/background/rspec_helpers.rb +++ b/lib/paper_trail/background/rspec_helpers.rb @@ -5,34 +5,25 @@ module Background module RSpecHelpers module InstanceMethods # enable versioning for specific blocks (at instance-level) - def with_versioning(expected_open_transactions: 1, &block) + def with_versioning(&block) was_enabled = ::PaperTrail.enabled? ::PaperTrail.enabled = true - normally_open_transactions = ActiveRecord::Base.normally_open_transactions - ActiveRecord::Base.normally_open_transactions = expected_open_transactions - # ensure that VersionJobs are executed perform_enqueued_jobs only: VersionJob, &block ensure ::PaperTrail.enabled = was_enabled - ActiveRecord::Base.normally_open_transactions = normally_open_transactions end end module ClassMethods # enable versioning for specific blocks (at class-level) - def with_versioning(expected_open_transactions: 1, &block) + def with_versioning(&block) context "with versioning", versioning: true do around do |example| - normally_open_transactions = ActiveRecord::Base.normally_open_transactions - ActiveRecord::Base.normally_open_transactions = expected_open_transactions - perform_enqueued_jobs only: VersionJob do example.run end - - ActiveRecord::Base.normally_open_transactions = normally_open_transactions end class_exec(&block) diff --git a/lib/paper_trail/background/version.rb b/lib/paper_trail/background/version.rb index 9f33eb1..d7fb720 100644 --- a/lib/paper_trail/background/version.rb +++ b/lib/paper_trail/background/version.rb @@ -2,6 +2,6 @@ module PaperTrail module Background - VERSION = "1.4.0" + VERSION = "2.0.0" end end diff --git a/lib/paper_trail/background_spec.rb b/lib/paper_trail/background_spec.rb index ccd9d2f..b38b1df 100644 --- a/lib/paper_trail/background_spec.rb +++ b/lib/paper_trail/background_spec.rb @@ -44,12 +44,12 @@ def data_for_destroy {} end - def data_for_update_columns - {} + def data_for_update + { source: :data_for_update } end - def force - true + def data_for_update_columns + { source: :data_for_update_columns } end end @@ -91,13 +91,21 @@ def self.perform_later(*args); end it "triggers a write if record is opted in and async is true" do allow(record).to receive(:paper_trail_options).and_return(async: true) allow(PaperTrail::Events::Create).to receive(:new).and_return(WithData.new({})) - allow(record.class).to receive(:paper_trail).and_return(WithVersionClass.new(Class)) - allow(record.class).to receive(:after_transaction).and_yield + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) DummyClass.new(options: { enabled: true }, record:).record_create expect(VersionJob).to have_received(:perform_later) end + + it "returns nil instead of the enqueued job, so paper_trail-association_tracking finds no version" do + allow(VersionJob).to receive(:perform_later).and_return(VersionJob.new) + allow(record).to receive(:paper_trail_options).and_return(async: true) + allow(PaperTrail::Events::Create).to receive(:new).and_return(WithData.new({})) + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) + + expect(DummyClass.new(options: { enabled: true }, record:).record_create).to be_nil + end end end @@ -136,8 +144,7 @@ def self.perform_later(*args); end it "triggers a write if record is opted in and async is true" do allow(record).to receive_messages(paper_trail_options: { async: true }, new_record?: false) allow(PaperTrail::Events::Destroy).to receive(:new).and_return(WithData.new({})) - allow(record.class).to receive(:paper_trail).and_return(WithVersionClass.new(Class)) - allow(record.class).to receive(:after_transaction).and_yield + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) DummyClass.new(options: { enabled: true }, record:).record_destroy("after") @@ -173,13 +180,22 @@ def self.perform_later(*args); end it "triggers a write if record is opted in and async is true" do allow(record).to receive_messages(paper_trail_options: { async: true }, new_record?: false) allow(PaperTrail::Events::Update).to receive(:new).and_return(WithData.new({})) - allow(record.class).to receive(:paper_trail).and_return(WithVersionClass.new(Class)) - allow(record.class).to receive(:after_transaction).and_yield + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) DummyClass.new(options: { enabled: true }, record:).record_update(force: true, in_after_callback: true, is_touch: false) expect(VersionJob).to have_received(:perform_later) end + + it "merges data_for_update into the job payload" do + allow(record).to receive_messages(paper_trail_options: { async: true }, new_record?: false) + allow(PaperTrail::Events::Update).to receive(:new).and_return(WithData.new({})) + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) + + DummyClass.new(options: { enabled: true }, record:).record_update(force: true, in_after_callback: true, is_touch: false) + + expect(VersionJob).to have_received(:perform_later).with("Class", hash_including(source: :data_for_update), :update) + end end end @@ -210,13 +226,22 @@ def self.perform_later(*args); end it "triggers a write if record is opted in and async is true" do allow(record).to receive_messages(paper_trail_options: { async: true }, new_record?: false) allow(PaperTrail::Events::Update).to receive(:new).and_return(WithData.new({})) - allow(record.class).to receive(:paper_trail).and_return(WithVersionClass.new(Class)) - allow(record.class).to receive(:after_transaction).and_yield + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) DummyClass.new(options: { enabled: true }, record:).record_update_columns({}) expect(VersionJob).to have_received(:perform_later) end + + it "merges data_for_update_columns into the job payload" do + allow(record).to receive_messages(paper_trail_options: { async: true }, new_record?: false) + allow(PaperTrail::Events::Update).to receive(:new).and_return(WithData.new({})) + allow(record.class).to receive_messages(current_transaction: ActiveRecord::Transaction::NULL_TRANSACTION, paper_trail: WithVersionClass.new(Class)) + + DummyClass.new(options: { enabled: true }, record:).record_update_columns({}) + + expect(VersionJob).to have_received(:perform_later).with("Class", hash_including(source: :data_for_update_columns), :update) + end end end end diff --git a/paper_trail-background.gemspec b/paper_trail-background.gemspec index a8572b1..05bafdd 100644 --- a/paper_trail-background.gemspec +++ b/paper_trail-background.gemspec @@ -15,7 +15,6 @@ Gem::Specification.new do |spec| spec.require_paths = ["lib"] spec.add_dependency "activerecord", ">= 8.0" - spec.add_dependency "ar_after_transaction", ">= 1.1.0" - spec.add_dependency "paper_trail", ">= 12" + spec.add_dependency "paper_trail", ">= 17.0", "< 18" spec.metadata["rubygems_mfa_required"] = "true" end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f10e258..7428bfb 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,3 @@ -require "pry" require "rspec" require "paper_trail-background"