Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Workflows compose named steps inside a plain perform method

Damian Legawiec4484d5533e1b
diff --git a/CLAUDE.md b/CLAUDE.md
index 4427e0412d..bd91b5d4e1 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) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `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-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` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `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.md
index d310b14eec..16f3ad8134 100644
--- a/docs/plans/6.0-service-workflows.md
+++ b/docs/plans/6.0-service-workflows.md
@@ -77,60 +77,55 @@ green and its observable semantics byte-identical.
because its modules cross process boundaries; inside one Rails process
they are ceremony. Durable flows get state from ActiveJob Continuations
(Phase 2), not from us.
-3. **Declared contracts.** `argument :cart` / `argument :quantity, default: 1` declare presence-validated
- per-line arguments (ActiveJob/GraphQL vocabulary); `step :name, provides: [:line_item]`
- declares what a step adds to the context. Unknown keys raise in test/dev, log in
- production. Context is an object (`flow.cart`), not a threaded hash.
-4. **Transaction boundaries are explicit DSL, not ambiance.** A bare `step`
- runs in the flow's ambient transaction started by `transaction do ... end`
- grouping blocks; `external_step` is forbidden inside one. This is the lesson
- `Carts::Complete` teaches: PREPARE is in-lock transactional, payment I/O
- must never be, FINALIZE is its own transaction. The DSL must express all
- three or it has failed the stress test.
-5. **`on_flow_failure:` pairs a step with its undo method,** run in reverse
- order for completed steps when a later step fails outside a shared
- transaction (inside one, rollback is the compensation — the undo arms
- only after the enclosing transaction commits). Formalizes
- `Carts::Complete#compensate!`; the name says when it runs and why (the
- plain-English rename from the saga literature's "compensation" was
- deliberate — see the naming discussion 2026-07-30).
-6. **`run_hooks :name` declares the extension point (ActiveSupport's run_callbacks verb — all registered handlers run there)**, registered through `Spree.hooks`
- with dotted keys and class handlers (decided 2026-07-30):
+3. **The #perform signature is the argument contract (2026-07-31 — the
+ perform-composed shape, superseding the class-declared `argument`/
+ context/`provides:` design).** A workflow defines a plain
+ `def perform(order:, canceler: nil, reason: 'other')`: Ruby itself
+ raises on missing/unknown keywords, YARD documents it, and a bare
+ `super` first line assigns every parameter — defaults applied — to an
+ ivar with a public reader. Data between steps flows through locals and
+ instance variables, the before_action idiom every Rails developer
+ already knows. The earlier shape's typed/union argument checks, alias
+ macros, Context classes and write-schema validation are gone; twin
+ vocabularies are plain overrides
+ (`def perform(order:, **rest) = super(cart: order, **rest)`), and
+ deprecated keywords are guard clauses in perform.
+
+4. **Transactions and locks are plain Rails.** `ApplicationRecord.transaction do`
+ and `cart.with_lock do` inside perform — no grouping DSL. What makes
+ that sound: `failure(...)` RAISES an internal control-flow signal
+ (Exception, not StandardError — the ActiveJob Continuation::Interrupt
+ precedent, so a plain `rescue` in perform can't swallow it), which
+ unwinds an open transaction into a natural rollback before the runner
+ converts it to the failure Result; `halt!(value)` is its successful
+ twin, forbidden inside workflow-opened transactions. `external_step`
+ refuses to run inside a transaction the workflow itself opened —
+ guarded by transaction-depth delta, so a caller-level wrapping
+ transaction (the admin API's order lock) stays the caller's business.
+
+5. **`on_flow_failure:` names a step's undo,** armed via
+ `ApplicationRecord.current_transaction.after_commit` when the
+ workflow-opened transaction around the step commits (immediately when
+ there is none), and popped in reverse when a later step fails —
+ rollback remains the compensation inside an uncommitted transaction.
+
+6. **Hooks: `hooks :after_cancel` declares the extension points**
+ (class-level, one line, so `Spree.hooks.validate!` still fails boot on
+ registrations against hooks that don't exist); `run_hooks :after_cancel`
+ inside perform dispatches every registered handler **with the workflow
+ instance** — argument readers plus whatever the workflow exposes via
+ plain `attr_reader` are the handler contract, visible in the file
+ instead of computed. Registry unchanged otherwise: dotted keys, class
+ name handlers constantized at dispatch, `Spree.hooks.register`,
+ introspection facade. Hook keys are public API.
+
+7. **Events are `publish_event`, not workflow syntax (2026-07-31).** The
+ established Publishable vocabulary is used inline in perform —
+ `order.publish_event('order.canceled', ...)` — positioned after the
+ transaction block and before `success(...)`, which gives
+ after-commit-only-on-success ordering for free. The earlier `emit`
+ declaration is gone.
- ```ruby
- Spree.hooks.register('carts.add_item.after_item_added', MyApp::UpdateExternalWMS)
- Spree.hooks.carts # introspection: flows → points → handlers
- Spree.hooks.for('carts.add_item.after_item_added') # resolved handler list
- ```
-
- Handlers are classes responding to `call(context)`, where the context at
- a hook point is exactly the declared arguments ∪ the `provides:` keys of
- every preceding step — a computed contract, not a documented one. Discovery, cheapest to
- strictest: `Spree.hooks.contract('carts.add_item.after_item_added')`
- returns the key list; unknown-key reads raise listing the available
- keys; the context supports `deconstruct_keys` for self-documenting
- pattern-matching destructure (`context => { cart:, line_item: }`); and
- an opt-in `uses :cart, :line_item` declaration (Spree::Flows::Handler)
- validates the handler against the contract at boot-finalize. The hook
- reference page is generated from these contracts (Typelizer
- philosophy — code is the source of truth). The registry stores
- class *names* and constantizes at dispatch (the Spree::Dependencies
- trick) — dev-reload safe, initializer safe, and re-registration dedupes
- by string identity. Blocks are accepted for one-line glue but class
- handlers are the documented norm. Hooks run in-transaction; exceptions
- abort the flow (that is the point — consistency-tier one). At
- boot-finalize every registered key is validated against hooks actually
- declared by flow classes (their `run_hooks` declarations), so typos fail loudly at boot instead of
- silently never firing. Hook keys are public API, versioned like
- dependency keys.
-7. **`emit 'name', payload: ->(ctx) { ... }`** declares an after-commit
- event with an explicit plain-Ruby payload lambda. The documented
- convention — enforced by review, visible at the declaration — is
- serializing through the record's `event_payload` (the V3 serializer
- path lifecycle events use), so flow events stay shape-identical to
- webhook payloads: `payload: ->(ctx) { ctx.order.event_payload.merge(notify_customer: ctx.order.notify_customer) }`. Same bus, same subscribers, same webhooks — the
- only change is that announcements are declarations, greppable at the top
- of the file. Inline `publish_event` remains valid for conditional edges.
8. **The consistency doctrine ships as documentation** in the same PR:
*step* — must be true in the same transaction; *sync subscriber* — must be
true in the same request (statuses); *async subscriber* — eventually
@@ -148,136 +143,53 @@ green and its observable semantics byte-identical.
## Design Details
-```ruby
-class Spree::Carts::AddItem < Spree::Service
- argument :cart
- argument :variant
- argument :quantity, default: 1
- argument :options, default: {}
-
- transaction do
- step :add_to_line_item, provides: [:line_item, :line_item_created]
- step :reserve_stock, if: ->(ctx) { ctx.cart.in_checkout? },
- undo: :release_reservation
- step :recalculate, with: -> { Spree.cart_recalculate_service }
- run_hooks :after_item_added
- end
-
- emit 'cart.item_added', payload: ->(ctx) { ctx.cart.event_payload.merge(line_item_id: ctx.line_item.prefixed_id) }
-
- private
-
- def add_to_line_item(ctx)
- # returns a hash merged into the context, validated against out:
- end
-end
-```
-
-The completion saga shape (the stress test — abbreviated):
-
-```ruby
-class Spree::Carts::Complete < Spree::Service
- argument :cart
- argument :expected_total, default: nil
- argument :payment_pending, default: false
-
- step :replay_completed, halt_with: :existing_order # P1 idempotency
-
- transaction lock: :cart do # PREPARE
- step :recalculate_in_lock
- step :verify_expected_total
- step :validate_cart
- step :stamp_completing
- step :copy_draft_order, provides: [:order]
- end
-
- external_step :process_payments, undo: :destroy_draft_and_repoint # Y — never in a txn
-
- transaction do # FINALIZE
- step :finalize_order
- step :stamp_cart_completed
- end
-
- step :release_reservations
- step :recompute_statuses
- emit 'order.placed', payload: ->(ctx) { ctx.order.event_payload.merge(notify_customer: ctx.order.notify_customer) }
-end
-```
-
-- **Context object**: thin struct over the accumulated hash; `ctx.cart`,
- `ctx[:line_item]`; writes only through step `provides:` merges. `Result.value`
- remains whatever `success(...)` returns, for caller compatibility.
-- **`halt_with:`** — early successful exit (replay paths) without treating it
- as failure.
-- **Compensation registry**: completed `on_flow_failure:`-bearing steps push
- their undo methods; a failure in a *later* non-shared-transaction step pops them in
- reverse. Inside a `transaction` block no compensation runs — rollback is it.
-- **`emit` timing**: collected during the flow, published after the outermost
- commit via `after_commit` on the flow's final transaction (or immediately
- when no transaction is open). Mirrors today's `finalize!` guarantee that a
- rolled-back completion never leaks `order.placed`.
-- **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.
+- **The whole workflow vocabulary is five words**: `step :name` (runs the
+ method of that name, instrumented), `external_step`, `run_hooks`,
+ `failure(...)`, `halt!(value)` — plus the class-level `hooks`
+ declaration and `with:`/`on_flow_failure:` step options. Everything
+ else in a workflow file is the Ruby a Rails developer already writes.
+- **`step :name, with: -> { Spree.cart_recalculate_totals_workflow }`**
+ delegates to a collaborator resolved from the lambda (the Dependencies
+ seam does the swapping); its keyword arguments are sliced from the
+ workflow's readers — a Workflow collaborator declares its contract on
+ #perform, a ServiceModule collaborator on its author-written #call.
+- **Observability**: every step run emits the `step.spree_workflow`
+ ActiveSupport::Notifications event with `{ workflow:, step: }` — APMs
+ and log subscribers consume it with zero new concepts. Workflow-backed
+ Dependencies seams are named `*_workflow` (legacy `*_service` names
+ stay settable/readable one release; writes are stashed, never applied —
+ an old service class is not workflow-contract compatible).
+- **Why not Medusa's function-composition shape** (analyzed 2026-07-31):
+ Medusa's `createWorkflow` body is a symbolic graph builder — their own
+ docs forbid if/else, loops, await, try/catch and direct variable use
+ inside it ("variables in the workflow don't have any values"),
+ replacing them with `when().then()` and `transform()`. That is a
+ heavier DSL than ours wearing function syntax; the honest Ruby
+ equivalent of what it actually does is the perform-composed shape:
+ runtime named steps with real Ruby control flow, the
+ ActiveJob::Continuable idiom — which also makes durable jobs and
+ workflows read identically across Spree.
## Editor & Typing Story
-The contracts are declared data — typing artifacts are generated from them,
-never hand-written (Typelizer philosophy, applied to Ruby):
-
-1. **Contexts are real classes** (Phase 1a requirement, not optional):
- per-flow `Context` classes metaprogrammed at load with defined reader
- methods + generated YARD. Solargraph and Ruby LSP then complete and
- navigate `ctx.line_item` with no extra toolchain — method_missing
- dispatch would forfeit the entire editor story and is forbidden.
-2. **Opt-in argument types, GraphQL-Ruby style** — the per-line `argument`
- freed the second positional for a type: `argument :cart, Spree::Cart`,
- `argument :quantity, Integer, default: 1`, `:boolean` for `[true,
- false]`, arrays as unions (`[Spree::Cart, Spree::Order]`, `nil` for
- nilable). Validated once at the `call` boundary against supplied
- arguments: ContractError in dev/test, log-warn in production
- (consistent with the other contract checks). **No coercion** — silent
- `"2"` → `2` hides caller bugs; controllers already cast. (RBS/sig
- generation was considered and dropped — 2026-07-30: the runtime
- contracts plus real reader methods carry the editor story on their
- own; no generated signature artifacts.)
-3. **`ruby-lsp-spree` addon (tooling backlog, separate from this plan):**
- ruby-lsp-rails-style addon giving in-string completion for hook keys in
- `Spree.hooks.register`, go-to-definition from key to `run_hooks` declaration,
- hover contracts, unknown-key diagnostics — generalizing to the wider
- string-registry family (`subscribes_to` event names, dependency keys).
+The contract is a plain method signature: editors, YARD and Solargraph
+understand `def perform(order:, canceler: nil)` natively — completion,
+go-to-definition and documented params with no toolchain. Argument
+readers are real methods defined from the signature; derived state
+exposed to hooks is plain `attr_reader`. (RBS/sig generation considered
+and dropped 2026-07-30; the generated-Context editor story retired with
+the perform-composed shape 2026-07-31.) The `ruby-lsp-spree` addon idea
+(in-string completion for hook keys, go-to-definition from key to the
+`hooks` declaration) stays on the tooling backlog, separate from this
+plan.
## Migration Path
-1. **Phase 1a — the DSL** (`Spree::Service`, context, `argument`/`step`/
- `transaction`/`external_step`/`on_flow_failure:`/`run_hooks`/`emit`/
- `halt_with:`) — **shipped**, with typed arguments and the
- provides:-as-write-schema rule; specs
- for every construct, consistency-tier doc. No production service changes.
+1. **Phase 1a — the DSL — shipped, then reshaped (2026-07-31)** into the
+ perform-composed form described above after the Medusa analysis; the
+ class-declared form (typed arguments, Context classes, provides:,
+ transaction grouping, emit) lives in branch history. Specs cover every
+ construct of the final surface.
2. **Phase 1b — reference retrofit — shipped.** Every Cart/Order service
was migrated as a stress exercise, then deliberately folded back
(2026-07-30): the DSL stays only on the four curated workflows;
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index a0a9441bc3..027ea2d92e 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -990,11 +990,9 @@ module Spree
end
def resume
- return false unless canceled?
-
- self.state_machine_resumed = true
- after_resume
- true
+ result = Spree.order_resume_workflow.call(order: self)
+ self.state_machine_resumed = true if result.success?
+ result.success?
end
def resume!
@@ -1188,15 +1186,6 @@ module Spree
end
end
- def after_resume
- update_column(:status, 'placed')
-
- fulfillments.each(&:resume!)
- consider_risk
- send_order_resumed_webhook
- publish_order_resumed_event
- end
-
def use_billing?
use_billing.in?([true, 'true', '1'])
end
@@ -1272,8 +1261,5 @@ module Spree
publish_event('order.completed', payload, { deprecated_alias_of: 'order.placed' })
end
- def publish_order_resumed_event
- publish_event('order.resumed')
- end
end
end
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index 850411c730..24f9fdaf26 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -1,21 +1,31 @@
module Spree
module Carts
class AddItem < Spree::Workflow
- argument :cart, [Spree::Cart, Spree::Order]
- argument :variant, Spree::Variant
- argument :quantity, default: nil
- argument :metadata, default: {}
- argument :public_metadata, default: {}
- argument :private_metadata, default: {}
- argument :options, default: {}
- alias_argument order: :cart, deprecated: true
- returns :line_item
+ hooks :after_item_added
- transaction do
- step :add_to_line_item, provides: [:line_item, :line_item_created]
- step :handle_stock_reservations, if: -> { cart.in_checkout? }
- step :recalculate, with: -> { Spree.cart_recalculate_workflow }
- run_hooks :after_item_added
+ # after_item_added handlers read these plus the argument readers.
+ attr_reader :line_item, :line_item_created
+
+ # @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
+ # @param variant [Spree::Variant]
+ # @param quantity [Integer, nil] defaults to 1
+ # @param metadata [Hash] primary API param (maps to private metadata)
+ def perform(variant:, cart: nil, order: nil, quantity: nil, metadata: {}, public_metadata: {}, private_metadata: {}, options: {})
+ if order
+ Spree::Deprecation.warn('Calling Spree::Carts::AddItem with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')
+ cart ||= order
+ end
+ super(cart: cart, variant: variant, quantity: quantity, metadata: metadata,
+ public_metadata: public_metadata, private_metadata: private_metadata, options: options)
+
+ ApplicationRecord.transaction do
+ step :add_to_line_item
+ step :handle_stock_reservations if cart.in_checkout?
+ step :recalculate, with: -> { Spree.cart_recalculate_workflow }
+ run_hooks :after_item_added
+ end
+
+ success(line_item)
end
private
@@ -24,40 +34,39 @@ module Spree
item_options = options || {}
requested_quantity = quantity || 1
- return failure(variant, "#{variant.name} is not available in #{cart.currency}") if variant.amount_in(cart.currency).nil?
+ failure(variant, "#{variant.name} is not available in #{cart.currency}") if variant.amount_in(cart.currency).nil?
- line_item = Spree.line_item_by_variant_finder.new.execute(cart: cart, variant: variant, options: item_options)
+ @line_item = Spree.line_item_by_variant_finder.new.execute(cart: cart, variant: variant, options: item_options)
+ @line_item_created = @line_item.nil?
- line_item_created = line_item.nil?
- if line_item.nil?
+ if @line_item.nil?
opts = ::Spree::PermittedAttributes.line_item_attributes.flatten.each_with_object({}) do |attribute, result|
result[attribute] = item_options[attribute]
end.merge(currency: cart.currency).delete_if { |_key, value| value.nil? }
- line_item = cart.line_items.new(quantity: requested_quantity,
- variant: variant,
- options: opts)
+ @line_item = cart.line_items.new(quantity: requested_quantity,
+ variant: variant,
+ options: opts)
else
- line_item.quantity += requested_quantity.to_i
+ @line_item.quantity += requested_quantity.to_i
end
# `metadata` is the primary API param (maps to private_metadata).
# Legacy `public_metadata`/`private_metadata` params kept for backward compatibility.
resolved_metadata = metadata.presence || private_metadata
- line_item.metadata = resolved_metadata.to_h if resolved_metadata.present?
- line_item.public_metadata = public_metadata.to_h if public_metadata.present?
+ @line_item.metadata = resolved_metadata.to_h if resolved_metadata.present?
+ @line_item.public_metadata = public_metadata.to_h if public_metadata.present?
- return failure(line_item) unless line_item.save
+ failure(@line_item) unless @line_item.save
- line_item.reload.recalculate_price
+ @line_item.reload.recalculate_price
- ::Spree.tax_provider.estimate(line_item.owner, [line_item]) if line_item_created
- { line_item: line_item, line_item_created: line_item_created }
+ ::Spree.tax_provider.estimate(@line_item.owner, [@line_item]) if @line_item_created
end
def handle_stock_reservations
result = Spree::StockReservations::Reserve.call(cart: cart)
- return failure(line_item, result.error) if result.failure?
+ failure(line_item, result.error) if result.failure?
end
end
end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 8fcf6696b0..e04a2ab6b8 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -5,12 +5,12 @@ module Spree
# a DB transaction; everything after a successful charge is small,
# idempotent and resumable (docs/plans/6.0-cart-order-split.md).
#
- # PREPARE (txn, cart lock) replay → TTL guard → in-lock recalculation
+ # PREPARE (locked txn) replay → TTL guard → in-lock recalculation
# → drift guard → validate → draft order +
# copies (unique orders.cart_id)
# PAYMENT (external_step) offline methods collapse into FINALIZE;
# gateways run outside any txn — a
- # pre-capture failure triggers the armed
+ # pre-capture failure pops the armed
# on_flow_failure compensation
# FINALIZE (own txn) inventory + counters + draft→placed +
# cart.completed_at + RecomputeStatuses;
@@ -18,62 +18,70 @@ module Spree
class Complete < Spree::Workflow
COMPLETING_TTL = 5.minutes
- argument :cart, [Spree::Cart, Spree::Order]
- argument :expected_total, default: nil
- argument :payment_pending, :boolean, default: false
- returns :order
+ hooks :before_finalize
+
+ # before_finalize handlers read this plus the argument readers.
+ attr_reader :order
+
+ # @param cart [Spree::Cart, Spree::Order] a draft order funnels into
+ # the same finalize semantics
+ # @param expected_total [String, BigDecimal, nil] client-side total for
+ # the drift guard
+ # @param payment_pending [Boolean] complete without processing payments
+ # (B2B / invoice-later)
+ def perform(cart:, expected_total: nil, payment_pending: false)
+ super
+
+ # Legacy signature bridge: completing an already-created draft order
+ # (admin/B2B path) reuses the same finalize semantics.
+ step :complete_draft_order if cart.is_a?(Spree::Order)
+
+ # P1 — replay: a double-clicked Place Order must get the order back.
+ step :replay_completed
+
+ cart.with_lock do
+ step :guard_concurrent_completion
+ step :recalculate_in_lock
+ step :verify_expected_total
+ step :validate_cart
+ step :mark_completing
+ step :create_draft_order, on_flow_failure: :rollback_draft_order
+ end
- # Concurrent completion lost the unique orders.cart_id race — re-enter
- # the flow: the replay step returns the winner's order (or the TTL
- # guard reports completion_in_progress).
- rescue_from ActiveRecord::RecordNotUnique do |_error|
- self.class.call(cart: cart.reload, expected_total: expected_total, payment_pending: payment_pending)
- end
+ external_step :process_payments if order.payment_required? && !payment_covered?(order)
- # Legacy signature bridge: completing an already-created draft order
- # (admin/B2B path) funnels through the same finalize semantics.
- step :complete_draft_order, if: -> { cart.is_a?(Spree::Order) },
- provides: [:draft_completion], halt_with: :draft_completion
-
- # P1 — replay: a double-clicked Place Order must get the order back.
- step :replay_completed, provides: [:replayed], halt_with: :replayed
-
- transaction lock: :cart do
- step :guard_concurrent_completion
- step :recalculate_in_lock
- step :verify_expected_total
- step :validate_cart
- step :mark_completing
- step :create_draft_order, provides: [:order], on_flow_failure: :rollback_draft_order
+ run_hooks :before_finalize
+ step :finalize_completion
+ success(order)
+ rescue ActiveRecord::RecordNotUnique
+ # Concurrent completion lost the unique orders.cart_id race —
+ # re-enter: the replay step returns the winner's order (or the TTL
+ # guard reports completion_in_progress).
+ self.class.call(cart: cart.reload, expected_total: expected_total, payment_pending: payment_pending)
end
- external_step :process_payments, if: -> { order.payment_required? && !payment_covered?(order) }
-
- run_hooks :before_finalize
- step :finalize_completion
-
private
# Admin/B2B draft orders bypass the cart but reuse the same finalize
# semantics (idempotency + inventory + reservation release in one home).
def complete_draft_order
order = cart
- return { draft_completion: order } if order.completed?
- return failure(order, 'Order is canceled') if order.canceled?
+ halt!(order) if order.completed?
+ failure(order, 'Order is canceled') if order.canceled?
order.with_lock do
skip_payments = payment_pending || !order.payment_required?
order.process_payments! if !skip_payments && !payment_covered?(order)
- return failure(order, order.errors.full_messages.to_sentence) if order.errors.any?
- return failure(order, Spree.t(:payment_processing_failed)) if !skip_payments && !payment_covered?(order)
+ failure(order, order.errors.full_messages.to_sentence) if order.errors.any?
+ failure(order, Spree.t(:payment_processing_failed)) if !skip_payments && !payment_covered?(order)
order.finalize! unless order.completed?
Spree::StockReservations::Release.call(owner: order)
Spree::Orders::RecomputeStatuses.call(order: order)
end
- { draft_completion: order }
+ halt!(order)
end
# A draft here means a previous attempt died mid-pipeline — re-verify
@@ -81,14 +89,15 @@ module Spree
def replay_completed
order = completion_result(cart)
return if order.nil?
- return { replayed: order } if order.placed? || order.canceled?
+
+ halt!(order) if order.placed? || order.canceled?
if order.payment_required? && !payment_covered?(order)
- return failure(cart, code: 'payment_failed', message: Spree.t(:payment_processing_failed))
+ failure(cart, code: 'payment_failed', message: Spree.t(:payment_processing_failed))
end
finalize!(cart, order)
- { replayed: order }
+ halt!(order)
end
def guard_concurrent_completion
@@ -117,7 +126,7 @@ module Spree
end
def create_draft_order
- { order: create_draft_order!(cart) }
+ @order = create_draft_order!(cart)
end
def process_payments
diff --git a/spree/core/app/workflows/spree/carts/recalculate.rb b/spree/core/app/workflows/spree/carts/recalculate.rb
index 1322387e4a..576be049ac 100644
--- a/spree/core/app/workflows/spree/carts/recalculate.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate.rb
@@ -1,19 +1,24 @@
module Spree
module Carts
class Recalculate < Spree::Workflow
- argument :cart, [Spree::Cart, Spree::Order]
- argument :line_item, Spree::LineItem, default: nil
- argument :line_item_created, :boolean, default: false
- argument :options, default: {}
- alias_argument order: :cart, deprecated: true
- returns :line_item
+ # @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
+ # @param line_item [Spree::LineItem, nil] the item whose change triggered this
+ def perform(cart: nil, order: nil, line_item: nil, line_item_created: false, options: {})
+ if order
+ Spree::Deprecation.warn('Calling Spree::Carts::Recalculate with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')
+ cart ||= order
+ end
+ super(cart: cart, line_item: line_item, line_item_created: line_item_created, options: options)
- step :unapply_stale_payment_sources
- step :refresh_totals
- step :rebuild_delivery_proposals
- step :activate_promotions
- # Typed rows (discounts + tax) are rebuilt by the full recalculation.
- step :final_recalculation, with: -> { Spree.cart_recalculate_totals_workflow }
+ step :unapply_stale_payment_sources
+ step :refresh_totals
+ step :rebuild_delivery_proposals
+ step :activate_promotions
+ # Typed rows (discounts + tax) are rebuilt by the full recalculation.
+ step :final_recalculation, with: -> { Spree.cart_recalculate_totals_workflow }
+
+ success(line_item)
+ end
private
diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
index 428328e1b4..85dc5d60ad 100644
--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
@@ -1,8 +1,8 @@
module Spree
module Carts
# Money recalculation — item counts, money totals (with the
- # typed-adjustment two-pass), one update_columns persist. Money ONLY: payment_status/fulfillment_status (and the
- # legacy payment_state column) are written exclusively by
+ # typed-adjustment two-pass), one update_columns persist. Money ONLY:
+ # payment_status/fulfillment_status are written exclusively by
# Spree::Orders::RecomputeStatuses, triggered from
# Spree::OrderStatusSubscriber on payment/refund/fulfillment/return
# events; completed-order fulfillment repricing belongs to the explicit
@@ -10,18 +10,21 @@ module Spree
#
# Granular math stays on the calculator objects (Spree::OrderUpdater /
# Spree::CartUpdater, resolved polymorphically via the model's #updater);
- # this service owns the sequence. Callers use this service (or the
- # model's #recalculate_totals! convenience) — never the calculator's
- # #update, which is deprecated.
+ # this workflow owns the sequence. Callers use it (or the model's
+ # #recalculate_totals! convenience) — never the calculator's #update,
+ # which is deprecated.
class RecalculateTotals < Spree::Workflow
- argument :cart, [Spree::Cart, Spree::Order]
- alias_argument order: :cart, deprecated: true
- returns :cart
-
- step :reset_association_caches
- step :update_item_count
- step :update_money_totals
- step :persist_totals
+ # @param cart [Spree::Cart, Spree::Order]
+ def perform(cart:)
+ super
+
+ step :reset_association_caches
+ step :update_item_count
+ step :update_money_totals
+ step :persist_totals
+
+ success(cart)
+ end
private
diff --git a/spree/core/app/workflows/spree/orders/add_item.rb b/spree/core/app/workflows/spree/orders/add_item.rb
index 595e6511e0..ffc30a725e 100644
--- a/spree/core/app/workflows/spree/orders/add_item.rb
+++ b/spree/core/app/workflows/spree/orders/add_item.rb
@@ -1,11 +1,12 @@
module Spree
module Orders
- # Draft-order twin of the cart service — order: is the canonical keyword
- # on this side, mapped onto the shared pipeline. Exists so cart-only
- # behavior (reservations, checkout warnings) can diverge without
- # branching one implementation.
+ # Draft-order twin of the cart workflow — order: is the canonical
+ # keyword on this side, mapped onto the shared pipeline so cart-only
+ # behavior can diverge without branching one implementation.
class AddItem < Spree::Carts::AddItem
- alias_argument order: :cart
+ def perform(order:, **rest)
+ super(cart: order, **rest)
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index b0709ff804..8e9edb0d91 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -1,46 +1,58 @@
module Spree
module Orders
# Cancels an order — the orchestration that used to hide inside
- # Order#after_cancel, as declared steps: the cancellation record, the
- # status flip and fulfillment cancellation commit atomically (with the
- # after_cancel hook inside the transaction), then payment settlement
- # runs as external I/O — voids and refunds are gateway calls and must
- # never share a database transaction — followed by money and status
- # recomputation and the order.canceled event after commit.
- #
- # Legacy `canceler:` and `canceled_at:` remain valid; new keywords are
- # additive and stored on the Spree::OrderCancellation record.
+ # Order#after_cancel: the cancellation record, the status flip and
+ # fulfillment cancellation commit atomically (with the after_cancel
+ # hook inside the transaction), then payment settlement runs as
+ # external I/O — voids and refunds are gateway calls and must never
+ # share a database transaction — followed by money and status
+ # recomputation and the order.canceled event.
class Cancel < Spree::Workflow
DEFAULT_REASON = 'other'.freeze
- argument :order, Spree::Order
- argument :canceler, default: nil
- argument :canceled_at, default: nil
- argument :reason, String, default: DEFAULT_REASON
- argument :note, default: nil
- argument :restock_items, :boolean, default: false
- argument :refund_payments, :boolean, default: false
- argument :refund_amount, default: nil
- argument :notify_customer, :boolean, default: false
- returns -> { order.reload }
+ hooks :after_cancel
- rescue_from ActiveRecord::RecordInvalid, StateMachines::InvalidTransition do |_error|
- failure(order)
- end
+ # after_cancel handlers read this plus the argument readers.
+ attr_reader :cancellation
+
+ # @param order [Spree::Order]
+ # @param canceler [Object, nil] the user/admin who initiated the cancellation
+ # @param canceled_at [Time, nil] timestamp (defaults to Time.current)
+ # @param reason [String] one of Spree::OrderCancellation::REASONS
+ # @param note [String, nil] staff-facing note
+ # @param restock_items [Boolean] whether to return inventory
+ # @param refund_payments [Boolean] whether to refund captured payments
+ # @param refund_amount [BigDecimal, Numeric, nil] defaults to
+ # order.payment_total when refund_payments is true
+ # @param notify_customer [Boolean] hint for subscribers
+ def perform(order:, canceler: nil, canceled_at: nil,
+ reason: DEFAULT_REASON, note: nil,
+ restock_items: false, refund_payments: false, refund_amount: nil,
+ notify_customer: false)
+ super
+
+ step :ensure_cancellable
+
+ @decided_at = canceled_at || Time.current
+ @amount_to_refund = refund_amount
+ @amount_to_refund ||= order.payment_total if refund_payments
+
+ ApplicationRecord.transaction do
+ step :record_cancellation
+ step :mark_canceled
+ step :cancel_fulfillments
+ run_hooks :after_cancel
+ end
- step :ensure_cancellable
- step :normalize, provides: [:decided_at, :amount_to_refund]
- transaction do
- step :record_cancellation, provides: [:cancellation]
- step :mark_canceled
- step :cancel_fulfillments
- run_hooks :after_cancel
+ external_step :settle_payments
+ step :recompute_totals, with: -> { Spree.order_recalculate_totals_workflow }
+ step :recompute_statuses, with: -> { Spree::Orders::RecomputeStatuses }
+ order.send_order_canceled_webhook
+ order.publish_event('order.canceled', order.event_payload.merge(notify_customer: notify_customer))
+ success(order.reload)
+ rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
+ failure(order)
end
- external_step :settle_payments
- step :recalculate_totals, with: -> { Spree::Orders::RecalculateTotals }
- step :recompute_statuses, with: -> { Spree::Orders::RecomputeStatuses }
- step :send_legacy_webhook
- emit 'order.canceled', payload: -> { order.event_payload.merge(notify_customer: notify_customer) }
private
@@ -48,29 +60,21 @@ module Spree
failure(order) unless order.allow_cancel?
end
- def normalize
- amount = refund_amount
- amount ||= order.payment_total if refund_payments
- { decided_at: canceled_at || Time.current, amount_to_refund: amount }
- end
-
def record_cancellation
- {
- cancellation: order.cancellations.create!(
- reason: reason,
- note: note,
- restock_items: restock_items,
- refund_payments: refund_payments,
- refund_amount: amount_to_refund,
- notify_customer: notify_customer,
- canceled_by: canceler,
- created_at: decided_at
- )
- }
+ @cancellation = order.cancellations.create!(
+ reason: reason,
+ note: note,
+ restock_items: restock_items,
+ refund_payments: refund_payments,
+ refund_amount: @amount_to_refund,
+ notify_customer: notify_customer,
+ canceled_by: canceler,
+ created_at: @decided_at
+ )
end
def mark_canceled
- changes = { status: 'canceled', canceled_at: decided_at }
+ changes = { status: 'canceled', canceled_at: @decided_at }
changes[:canceler_id] = canceler.id if canceler.present?
order.update_columns(changes)
end
@@ -94,10 +98,6 @@ module Spree
order.payments.store_credits.pending.each(&:void!)
end
end
-
- def send_legacy_webhook
- order.send_order_canceled_webhook
- end
end
end
end
diff --git a/spree/core/app/workflows/spree/orders/recalculate.rb b/spree/core/app/workflows/spree/orders/recalculate.rb
index 3354bb2e0a..9b0b4d8f42 100644
--- a/spree/core/app/workflows/spree/orders/recalculate.rb
+++ b/spree/core/app/workflows/spree/orders/recalculate.rb
@@ -1,11 +1,11 @@
module Spree
module Orders
- # Draft-order twin of the cart service — order: is the canonical keyword
- # on this side, mapped onto the shared pipeline. Exists so cart-only
- # behavior (reservations, checkout warnings) can diverge without
- # branching one implementation.
+ # Draft-order twin of the cart workflow — order: is the canonical
+ # keyword on this side, mapped onto the shared pipeline.
class Recalculate < Spree::Carts::Recalculate
- alias_argument order: :cart
+ def perform(order:, **rest)
+ super(cart: order, **rest)
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/orders/recalculate_totals.rb b/spree/core/app/workflows/spree/orders/recalculate_totals.rb
index 7ce5af51cd..2dc8aa2393 100644
--- a/spree/core/app/workflows/spree/orders/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/orders/recalculate_totals.rb
@@ -1,10 +1,12 @@
module Spree
module Orders
- # Order twin of the cart service — order: is the canonical keyword on
- # this side, mapped onto the shared flow (the calculator resolves
- # polymorphically through the model's #updater).
+ # Order twin of the cart workflow — order: is the canonical keyword on
+ # this side (the calculator resolves polymorphically through the
+ # model's #updater).
class RecalculateTotals < Spree::Carts::RecalculateTotals
- alias_argument order: :cart
+ def perform(order:)
+ super(cart: order)
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/orders/resume.rb b/spree/core/app/workflows/spree/orders/resume.rb
new file mode 100644
index 0000000000..ad11e04d85
--- /dev/null
+++ b/spree/core/app/workflows/spree/orders/resume.rb
@@ -0,0 +1,47 @@
+module Spree
+ module Orders
+ # Resumes a canceled order — the counterpart of {Spree::Orders::Cancel},
+ # absorbing what Order#after_resume buried: the status flip and
+ # fulfillment resumption commit atomically (with the after_resume hook
+ # inside the transaction), then risk reassessment, status recomputation
+ # and the order.resumed event.
+ class Resume < Spree::Workflow
+ hooks :after_resume
+
+ # @param order [Spree::Order]
+ def perform(order:)
+ super
+
+ step :ensure_resumable
+
+ ApplicationRecord.transaction do
+ step :mark_placed
+ step :resume_fulfillments
+ run_hooks :after_resume
+ end
+
+ order.consider_risk
+ step :recompute_statuses, with: -> { Spree::Orders::RecomputeStatuses }
+ order.send_order_resumed_webhook
+ order.publish_event('order.resumed')
+ success(order.reload)
+ rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
+ failure(order)
+ end
+
+ private
+
+ def ensure_resumable
+ failure(order) unless order.canceled?
+ end
+
+ def mark_placed
+ order.update_columns(status: 'placed')
+ end
+
+ def resume_fulfillments
+ order.fulfillments.each(&:resume!)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index adbf351d23..816a3dd29f 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -55,6 +55,7 @@ module Spree
# order
order_approve_service: 'Spree::Orders::Approve',
order_cancel_workflow: 'Spree::Orders::Cancel',
+ order_resume_workflow: 'Spree::Orders::Resume',
order_complete_service: 'Spree::Orders::Complete',
order_add_manual_discount_service: 'Spree::Orders::AddManualDiscount',
order_create_service: 'Spree::Orders::Create',
diff --git a/spree/core/lib/spree/hooks.rb b/spree/core/lib/spree/hooks.rb
index da4249ebca..0eb30da3b3 100644
--- a/spree/core/lib/spree/hooks.rb
+++ b/spree/core/lib/spree/hooks.rb
@@ -50,15 +50,6 @@ module Spree
@workflows[workflow_key.to_s] = class_name.to_s
end
- # @return [Array<String>] context keys available at the hook point
- def contract(key)
- workflow_key, hook_name = split_key(key)
- workflow = @workflows[workflow_key]&.safe_constantize
- raise UnknownHookError, "No workflow registered for '#{workflow_key}'" if workflow.nil?
-
- workflow.hook_contract(hook_name.to_sym)
- end
-
# Validates every registered key against hooks declared by workflow
# classes. Call after eager load — a typo fails the boot instead of
# never firing.
diff --git a/spree/core/lib/spree/workflow.rb b/spree/core/lib/spree/workflow.rb
index 88e9f3882d..af75fa05ce 100644
--- a/spree/core/lib/spree/workflow.rb
+++ b/spree/core/lib/spree/workflow.rb
@@ -2,550 +2,244 @@ require 'spree/service_module'
require 'spree/hooks'
module Spree
- # Declared-step workflow base — the DSL from
- # docs/plans/6.0-service-workflows.md, reserved for the curated flows in
- # app/workflows/ (regular services stay plain ServiceModule classes).
- # Caller-compatible with ServiceModule (Callable.call, Result,
- # success/failure); adds declared argument contracts, real context
- # classes, explicit transaction grouping, per-step undo, extension hooks
- # and declared event emission.
+ # Workflow — Tier 2 of the services doctrine
+ # (docs/plans/6.0-service-workflows.md): named steps inside a plain
+ # #perform method, the ActiveJob::Continuable shape.
#
- # class Spree::Carts::AddItem < Spree::Workflow
- # workflow_key 'carts.add_item'
- # argument :cart
- # argument :variant
- # argument :quantity, default: 1
- # alias_argument order: :cart, deprecated: true
+ # class Spree::Orders::Cancel < Spree::Workflow
+ # hooks :after_cancel
+ # attr_reader :cancellation # derived state hook handlers may read
#
- # transaction do
- # step :add_to_line_item, provides: [:line_item]
- # run_hooks :after_item_added
- # end
- #
- # private
+ # # @param order [Spree::Order] the order to cancel
+ # def perform(order:, canceler: nil, reason: 'other')
+ # super
#
- # # Steps are zero-arg methods; arguments and provided keys read as
- # # private methods (the #context accessor also remains available)
- # def add_to_line_item
- # { line_item: cart.line_items.find_or_initialize_by(variant: variant) }
+ # step :ensure_cancellable
+ # ApplicationRecord.transaction do
+ # step :record_cancellation
+ # run_hooks :after_cancel
+ # end
+ # external_step :settle_payments
+ # order.publish_event('order.canceled')
+ # success(order.reload)
+ # rescue ActiveRecord::RecordInvalid
+ # failure(order)
# end
- #
- # emit 'cart.item_added', payload: -> { { id: cart.prefixed_id } }
# end
+ #
+ # The #perform signature IS the argument contract: Ruby itself raises on
+ # missing or unknown keywords, YARD documents it. A bare `super` first
+ # assigns every parameter — defaults applied — to an instance variable
+ # with a public reader, so step bodies and hook handlers read plain
+ # methods. Everything else is ordinary Rails: plain transactions and
+ # locks, plain `if`, plain `rescue`, `publish_event` for announcements.
+ #
+ # The workflow vocabulary is five words. `step :name` runs the method of
+ # that name (instrumented as 'step.spree_workflow'); `on_flow_failure:`
+ # names its undo, armed when the surrounding transaction commits and run
+ # in reverse when a later step fails; `with:` delegates the step to a
+ # collaborator resolved from the lambda, its keyword arguments sliced
+ # from this workflow's readers. `external_step` marks gateway/network
+ # I/O and refuses to run inside a database transaction. `run_hooks`
+ # dispatches a declared extension point (see .hooks) with the workflow
+ # instance. `failure(...)` aborts the flow from anywhere — it raises
+ # internally, so an open plain transaction rolls back naturally — and
+ # `halt!(value)` is its successful twin (outside transactions only).
class Workflow
prepend Spree::ServiceModule::Base
class ContractError < StandardError; end
- Halt = Struct.new(:value)
+ # Internal control flow — Exception, not StandardError (the ActiveJob
+ # Continuation::Interrupt precedent), so a plain `rescue` inside
+ # #perform can't swallow it.
+ class FailureSignal < Exception # rubocop:disable Lint/InheritException
+ attr_reader :result
+
+ def initialize(result)
+ @result = result
+ super('workflow failure')
+ end
+ end
+
+ class Halted < Exception # rubocop:disable Lint/InheritException
+ attr_reader :value
+
+ def initialize(value)
+ @value = value
+ super('workflow halted')
+ end
+ end
+
+ # failure(...) must abort the flow, but the prepended ServiceModule
+ # helper sits ahead of this class in the lookup chain — this module
+ # sits ahead of both, builds the Result via super and raises it.
+ module ControlFlow
+ def failure(value = nil, error = nil)
+ raise FailureSignal.new(super)
+ end
+ end
+ prepend ControlFlow
class << self
attr_reader :declared_hooks
def inherited(subclass)
super
- subclass.instance_variable_set(:@return_selector, return_selector)
- subclass.instance_variable_set(:@rescue_contracts, rescue_contracts.dup)
- subclass.instance_variable_set(:@flow_items, flow_items.dup)
- subclass.instance_variable_set(:@required_arguments, required_arguments.dup)
- subclass.instance_variable_set(:@optional_arguments, optional_arguments.dup)
- subclass.instance_variable_set(:@argument_aliases, argument_aliases.dup)
- subclass.instance_variable_set(:@argument_types, argument_types.dup)
- subclass.instance_variable_set(:@emits, emits.dup)
subclass.instance_variable_set(:@declared_hooks, (declared_hooks || []).dup)
- subclass.instance_variable_set(:@context_keys, context_keys.dup)
end
- def flow_items = @flow_items ||= []
- def required_arguments = @required_arguments ||= []
- def optional_arguments = @optional_arguments ||= {}
- def argument_aliases = @argument_aliases ||= {}
- def argument_types = @argument_types ||= {}
- def emits = @emits ||= []
- def context_keys = @context_keys ||= []
-
- # Dotted identity used for hook keys; derived from the class name
- # (Spree::Carts::AddItem => 'carts.add_item') unless set explicitly.
+ # Dotted identity used for hook keys and instrumentation; derived
+ # from the class name (Spree::Carts::AddItem => 'carts.add_item')
+ # unless set explicitly.
def workflow_key(value = nil)
@workflow_key = value.to_s if value
@workflow_key ||= name.delete_prefix('Spree::').split('::').map(&:underscore).join('.')
end
- REQUIRED = Object.new.freeze
-
- # One declared argument per line, ActiveJob/GraphQL-style. The
- # optional second positional declares a runtime-checked type: a
- # class/module, an array union (nil in the union means nilable), or
- # :boolean for [true, false]. Checked once at the call boundary —
- # ContractError in dev/test, log-warn in production. Never coerces.
- #
- # argument :cart, Spree::Cart
- # argument :quantity, Integer, default: 1
- # argument :owner, [Spree::Cart, Spree::Order]
- def argument(name, type = nil, default: REQUIRED)
- name = name.to_sym
- argument_types[name] = type unless type.nil?
- if default.equal?(REQUIRED)
- @required_arguments = required_arguments | [name]
- else
- optional_arguments[name] = default
- end
- register_context_keys([name])
- end
-
- # alias_argument order: :cart, deprecated: true — accepts the legacy
- # keyword, warns when deprecated, maps onto the canonical argument.
- # Retires ad-hoc kwarg bridges and rewrite_input!.
- def alias_argument(deprecated: false, **mapping)
- mapping.each { |from, to| argument_aliases[from.to_sym] = { to: to.to_sym, deprecated: deprecated } }
- end
-
- def step(name, provides: [], if: nil, on_flow_failure: nil, with: nil, halt_with: nil)
- condition = binding.local_variable_get(:if)
- flow_items << { type: :step, name: name.to_sym, provides: Array(provides).map(&:to_sym),
- if: condition, on_flow_failure: on_flow_failure&.to_sym, with: binding.local_variable_get(:with),
- halt_with: halt_with&.to_sym, io: false,
- transaction: @building_transaction }
- register_context_keys(Array(provides).map(&:to_sym) + [halt_with].compact.map(&:to_sym))
- end
-
- # External I/O — structurally forbidden inside a transaction block.
- def external_step(name, provides: [], if: nil, on_flow_failure: nil, halt_with: nil)
- raise ContractError, "external_step #{name} cannot be declared inside a transaction block" if @building_transaction
-
- condition = binding.local_variable_get(:if)
- flow_items << { type: :step, name: name.to_sym, provides: Array(provides).map(&:to_sym),
- if: condition, on_flow_failure: on_flow_failure&.to_sym, with: nil,
- halt_with: halt_with&.to_sym, io: true, transaction: nil }
- register_context_keys(Array(provides).map(&:to_sym) + [halt_with].compact.map(&:to_sym))
- end
-
- # transaction(lock: :cart) do ... end — steps inside share one
- # database transaction (optionally holding a row lock); rollback is
- # their compensation.
- def transaction(lock: nil, &block)
- group = { lock: lock&.to_sym }
- @building_transaction = group
- instance_eval(&block)
- ensure
- @building_transaction = nil
- end
-
- def run_hooks(name)
- (@declared_hooks ||= []) << name.to_sym
- flow_items << { type: :hook, name: name.to_sym, transaction: @building_transaction }
+ # Declares the extension points this workflow dispatches via
+ # run_hooks. Class-level so Spree.hooks.validate! can fail boot on
+ # registrations against hooks that don't exist.
+ def hooks(*names)
+ @declared_hooks = (declared_hooks || []) | names.map(&:to_sym)
Spree.hooks.register_workflow(workflow_key, self.name)
end
- # Declared after-commit event. The payload lambda is explicit plain
- # Ruby — by convention it serializes through the record's
- # event_payload (the same V3 serializer path lifecycle events use),
- # so what feeds the event is visible at the declaration:
- #
- # emit 'order.placed', payload: -> { order.event_payload.merge(notify_customer: order.notify_customer) }
- def emit(event_name, payload:)
- emits << { name: event_name.to_s, payload: payload }
- end
-
- # Declarative exception contract: convert matching exceptions raised
- # anywhere in the flow into failure Results (the block builds the
- # Result via the failure helper). Unmatched exceptions keep raising.
- #
- # rescue_from ActiveRecord::RecordInvalid do |error|
- # failure(cart, error.record.errors.full_messages.to_sentence)
- # end
- def rescue_from(*exception_classes, &block)
- raise ArgumentError, 'rescue_from requires a block building the failure Result' if block.nil?
-
- exception_classes.each { |klass| rescue_contracts << { klass: klass, handler: block } }
- end
-
- def rescue_contracts = @rescue_contracts ||= []
+ # Public readers for #perform's parameters, memoized per class. An
+ # author-defined method of the same name wins.
+ def define_argument_readers(names)
+ @argument_readers ||= {}
+ names.each do |name|
+ next if @argument_readers[name]
- # Selects the successful Result value (a context key, or a lambda on
- # the context). Defaults to the context itself.
- def returns(key = nil, &block)
- @return_selector = block || key
- end
+ @argument_readers[name] = true
+ next if method_defined?(name) || private_method_defined?(name)
- def return_selector
- @return_selector
- end
-
- # @return [Array<Symbol>] context keys available at the given hook
- def hook_contract(hook_name)
- available = required_arguments + optional_arguments.keys
- flow_items.each do |item|
- return available.uniq if item[:type] == :hook && item[:name] == hook_name.to_sym
-
- available += item[:provides] if item[:type] == :step
- end
- raise Spree::Hooks::UnknownHookError, "#{name} declares no hook '#{hook_name}'"
- end
-
- # Real context class with defined readers — the editor story depends
- # on these being actual methods (never method_missing). Named as the
- # flow's Context constant (Spree::Carts::AddItem::Context) so YARD
- # references and the generated RBS have a real type to point at.
- def context_class
- @context_class ||= begin
- klass = Workflow.build_context_class(context_keys)
- remove_const(:Context) if const_defined?(:Context, false)
- const_set(:Context, klass)
- end
- end
-
- def build_context_class(keys)
- Class.new do
- define_method(:initialize) { |values| @values = values }
-
- keys.each do |key|
- define_method(key) { @values[key] }
- end
-
- define_method(:[]) { |key| @values[key.to_sym] }
- define_method(:to_h) { @values.dup }
- define_method(:deconstruct_keys) { |requested| requested.nil? ? @values.dup : @values.slice(*requested) }
- define_method(:key?) { |key| @values.key?(key.to_sym) }
-
- define_method(:merge!) do |hash|
- @values.merge!(hash.transform_keys(&:to_sym))
- self
- end
-
- def method_missing(name, *args)
- raise NoMethodError,
- "Unknown context key :#{name} — available: #{@values.keys.join(', ')}"
- end
-
- def respond_to_missing?(_name, _include_private = false)
- false
- end
- end
- end
-
- # Keys the reader-definition must never shadow — the DSL's own API.
- def reserved_context_key?(key)
- @reserved_context_keys ||= (Workflow.instance_methods(false) +
- Workflow.private_instance_methods(false) +
- Spree::ServiceModule::Base.instance_methods(false)).to_set
- @reserved_context_keys.include?(key)
- end
-
- private
-
- # Arguments and provided keys become private zero-arg readers on the
- # service (ActiveInteraction-style), so step bodies read +cart+, not
- # +context.cart+. An author-defined method of the same name wins; a
- # collision with the Spree::Workflow API itself is a definition error.
- def register_context_keys(keys)
- keys.each do |key|
- raise ContractError, "#{name}: context key :#{key} collides with the Spree::Workflow API" if Workflow.reserved_context_key?(key)
-
- unless method_defined?(key, false) || private_method_defined?(key, false)
- define_method(key) { @context[key] }
- private key
- end
+ define_method(name) { instance_variable_get(:"@#{name}") }
end
- @context_keys = context_keys | keys
- @context_class = nil
end
end
- attr_reader :context
-
- # Events collected by emit declarations; published after all
- # transactions commit. Exposed for specs.
- attr_reader :emitted_events
+ # Bare `super` from the subclass's #perform lands here with the
+ # parameter values as currently bound — defaults applied — and turns
+ # each into an ivar + public reader.
+ def perform(**arguments)
+ arguments.each { |name, value| instance_variable_set(:"@#{name}", value) }
+ self.class.define_argument_readers(arguments.keys)
+ end
def call(**kwargs)
- kwargs = resolve_aliases(kwargs)
- validate_arguments!(kwargs)
-
- values = self.class.optional_arguments.merge(kwargs)
- @context = self.class.context_class.new(values)
@undo_stack = []
- @emitted_events = []
-
- result = execute_flow
- result = success(default_return_value) unless result.is_a?(Spree::ServiceModule::Result)
-
- if result.success?
- collect_emits
- publish_emitted_events
- end
-
- result
- rescue StandardError => e
+ @outer_transaction_depth = ApplicationRecord.connection.open_transactions
+ outcome = perform(**kwargs)
+ outcome.is_a?(Spree::ServiceModule::Result) ? outcome : success(outcome)
+ rescue Halted => halted
+ success(halted.value)
+ rescue FailureSignal => signal
run_undo_stack!
- contract = self.class.rescue_contracts.find { |entry| e.is_a?(entry[:klass]) }
- raise if contract.nil?
-
- handler = contract[:handler]
- outcome = handler.arity == 1 ? instance_exec(e, &handler) : instance_exec(e, @context, &handler)
- raise unless outcome.is_a?(Spree::ServiceModule::Result)
-
- outcome
- end
-
- private
-
- def default_return_value
- selector = self.class.return_selector
- case selector
- when nil then @context
- when Symbol then @context[selector]
- when Proc then exec_in_service(selector)
- end
- end
-
- # DSL lambdas (if:, returns, emit payloads) run in the service instance
- # and read the #context accessor; legacy one-arg lambdas still receive
- # the context.
- def exec_in_service(block)
- block.arity.zero? ? instance_exec(&block) : instance_exec(@context, &block)
- end
-
- def resolve_aliases(kwargs)
- self.class.argument_aliases.each do |from, config|
- next unless kwargs.key?(from)
-
- if config[:deprecated]
- Spree::Deprecation.warn(
- "Calling #{self.class.name} with #{from}: is deprecated and will be removed in Spree 6.1. Pass #{config[:to]}: instead."
- )
- end
- legacy_value = kwargs.delete(from)
- kwargs[config[:to]] = legacy_value if kwargs[config[:to]].nil?
- end
- kwargs
- end
-
- def validate_arguments!(kwargs)
- unknown = kwargs.keys.map(&:to_sym) - self.class.context_keys
- if unknown.any?
- message = "#{self.class.name}: unknown argument #{unknown.join(', ')} (accepts: #{(self.class.required_arguments + self.class.optional_arguments.keys).join(', ')})"
- raise ContractError, message unless Rails.env.production?
-
- Rails.logger.warn(message)
- end
-
- missing = self.class.required_arguments.select { |key| !kwargs.key?(key) || kwargs[key].nil? }
- raise ContractError, "#{self.class.name}: missing required argument #{missing.join(', ')}" if missing.any?
-
- validate_argument_types!(kwargs)
- end
-
- # Presence is the required-check's job — nil supplied values are skipped
- # here, so optional arguments are nilable without declaring it.
- def validate_argument_types!(kwargs)
- self.class.argument_types.each do |key, type|
- value = kwargs[key]
- next if value.nil? || type_matches?(value, type)
-
- message = "#{self.class.name}: expected #{key} to be #{describe_type(type)}, got #{value.class.name}"
- raise ContractError, message unless Rails.env.production?
-
- Rails.logger.warn(message)
- end
- end
-
- def type_matches?(value, type)
- case type
- when Array then type.any? { |member| type_matches?(value, member) }
- when :boolean then value == true || value == false
- when nil then value.nil?
- when Module then value.is_a?(type)
- else false
- end
- end
-
- def describe_type(type)
- case type
- when Array then type.map { |member| describe_type(member) }.join(' | ')
- when :boolean then 'boolean'
- when nil then 'nil'
- else type.name
- end
- end
-
- def execute_flow
- items = self.class.flow_items
- index = 0
-
- while index < items.length
- item = items[index]
-
- if (group = item[:transaction])
- group_items = []
- group_items << items[index] and index += 1 while index < items.length && items[index][:transaction].equal?(group)
-
- result = run_transaction_group(group, group_items)
- else
- result = run_item(item, compensable: true)
- index += 1
- end
-
- return result if result.is_a?(Spree::ServiceModule::Result) || result.is_a?(Halt)
- end
-
- nil
+ signal.result
rescue StandardError
+ run_undo_stack!
raise
- ensure
- # Halt is success — unwrap for the caller.
end
- def run_transaction_group(group, group_items)
- completed_in_group = []
- outcome = nil
-
- run_in_lock(group[:lock]) do
- ApplicationRecord.transaction do
- group_items.each do |item|
- outcome = run_item(item, compensable: false)
- if outcome.is_a?(Spree::ServiceModule::Result)
- raise ActiveRecord::Rollback if outcome.failure?
+ # Successful early exit from anywhere — the caller receives
+ # success(value). Not from inside a transaction the workflow itself
+ # opened: there is nothing committed to halt with (use failure to
+ # roll back). A transaction the caller wrapped around the whole run
+ # is theirs to commit and doesn't count.
+ def halt!(value)
+ raise ContractError, 'halt! cannot be called inside a database transaction' if in_workflow_transaction?
- break
- end
- break if outcome.is_a?(Halt)
+ raise Halted.new(value)
+ end
- completed_in_group << item
- end
- end
- end
+ private
- if outcome.is_a?(Spree::ServiceModule::Result) && outcome.failure?
- # The group rolled back — undo previously committed work.
- run_undo_stack!
- return outcome
+ def step(name, with: nil, on_flow_failure: nil)
+ outcome = ActiveSupport::Notifications.instrument(
+ 'step.spree_workflow', workflow: self.class.workflow_key, step: name
+ ) do
+ with ? call_collaborator(instance_exec(&with)) : send(name)
end
- # Once the group committed, its compensable steps join the stack.
- completed_in_group.each do |item|
- @undo_stack << item[:on_flow_failure] if item[:on_flow_failure]
- end
+ raise FailureSignal.new(outcome) if outcome.is_a?(Spree::ServiceModule::Result) && outcome.failure?
+ arm_undo(on_flow_failure) if on_flow_failure
outcome
end
- def run_in_lock(lock_key, &block)
- return yield if lock_key.nil?
+ # Gateway/network I/O — must never share a database transaction the
+ # workflow opened (a caller-level wrapping transaction is the caller's
+ # responsibility).
+ def external_step(name, **options)
+ raise ContractError, "external_step #{name} must not run inside a database transaction" if in_workflow_transaction?
- @context[lock_key].with_lock(&block)
+ step(name, **options)
end
- def run_item(item, compensable:)
- case item[:type]
- when :hook
- Spree.hooks.dispatch("#{self.class.workflow_key}.#{item[:name]}", @context)
- nil
- when :step
- run_step(item, compensable: compensable)
- end
- end
-
- def run_step(item, compensable:)
- return nil if item[:if] && !exec_in_service(item[:if])
-
- outcome =
- if item[:with]
- callable = instance_exec(&item[:with])
- callable.call(**@context.to_h.slice(*callable_kwargs(callable)))
- else
- send(item[:name])
- end
-
- case outcome
- when Spree::ServiceModule::Result
- if outcome.failure?
- run_undo_stack!
- return outcome
- end
- merge_step_output(item, outcome.value) if outcome.value.is_a?(Hash)
- when Hash
- merge_step_output(item, outcome)
- end
-
- @undo_stack << item[:on_flow_failure] if compensable && item[:on_flow_failure]
-
- if item[:halt_with] && @context.key?(item[:halt_with]) && @context[item[:halt_with]]
- return success(@context[item[:halt_with]])
+ # Dispatches every handler registered for this extension point with
+ # the workflow instance — argument readers plus whatever the workflow
+ # exposes via attr_reader are the handler's contract.
+ def run_hooks(name)
+ unless self.class.declared_hooks&.include?(name.to_sym)
+ raise ContractError, "#{self.class.name} does not declare hook :#{name} — add `hooks :#{name}` to the class"
end
- nil
+ Spree.hooks.dispatch("#{self.class.workflow_key}.#{name}", self)
end
- # provides: is the step's write schema — a step declaring no outputs
- # writes nothing, so bodies can end on any expression (no defensive
- # trailing nils) without incidental hashes polluting the context.
- def merge_step_output(item, hash)
- allowed = item[:provides] + [item[:halt_with]].compact
- return if allowed.empty?
-
- extras = hash.keys.map(&:to_sym) - allowed
- if extras.any?
- message = "#{self.class.name}##{item[:name]} returned undeclared keys #{extras.join(', ')} (declared provides: #{item[:provides].join(', ')})"
- raise ContractError, message unless Rails.env.production?
-
- Rails.logger.warn(message)
- end
- @context.merge!(hash)
- end
-
- def callable_kwargs(callable)
- if callable.is_a?(Class) && callable < Spree::Workflow
- return callable.required_arguments + callable.optional_arguments.keys + callable.argument_aliases.keys
- end
-
- target = callable.respond_to?(:new) ? callable.instance_method(:call) : callable.method(:call)
- # Skip the prepended wrappers (ServiceModule::Base / Service) to read
- # the signature the author actually wrote.
- while target.respond_to?(:owner) && [Spree::ServiceModule::Base, Spree::Workflow].include?(target.owner) && target.super_method
- target = target.super_method
+ # Undo methods arm when the workflow-opened transaction around their
+ # step commits — inside a rolled-back transaction the rollback already
+ # was the undo.
+ def arm_undo(name)
+ if in_workflow_transaction?
+ ApplicationRecord.current_transaction.after_commit { @undo_stack << name.to_sym }
+ else
+ @undo_stack << name.to_sym
end
- params = target.parameters
- return @context.to_h.keys if params.any? { |type, _| type == :keyrest }
-
- params.filter_map { |type, name| name if [:key, :keyreq].include?(type) }
end
def run_undo_stack!
return if @undo_stack.nil?
- @undo_stack.reverse_each do |compensation|
- send(compensation)
+ @undo_stack.reverse_each do |undo|
+ send(undo)
rescue StandardError => e
Rails.error.report(e, context: { workflow: self.class.workflow_key }, source: 'spree.workflow')
end
@undo_stack = []
end
- def collect_emits
- self.class.emits.each do |declaration|
- payload =
- case declaration[:payload]
- when Proc then exec_in_service(declaration[:payload])
- when Symbol then send(declaration[:payload])
- end
- @emitted_events << { name: declaration[:name], payload: payload }
- end
+ # A transaction opened during this run (fixture wrappers and
+ # caller-level transactions sit at or below the baseline).
+ def in_workflow_transaction?
+ ApplicationRecord.connection.open_transactions > (@outer_transaction_depth || 0)
end
- def publish_emitted_events
- events = @emitted_events
- return if events.empty?
+ # Calls a with: collaborator, slicing its keyword arguments from this
+ # workflow's readers. Workflow collaborators declare their contract on
+ # #perform; ServiceModule collaborators on the #call the author wrote
+ # (behind the prepended wrappers).
+ def call_collaborator(callable)
+ wanted = collaborator_keywords(callable)
+ arguments = wanted.select { |name| respond_to?(name) }.index_with { |name| public_send(name) }
+ callable.call(**arguments)
+ end
- publish = -> { events.each { |event| Spree::Events.publish(event[:name], event[:payload]) } }
+ def collaborator_keywords(callable)
+ target =
+ if callable.is_a?(Class) && callable < Spree::Workflow
+ callable.instance_method(:perform)
+ elsif callable.respond_to?(:new)
+ method = callable.instance_method(:call)
+ method = method.super_method while [Spree::ServiceModule::Base, ControlFlow].include?(method.owner) && method.super_method
+ method
+ else
+ callable.method(:call)
+ end
- # Non-joinable transactions are test fixtures — deferring behind one
- # would postpone past the example's rollback, so publish immediately.
- if ApplicationRecord.connection.transaction_open? && ApplicationRecord.connection.current_transaction.joinable?
- ActiveRecord.after_all_transactions_commit(&publish)
- else
- publish.call
- end
+ target.parameters.filter_map { |type, name| name if [:key, :keyreq].include?(type) }
end
end
end
diff --git a/spree/core/spec/lib/spree/workflow_spec.rb b/spree/core/spec/lib/spree/workflow_spec.rb
index 173402d1c5..1949eb7989 100644
--- a/spree/core/spec/lib/spree/workflow_spec.rb
+++ b/spree/core/spec/lib/spree/workflow_spec.rb
@@ -14,164 +14,129 @@ RSpec.describe Spree::Workflow do
workflow
end
- describe 'argument contracts' do
- it 'validates required arguments, applies defaults, and rejects unknown keys' do
+ describe 'the perform signature as the argument contract' do
+ it 'raises Ruby argument errors for missing and unknown keywords' do
workflow = build_workflow do
- argument :subject
- argument :quantity, default: 2
- step :inspect_inputs, provides: [:seen]
- def inspect_inputs = { seen: [context.subject, context.quantity] }
+ def perform(subject:) = success(subject)
end
- expect(workflow.call(subject: 'a').value.seen).to eq(['a', 2])
- expect(workflow.call(subject: 'a', quantity: 5).value.seen).to eq(['a', 5])
- expect { workflow.call(quantity: 1) }.to raise_error(Spree::Workflow::ContractError, /missing required argument subject/)
- expect { workflow.call(subject: 'a', bogus: 1) }.to raise_error(Spree::Workflow::ContractError, /unknown argument bogus/)
+ expect(workflow.call(subject: 1)).to be_success
+ expect { workflow.call }.to raise_error(ArgumentError, /missing keyword: :subject/)
+ expect { workflow.call(subject: 1, bogus: 2) }.to raise_error(ArgumentError, /unknown keyword: :bogus/)
end
- it 'validates declared argument types at the call boundary without coercing' do
+ it 'assigns parameters — defaults applied — to readers via bare super' do
workflow = build_workflow do
- argument :cart, Spree::Cart
- argument :quantity, Integer, default: 1
- argument :confirmed, :boolean, default: false
- step :noop
- def noop = nil
- end
+ def perform(subject:, quantity: 2)
+ super
+ step :inspect_arguments
+ end
- cart = build(:cart)
- expect(workflow.call(cart: cart)).to be_success
- expect(workflow.call(cart: cart, quantity: 3, confirmed: true)).to be_success
- expect { workflow.call(cart: 'cart_123') }
- .to raise_error(Spree::Workflow::ContractError, /expected cart to be Spree::Cart, got String/)
- expect { workflow.call(cart: cart, quantity: '3') }
- .to raise_error(Spree::Workflow::ContractError, /expected quantity to be Integer, got String/)
- expect { workflow.call(cart: cart, confirmed: 1) }
- .to raise_error(Spree::Workflow::ContractError, /expected confirmed to be boolean, got Integer/)
- end
+ private
- it 'accepts any member of a union type and skips nil optionals' do
- workflow = build_workflow do
- argument :owner, [Spree::Cart, Spree::Order], default: nil
- step :noop
- def noop = nil
+ def inspect_arguments = success([subject, quantity])
end
- expect(workflow.call).to be_success
- expect(workflow.call(owner: build(:order))).to be_success
- expect { workflow.call(owner: 42) }
- .to raise_error(Spree::Workflow::ContractError, /expected owner to be Spree::Cart \| Spree::Order, got Integer/)
+ expect(workflow.call(subject: 'a').value).to eq(['a', 2])
+ expect(workflow.call(subject: 'a', quantity: 5).value).to eq(['a', 5])
end
- it 'maps deprecated aliases onto canonical keys with a warning' do
+ it 'wraps a bare perform return value in success' do
workflow = build_workflow do
- argument :cart
- alias_argument order: :cart, deprecated: true
- step :read, provides: [:value]
- def read = { value: context.cart }
+ def perform(subject:) = subject * 2
end
- expect(Spree::Deprecation).to receive(:warn).with(/order: is deprecated/)
- expect(workflow.call(order: 'the-cart').value.value).to eq('the-cart')
+ result = workflow.call(subject: 21)
+ expect(result).to be_success
+ expect(result.value).to eq(42)
end
end
- describe 'steps and context' do
- it 'threads declared outs through real context readers' do
+ describe 'steps and control flow' do
+ it 'aborts the flow when a step fails, skipping later steps' do
+ ran = []
workflow = build_workflow do
- argument :base
- step :double, provides: [:doubled]
- step :describe, provides: [:text]
- def double = { doubled: context.base * 2 }
- def describe = { text: "got #{context.doubled}" }
- end
+ define_method(:noted) { |name| ran << name }
- result = workflow.call(base: 21)
- expect(result).to be_success
- expect(result.value.text).to eq('got 42')
- expect(result.value.to_h).to include(base: 21, doubled: 42)
- result.value => { doubled: }
- expect(doubled).to eq(42)
- end
+ def perform(subject:)
+ super
+ step :first
+ step :explode
+ step :never
+ success(subject)
+ end
- it 'raises a teaching error for unknown context keys and undeclared outs' do
- workflow = build_workflow do
- argument :base
- step :bad, provides: [:declared]
- def bad = { undeclared: 1 }
- end
- expect { workflow.call(base: 1) }.to raise_error(Spree::Workflow::ContractError, /undeclared keys undeclared/)
+ private
- workflow2 = build_workflow do
- argument :base
- step :peek, provides: []
- def peek = context.missing_key && {}
+ def first = noted(:first)
+ def explode = failure(:exploded, 'boom')
+ def never = noted(:never)
end
- expect { workflow2.call(base: 1) }.to raise_error(NoMethodError, /Unknown context key :missing_key — available: base/)
+
+ result = workflow.call(subject: 1)
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('boom')
+ expect(ran).to eq([:first])
end
- it 'ignores incidental hashes from steps that declare no provides' do
+ it 'cannot have its failure swallowed by a plain rescue in perform' do
workflow = build_workflow do
- argument :base
- step :side_effect
- step :peek, provides: [:seen]
- def side_effect = { junk: 1 }
- def peek = { seen: context.key?(:junk) }
- end
+ def perform(subject:)
+ super
+ step :explode
+ success(subject)
+ rescue StandardError
+ success(:swallowed)
+ end
- expect(workflow.call(base: 1).value.seen).to be(false)
- end
+ private
- it 'supports conditional steps, failure short-circuit, and halt_with' do
- workflow = build_workflow do
- argument :mode
- step :maybe_fail, if: -> { context.mode == :fail }
- step :maybe_halt, provides: [:early], halt_with: :early
- step :after, provides: [:reached]
- def maybe_fail = failure('nope')
- def maybe_halt = { early: (context.mode == :halt ? 'halted' : nil) }
- def after = { reached: true }
+ def explode = failure(:exploded, 'boom')
end
- expect(workflow.call(mode: :fail)).to be_failure
- halted = workflow.call(mode: :halt)
- expect(halted).to be_success
- expect(halted.value).to eq('halted')
- expect(workflow.call(mode: :run).value.reached).to be(true)
+ expect(workflow.call(subject: 1)).to be_failure
end
- it 'delegates with: steps and merges their kwargs from the context' do
- collaborator = Class.new do
- prepend Spree::ServiceModule::Base
- def call(base:)
- success(tripled: base * 3)
+ it 'halts successfully with halt! and forbids it inside a transaction' do
+ workflow = build_workflow do
+ def perform(subject:)
+ super
+ halt!(:early) if subject == :halt
+ ApplicationRecord.transaction { halt!(:inside) } if subject == :inside_txn
+ success(:reached_end)
end
end
- workflow = build_workflow do
- argument :base
- step :triple, with: -> { @collaborator }, provides: [:tripled]
- end
- instance = workflow.new
- instance.instance_variable_set(:@collaborator, collaborator)
- result = instance.call(base: 3)
- expect(result.value.tripled).to eq(9)
+ halted = workflow.call(subject: :halt)
+ expect(halted).to be_success
+ expect(halted.value).to eq(:early)
+ expect(workflow.call(subject: :run).value).to eq(:reached_end)
+ expect { workflow.call(subject: :inside_txn) }
+ .to raise_error(Spree::Workflow::ContractError, /halt! cannot be called inside a database transaction/)
end
end
- describe 'transactions and undo' do
- it 'rolls back a transaction group on failure and runs earlier undos' do
+ describe 'transactions and compensation' do
+ it 'rolls back a plain transaction on failure and runs undos armed before it' do
undo_log = []
workflow = build_workflow do
- argument :product
- step :outside_work, on_flow_failure: :undo_outside
- transaction do
- step :rename
- step :explode
- end
- define_method(:outside_work) { nil }
define_method(:undo_outside) { undo_log << :undone }
- def rename = context.product.update!(name: 'Renamed') && nil
- def explode = failure('boom')
+
+ def perform(product:)
+ super
+ step :outside_work, on_flow_failure: :undo_outside
+ ApplicationRecord.transaction do
+ step :rename
+ step :explode
+ end
+ success(product)
+ end
+
+ private
+
+ def outside_work = nil
+ def rename = product.update!(name: 'Renamed')
+ def explode = failure(:exploded, 'boom')
end
product = create(:product, name: 'Original')
@@ -182,166 +147,235 @@ RSpec.describe Spree::Workflow do
expect(undo_log).to eq([:undone])
end
- it 'runs undos in reverse order on exceptions' do
+ it 'does not run undos armed inside a transaction that rolled back' do
undo_log = []
workflow = build_workflow do
- argument :subject
- step :first, on_flow_failure: :undo_first
- step :second, on_flow_failure: :undo_second
- step :third
- define_method(:first) { nil }
- define_method(:second) { nil }
- define_method(:undo_first) { undo_log << :first }
- define_method(:undo_second) { undo_log << :second }
- def third = raise('io blew up')
+ define_method(:undo_created) { undo_log << :undone }
+
+ def perform(product:)
+ super
+ ApplicationRecord.transaction do
+ step :rename, on_flow_failure: :undo_created
+ step :explode
+ end
+ success(product)
+ end
+
+ private
+
+ def rename = product.update!(name: 'Renamed')
+ def explode = failure(:exploded, 'boom')
end
- expect { workflow.call(subject: 1) }.to raise_error('io blew up')
- expect(undo_log).to eq([:second, :first])
+ expect(workflow.call(product: create(:product))).to be_failure
+ expect(undo_log).to be_empty
end
- it 'forbids external_step inside a transaction block at definition time' do
- expect do
- build_workflow do
- argument :subject
- transaction do
- external_step :charge
+ it 'arms undos at commit and pops them in reverse on later exceptions' do
+ undo_log = []
+ workflow = build_workflow do
+ define_method(:undo_first) { undo_log << :first }
+ define_method(:undo_second) { undo_log << :second }
+
+ def perform(product:)
+ super
+ ApplicationRecord.transaction do
+ step :committed_work, on_flow_failure: :undo_first
end
+ step :more_work, on_flow_failure: :undo_second
+ step :explode
+ success(product)
end
- end.to raise_error(Spree::Workflow::ContractError, /external_step charge cannot be declared inside a transaction/)
+
+ private
+
+ def committed_work = product.update!(name: 'Renamed')
+ def more_work = nil
+ def explode = raise('io blew up')
+ end
+
+ expect { workflow.call(product: create(:product)) }.to raise_error('io blew up')
+ expect(undo_log).to eq([:second, :first])
end
- it 'converts declared exceptions into failures and re-raises the rest' do
+ it 'tolerates a caller-level transaction around the whole run' do
workflow = build_workflow do
- argument :subject
- rescue_from ArgumentError do |error|
- failure(context.subject, "handled: #{error.message}")
+ def perform(subject:)
+ super
+ external_step :charge
+ halt!(:early)
end
- step :explode
- def explode = raise(context.subject == :known ? ArgumentError.new('bad input') : 'unknown boom')
- end
- result = workflow.call(subject: :known)
- expect(result).to be_failure
- expect(result.error.to_s).to eq('handled: bad input')
+ private
+
+ def charge = nil
+ end
- expect { workflow.call(subject: :other) }.to raise_error('unknown boom')
+ result = nil
+ ApplicationRecord.transaction { result = workflow.call(subject: 1) }
+ expect(result).to be_success
+ expect(result.value).to eq(:early)
end
- it 'holds the declared row lock around the group' do
+ it 'refuses external_step inside a database transaction' do
workflow = build_workflow do
- argument :product
- transaction lock: :product do
- step :touch_name
+ def perform(subject:)
+ super
+ ApplicationRecord.transaction { external_step :charge }
+ success(subject)
end
- def touch_name = context.product.update!(name: 'Locked') && nil
+
+ private
+
+ def charge = nil
end
- product = create(:product)
- expect(product).to receive(:with_lock).and_call_original
- workflow.call(product: product)
- expect(product.reload.name).to eq('Locked')
+ expect { workflow.call(subject: 1) }
+ .to raise_error(Spree::Workflow::ContractError, /external_step charge must not run inside a database transaction/)
end
end
describe 'hooks' do
- it 'dispatches registered handlers with the context and computes contracts' do
+ it 'dispatches handlers with the workflow instance and validates declarations' do
workflow = build_workflow do
- argument :subject
- step :produce, provides: [:artifact]
- run_hooks :after_produce
- def produce = { artifact: 'thing' }
+ hooks :after_produce
+ attr_reader :artifact
+
+ def perform(subject:)
+ super
+ step :produce
+ run_hooks :after_produce
+ success(artifact)
+ end
+
+ private
+
+ def produce = @artifact = "made-from-#{subject}"
end
seen = nil
- Spree.hooks.register('testing.sample_workflow.after_produce') { |hook_context| seen = hook_context.artifact }
+ Spree.hooks.register('testing.sample_workflow.after_produce') { |flow| seen = [flow.subject, flow.artifact] }
workflow.call(subject: 1)
- expect(seen).to eq('thing')
- expect(workflow.hook_contract(:after_produce)).to contain_exactly(:subject, :artifact)
- expect(Spree.hooks.contract('testing.sample_workflow.after_produce')).to contain_exactly(:subject, :artifact)
- end
-
- it 'validates registrations against declared hooks at boot' do
- build_workflow do
- argument :subject
- run_hooks :real_hook
- end
- Spree.hooks.register('testing.sample_workflow.real_hook', 'SomeHandler')
+ expect(seen).to eq([1, 'made-from-1'])
expect(Spree.hooks.validate!).to be(true)
Spree.hooks.register('testing.sample_workflow.typo_hook', 'SomeHandler')
expect { Spree.hooks.validate! }.to raise_error(Spree::Hooks::UnknownHookError, /declares no hook 'typo_hook'/)
end
- it 'dedupes class-name registrations' do
- build_workflow do
- argument :subject
- run_hooks :point
+ it 'raises when dispatching a hook the class does not declare' do
+ workflow = build_workflow do
+ def perform(subject:)
+ super
+ run_hooks :never_declared
+ success(subject)
+ end
end
- Spree.hooks.register('testing.sample_workflow.point', 'MyHandler')
- Spree.hooks.register('testing.sample_workflow.point', 'MyHandler')
- expect(Spree.hooks.keys.count { |k| k == 'testing.sample_workflow.point' }).to eq(1)
- handler = Class.new { def call = nil }
- stub_const('MyHandler', handler)
- expect(Spree.hooks.for('testing.sample_workflow.point').size).to eq(1)
+ expect { workflow.call(subject: 1) }
+ .to raise_error(Spree::Workflow::ContractError, /does not declare hook :never_declared/)
end
end
- describe 'emits' do
- it 'serializes through event_payload by convention, explicitly in the lambda' do
+ describe 'with: collaborators' do
+ it 'slices keyword arguments from the workflow readers for workflows and services' do
+ collaborator_workflow = Class.new(Spree::Workflow) do
+ def self.name = 'Spree::Testing::TripleWorkflow'
+ def perform(base:) = success(base * 3)
+ end
+ stub_const('Spree::Testing::TripleWorkflow', collaborator_workflow)
+
+ collaborator_service = Class.new do
+ prepend Spree::ServiceModule::Base
+ def call(base:)
+ success(base + 1)
+ end
+ end
+ stub_const('Spree::Testing::PlusOneService', collaborator_service)
+
workflow = build_workflow do
- argument :subject
- emit 'testing.finished', payload: -> { context.subject.event_payload.merge(extra: context.subject.class.name) }
+ def perform(base:)
+ super
+ tripled = step :triple, with: -> { Spree::Testing::TripleWorkflow }
+ plus_one = step :plus_one, with: -> { Spree::Testing::PlusOneService }
+ success([tripled.value, plus_one.value])
+ end
end
- record = create(:cart, store: @default_store)
- instance = workflow.new
- result = instance.call(subject: record)
- expect(result).to be_success
- event = instance.emitted_events.sole
- expect(event[:name]).to eq('testing.finished')
- expect(event[:payload][:id]).to eq(record.prefixed_id)
- expect(event[:payload][:extra]).to eq('Spree::Cart')
+ expect(workflow.call(base: 3).value).to eq([9, 4])
end
- it 'collects declared events on success and exposes them' do
+ it 'propagates a collaborator failure' do
+ failing = Class.new do
+ prepend Spree::ServiceModule::Base
+ def call(base:)
+ failure(base, 'nope')
+ end
+ end
+ stub_const('Spree::Testing::FailingService', failing)
+
workflow = build_workflow do
- argument :subject
- step :work, provides: [:artifact]
- emit 'testing.finished', payload: -> { { artifact: context.artifact } }
- def work = { artifact: 'done' }
+ def perform(base:)
+ super
+ step :doomed, with: -> { Spree::Testing::FailingService }
+ success(:never)
+ end
end
- instance = workflow.new
- result = instance.call(subject: 1)
- expect(result).to be_success
- expect(instance.emitted_events).to eq([{ name: 'testing.finished', payload: { artifact: 'done' } }])
+ result = workflow.call(base: 3)
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('nope')
end
+ end
- it 'names the context class as the flow Context constant' do
- workflow = build_workflow do
- argument :subject
- step :noop
- def noop = nil
+ describe 'twins' do
+ it 'maps a legacy vocabulary through a plain perform override' do
+ parent = build_workflow do
+ def perform(cart:)
+ super
+ success("carted-#{cart}")
+ end
end
- workflow.call(subject: 1)
- expect(workflow.const_get(:Context).instance_methods).to include(:subject)
+ twin = Class.new(parent) do
+ def self.name = 'Spree::Testing::TwinWorkflow'
+ def perform(order:, **rest) = super(cart: order, **rest)
+ end
+ stub_const('Spree::Testing::TwinWorkflow', twin)
+
+ expect(twin.call(order: 'x').value).to eq('carted-x')
end
+ end
+
+ describe 'observability' do
+ it 'instruments every step as step.spree_workflow' do
+ events = []
+ subscriber = ActiveSupport::Notifications.subscribe('step.spree_workflow') do |*, payload|
+ events << payload.slice(:workflow, :step)
+ end
- it 'does not collect events on failure' do
workflow = build_workflow do
- argument :subject
- step :work
- emit 'testing.finished', payload: -> { { subject: context.subject } }
- def work = failure('no')
+ def perform(subject:)
+ super
+ step :one
+ step :two
+ success(subject)
+ end
+
+ private
+
+ def one = nil
+ def two = nil
end
+ workflow.call(subject: 1)
- instance = workflow.new
- expect(instance.call(subject: 1)).to be_failure
- expect(instance.emitted_events).to be_empty
+ expect(events).to eq([
+ { workflow: 'testing.sample_workflow', step: :one },
+ { workflow: 'testing.sample_workflow', step: :two }
+ ])
+ ensure
+ ActiveSupport::Notifications.unsubscribe(subscriber)
end
end
end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 810a9a6e55..01ab842ce5 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -294,15 +294,15 @@ describe Spree::Order, type: :model do
end
end
- describe '#after_resume' do
+ describe '#resume!' do
let(:order) { create(:completed_order_with_totals, store: store) }
before { order.cancel! }
it 'publishes order.resumed event', :events do
- expect(order).to receive(:publish_event).with('order.resumed').at_least(:once)
- allow(order).to receive(:publish_event).with(anything)
+ allow(Spree::Events).to receive(:publish)
order.resume!
+ expect(Spree::Events).to have_received(:publish).with('order.resumed', any_args)
end
it 'restores status to placed' do
diff --git a/spree/core/spec/workflows/spree/orders/resume_spec.rb b/spree/core/spec/workflows/spree/orders/resume_spec.rb
new file mode 100644
index 0000000000..8e188a6930
--- /dev/null
+++ b/spree/core/spec/workflows/spree/orders/resume_spec.rb
@@ -0,0 +1,39 @@
+require 'spec_helper'
+
+module Spree
+ RSpec.describe Orders::Resume do
+ let(:store) { @default_store }
+ let(:order) { create(:completed_order_with_totals, store: store) }
+
+ before { Orders::Cancel.call(order: order) }
+
+ it 'restores the order and its fulfillments to their pre-cancel statuses' do
+ result = described_class.call(order: order.reload)
+
+ expect(result).to be_success
+ expect(result.value.status).to eq('placed')
+ expect(order.reload.fulfillments.map(&:status)).to all(eq('pending'))
+ end
+
+ it 'publishes order.resumed after commit', :events do
+ allow(Spree::Events).to receive(:publish)
+ described_class.call(order: order.reload)
+ expect(Spree::Events).to have_received(:publish).with('order.resumed', any_args)
+ end
+
+ it 'dispatches the after_resume hook with the workflow context' do
+ seen = nil
+ Spree.hooks.register('orders.resume.after_resume') { |hook_context| seen = hook_context.order }
+ described_class.call(order: order.reload)
+
+ expect(seen&.id).to eq(order.id)
+ ensure
+ Spree.hooks.clear!
+ end
+
+ it 'fails on an order that is not canceled' do
+ placed = create(:completed_order_with_totals, store: store)
+ expect(described_class.call(order: placed)).to be_failure
+ end
+ end
+end