Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Trim lifecycle event noise: no touch duplicates, one event per import group
Damian Legawiec287c52060410
diff --git a/spree/core/app/jobs/spree/imports/process_group_job.rb b/spree/core/app/jobs/spree/imports/process_group_job.rbindex da1bbaab82..df1c1825af 100644--- a/spree/core/app/jobs/spree/imports/process_group_job.rb+++ b/spree/core/app/jobs/spree/imports/process_group_job.rb@@ -28,6 +28,9 @@ module Spreemappings = import.mappings.mapped.to_aschema_fields = import.schema_fieldslarge = import.large_import?+ grouped = import.group_column.present? && mappings.any? { |m| m.schema_field == import.group_column }+ started_at = Time.current+ processed_rows = []row_ids.each_slice(ROWS_BATCH_SIZE) do |ids|# Skip rows already completed on a prior attempt so retries don't double-process them.@@ -41,18 +44,45 @@ module SpreeSpree::Events.disable dorows.each { |row| row.bulk_process!(mappings: mappings, schema_fields: schema_fields) }end+ elsif grouped+ # A group is one product plus its variants: per-record lifecycle+ # events (variant.created, price.created, product.updated per+ # touch) are noise to subscribers — one product event is published+ # for the whole group below. import_row.* events still flow.+ Spree::Events.disable_lifecycle do+ rows.each { |row| row.process!(mappings: mappings, schema_fields: schema_fields) }+ endelserows.each do |row|row.process!(mappings: mappings, schema_fields: schema_fields)endend+ processed_rows.concat(rows)end+ publish_group_events(processed_rows, started_at) if groupedcheck_import_completion(import, large)endprivate+ # One event per product touched by this group: `product.created` when the+ # product came into existence during this run, `product.updated` otherwise+ # (including retries of a group whose first attempt created it).+ def publish_group_events(rows, started_at)+ products = rows.select { |row| row.status == 'completed' }.filter_map do |row|+ item = row.item+ next item if item.is_a?(Spree::Product)++ item.product if item.respond_to?(:product)+ end.uniq++ products.each do |product|+ event = product.created_at >= started_at ? 'product.created' : 'product.updated'+ product.publish_event(event)+ end+ end+# Completion is row-state-derived so retry-induced over-increments of the counter# stay harmless. The counter pre-check just shortcuts the row scan for workers# that obviously can't be the last group to finish. `in_flight` excludes orphaneddiff --git a/spree/core/app/models/concerns/spree/publishable.rb b/spree/core/app/models/concerns/spree/publishable.rbindex a8e75e34e8..0b67301f76 100644--- a/spree/core/app/models/concerns/spree/publishable.rb+++ b/spree/core/app/models/concerns/spree/publishable.rb@@ -39,6 +39,18 @@ module Spreeincluded doclass_attribute :publish_events, default: trueclass_attribute :lifecycle_events_enabled, default: false++ after_update :mark_real_update_for_events+ end++ # A bare `touch` (variant → product, price → variant, asset → variants)+ # writes no attribute changes — the resulting update event would carry+ # nothing subscribers haven't already been told. Track it here so the+ # commit callback can tell a touch-only commit from a real update;+ # `saved_changes` can't (a touch replays the previous save's changeset).+ def touch(*names, time: nil)+ @_spree_touched_for_events = true+ superendclass_methods do@@ -228,7 +240,21 @@ module Spreeenddef should_publish_events?- self.class.publish_events && Spree::Events.enabled?+ self.class.publish_events && Spree::Events.lifecycle_enabled?+ end++ # True when this commit was caused only by `touch` — no real save ran+ # (`after_update` fires for saves, never for touches). Flags reset every+ # commit so a later genuine update publishes normally.+ def touch_only_update?+ touched = @_spree_touched_for_events+ updated = @_spree_updated_for_events+ @_spree_touched_for_events = @_spree_updated_for_events = nil+ touched && !updated+ end++ def mark_real_update_for_events+ @_spree_updated_for_events = trueenddef publish_create_event@@ -236,6 +262,8 @@ module Spreeenddef publish_update_event+ return if touch_only_update?+publish_event("#{event_prefix}.updated")enddiff --git a/spree/core/lib/spree/events.rb b/spree/core/lib/spree/events.rbindex dcee991b5c..e761afc86e 100644--- a/spree/core/lib/spree/events.rb+++ b/spree/core/lib/spree/events.rb@@ -187,7 +187,7 @@ module Spree## @return [Boolean]def enabled?- !@globally_disabled && !Thread.current[:spree_events_disabled]+ !@globally_disabled && !RequestStore.store[:spree_events_disabled]end# Temporarily disable events within a block@@ -202,11 +202,35 @@ module Spree# end#def disable- previous = Thread.current[:spree_events_disabled]- Thread.current[:spree_events_disabled] = true+ previous = RequestStore.store[:spree_events_disabled]+ RequestStore.store[:spree_events_disabled] = trueyieldensure- Thread.current[:spree_events_disabled] = previous+ RequestStore.store[:spree_events_disabled] = previous+ end++ # Check if automatic lifecycle events (*.created/updated/deleted) are enabled+ #+ # @return [Boolean]+ def lifecycle_enabled?+ enabled? && !RequestStore.store[:spree_lifecycle_events_disabled]+ end++ # Temporarily disable automatic lifecycle events within a block+ #+ # Unlike {disable}, explicitly published events (`publish_event`) still+ # flow — only the per-record *.created/updated/deleted callbacks are+ # suppressed. Used by bulk operations that emit their own coarser events+ # afterwards (e.g. one product event per imported group).+ #+ # @yield Block during which lifecycle events are disabled+ # @return [Object] Return value of the block+ def disable_lifecycle+ previous = RequestStore.store[:spree_lifecycle_events_disabled]+ RequestStore.store[:spree_lifecycle_events_disabled] = true+ yield+ ensure+ RequestStore.store[:spree_lifecycle_events_disabled] = previousend# Globally disable events@@ -233,13 +257,13 @@ module Spree#def enableprevious_global = @globally_disabled- previous_thread = Thread.current[:spree_events_disabled]+ previous_thread = RequestStore.store[:spree_events_disabled]@globally_disabled = false- Thread.current[:spree_events_disabled] = false+ RequestStore.store[:spree_events_disabled] = falseyieldensure@globally_disabled = previous_global- Thread.current[:spree_events_disabled] = previous_thread+ RequestStore.store[:spree_events_disabled] = previous_threadend# Globally enable eventsdiff --git a/spree/core/lib/spree/testing_support/lifecycle_events.rb b/spree/core/lib/spree/testing_support/lifecycle_events.rbindex 6a3f1cb4d9..9f4a2dce5f 100644--- a/spree/core/lib/spree/testing_support/lifecycle_events.rb+++ b/spree/core/lib/spree/testing_support/lifecycle_events.rb@@ -21,6 +21,18 @@ shared_examples_for 'lifecycle events' do |factory: nil, event_prefix: nil|expect(record).to receive(:publish_event).with("#{lifecycle_event_prefix}.updated")allow(record).to receive(:publish_event).with(anything)+ # update_attribute, not update!: Spree::Shipment#update! shadows the+ # Active Record method with the legacy state-recalculation API.+ Timecop.travel(1.minute.from_now) do+ record.update_attribute(:updated_at, Time.current)+ end+ end++ it 'does not publish updated event on a bare touch' do+ record = create(lifecycle_factory)+ expect(record).not_to receive(:publish_event).with("#{lifecycle_event_prefix}.updated")+ allow(record).to receive(:publish_event).with(anything)+record.touchendenddiff --git a/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb b/spree/core/spec/jobs/spree/imports/process_group_job_spec.rbindex b98c987e77..c03cbdd887 100644--- a/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb+++ b/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb@@ -40,6 +40,48 @@ RSpec.describe Spree::Imports::ProcessGroupJob, type: :job doexpect(import.status).to eq('completed')end+ context 'group-level events', events: true do+ before do+ Spree::Events.reset!+ end++ after do+ Spree::Events.reset!+ end++ it 'publishes one product event per group instead of per-record lifecycle noise' do+ published = Hash.new(0)+ %w[product.created product.updated variant.created price.created].each do |name|+ Spree::Events.subscribe(name, async: false) { published[name] += 1 }+ end+ Spree::Events.activate!++ described_class.perform_now(import.id, [row.id])++ expect(published['product.created']).to eq(1)+ expect(published['variant.created']).to eq(0)+ expect(published['price.created']).to eq(0)+ expect(published['product.updated']).to eq(0)+ end++ it 'publishes product.updated when the product existed before this run' do+ described_class.perform_now(import.id, [row.id])+ row.reload.update_columns(status: 'pending')+ import.update_columns(status: 'processing', completed_groups_count: 0)++ published = Hash.new(0)+ %w[product.created product.updated].each do |name|+ Spree::Events.subscribe(name, async: false) { published[name] += 1 }+ end+ Spree::Events.activate!++ described_class.perform_now(import.id, [row.id])++ expect(published['product.created']).to eq(0)+ expect(published['product.updated']).to eq(1)+ end+ end+it 'does not complete import when other groups still have pending rows' do# A second group's rows exist but haven't been processed yet; this group finishing# its own rows must not flip the import to completed.diff --git a/spree/core/spec/models/concerns/spree/publishable_spec.rb b/spree/core/spec/models/concerns/spree/publishable_spec.rbindex 1465058b54..3ec1b2cd22 100644--- a/spree/core/spec/models/concerns/spree/publishable_spec.rb+++ b/spree/core/spec/models/concerns/spree/publishable_spec.rb@@ -302,6 +302,50 @@ RSpec.describe Spree::Publishable, events: true doexpect(skipped_class.publish_events).to be falseendend++ context 'on touch' do+ let!(:product) { create(:product) }++ it 'does not publish an update event for a touch-only save' do+ received = false+ Spree::Events.subscribe('product.updated', async: false) { received = true }+ Spree::Events.activate!++ product.touch++ expect(received).to be false+ end++ it 'still publishes an update event for a real attribute change' do+ received = false+ Spree::Events.subscribe('product.updated', async: false) { received = true }+ Spree::Events.activate!++ product.update!(name: 'Renamed')++ expect(received).to be true+ end+ end++ context 'within Spree::Events.disable_lifecycle' do+ let(:product) { create(:product) }++ it 'suppresses lifecycle events but lets explicit events through' do+ lifecycle_received = false+ explicit_received = false+ Spree::Events.subscribe('product.updated', async: false) { lifecycle_received = true }+ Spree::Events.subscribe('product.custom', async: false) { explicit_received = true }+ Spree::Events.activate!++ Spree::Events.disable_lifecycle do+ product.update!(name: 'Renamed')+ product.publish_event('product.custom')+ end++ expect(lifecycle_received).to be false+ expect(explicit_received).to be true+ end+ endenddescribe '.event_prefix' dodiff --git a/spree/core/spec/models/spree/customer_return_spec.rb b/spree/core/spec/models/spree/customer_return_spec.rbindex c1d083038c..bada15f534 100644--- a/spree/core/spec/models/spree/customer_return_spec.rb+++ b/spree/core/spec/models/spree/customer_return_spec.rb@@ -27,7 +27,9 @@ describe Spree::CustomerReturn, type: :model doexpect(record).to receive(:publish_event).with('customer_return.updated')allow(record).to receive(:publish_event).with(anything)- record.touch+ Timecop.travel(1.minute.from_now) do+ record.update_attribute(:updated_at, Time.current)+ endendenddiff --git a/spree/core/spec/models/spree/gift_card_batch_spec.rb b/spree/core/spec/models/spree/gift_card_batch_spec.rbindex 5046f6fac2..e2f918a4a9 100644--- a/spree/core/spec/models/spree/gift_card_batch_spec.rb+++ b/spree/core/spec/models/spree/gift_card_batch_spec.rb@@ -20,7 +20,9 @@ RSpec.describe Spree::GiftCardBatch, type: :model doexpect(record).to receive(:publish_event).with('gift_card_batch.updated')allow(record).to receive(:publish_event).with(anything)- record.touch+ Timecop.travel(1.minute.from_now) do+ record.update_attribute(:updated_at, Time.current)+ endendenddiff --git a/spree/core/spec/models/spree/return_authorization_spec.rb b/spree/core/spec/models/spree/return_authorization_spec.rbindex c76f19443e..080da1d865 100644--- a/spree/core/spec/models/spree/return_authorization_spec.rb+++ b/spree/core/spec/models/spree/return_authorization_spec.rb@@ -31,7 +31,9 @@ describe Spree::ReturnAuthorization, type: :model doexpect(record).to receive(:publish_event).with('return_authorization.updated')allow(record).to receive(:publish_event).with(anything)- record.touch+ Timecop.travel(1.minute.from_now) do+ record.update_attribute(:updated_at, Time.current)+ endendenddiff --git a/spree/core/spec/models/spree/wishlist_spec.rb b/spree/core/spec/models/spree/wishlist_spec.rbindex 4407bb7a46..4e2a01088c 100644--- a/spree/core/spec/models/spree/wishlist_spec.rb+++ b/spree/core/spec/models/spree/wishlist_spec.rb@@ -26,7 +26,9 @@ describe Spree::Wishlist, type: :model doexpect(wishlist).to receive(:publish_event).with('wishlist.updated')allow(wishlist).to receive(:publish_event).with(anything)- wishlist.touch+ Timecop.travel(1.minute.from_now) do+ wishlist.update_attribute(:updated_at, Time.current)+ endendend