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
Import spine on ActiveJob Continuations
Damian Legawiec7ff25d7cf541
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0c824d4cca..570335c0c0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -31,7 +31,7 @@ Active plans (6.0 target, work pending):- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). Phase 1 rides the 6.0 core-rewrite finishing work.-- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` step DSL (`argument` typed contracts, `provides:`, `transaction`/`external_step`, `on_flow_failure:`, `rescue_from`, `run_hooks` + `Spree.hooks`, `emit`, bare argument readers), reserved for flows needing hooks, compensation/external I/O, replay, or durability — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins). A service graduates to the workflow tier when it earns a hook, never speculatively. `Carts::Complete` battery must pass unmodified; durable flows via ActiveJob Continuations in Phase 2.+- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` step DSL (`argument` typed contracts, `provides:`, `transaction`/`external_step`, `on_flow_failure:`, `rescue_from`, `run_hooks` + `Spree.hooks`, `emit`, bare argument readers), reserved for flows needing hooks, compensation/external I/O, replay, or durability — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins). A service graduates to the workflow tier when it earns a hook, never speculatively. `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.Multi-version plans (some phases shipped, some pending):diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.mdindex e3c7a2bf60..b7c9fd23d7 100644--- a/docs/plans/6.0-service-workflows.md+++ b/docs/plans/6.0-service-workflows.md@@ -199,45 +199,33 @@ endcommit via `after_commit` on the flow's final transaction (or immediatelywhen no transaction is open). Mirrors today's `finalize!` guarantee that arolled-back completion never leaks `order.placed`.-- **Durable flows (Phase 2 — design settled 2026-07-30, starts after the- cart/order service migrations complete)**: the declared flow structure is- what makes durability mechanical — a different runner walks the same- `flow_items` under checkpointed execution, and services need no rewrite.- - **Crash-resume via ActiveJob Continuations** (Rails 8.1 is the floor): a- generic `Spree::FlowJob` (`include ActiveJob::Continuable`) receives the- flow class name + serialized arguments and wraps each DSL step in a- continuation step. Mapping rules: one DSL step → one checkpoint; a- `transaction do ... end` group → **one** checkpoint (the group is the- atomic unit — no checkpointing inside an open transaction); an- `external_step` → its own checkpoint (the reason the keyword exists).- A deploy/crash re-enqueues and resumes after the last completed step.- - **`provides:` is the checkpoint schema**: after each step the runner- serializes exactly the provided keys into the continuation cursor —- records as GlobalIDs, re-resolved fresh on resume (no stale marshaled- objects). Flows opting into durability get a lint that provided values- must be serializable.- - **Parking** (wait for webhook / 3DS return / manual approval — Medusa's- async steps): beyond Continuations' interruption-resume; needs a- `Spree::FlowExecution` row (flow key, serialized context, position,- `status: 'waiting'`, resume token) + `FlowExecution.resume(token,- payload)` re-enqueueing at the parked step with the payload merged into- context. Precedent: `Carts::Complete` already does this by hand — the- `requires_action` payment session is the park, the customer's redirect- is the external event, `completion_result` replay via `halt_with` is the- resume. Phase 2 generalizes that pattern; whether the stuck-completion- sweeper generalizes with it is decided then.- - **At-least-once, honestly**: an `external_step` crashing after the side- effect but before its checkpoint re-runs on resume. Mitigation the DSL- can offer that ad-hoc services never get: an idempotency key derived per- `(execution_id, step_name)` handed to the step via ctx, for server-side- dedupe (e.g. Stripe idempotency keys).- - **Boundaries**: opt-in per invocation (`Flow.call_later(...)`) or per- flow (`durable!`); synchronous `.call` stays the default for- request-cycle flows. No event-sourced replay à la Temporal (demands- deterministic code — alien to Rails), no separate engine process, no- Redis: Solid Queue + Continuations + one table. Targets: CSV imports,- `spree:upgrade` data migrations, payout runs. Explicitly out of scope- for the 6.0 GA gate if it slips — the DSL must not block on it.+- **Durable flows (Phase 2 — resolved 2026-07-30): plain ActiveJob+ Continuations IS the durability tool.** Rails 8.1's+ `ActiveJob::Continuable` already provides checkpointed steps, cursors+ and interruption-resume; long-running background work uses it directly+ as a plain job — no workflow involvement. Reference implementation:+ `Spree::Imports::ProcessJob` (the CSV import spine — row creation+ resumes from a row-number cursor, then group dispatch; the parallel+ per-group fan-out keeps its own row-status crash-safety). Inline+ callers use `perform_now`; permanent errors are rescued inside the+ step (Continuable resumes errors raised after progress, so+ `discard_on` handlers never run for them); checkpoints are forbidden+ inside open transactions, so transition-callback callers defer the+ inline run to `ActiveRecord.after_all_transactions_commit`.++ A full Workflow-level durable layer (`durable!`, a Continuations-backed+ `Spree::WorkflowJob` walking `flow_items` as checkpoint segments,+ context carried in job data as GlobalIDs) was built, validated+ end-to-end — including interruption/resume with context intact — and+ then deliberately removed as unconsumed framework: every capability it+ added over plain Continuable went unused by the import, and the+ workflows that would use it don't exist yet. It returns only if a flow+ genuinely needs DSL semantics (cross-checkpoint provides, re-armed+ compensation, hooks) *and* durability together — the marketplace+ payout run is the candidate, and it additionally needs the two pieces+ never built: parking (`FlowExecution` rows + resume tokens for KYC+ webhooks) and per-(execution, step) idempotency keys. Design against+ those real requirements then, not before.## Editor & Typing Story@@ -285,9 +273,11 @@ never hand-written (Typelizer philosophy, applied to Ruby):hooks are added by demand, not speculation. Extension-facing docs pending.4. **Rolling adoption:** services migrate when meaningfully touched — never abig-bang sweep. `ServiceModule::Base` is not deprecated in 6.0.-5. **Phase 2 (starts once the cart/order service migrations complete; may- land post-GA):** durable flows per the settled design above — first- consumer is the CSV import pipeline, second the upgrade data migrations.+5. **Phase 2 — resolved:** plain `ActiveJob::Continuable` jobs are the+ durability tool (`Spree::Imports::ProcessJob` is the reference); the+ upgrade data migrations adopt the same pattern. Workflow-level durable+ execution is deliberately not shipped — revisit with the payout run+ per the note above.## Constraints on Current Workdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rbindex 2876cde2a6..e56346fdef 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb@@ -214,7 +214,7 @@ RSpec.describe Spree::Api::V3::Admin::ImportsController, type: :controller doit 'transitions into completed_mapping and enqueues row creation' doexpect {patch :complete_mapping, params: { id: import.prefixed_id }, as: :json- }.to have_enqueued_job(Spree::Imports::CreateRowsJob)+ }.to have_enqueued_job(Spree::Imports::ProcessJob)expect(response).to have_http_status(:ok)expect(json_response['status']).to eq('completed_mapping')@@ -281,7 +281,7 @@ RSpec.describe Spree::Api::V3::Admin::ImportsController, type: :controller doit 're-enters processing and re-dispatches the rows' doexpect {patch :retry_failed_rows, params: { id: product_import.prefixed_id }, as: :json- }.to have_enqueued_job(Spree::Imports::ProcessRowsJob)+ }.to have_enqueued_job(Spree::Imports::ProcessJob)expect(response).to have_http_status(:ok)expect(json_response['status']).to eq('processing')diff --git a/spree/core/app/jobs/spree/imports/create_rows_job.rb b/spree/core/app/jobs/spree/imports/create_rows_job.rbindex c1c3bd853f..695d366698 100644--- a/spree/core/app/jobs/spree/imports/create_rows_job.rb+++ b/spree/core/app/jobs/spree/imports/create_rows_job.rb@@ -1,69 +1,10 @@module Spreemodule Imports+ # @deprecated Use {Spree::Imports::ProcessJob}; removed in 6.1.class CreateRowsJob < Spree::Imports::BaseJob- discard_on ::CSV::MalformedCSVError, EncodingError do |job, error|- import = Spree::Import.find(job.arguments.first)- import.update_columns(processing_errors: error.message, status: :failed, updated_at: Time.current)- Rails.error.report error- end-- BATCH_SIZE = 1000-def perform(import_id)- import = Spree::Import.find(import_id)- import.start_processing! if import.status != 'processing'-- create_rows_sequentially(import)-- # enqueue processing rows job after creating rows in a separate job- import.process_rows_async- end-- private-- def create_rows_sequentially(import)- rows_to_insert = []- row_number = 1-- created_at = updated_at = Time.current-- upsert_options = {}- if %w[PostgreSQL SQLite].include?(ActiveRecord::Base.connection.adapter_name)- upsert_options[:unique_by] = :index_spree_import_rows_on_import_id_and_row_number- end- # NOTE: Ensure a DB-level unique index on [:import_id, :row_number] for all adapters.-- # Stream CSV to avoid loading entire file in memory- # This maintains order by processing sequentially- ::CSV.foreach(StringIO.new(import.attachment_file_content),- headers: true,- col_sep: import.preferred_delimiter,- encoding: 'UTF-8') do |csv_row|-- rows_to_insert << {- import_id: import.id,- row_number: row_number,- data: csv_row.to_h.to_json,- status: 'pending',- created_at: created_at,- updated_at: updated_at- }-- row_number += 1-- # Bulk upsert when we reach batch size- if rows_to_insert.size >= BATCH_SIZE- Spree::ImportRow.upsert_all(rows_to_insert, **upsert_options)- rows_to_insert.clear- end- end-- # Upsert any remaining rows- if rows_to_insert.any?- Spree::ImportRow.upsert_all(rows_to_insert, **upsert_options)- end-- Spree::Import.reset_counters(import.id, :rows)+ Spree::Deprecation.warn('Spree::Imports::CreateRowsJob is deprecated and will be removed in Spree 6.1. Use Spree::Imports::ProcessJob instead.')+ Spree::Imports::ProcessJob.perform_now(import_id)endendenddiff --git a/spree/core/app/jobs/spree/imports/process_job.rb b/spree/core/app/jobs/spree/imports/process_job.rbnew file mode 100644index 0000000000..581e0c7464--- /dev/null+++ b/spree/core/app/jobs/spree/imports/process_job.rb@@ -0,0 +1,158 @@+module Spree+ module Imports+ # The sequential spine of the import pipeline on ActiveJob+ # Continuations: CSV streaming into ImportRow records (cursor = row+ # number, so a deploy mid-stream resumes instead of restarting the+ # parse), then group dispatch. The parallel per-group processing stays+ # on ProcessGroupJob — its crash-safety comes from row statuses and+ # the completion counters. A malformed file is a permanent failure,+ # handled inside the create_rows step, never a retry loop.+ #+ # `skip_row_creation: true` is the retry entry (rows already exist,+ # only failed/pending ones get re-dispatched). Inline callers (seeds,+ # sample data) run the same steps synchronously via `perform_now`.+ class ProcessJob < Spree::Imports::BaseJob+ include ActiveJob::Continuable++ ROW_BATCH_SIZE = 1000+ GROUP_BATCH_SIZE = 100+ UNGROUPED_KEY = '__ungrouped__'.freeze++ def perform(import_id, skip_row_creation: false)+ # Outside the steps on purpose — runs on every execution, including+ # resumes after an interruption.+ @import = Spree::Import.find(import_id)++ unless skip_row_creation+ step :begin_processing do+ @import.start_processing! if @import.status != 'processing'+ end+ step :create_rows, start: 1+ # A permanent CSV failure marked the import failed inside the step+ # (rescuing there, not via discard_on — Continuable resumes errors+ # raised after progress, so discard handlers would never run).+ return if @csv_failed++ step :reset_row_counters do+ Spree::Import.reset_counters(@import.id, :rows)+ end+ end++ step :dispatch_row_groups+ end++ private++ # Streams the CSV so the whole file never sits in memory; the cursor+ # is the next row number to insert, checkpointed once per batch. On+ # resume the stream is re-read but rows below the cursor are skipped —+ # progress is monotonic even under a rolling-deploy storm.+ def create_rows(step)+ rows_to_insert = []+ row_number = 1+ created_at = updated_at = Time.current++ upsert_options = {}+ if %w[PostgreSQL SQLite].include?(ActiveRecord::Base.connection.adapter_name)+ upsert_options[:unique_by] = :index_spree_import_rows_on_import_id_and_row_number+ end++ ::CSV.foreach(StringIO.new(@import.attachment_file_content),+ headers: true,+ col_sep: @import.preferred_delimiter,+ encoding: 'UTF-8') do |csv_row|+ if row_number < step.cursor+ row_number += 1+ next+ end++ rows_to_insert << {+ import_id: @import.id,+ row_number: row_number,+ data: csv_row.to_h.to_json,+ status: 'pending',+ created_at: created_at,+ updated_at: updated_at+ }+ row_number += 1++ if rows_to_insert.size >= ROW_BATCH_SIZE+ Spree::ImportRow.upsert_all(rows_to_insert, **upsert_options)+ rows_to_insert.clear+ step.set!(row_number)+ end+ end++ Spree::ImportRow.upsert_all(rows_to_insert, **upsert_options) if rows_to_insert.any?+ rescue ::CSV::MalformedCSVError, EncodingError => e+ @import.update_columns(processing_errors: e.message, status: :failed, updated_at: Time.current)+ Rails.error.report(e)+ @csv_failed = true+ end++ def dispatch_row_groups+ group_field = @import.group_column+ group_mapping = group_field && @import.mappings.mapped.find_by(schema_field: group_field)+ file_column = group_mapping&.file_column++ if file_column+ dispatch_grouped(file_column)+ else+ dispatch_batched+ end+ end++ # Inline callers need the group finished before `perform` returns; the+ # group job's completion bookkeeping works either way.+ def dispatch_group(row_ids)+ return ProcessGroupJob.perform_now(@import.id, row_ids) if @import.preferred_inline++ ProcessGroupJob.perform_later(@import.id, row_ids)+ end++ def dispatch_grouped(file_column)+ groups = Hash.new { |hash, key| hash[key] = [] }++ @import.rows.pending_and_failed.order(:row_number).pluck(:id, :data).each do |id, data|+ parsed = JSON.parse(data)+ key = parsed[file_column].to_s.strip.downcase.presence || UNGROUPED_KEY+ groups[key] << id+ rescue JSON::ParserError+ groups[UNGROUPED_KEY] << id+ end++ # Rows without a group value don't depend on each other, so they don't have+ # to share a single job — split them into bounded batches. Real groups stay+ # intact: their rows must run sequentially (product row before variant rows).+ ungrouped = groups.delete(UNGROUPED_KEY)+ batches = groups.values+ ungrouped&.each_slice(GROUP_BATCH_SIZE) { |row_ids| batches << row_ids }++ # Set count before enqueuing so workers can't complete prematurely+ @import.update_columns(+ processing_groups_count: batches.size,+ completed_groups_count: 0,+ updated_at: Time.current+ )++ batches.each { |row_ids| dispatch_group(row_ids) }+ end++ def dispatch_batched+ # Count first, then enqueue — prevents premature completion+ row_id_batches = @import.rows.pending_and_failed.order(:row_number)+ .pluck(:id)+ .each_slice(GROUP_BATCH_SIZE)+ .to_a++ @import.update_columns(+ processing_groups_count: row_id_batches.size,+ completed_groups_count: 0,+ updated_at: Time.current+ )++ row_id_batches.each { |row_ids| dispatch_group(row_ids) }+ end+ end+ end+enddiff --git a/spree/core/app/jobs/spree/imports/process_rows_job.rb b/spree/core/app/jobs/spree/imports/process_rows_job.rbindex 47b8e0c359..bda5dbcb49 100644--- a/spree/core/app/jobs/spree/imports/process_rows_job.rb+++ b/spree/core/app/jobs/spree/imports/process_rows_job.rb@@ -1,78 +1,11 @@module Spreemodule Imports+ # @deprecated Use {Spree::Imports::ProcessJob} with skip_row_creation:+ # true; removed in 6.1.class ProcessRowsJob < Spree::Imports::BaseJob- BATCH_SIZE = 100- UNGROUPED_KEY = '__ungrouped__'.freeze-def perform(import_id)- import = Spree::Import.find(import_id)- dispatch_groups(import)- end-- private-- def dispatch_groups(import)- group_field = import.group_column- group_mapping = group_field && import.mappings.mapped.find_by(schema_field: group_field)- file_column = group_mapping&.file_column-- if file_column- dispatch_grouped(import, file_column)- else- dispatch_batched(import)- end- end-- # Inline callers need the group finished before `perform` returns; the- # group job's completion bookkeeping works either way.- def dispatch_group(import, row_ids)- return ProcessGroupJob.perform_now(import.id, row_ids) if import.preferred_inline-- ProcessGroupJob.perform_later(import.id, row_ids)- end-- def dispatch_grouped(import, file_column)- groups = Hash.new { |h, k| h[k] = [] }-- import.rows.pending_and_failed.order(:row_number).pluck(:id, :data).each do |id, data|- parsed = JSON.parse(data)- key = parsed[file_column].to_s.strip.downcase.presence || UNGROUPED_KEY- groups[key] << id- rescue JSON::ParserError- groups[UNGROUPED_KEY] << id- end-- # Rows without a group value don't depend on each other, so they don't have- # to share a single job — split them into bounded batches. Real groups stay- # intact: their rows must run sequentially (product row before variant rows).- ungrouped = groups.delete(UNGROUPED_KEY)- batches = groups.values- ungrouped&.each_slice(BATCH_SIZE) { |row_ids| batches << row_ids }-- # Set count before enqueuing so workers can't complete prematurely- import.update_columns(- processing_groups_count: batches.size,- completed_groups_count: 0,- updated_at: Time.current- )-- batches.each { |row_ids| dispatch_group(import, row_ids) }- end-- def dispatch_batched(import)- # Count first, then enqueue — prevents premature completion- row_id_batches = import.rows.pending_and_failed.order(:row_number)- .pluck(:id)- .each_slice(BATCH_SIZE)- .to_a-- import.update_columns(- processing_groups_count: row_id_batches.size,- completed_groups_count: 0,- updated_at: Time.current- )-- row_id_batches.each { |row_ids| dispatch_group(import, row_ids) }+ Spree::Deprecation.warn('Spree::Imports::ProcessRowsJob is deprecated and will be removed in Spree 6.1. Use Spree::Imports::ProcessJob instead.')+ Spree::Imports::ProcessJob.perform_now(import_id, skip_row_creation: true)endendenddiff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rbindex 0294802dc4..2fea33ce33 100644--- a/spree/core/app/models/spree/import.rb+++ b/spree/core/app/models/spree/import.rb@@ -183,7 +183,7 @@ module Spreeend# Imports are deletable only while no processing jobs can be in flight —- # CreateRowsJob/ProcessGroupJob re-load the record mid-run.+ # ProcessJob/ProcessGroupJob re-load the record mid-run.# @return [Boolean]def can_be_deleted?%w[pending mapping completed failed].include?(status)@@ -345,19 +345,28 @@ module Spree# Creates rows asynchronously# @return [void]def create_rows_async- # The 2s delay lets the attachment settle before the job reads it; running- # inline there is nothing to wait for.- return Spree::Imports::CreateRowsJob.perform_now(id) if preferred_inline+ if preferred_inline+ # The transition callback runs inside the state machine's+ # transaction and Continuations forbid checkpoints there — the+ # inline run starts at commit, still before the transition call+ # returns to the caller.+ ActiveRecord.after_all_transactions_commit { Spree::Imports::ProcessJob.perform_now(id) }+ return+ end- Spree::Imports::CreateRowsJob.set(wait: 2.seconds).perform_later(id)+ # The 2s delay lets the attachment settle before the job reads it.+ Spree::Imports::ProcessJob.set(wait: 2.seconds).perform_later(id)end# Processes rows asynchronously# @return [void]def process_rows_async- return Spree::Imports::ProcessRowsJob.perform_now(id) if preferred_inline+ if preferred_inline+ ActiveRecord.after_all_transactions_commit { Spree::Imports::ProcessJob.perform_now(id, skip_row_creation: true) }+ return+ end- Spree::Imports::ProcessRowsJob.perform_later(id)+ Spree::Imports::ProcessJob.perform_later(id, skip_row_creation: true)end# Returns the store for the importdiff --git a/spree/core/spec/jobs/spree/imports/create_rows_job_spec.rb b/spree/core/spec/jobs/spree/imports/create_rows_job_spec.rbindex d743cc8b0e..3d8d52c05a 100644--- a/spree/core/spec/jobs/spree/imports/create_rows_job_spec.rb+++ b/spree/core/spec/jobs/spree/imports/create_rows_job_spec.rb@@ -1,71 +1,12 @@require 'spec_helper'RSpec.describe Spree::Imports::CreateRowsJob, type: :job do- let(:user) { create(:admin_user) }- let(:store) { @default_store }+ let(:import) { create(:import, owner: @default_store, type: 'Spree::Imports::Products', status: :completed_mapping) }- let(:csv_content) do- <<~CSV- slug,sku,name,price,option1_name,option1_value- denim-shirt,SKU1,Denim Shirt,9.99- denim-shirt,SKU2,,19.99,Color,Red- CSV- end-- let!(:import) do- create(- :import,- user: user,- owner: store,- type: 'Spree::Imports::Products',- status: :completed_mapping- )- end-- before do- # Attach CSV as import attachment- import.attachment.attach(- io: StringIO.new(csv_content),- filename: 'products.csv',- content_type: 'text/csv'- )- end-- it 'creates import rows from the CSV file' do- expect {- described_class.perform_now(import.id)- }.to change { Spree::ImportRow.where(import: import).count }.by(2)-- first_row = import.rows.find_by(row_number: 1)- expect(first_row.data).to eq({ 'slug' => 'denim-shirt', 'sku' => 'SKU1', 'name' => 'Denim Shirt', 'price' => '9.99', 'option1_name' => nil, 'option1_value' => nil }.to_json)- expect(first_row.status).to eq('pending')-- second_row = import.rows.find_by(row_number: 2)- expect(second_row.data).to eq({ 'slug' => 'denim-shirt', 'sku' => 'SKU2', 'name' => nil, 'price' => '19.99', 'option1_name' => 'Color', 'option1_value' => 'Red' }.to_json)- expect(second_row.status).to eq('pending')- end-- it 'transitions import to processing if not already processing' do- expect { described_class.perform_now(import.id) }.to change { import.reload.status }.from('completed_mapping').to('processing')- end-- it 'persists rows count' do- expect { described_class.perform_now(import.id) }.to change { import.reload.rows_count }.from(0).to(2)- end+ it 'warns and delegates to ProcessJob' do+ expect(Spree::Deprecation).to receive(:warn).with(/CreateRowsJob is deprecated/)+ expect(Spree::Imports::ProcessJob).to receive(:perform_now).with(import.id)- it 'enqueues process_rows_async after rows creation' do- expect_any_instance_of(Spree::Import).to receive(:process_rows_async).oncedescribed_class.perform_now(import.id)end-- context 'when CSV is malformed' do- let(:csv_content) { "bad data \x80" }-- it 'sets processing_errors and fails the import' do- described_class.perform_now(import.id)- import.reload- expect(import.status).to eq('failed')- expect(import.processing_errors).to be_present- end- endenddiff --git a/spree/core/spec/jobs/spree/imports/process_job_spec.rb b/spree/core/spec/jobs/spree/imports/process_job_spec.rbnew file mode 100644index 0000000000..0f9f844907--- /dev/null+++ b/spree/core/spec/jobs/spree/imports/process_job_spec.rb@@ -0,0 +1,219 @@+require 'spec_helper'+require 'active_job/continuation/test_helper'++RSpec.describe Spree::Imports::ProcessJob, type: :job do+ let(:user) { create(:admin_user) }+ let(:store) { @default_store }++ describe 'row creation from the CSV attachment' do+ let(:csv_content) do+ <<~CSV+ slug,sku,name,price,option1_name,option1_value+ denim-shirt,SKU1,Denim Shirt,9.99+ denim-shirt,SKU2,,19.99,Color,Red+ CSV+ end++ let!(:import) do+ create(:import, user: user, owner: store, type: 'Spree::Imports::Products', status: :completed_mapping)+ end++ before do+ import.attachment.attach(io: StringIO.new(csv_content), filename: 'products.csv', content_type: 'text/csv')+ end++ it 'creates import rows from the CSV file' do+ expect {+ described_class.perform_now(import.id)+ }.to change { Spree::ImportRow.where(import: import).count }.by(2)++ first_row = import.rows.find_by(row_number: 1)+ expect(first_row.data).to eq({ 'slug' => 'denim-shirt', 'sku' => 'SKU1', 'name' => 'Denim Shirt', 'price' => '9.99', 'option1_name' => nil, 'option1_value' => nil }.to_json)+ expect(first_row.status).to eq('pending')++ second_row = import.rows.find_by(row_number: 2)+ expect(second_row.data).to eq({ 'slug' => 'denim-shirt', 'sku' => 'SKU2', 'name' => nil, 'price' => '19.99', 'option1_name' => 'Color', 'option1_value' => 'Red' }.to_json)+ expect(second_row.status).to eq('pending')+ end++ it 'transitions the import to processing and dispatches groups in the same run' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later).at_least(:once)++ expect { described_class.perform_now(import.id) }+ .to change { import.reload.status }.from('completed_mapping').to('processing')++ expect(import.reload.processing_groups_count).to be > 0+ end++ it 'persists rows count' do+ expect { described_class.perform_now(import.id) }.to change { import.reload.rows_count }.from(0).to(2)+ end++ context 'when CSV is malformed' do+ let(:csv_content) { "bad data \x80" }++ it 'sets processing_errors and fails the import' do+ described_class.perform_now(import.id)++ import.reload+ expect(import.status).to eq('failed')+ expect(import.processing_errors).to be_present+ end+ end++ describe 'interruption and resume' do+ include ActiveJob::Continuation::TestHelper++ around do |example|+ original = ActiveJob::Base.queue_adapter+ ActiveJob::Base.queue_adapter = :test+ example.run+ ensure+ ActiveJob::Base.queue_adapter = original+ end++ before { stub_const('Spree::Imports::ProcessJob::ROW_BATCH_SIZE', 1) }++ it 'resumes row creation from the cursor after an interruption' do+ described_class.perform_later(import.id)++ interrupt_job_during_step(described_class, :create_rows, cursor: 2) { perform_enqueued_jobs }+ expect(import.rows.count).to eq(1)+ expect(import.reload.status).to eq('processing')++ perform_enqueued_jobs++ expect(import.rows.order(:row_number).pluck(:row_number)).to eq([1, 2])+ expect(import.reload.rows_count).to eq(2)+ expect(import.processing_groups_count).to be > 0+ end+ end+ end++ describe 'group dispatch (skip_row_creation: true)' do+ describe 'grouped import (Products)' do+ let!(:import) do+ create(:import, owner: store, type: 'Spree::Imports::Products', status: :processing)+ end++ before do+ allow_any_instance_of(Spree::Import).to receive(:csv_headers).and_return(['slug', 'sku', 'name', 'price', 'option1_name', 'option1_value'])+ import.create_mappings+ end++ let!(:product_row) do+ create(:import_row, import: import, row_number: 1, status: :pending,+ data: { 'slug' => 'denim-shirt', 'sku' => 'SKU1', 'name' => 'Denim Shirt', 'price' => '9.99' }.to_json)+ end++ let!(:variant_row) do+ create(:import_row, import: import, row_number: 2, status: :pending,+ data: { 'slug' => 'denim-shirt', 'sku' => 'SKU2', 'price' => '19.99', 'option1_name' => 'Color', 'option1_value' => 'Red' }.to_json)+ end++ let!(:other_product_row) do+ create(:import_row, import: import, row_number: 3, status: :pending,+ data: { 'slug' => 'cotton-tee', 'sku' => 'SKU3', 'name' => 'Cotton Tee', 'price' => '14.99' }.to_json)+ end++ it 'groups rows by slug and dispatches one job per product' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [product_row.id, variant_row.id])+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [other_product_row.id])++ described_class.perform_now(import.id, skip_row_creation: true)++ import.reload+ expect(import.processing_groups_count).to eq(2)+ expect(import.completed_groups_count).to eq(0)+ end++ it 'skips already completed rows' do+ product_row.update_columns(status: 'completed')++ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [variant_row.id])+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [other_product_row.id])++ described_class.perform_now(import.id, skip_row_creation: true)++ expect(import.reload.processing_groups_count).to eq(2)+ end++ context 'with failed rows' do+ before { variant_row.update_columns(status: 'failed') }++ it 'includes failed rows for reprocessing' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [product_row.id, variant_row.id])+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [other_product_row.id])++ described_class.perform_now(import.id, skip_row_creation: true)+ end+ end++ context 'with rows missing the group value' do+ before { stub_const('Spree::Imports::ProcessJob::GROUP_BATCH_SIZE', 2) }++ let!(:ungrouped_rows) do+ 3.times.map do |i|+ create(:import_row, import: import, row_number: 4 + i, status: :pending,+ data: { 'sku' => "LONE#{i}", 'name' => "Lone #{i}", 'price' => '5.00' }.to_json)+ end+ end++ it 'splits ungrouped rows into bounded batches instead of one unbounded job' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [product_row.id, variant_row.id])+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [other_product_row.id])+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, ungrouped_rows.first(2).map(&:id))+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, [ungrouped_rows.last.id])++ described_class.perform_now(import.id, skip_row_creation: true)++ expect(import.reload.processing_groups_count).to eq(4)+ end+ end+ end++ describe 'batched import (Customers — no group_column)' do+ let!(:import) do+ create(:import, owner: store, type: 'Spree::Imports::Customers', status: :processing)+ end++ let!(:rows) do+ 5.times.map do |i|+ create(:import_row, import: import, row_number: i + 1, status: :pending,+ data: { 'email' => "user#{i}@example.com" }.to_json)+ end+ end++ it 'batches all rows into chunks and dispatches' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)+ .with(import.id, rows.map(&:id))++ described_class.perform_now(import.id, skip_row_creation: true)++ expect(import.reload.processing_groups_count).to eq(1)+ end++ context 'with more rows than GROUP_BATCH_SIZE' do+ before { stub_const('Spree::Imports::ProcessJob::GROUP_BATCH_SIZE', 2) }++ it 'dispatches multiple batch jobs' do+ expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later).exactly(3).times++ described_class.perform_now(import.id, skip_row_creation: true)++ expect(import.reload.processing_groups_count).to eq(3)+ end+ end+ end+ end+enddiff --git a/spree/core/spec/jobs/spree/imports/process_rows_job_spec.rb b/spree/core/spec/jobs/spree/imports/process_rows_job_spec.rbindex c9b66ae7a0..d3c33a348d 100644--- a/spree/core/spec/jobs/spree/imports/process_rows_job_spec.rb+++ b/spree/core/spec/jobs/spree/imports/process_rows_job_spec.rb@@ -1,130 +1,12 @@require 'spec_helper'RSpec.describe Spree::Imports::ProcessRowsJob, type: :job do- let(:store) { @default_store }+ let(:import) { create(:import, owner: @default_store, type: 'Spree::Imports::Products', status: :processing) }- describe 'grouped import (Products)' do- let!(:import) do- create(:import, owner: store, type: 'Spree::Imports::Products', status: :processing)- end+ it 'warns and delegates to ProcessJob, skipping row creation' do+ expect(Spree::Deprecation).to receive(:warn).with(/ProcessRowsJob is deprecated/)+ expect(Spree::Imports::ProcessJob).to receive(:perform_now).with(import.id, skip_row_creation: true)- before do- allow_any_instance_of(Spree::Import).to receive(:csv_headers).and_return(['slug', 'sku', 'name', 'price', 'option1_name', 'option1_value'])- import.create_mappings- end-- let!(:product_row) do- create(:import_row, import: import, row_number: 1, status: :pending,- data: { 'slug' => 'denim-shirt', 'sku' => 'SKU1', 'name' => 'Denim Shirt', 'price' => '9.99' }.to_json)- end-- let!(:variant_row) do- create(:import_row, import: import, row_number: 2, status: :pending,- data: { 'slug' => 'denim-shirt', 'sku' => 'SKU2', 'price' => '19.99', 'option1_name' => 'Color', 'option1_value' => 'Red' }.to_json)- end-- let!(:other_product_row) do- create(:import_row, import: import, row_number: 3, status: :pending,- data: { 'slug' => 'cotton-tee', 'sku' => 'SKU3', 'name' => 'Cotton Tee', 'price' => '14.99' }.to_json)- end-- it 'groups rows by slug and dispatches one job per product' do- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [product_row.id, variant_row.id])- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [other_product_row.id])-- described_class.perform_now(import.id)-- import.reload- expect(import.processing_groups_count).to eq(2)- expect(import.completed_groups_count).to eq(0)- end-- it 'skips already completed rows' do- product_row.update_columns(status: 'completed')-- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [variant_row.id])- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [other_product_row.id])-- described_class.perform_now(import.id)-- expect(import.reload.processing_groups_count).to eq(2)- end-- context 'with failed rows' do- before { variant_row.update_columns(status: 'failed') }-- it 'includes failed rows for reprocessing' do- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [product_row.id, variant_row.id])- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [other_product_row.id])-- described_class.perform_now(import.id)- end- end-- context 'with rows missing the group value' do- before { stub_const('Spree::Imports::ProcessRowsJob::BATCH_SIZE', 2) }-- let!(:ungrouped_rows) do- 3.times.map do |i|- create(:import_row, import: import, row_number: 4 + i, status: :pending,- data: { 'sku' => "LONE#{i}", 'name' => "Lone #{i}", 'price' => '5.00' }.to_json)- end- end-- it 'splits ungrouped rows into bounded batches instead of one unbounded job' do- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [product_row.id, variant_row.id])- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [other_product_row.id])- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, ungrouped_rows.first(2).map(&:id))- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, [ungrouped_rows.last.id])-- described_class.perform_now(import.id)-- expect(import.reload.processing_groups_count).to eq(4)- end- end- end-- describe 'batched import (Customers — no group_column)' do- let!(:import) do- create(:import, owner: store, type: 'Spree::Imports::Customers', status: :processing)- end-- let!(:rows) do- 5.times.map do |i|- create(:import_row, import: import, row_number: i + 1, status: :pending,- data: { 'email' => "user#{i}@example.com" }.to_json)- end- end-- it 'batches all rows into chunks and dispatches' do- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later)- .with(import.id, rows.map(&:id))-- described_class.perform_now(import.id)-- expect(import.reload.processing_groups_count).to eq(1)- end-- context 'with more rows than BATCH_SIZE' do- before { stub_const('Spree::Imports::ProcessRowsJob::BATCH_SIZE', 2) }-- it 'dispatches multiple batch jobs' do- expect(Spree::Imports::ProcessGroupJob).to receive(:perform_later).exactly(3).times-- described_class.perform_now(import.id)-- expect(import.reload.processing_groups_count).to eq(3)- end- end+ described_class.perform_now(import.id)endenddiff --git a/spree/core/spec/models/spree/import_spec.rb b/spree/core/spec/models/spree/import_spec.rbindex 19f64b869b..349e7ec01b 100644--- a/spree/core/spec/models/spree/import_spec.rb+++ b/spree/core/spec/models/spree/import_spec.rb@@ -341,16 +341,18 @@ RSpec.describe Spree::Import, :job, type: :model dodescribe '#create_rows_async' dobefore { import.save! }- it 'enqueues CreateRowsJob' do- expect { import.create_rows_async }.to have_enqueued_job(Spree::Imports::CreateRowsJob).with(import.id)+ it 'enqueues ProcessJob' do+ expect { import.create_rows_async }+ .to have_enqueued_job(Spree::Imports::ProcessJob).with(import.id).on_queue(Spree.queues.imports)endenddescribe '#process_rows_async' dobefore { import.save! }- it 'enqueues ProcessRowsJob' do- expect { import.process_rows_async }.to have_enqueued_job(Spree::Imports::ProcessRowsJob).with(import.id)+ it 'enqueues ProcessJob, skipping row creation' do+ expect { import.process_rows_async }+ .to have_enqueued_job(Spree::Imports::ProcessJob).with(import.id, skip_row_creation: true)endenddiff --git a/spree/core/spec/services/spree/sample_data/import_runner_spec.rb b/spree/core/spec/services/spree/sample_data/import_runner_spec.rbindex ddf7b77e65..d946795794 100644--- a/spree/core/spec/services/spree/sample_data/import_runner_spec.rb+++ b/spree/core/spec/services/spree/sample_data/import_runner_spec.rb@@ -23,7 +23,7 @@ RSpec.describe Spree::SampleData::ImportRunner, type: :service doendit 'enqueues row creation' do- expect { result }.to have_enqueued_job(Spree::Imports::CreateRowsJob)+ expect { result }.to have_enqueued_job(Spree::Imports::ProcessJob)endit 'auto-maps the sample CSV columns' do