state_machines 0.303.0 → 0.304.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9a29b27e5695470275a9549dd92e27dce0e37c3bdf00541bcfd1fc5194aa506c
4
- data.tar.gz: 05f7e2bf30fe31ca8f616d2983a4ea2fa248a1b585f529c79ad7dd5f012c77ab
3
+ metadata.gz: 338ccdcb73c4d48a79f2c315c7d4d75a7c536cc14e14f317f3ae143714898d8c
4
+ data.tar.gz: a69ab4c2ed3017be001800afd17ab3f5846487f2fb72a98ce072a361b43e1e31
5
5
  SHA512:
6
- metadata.gz: ca1284da8da46118da332893513394e21afdadc7aa7f759327787c6e0d55d8acff3ba52e981e5cac1f2527ee3419a42d3f08443ad6c3d2b66d625c1ad246659d
7
- data.tar.gz: c571cc39176f7d0f20e4cd75c76734a76b508678811d48faa2d34a41bc4cc72e01c063c91ee8c74861e47e3d25640df8853bdd7fe0bab4afd9481bb449035491
6
+ metadata.gz: 89ed8906794be85e5a5dd93f157c486e4390196ff8413df790705f684ccf16fb59007445c74e44ad73808303a52286f31d1e4cbf6b7580daa346f6c30b3e9cf9
7
+ data.tar.gz: eb1e74b5b5509eda7ac188b8a7dc46b102084befb79623fc5656c8c5d6b715faf783af9e986d7eb551216c0f05589142637670da4cb9c4f94f1f1adcb4e4e381
data/README.md CHANGED
@@ -351,6 +351,65 @@ end
351
351
  The reader is also available on the event itself:
352
352
  `Vehicle.state_machine.events[:park].refusal(vehicle)`.
353
353
 
354
+ ## Branch Callbacks
355
+
356
+ A `transition` can carry its own `before:`, `after:` and `around:` callbacks.
357
+ They run only when that transition is the branch chosen for the event, so they
358
+ share its guards without repeating them in an `after_transition`:
359
+
360
+ ```ruby
361
+ class Vehicle
362
+ state_machine initial: :parked do
363
+ event :ignite do
364
+ transition parked: :idling, if: :warm?
365
+ transition parked: :preheating, after: :start_glow_plugs
366
+ transition stalled: :idling, before: :check_battery, after: %i[log_restart notify_owner]
367
+ end
368
+ end
369
+ end
370
+ ```
371
+
372
+ Each takes what `after_transition`'s `do:` takes: a method name (Symbol or
373
+ String), an Array of them, or a Proc/Method. They are ordinary callbacks:
374
+ `bind_to_object`, the integration's terminator and `throw :halt` behave as for
375
+ `before_transition`/`after_transition`.
376
+
377
+ They wrap closest to the state change: the machine's `before_transition` and
378
+ `around_transition` callbacks run first, then the branch's `before:`/`around:`
379
+ (in the order written), then the change; then the branch's `after:`, then the
380
+ machine's `after_transition`. A branch `after:` runs only when the transition
381
+ succeeds; there is no branch-level `after_failure` (use `after_failure`).
382
+ `assert_before_transition`/`assert_after_transition` see branch callbacks, matched
383
+ against their branch.
384
+
385
+ A transition takes its callback chain when it starts: a `before_transition`
386
+ registered while that chain is running applies from the next transition on.
387
+
388
+ Validating before saving (ActiveModel and ActiveRecord with a pending event, e.g.
389
+ `valid?` before `save`) runs a preview of the transition: every
390
+ `before_transition` callback, skipping the `around_transition` callbacks (not
391
+ entered, their conditions not evaluated), then the validation in the new state,
392
+ and no after callbacks. Validation therefore sees everything the save's before
393
+ callbacks set. The save does not repeat those before callbacks; its around
394
+ callbacks wrap the save alone, on its own stack. So when `valid?` ran first, a
395
+ `before_transition` declared after an `around_transition` has already run outside
396
+ that around; a save without a prior `valid?` interleaves the callbacks exactly as
397
+ declared. An around callback never stays suspended between two calls.
398
+
399
+ `before`, `after`, `around` and `do` are reserved keys in a transition's hash, like
400
+ `from`, `to`, `if` and `unless`. `do:` is refused, since a branch has three kinds
401
+ of callbacks. A state named `:after` (or `:before`, `:around`) is written with
402
+ `from:`/`to:`:
403
+
404
+ ```ruby
405
+ transition from: :after, to: :parked
406
+ ```
407
+
408
+ The branches keep their callbacks in `Branch#callbacks`
409
+ (`Vehicle.state_machine.events[:ignite].branches.last.callbacks`), as
410
+ `StateMachines::Callback` objects with `#type` and `#callables`, for renderers
411
+ and tooling.
412
+
354
413
  # Coordinated State Management
355
414
 
356
415
  State machines can coordinate with each other using state guards, allowing transitions to depend on the state of other state machines within the same object. This enables complex system modeling where components are interdependent.
@@ -37,8 +37,29 @@ module StateMachines
37
37
  # * +to+ / +except_to+
38
38
  attr_reader :known_states
39
39
 
40
+ # The callbacks scoped to this branch by an event's
41
+ # <tt>transition ..., before: / after: / around:</tt>, in the order they
42
+ # were given, as StateMachines::Callback instances (see Callback#type and
43
+ # Callback#callables). They run only when this branch is the one selected
44
+ # for a transition, so this branch's guards apply to them. Frozen; empty
45
+ # for branches without callbacks.
46
+ attr_reader :callbacks
47
+
48
+ # Key under which Event#transition hands over the branch callbacks: not a
49
+ # Symbol, so no state name can collide with it
50
+ CALLBACKS = Object.new.freeze
51
+ private_constant :CALLBACKS
52
+
53
+ # Builds the options hash for a branch with callbacks (used by Event)
54
+ def self.options_with_callbacks(options, callbacks) # :nodoc:
55
+ options.merge(CALLBACKS => callbacks)
56
+ end
57
+
40
58
  # Creates a new branch
41
59
  def initialize(options = {}) # :nodoc:
60
+ options = options.dup
61
+ @callbacks = (options.delete(CALLBACKS) || []).freeze
62
+
42
63
  # Build conditionals
43
64
  @if_condition = options.delete(:if)
44
65
  @unless_condition = options.delete(:unless)
@@ -121,14 +121,45 @@ module StateMachines
121
121
  #
122
122
  # See StateMachines::Machine#transition for a description of the possible
123
123
  # configurations for defining transitions.
124
+ #
125
+ # Branch callbacks:
126
+ # * <tt>:before</tt>, <tt>:around</tt>, <tt>:after</tt> - Callbacks that
127
+ # run only when this branch is the one selected, so its guards apply.
128
+ # Each takes what after_transition's +:do+ takes: a method name, an
129
+ # Array of them, or a Proc / Method. They run closest to the state
130
+ # change: after the machine's before / around callbacks, in the order
131
+ # written, and (+:after+, on success only) before the machine's after
132
+ # callbacks. See StateMachines::Branch#callbacks.
133
+ #
134
+ # transition :parked => :idling, :after => :log_ignition
135
+ #
136
+ # These keys, and +:do+ (refused: use +:after+), are reserved: a state
137
+ # named :after is written <tt>transition from: :after, to: :parked</tt>.
124
138
  def transition(options)
125
139
  raise ArgumentError, 'Must specify as least one transition requirement' if options.empty?
140
+ raise ArgumentError, 'transition does not take do:; use after: (or before:/around:)' if options.key?(:do)
141
+
142
+ # before: / after: / around: are this branch's callbacks, in the order
143
+ # given; the keys are reserved, so they are never read as a state
144
+ # select, not slice: the order the callbacks were written is their order
145
+ given = options.select { |key, _| BRANCH_CALLBACK_TYPES.include?(key) } # rubocop:disable Style/HashSlice
146
+ options = options.except(*BRANCH_CALLBACK_TYPES)
147
+ # Callback keys are always callbacks. Without any state requirement left
148
+ # (only guards and/or callbacks), the transition reads as the old
149
+ # `transition after: :x` (from a state named :after), so refuse it rather
150
+ # than silently turning it into an all => all branch
151
+ raise reserved_key_error(*given.first) if given.any? && (options.keys - NON_STATE_KEYS).empty?
152
+
153
+ callbacks = given.map do |type, callables|
154
+ assert_branch_callback!(type, callables)
155
+ machine.branch_callback(type, callables)
156
+ end
126
157
 
127
158
  # Only a certain subset of explicit options are allowed for transition
128
159
  # requirements
129
160
  StateMachines::OptionsValidator.assert_valid_keys!(options, :from, :to, :except_from, :except_to, :if, :unless, :if_state, :unless_state, :if_all_states, :unless_all_states, :if_any_state, :unless_any_state) if (options.keys - %i[from to on except_from except_to except_on if unless if_state unless_state if_all_states unless_all_states if_any_state unless_any_state]).empty?
130
161
 
131
- branches << branch = Branch.new(options.merge(on: name))
162
+ branches << branch = Branch.new(Branch.options_with_callbacks(options.merge(on: name), callbacks))
132
163
  @known_states |= branch.known_states
133
164
  branch
134
165
  end
@@ -174,7 +205,7 @@ module StateMachines
174
205
  match[:to].filter(values).first
175
206
  end
176
207
 
177
- return Transition.new(object, machine, name, from, to, !custom_from_state)
208
+ return Transition.new(object, machine, name, from, to, !custom_from_state, branch: branch)
178
209
  end
179
210
 
180
211
  # No transition matched
@@ -368,5 +399,32 @@ module StateMachines
368
399
  object.send(qualified_name, *args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, machine, name))
369
400
  end
370
401
  end
402
+ # The keys of a transition's options that hold branch callbacks
403
+ BRANCH_CALLBACK_TYPES = %i[before around after].freeze
404
+ private_constant :BRANCH_CALLBACK_TYPES
405
+
406
+ # Transition options that are not state requirements (the event and guards)
407
+ NON_STATE_KEYS = %i[on except_on if unless if_state unless_state if_all_states unless_all_states if_any_state unless_any_state].freeze
408
+ private_constant :NON_STATE_KEYS
409
+
410
+ private
411
+
412
+ # Checks a branch callback's value by type only, so the outcome never
413
+ # depends on which states exist or were declared first
414
+ def assert_branch_callback!(type, callables)
415
+ values = callables.is_a?(Array) ? callables : [callables]
416
+ raise ArgumentError, "#{type}: needs at least one method name, Proc or Method" if values.empty?
417
+
418
+ invalid = values.reject { |value| value.is_a?(Symbol) || value.is_a?(String) || value.is_a?(Proc) || value.is_a?(Method) }
419
+ return if invalid.empty?
420
+
421
+ raise ArgumentError, "#{type}: takes method names (Symbol/String), Procs or Methods, not #{invalid.first.inspect}"
422
+ end
423
+
424
+ def reserved_key_error(type, value)
425
+ to = value.is_a?(Matcher) ? value.description : value.inspect
426
+ ArgumentError.new("#{type}: is reserved in transition for a branch callback; " \
427
+ "to transition from a state named #{type.inspect}, write `transition from: #{type.inspect}, to: #{to}`")
428
+ end
371
429
  end
372
430
  end
@@ -316,8 +316,23 @@ module StateMachines
316
316
  add_callback(:failure, parsed_options, &)
317
317
  end
318
318
 
319
+ # Builds the Callback for a branch's before: / after: / around: (see
320
+ # Event#transition), configured like the machine's own callbacks
321
+ def branch_callback(type, callables) # :nodoc:
322
+ options = { do: callables }
323
+ terminator = callback_terminator
324
+ options[:terminator] = terminator if terminator
325
+ Callback.new(type, options)
326
+ end
327
+
319
328
  private
320
329
 
330
+ # The terminator for this machine's callbacks; integrations override it
331
+ # (nil keeps Callback's default)
332
+ def callback_terminator
333
+ nil
334
+ end
335
+
321
336
  def add_transition_callback(type, args, options, &)
322
337
  # Extract legacy positional arguments and merge with keyword options
323
338
  parsed_options = parse_callback_arguments(args, options)
@@ -87,10 +87,15 @@ module StateMachines
87
87
  # end
88
88
  # end
89
89
  #
90
+ # Branch callbacks (<tt>:before</tt>, <tt>:around</tt>, <tt>:after</tt>)
91
+ # work as in StateMachines::Event#transition, e.g.
92
+ # <tt>transition to: :idling, on: :ignite, after: :log_ignition</tt>.
93
+ #
90
94
  # See StateMachines::Machine#transition for a description of the possible
91
95
  # configurations for defining transitions.
92
96
  def transition(options)
93
- StateMachines::OptionsValidator.assert_valid_keys!(options, :from, :to, :on, :if, :unless)
97
+ # :do is not valid, but is let through so Event#transition explains it
98
+ StateMachines::OptionsValidator.assert_valid_keys!(options.except(:do), :from, :to, :on, :if, :unless, :before, :around, :after)
94
99
  raise ArgumentError, 'Must specify :on event' unless options[:on]
95
100
  raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from]
96
101
 
@@ -768,7 +768,18 @@ module StateMachines
768
768
  machine = machine_or_class.is_a?(StateMachines::Machine) ? machine_or_class : machine_or_class.state_machine
769
769
  raise ArgumentError, 'No state machine found' unless machine
770
770
 
771
- callbacks = machine.callbacks[callback_type] || []
771
+ # Each candidate is [callback, branch it is matched against]: a
772
+ # machine-wide callback has its own branch; a transition's before: /
773
+ # around: / after: callback is matched against that transition branch
774
+ # (its event, states and guards). Before includes around, as the
775
+ # machine keeps both in one chain.
776
+ branch_types = callback_type == :before ? %i[before around] : [callback_type]
777
+ candidates = (machine.callbacks[callback_type] || []).map { |callback| [callback, callback.branch] }
778
+ machine.events.each do |event|
779
+ event.branches.each do |branch|
780
+ branch.callbacks.each { |callback| candidates << [callback, branch] if branch_types.include?(callback.type) }
781
+ end
782
+ end
772
783
 
773
784
  # Extract expected conditions. States and events resolve to their
774
785
  # canonical names first, since the branch matchers compare those: a raw
@@ -785,9 +796,7 @@ module StateMachines
785
796
  # Find matching callback. Requirements are checked with the matchers'
786
797
  # own matches?, so all / all - [...] / same behave as they do at runtime,
787
798
  # and an expected nil state is an expectation, not an omission.
788
- matching_callback = callbacks.find do |callback|
789
- branch = callback.branch
790
-
799
+ matching_callback = candidates.find do |(callback, branch)|
791
800
  next false if options.key?(:on) && !branch.event_requirement.matches?(expected_event)
792
801
  next false if states.any? &&
793
802
  branch.state_requirements.none? { |requirement| _sm_state_requirement_matches?(requirement, states) }
@@ -1,11 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module StateMachines
4
- # Module to extend Fiber instances for pausable state tracking
5
- module PausableFiber
6
- attr_accessor :state_machine_fiber_pausable
7
- end
8
-
9
4
  # A transition represents a state change for a specific attribute.
10
5
  #
11
6
  # Transitions consist of:
@@ -43,16 +38,17 @@ module StateMachines
43
38
  # @see StateMachines::Event#refusal for the meaning of each reason
44
39
  attr_accessor :refusal
45
40
 
41
+ # The event branch selected for this transition, whose before: / after: /
42
+ # around: callbacks it runs; nil for a transition not built by an event
43
+ attr_reader :branch
44
+
46
45
  # Creates a new, specific transition
47
- def initialize(object, machine, event, from_name, to_name, read_state = true) # :nodoc:
46
+ def initialize(object, machine, event, from_name, to_name, read_state = true, branch: nil) # :nodoc:
48
47
  @object = object
49
48
  @machine = machine
49
+ @branch = branch
50
50
  @args = []
51
51
  @transient = false
52
- @paused_fiber = nil
53
- @resuming = false
54
- @continuation_block = nil
55
- @fiber_thread_storage = nil
56
52
 
57
53
  @event = machine.events.fetch(event)
58
54
  @from_state = machine.states.fetch(from_name)
@@ -200,35 +196,35 @@ module StateMachines
200
196
  #
201
197
  # Configuration options:
202
198
  # * +before+ - Whether to run before callbacks.
203
- # * +after+ - Whether to run after callbacks. If false, then any around
204
- # callbacks will be paused until called again with +after+ enabled.
199
+ # * +after+ - Whether to run after callbacks. If false (and +before+ is
200
+ # enabled), the run is a preview (e.g. validating before a save): every
201
+ # before callback runs, the around callbacks are skipped (not entered,
202
+ # their conditions not evaluated), then the block, and no after
203
+ # callbacks (failure callbacks if it halts or the block fails). The
204
+ # next run with +after+ enabled does not repeat those before callbacks;
205
+ # its around callbacks wrap only its action. So after a preview, a
206
+ # before callback declared after an around callback has run outside
207
+ # that around; without a preview, callbacks interleave as declared.
205
208
  # Default is true.
206
209
  #
207
210
  # This will return true if all before callbacks gets executed. After
208
211
  # callbacks will not have an effect on the result.
209
- def run_callbacks(options = {}, &block)
212
+ def run_callbacks(options = {}, &)
210
213
  options = { before: true, after: true }.merge(options)
214
+ return preview(&) if options[:before] && !options[:after]
211
215
 
212
- # If we have a paused fiber and we're not trying to resume (after: false),
213
- # this is an idempotent call on an already-paused transition. Just return true.
214
- return true if @paused_fiber&.alive? && !options[:after]
215
-
216
- # Always use fibers for compatibility with existing pause/resume functionality
217
- # The fiber argument can still be used to explicitly control fiber usage
218
- pausable_options = options.key?(:fiber) ? { fiber: options[:fiber] } : {}
219
-
220
- # Check if we're resuming from a pause
221
- if @paused_fiber&.alive? && options[:after]
222
- # Resume the paused fiber
223
- # Don't reset @success when resuming - preserve the state from the pause
224
- # Store the block for later execution
225
- @continuation_block = block if block_given?
226
- halted = pausable(pausable_options) { true }
227
- else
216
+ if options[:before]
228
217
  @success = false
229
- # For normal execution (not pause/resume), default to success
230
- # The action block will override this if needed
231
- halted = pausable(pausable_options) { before(options[:after], &block) } if options[:before]
218
+ begin
219
+ halted = !catch(:halt) do
220
+ before(&)
221
+ true
222
+ end
223
+ ensure
224
+ # However it ends, the full run consumed any preview: the
225
+ # transition is now like one never previewed after the same run
226
+ @previewed = nil
227
+ end
232
228
  end
233
229
 
234
230
  # After callbacks are only run if:
@@ -298,13 +294,8 @@ module StateMachines
298
294
  # the state has already been persisted
299
295
  def reset
300
296
  @before_run = @persisted = @after_run = false
301
- # Kill so ensure blocks in paused callbacks still run (CRuby only:
302
- # TruffleRuby lacks Fiber#kill, JRuby's doesn't wait for ensure)
303
- @paused_fiber.kill if RUBY_ENGINE == 'ruby' && @paused_fiber&.alive? && !@paused_fiber.equal?(Fiber.current)
304
- @paused_fiber = nil
305
- @resuming = false
306
- @continuation_block = nil
307
- @fiber_thread_storage = nil
297
+ @before_callbacks = nil
298
+ @previewed = nil
308
299
  end
309
300
 
310
301
  # Determines equality of transitions by testing whether the object, states,
@@ -328,45 +319,19 @@ module StateMachines
328
319
  "#<#{self.class} #{%w[attribute event from from_name to to_name].map { |attr| "#{attr}=#{send(attr).inspect}" } * ' '}>"
329
320
  end
330
321
 
331
- # Checks whether this transition is currently paused.
332
- # Returns true if there is a paused fiber, false otherwise.
333
- def paused?
334
- @paused_fiber&.alive? || false
335
- end
336
-
337
- # Checks whether this transition has a paused fiber that can be resumed.
338
- # Returns true if there is a paused fiber, false otherwise.
339
- #
340
- # Note: The actual resuming happens automatically when run_callbacks is called
341
- # again on a transition with a paused fiber.
342
- def resumable?
343
- paused?
344
- end
345
-
346
- # Manually resumes the execution of a previously paused callback.
347
- # Returns true if the transition was successfully resumed and completed,
348
- # false if there was no paused fiber, and raises an exception if the
349
- # transition was halted.
350
- def resume!(&block)
351
- return false unless paused?
352
-
353
- # Store continuation block if provided
354
- @continuation_block = block if block_given?
355
-
356
- # Run the pausable block which will resume the fiber
357
- halted = pausable { true }
358
-
359
- # Return whether the transition completed successfully
360
- !halted
322
+ # Whether a preview run (run_callbacks with after: false) has run part of
323
+ # this transition's before chain, which the next full run continues
324
+ def previewed?
325
+ !@previewed.nil?
361
326
  end
362
327
 
363
328
  # Completes a transition whose before phase has already run by executing
364
- # its after callbacks, resuming any paused around callbacks first. Used
329
+ # its after callbacks, running any around callbacks its preview left first. Used
365
330
  # to finish transitions that were stored for deferred completion (e.g.
366
331
  # generated mid-action from an event attribute) once their action has
367
332
  # succeeded.
368
333
  def complete_deferred_after_callbacks
369
- if paused?
334
+ if previewed?
370
335
  run_callbacks(after: true)
371
336
  else
372
337
  after
@@ -375,141 +340,49 @@ module StateMachines
375
340
 
376
341
  private
377
342
 
378
- # Runs a block that may get paused. If the block doesn't pause, then
379
- # execution will continue as normal. If the block gets paused, then it
380
- # will take care of switching the execution context when it's resumed.
343
+ # A preview run: every before callback not run by an earlier preview,
344
+ # skipping the around callbacks (not entered, nor their conditions
345
+ # evaluated: they wrap the action of the full run), then the block; on a
346
+ # halt or a failed block, the failure callbacks. Running all the befores
347
+ # lets a validation in the block see what the full run's befores set, so
348
+ # it agrees with the full run. Returns false if it halted, including a
349
+ # halt from the block.
381
350
  #
382
- # This will return true if the given block halts for a reason other than
383
- # getting paused.
384
- #
385
- # Options:
386
- # * :fiber - Whether to use fiber-based execution (default: true)
387
- def pausable(options = {})
388
- # If fiber is disabled, use simple synchronous execution
389
- if options[:fiber] == false
390
- halted = !catch(:halt) do
391
- yield
392
- true
393
- end
394
- return halted
395
- end
396
-
397
- if @paused_fiber
398
- # Resume the paused fiber
399
- @resuming = true
400
- begin
401
- result = @paused_fiber.resume
402
- rescue StandardError => e
403
- # Clean up on exception
404
- @resuming = false
405
- @paused_fiber = nil
406
- raise e
351
+ # Preview bookkeeping (which befores ran) exists only from a successful
352
+ # preview to the end of its full run: it is built aside and kept only if
353
+ # this preview succeeds, so a preview that halts, fails or raises leaves
354
+ # the transition as it found it, minus any earlier preview.
355
+ def preview # rubocop:disable Naming/PredicateMethod -- returns whether the befores ran, as run_callbacks does
356
+ previewed = @previewed ? @previewed.dup : {}.compare_by_identity
357
+ @previewed = nil
358
+ halted = !catch(:halt) do
359
+ before_callbacks.each do |callback|
360
+ next if callback.type == :around || previewed.key?(callback)
361
+
362
+ previewed[callback] = true
363
+ callback.call(object, context, self)
407
364
  end
408
- @resuming = false
409
365
 
410
- result_value = unwrap_fiber_result(result)
411
-
412
- # Check if fiber is still alive after resume
413
- if @paused_fiber.alive?
414
- # Still paused, keep the fiber
415
- true
416
- else
417
- # Fiber completed
418
- @paused_fiber = nil
419
- result_value == :halted
420
- end
421
- else
422
- # Capture current fiber's Thread.current storage to preserve object identity
423
- # This is needed for compatibility but has limitations with dynamic assignments
424
- parent_fiber_locals = capture_thread_locals
425
-
426
- # Create a new fiber to run the block
427
- fiber = Fiber.new do
428
- # Restore parent's Thread.current storage with exact same object references
429
- parent_fiber_locals.each do |key, value|
430
- Thread.current[key] = value
431
- end
432
-
433
- # Mark that we're inside a pausable fiber
434
- Fiber.current.extend(StateMachines::PausableFiber)
435
- Fiber.current.state_machine_fiber_pausable = true
436
- begin
437
- halted = !catch(:halt) do
438
- yield
439
- true
440
- end
441
-
442
- # Export the final thread storage state along with the result
443
- [halted ? :halted : :completed, capture_thread_locals]
444
- rescue StandardError => e
445
- # Store the exception for re-raising
446
- [:error, e]
447
- ensure
448
- # Clean up the flag
449
- Fiber.current.state_machine_fiber_pausable = false
450
- end
451
- end
452
-
453
- # Run the fiber
454
- result = fiber.resume
455
-
456
- result_value = unwrap_fiber_result(result)
457
-
458
- # Save if paused
459
- if fiber.alive?
460
- @paused_fiber = fiber
461
- # Return true to indicate paused (treated as halted for flow control)
462
- true
463
- else
464
- # Fiber completed, return whether it was halted
465
- result_value == :halted
466
- end
467
- end
468
- end
469
-
470
- # Snapshots the current fiber's Thread.current storage, preserving object
471
- # identity of the stored values
472
- def capture_thread_locals
473
- Thread.current.keys.each_with_object({}) do |key, storage|
474
- storage[key] = Thread.current[key]
366
+ # Inside the catch, as in a full run: the block (e.g. the collection
367
+ # running the next machine's transition) may halt, which fails this
368
+ # transition too
369
+ action = block_given? ? { success: true }.merge(yield) : { success: true }
370
+ @result = action[:result]
371
+ @success = action[:success]
372
+ true
475
373
  end
476
- end
477
-
478
- # Unwraps a result returned from a pausable fiber, re-raising any exception
479
- # captured inside the fiber and importing its exported thread storage
480
- def unwrap_fiber_result(result)
481
- return result unless result.is_a?(Array)
374
+ @success = false if halted
482
375
 
483
- if result[0] == :error
484
- @paused_fiber = nil
485
- raise result[1]
376
+ if @success
377
+ @previewed = previewed
378
+ else
379
+ # A preview that halts or fails is a failed transition: its failure
380
+ # callbacks run, as in a full run, without marking the after phase
381
+ # as done (the full run that may follow runs its own)
382
+ after
383
+ @after_run = false
486
384
  end
487
-
488
- @fiber_thread_storage = result[1] if result.length == 2 && result[1].is_a?(Hash)
489
- result[0]
490
- end
491
-
492
- # Pauses the current callback execution. This should only occur within
493
- # around callbacks when the remainder of the callback will be executed at
494
- # a later point in time.
495
- def pause
496
- # Don't pause if we're in the middle of resuming
497
- return if @resuming
498
-
499
- # Only yield if we're actually inside a fiber created by pausable
500
- # We use a module extension to track this
501
- current_fiber = Fiber.current
502
- return unless current_fiber.respond_to?(:state_machine_fiber_pausable) && current_fiber.state_machine_fiber_pausable
503
-
504
- Fiber.yield
505
-
506
- # When we resume from the pause, execute the continuation block if present
507
- return unless @continuation_block && !@result
508
-
509
- action = { success: true }.merge(@continuation_block.call)
510
- @result = action[:result]
511
- @success = action[:success]
512
- @continuation_block = nil
385
+ !halted
513
386
  end
514
387
 
515
388
  # Runs the machine's +before+ callbacks for this transition. Only
@@ -518,38 +391,28 @@ module StateMachines
518
391
  #
519
392
  # Once the callbacks are run, they cannot be run again until this transition
520
393
  # is reset.
521
- def before(complete = true, index = 0, &)
394
+ def before(index = 0, &)
522
395
  return if @before_run
523
396
 
524
- callback = machine.callbacks[:before][index]
397
+ callback = before_callbacks[index]
525
398
 
526
399
  if callback
527
- # Check if callback matches this transition using branch
528
- if callback.branch.matches?(object, context)
529
- if callback.type == :around
530
- # Around callback: need to handle recursively. Execution only gets
531
- # paused if:
532
- # * The block fails and the callback doesn't run on failures OR
533
- # * The block succeeds, but after callbacks are disabled (in which
534
- # case a continuation is stored for later execution)
535
- callback.call(object, context, self) do
536
- before(complete, index + 1, &)
537
-
538
- pause if @success && !complete
539
-
540
- # If the block failed (success is false), we should halt
541
- # the around callback from continuing
542
- throw :halt unless @success
543
- end
544
- else
545
- # Normal before callback
546
- callback.call(object, context, self)
547
- # Continue with next callback
548
- before(complete, index + 1, &)
400
+ # Callback#call evaluates the callback's conditions (once) and answers
401
+ # whether it applied
402
+ if callback.type == :around
403
+ # The rest of the chain, and the action, run inside the around
404
+ applied = callback.call(object, context, self) do
405
+ before(index + 1, &)
406
+
407
+ # If the block failed (success is false), we should halt
408
+ # the around callback from continuing
409
+ throw :halt unless @success
549
410
  end
411
+ before(index + 1, &) unless applied
550
412
  else
551
- # Skip to next callback if it doesn't match
552
- before(complete, index + 1, &)
413
+ # A preview already ran this before callback
414
+ callback.call(object, context, self) unless @previewed&.key?(callback)
415
+ before(index + 1, &)
553
416
  end
554
417
  else
555
418
  # No more callbacks, execute the action block if at the end
@@ -582,13 +445,11 @@ module StateMachines
582
445
  def after
583
446
  return if @after_run
584
447
 
585
- # Restore the fiber's thread storage to ensure consistency
586
- # This preserves Thread.current state from before/around callbacks to after callbacks
587
- @fiber_thread_storage.each { |key, value| Thread.current[key] = value } if @fiber_thread_storage
588
-
589
448
  catch(:halt) do
590
- type = @success ? :after : :failure
591
- machine.callbacks[type].each { |callback| callback.call(object, context, self) }
449
+ # A branch's afters run before the machine's, closest to the change;
450
+ # they run on success only (a branch has no after_failure)
451
+ callbacks = @success ? branch_callbacks(:after) + machine.callbacks[:after] : machine.callbacks[:failure]
452
+ callbacks.each { |callback| callback.call(object, context, self) }
592
453
  end
593
454
 
594
455
  @after_run = true
@@ -605,5 +466,20 @@ module StateMachines
605
466
  def context
606
467
  @context ||= { on: event, from: from_name, to: to_name }
607
468
  end
469
+
470
+ # The before chain: the machine's before / around callbacks, then the
471
+ # selected branch's, so branch callbacks wrap closest to the state change.
472
+ # It is taken once per run: a callback registered while the chain runs
473
+ # (e.g. from inside a before_transition) applies from the next transition,
474
+ # not to the one in progress, whose chain cannot change under it.
475
+ def before_callbacks
476
+ @before_callbacks ||= machine.callbacks[:before] + branch_callbacks(:before, :around)
477
+ end
478
+
479
+ def branch_callbacks(*types)
480
+ return [] unless branch
481
+
482
+ branch.callbacks.select { |callback| types.include?(callback.type) }
483
+ end
608
484
  end
609
485
  end
@@ -34,17 +34,17 @@ module StateMachines
34
34
  attributes = map(&:attribute).uniq
35
35
  raise ArgumentError, 'Cannot perform multiple transitions in parallel for the same state machine attribute' if attributes.length != length
36
36
 
37
- StateMachines::OptionsValidator.assert_valid_keys!(options, :actions, :after, :use_transactions, :fiber)
37
+ StateMachines::OptionsValidator.assert_valid_keys!(options, :actions, :after, :use_transactions)
38
38
  options = { actions: true, after: true, use_transactions: true }.merge(options)
39
39
  @skip_actions = !options[:actions]
40
40
  @skip_after = !options[:after]
41
41
  @use_transactions = options[:use_transactions]
42
42
  @options = options
43
43
 
44
- # Reset transitions when creating a new collection
45
- # But preserve paused transitions to allow resuming
44
+ # Reset transitions when creating a new collection, except those a
45
+ # preview run started, which this collection continues
46
46
  each do |transition|
47
- transition.reset unless transition.paused?
47
+ transition.reset unless transition.previewed?
48
48
  end
49
49
  end
50
50
 
@@ -106,7 +106,7 @@ module StateMachines
106
106
  end
107
107
  end
108
108
 
109
- # The fiber-local stack of collections whose actions are running
109
+ # The stack (Thread.current, so per fiber) of collections whose actions are running
110
110
  RUNNING_ACTIONS_KEY = :state_machines_running_actions
111
111
 
112
112
  # The reason an event attribute performed inside this collection's action
@@ -228,19 +228,11 @@ module StateMachines
228
228
  # If any transition fails to run its callbacks, :halt will be thrown.
229
229
  def run_callbacks(index = 0, &)
230
230
  if (transition = self[index])
231
- # Pass through any options that affect callback execution (e.g., fiber: false)
232
- callback_options = { after: !skip_after }
233
- callback_options[:fiber] = options[:fiber] if options.key?(:fiber)
234
-
235
- callback_result = transition.run_callbacks(callback_options) do
231
+ callback_result = transition.run_callbacks(after: !skip_after) do
236
232
  run_callbacks(index + 1, &)
237
233
  { result: results[transition.action], success: success? }
238
234
  end
239
235
 
240
- # If we're skipping after callbacks and the transition is paused,
241
- # consider it successful (the pause was intentional)
242
- @success = true if skip_after && transition.paused?
243
-
244
236
  unless callback_result
245
237
  # The innermost transition to halt is the one that caused it; the
246
238
  # ones wrapping it halt as a consequence
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module StateMachines
4
- VERSION = '0.303.0'
4
+ VERSION = '0.304.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: state_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.303.0
4
+ version: 0.304.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih