mu-action 0.3.0 → 0.4.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.
data/lib/mu/action.rb CHANGED
@@ -1,14 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "action/version"
4
3
  require "literal"
5
4
 
5
+ require_relative "action/version"
6
+ require_relative "action/failure_error"
7
+ require_relative "action/result"
8
+ require_relative "action/context"
9
+ require_relative "action/metadata"
10
+ require_relative "action/hooks"
11
+ require_relative "action/failures"
12
+
6
13
  module Mu
7
14
  # Provides an interactor pattern implementation with hooks, metadata tracking,
8
15
  # and result wrapping.
16
+ #
17
+ # An action class resolves the constants defined here by their bare name,
18
+ # ahead of the application's top-level constants, so each constant added
19
+ # under Mu::Action is a name applications can no longer use unqualified.
9
20
  module Action
10
- # Global settings, available as Mu::Action.on_undeclared_failure and so on.
11
- module Configuration
21
+ class << self
12
22
  # How an action handles a failure that its declarations don't allow:
13
23
  # +:raise+ (the default) raises an ArgumentError, while a callable is
14
24
  # called with the action, the error code and the details.
@@ -23,249 +33,66 @@ module Mu
23
33
  end
24
34
  end
25
35
 
26
- extend Configuration
27
-
28
36
  self.on_undeclared_failure = :raise
29
37
 
30
- # Fiber storage key holding the context of the running action, inherited
31
- # by the actions it calls.
32
- CONTEXT_KEY = :mu_action_context
33
-
34
38
  def self.included(base)
35
- base.class_eval do
36
- extend Literal::Properties
37
- extend ClassMethods
38
- include Initializer
39
- include FailureChecking
40
- singleton_class.prepend(MetaPropAdder)
41
- singleton_class.prepend(HookPropagator)
42
-
43
- attr_reader :meta, :context
44
- end
45
- end
46
-
47
- # Internal module that automatically adds the meta and context properties
48
- # to action classes when they are instantiated. Ensures proper metadata
49
- # initialization.
50
- module MetaPropAdder
51
- def new(...)
52
- unless @meta_prop_added
53
- prop :meta, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
54
- prop :context, _Nilable(_Any), default: -> { Fiber[CONTEXT_KEY] }
55
- @meta_prop_added = true
56
- end
57
- instance = super
58
- # Ensure meta is initialized for this specific class
59
- instance.send(:initialize_meta) if instance.respond_to?(:initialize_meta, true)
60
- instance
61
- end
62
-
63
- def inherited(subclass)
64
- super
65
- subclass.instance_variable_set(:@meta_prop_added, false)
66
- end
67
- end
68
-
69
- # Internal module that ensures hook arrays and failure declarations are
70
- # properly duplicated when action classes are inherited, preventing shared
71
- # state between classes.
72
- module HookPropagator
73
- def inherited(subclass)
74
- super
75
- subclass.instance_variable_set(:@before_hooks, before_hooks.dup)
76
- subclass.instance_variable_set(:@after_hooks, after_hooks.dup)
77
- subclass.instance_variable_set(:@around_hooks, around_hooks.dup)
78
- subclass.instance_variable_set(:@own_failures, own_failures.dup)
79
- subclass.instance_variable_set(:@failure_sources, failure_sources.dup)
80
- subclass.instance_variable_set(:@props_recording, props_recording)
81
- end
82
- end
83
-
84
- # Exception class for action failures. Carries the error code and its
85
- # details. When raised by +call!+, it also carries the Failure result.
86
- class FailureError < StandardError
87
- attr_reader :error, :details, :failure
88
-
89
- def initialize(error, details: {}, failure: nil)
90
- @error = error
91
- @details = details
92
- @failure = failure
93
- super(error)
94
- end
95
- end
96
-
97
- # Base result class that wraps action outcomes with success/failure state
98
- # and metadata. Extended by Success and Failure classes for pattern matching.
99
- class Result < Literal::Struct
100
- prop :meta, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
101
-
102
- attr_reader :meta
103
- end
104
-
105
- # Success result class for pattern matching
106
- class Success < Result
107
- prop :value, _Nilable(_Any), :positional
108
-
109
- attr_reader :value
110
-
111
- def success? = true
112
- def failure? = false
113
- end
114
-
115
- # Failure result class for pattern matching
116
- class Failure < Result
117
- prop :error, _Any, :positional
118
- prop :details, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
119
-
120
- attr_reader :error, :details
121
-
122
- def success? = false
123
- def failure? = true
124
- end
125
-
126
- # Internal module that handles action initialization, automatically
127
- # tracking class information and property values in metadata.
128
- module Initializer
129
- def initialize(...)
130
- super
131
- initialize_meta
132
- end
133
-
134
- private
135
-
136
- def initialize_meta
137
- @meta = meta.dup
138
- meta[:class] = self.class
139
- props = recorded_props
140
- meta[:props] = props if props
141
- meta[:context] = context unless context.nil?
142
- end
143
-
144
- def recorded_props
145
- recording = self.class.props_recording
146
- return if recording == false
147
-
148
- props = self.class.literal_properties.to_h do |prop|
149
- [prop.name, instance_variable_get(:"@#{prop.name}")] #: [Symbol, untyped]
150
- end.except(:meta, :context)
151
-
152
- case recording
153
- in { only: } then props.slice(*only)
154
- in { except: } then props.except(*except)
155
- else props
156
- end
157
- end
158
- end
159
-
160
- # Internal module that builds Failure results and checks failures against
161
- # the action's declarations.
162
- module FailureChecking
163
- private
164
-
165
- def failure_from(exception)
166
- cause = exception.failure
167
- check_failure(exception.error, exception.details, origin: cause.meta[:class]) if cause
168
- # @type var failure_meta: ::Hash[Symbol, untyped]
169
- failure_meta = { **meta, failure_error: exception }
170
- failure_meta[:cause] = cause if cause
171
- Failure.new(exception.error, details: exception.details, meta: failure_meta)
172
- end
173
-
174
- def check_failure(error, details, origin: nil)
175
- return unless self.class.declares_failures?
176
- return if origin && self.class.failure_sources.any? { origin <= _1 }
177
-
178
- problem = failure_problem(error, details)
179
- return unless problem
180
-
181
- case (handler = Mu::Action.on_undeclared_failure)
182
- when :raise then raise ArgumentError, "#{self.class}: #{problem}"
183
- else handler.call(self, error, details)
184
- end
185
- end
186
-
187
- def failure_problem(error, details)
188
- failures = self.class.failures
189
- return "undeclared failure #{error.inspect}" unless failures.key?(error)
190
-
191
- types = failures[error]
192
- unexpected = details.keys - types.keys
193
- return "unexpected details #{unexpected.inspect} for failure #{error.inspect}" if unexpected.any?
194
-
195
- detail_problem(error, types, details)
196
- end
197
-
198
- def detail_problem(error, types, details)
199
- types.each do |key, type|
200
- value = details[key]
201
- next if type === value # rubocop:disable Style/CaseEquality
202
-
203
- return "detail #{key.inspect} of failure #{error.inspect} must be #{type.inspect}, got #{value.inspect}"
39
+ # Ruby calls this hook each time, so including Mu::Action again, in the
40
+ # same class or in a subclass, must change nothing.
41
+ return if base.singleton_class.include?(ClassMethods)
42
+
43
+ base.extend(Literal::Properties)
44
+ base.extend(ClassMethods)
45
+ # Metadata and Context declare the meta and context props here, before
46
+ # the props of the action itself.
47
+ [Metadata, Context, Hooks, Failures].each { _1.install(base) }
48
+ end
49
+
50
+ # The parent class of an action class, when it is an action class too. What
51
+ # a class declares is combined with what its parent declares through it.
52
+ #
53
+ # @api private
54
+ def self.parent(action_class)
55
+ parent = action_class.superclass
56
+ parent if parent&.include?(self)
57
+ end
58
+
59
+ # The Success an action built, which is what its call and its around hooks
60
+ # must return. A Failure can only be returned by another action: it is
61
+ # raised as the FailureError of a call! would be, so that it reaches the
62
+ # around hooks as an exception and becomes the failure of this action.
63
+ #
64
+ # @api private
65
+ def self.own_result(action, value, source)
66
+ return value if value.is_a?(Success) && value.meta.equal?(action.meta)
67
+ raise FailureError.new(value.error, details: value.details, failure: value) if value.is_a?(Failure)
68
+
69
+ problem =
70
+ if value.is_a?(Success)
71
+ "the result of another action. Return Success(...) with its value, as in Success(OtherAction.call!(...))"
72
+ else
73
+ "#{value.inspect}. It must return Success(...), or call Failure(...)"
204
74
  end
205
- nil
206
- end
75
+ raise TypeError, "#{action.class}: #{source} returned #{problem}"
207
76
  end
208
77
 
209
- # Class methods added to action classes when including Mu::Action.
210
- # Provides hook registration, execution methods, and result type definition.
78
+ # Class methods added to action classes when including Mu::Action: the
79
+ # entry points and the result type definition.
211
80
  module ClassMethods
212
- def around(*method_names, &block) = register_hook(around_hooks, method_names, block, name: :around)
213
- def before(*method_names, &block) = register_hook(before_hooks, method_names, block, name: :before)
214
- def after(*method_names, &block) = register_hook(after_hooks, method_names, block, name: :after)
215
-
216
- def around_hooks = (@around_hooks ||= [])
217
- def before_hooks = (@before_hooks ||= [])
218
- def after_hooks = (@after_hooks ||= [])
81
+ # The props that Mu::Action declares itself. An action cannot declare a
82
+ # prop with one of these names.
83
+ RESERVED_PROPS = %i[meta context].freeze
219
84
 
220
- def call(...) = new(...).run
221
-
222
- def call!(...)
223
- result = new(...).run
224
- case result
225
- in Success(value:)
226
- value
227
- in Failure(error:, details:, meta:)
228
- raise FailureError.new(error, details:, failure: result), cause: meta[:failure_error]
229
- else
230
- result
85
+ def prop(name, ...)
86
+ if RESERVED_PROPS.include?(name) && literal_properties.any? { _1.name == name }
87
+ raise ArgumentError, "#{self}: the #{name} prop is reserved by Mu::Action"
231
88
  end
232
- end
233
89
 
234
- # Chooses which props are recorded in meta[:props]: all of them (the
235
- # default), none, or a subset.
236
- #
237
- # record_props false
238
- # record_props only: %i[site_id]
239
- # record_props except: %i[payload]
240
- def record_props(enabled = true, only: nil, except: nil) # rubocop:disable Style/OptionalBooleanParameter
241
- @props_recording = build_props_recording(enabled, only, except)
242
- end
243
-
244
- def props_recording = (defined?(@props_recording) ? @props_recording : true)
245
-
246
- # Declares the failures this action can return. Once an action declares
247
- # any, other failures are handled by Mu::Action.on_undeclared_failure.
248
- #
249
- # failure :site_disabled
250
- # failure :invalid, errors: ActiveModel::Errors
251
- # failure from: OtherAction
252
- def failure(*codes, from: nil, **details)
253
- raise ArgumentError, "failure requires a code or from:" if codes.empty? && !from
254
- raise ArgumentError, "details can only be declared for a single failure" if codes.size > 1 && details.any?
255
-
256
- codes.each { own_failures[_1] = details }
257
- failure_sources.concat(Array(from))
90
+ super
258
91
  end
259
92
 
260
- # The declared failures, including those of the +from:+ actions,
261
- # as a hash of error code to details types.
262
- def failures
263
- failure_sources.map(&:failures).reduce({}, :merge).merge(own_failures)
264
- end
93
+ def call(...) = new(...).run
265
94
 
266
- def declares_failures? = own_failures.any? || failure_sources.any?
267
- def own_failures = (@own_failures ||= {})
268
- def failure_sources = (@failure_sources ||= [])
95
+ def call!(...) = new(...).run!.value
269
96
 
270
97
  def result(type)
271
98
  success_class = Class.new(::Mu::Action::Success) do
@@ -275,148 +102,62 @@ module Mu
275
102
 
276
103
  const_set(:Success, success_class)
277
104
  end
105
+ end
278
106
 
279
- private
280
-
281
- def build_props_recording(enabled, only, except)
282
- raise ArgumentError, "record_props accepts only: or except:, not both" if only && except
283
-
284
- # @type var filter: ::Hash[Symbol, ::Array[Symbol]]
285
- filter = { only:, except: }.compact.transform_values { Array(_1) }
286
- return filter.empty? || filter if enabled
287
- raise ArgumentError, "record_props false accepts no only: or except:" if filter.any?
288
-
289
- false
290
- end
291
-
292
- def register_hook(collection, method_names, block, name:)
293
- ensure_valid_hook_inputs(method_names, block, name:)
294
- additions = normalize_hook_inputs(method_names, block, name:)
295
- collection.concat(additions)
296
- end
297
-
298
- def normalize_hook_inputs(method_names, block, name:)
299
- if block
300
- [block]
301
- else
302
- symbolize_hook_names(method_names, name:)
303
- end
304
- end
305
-
306
- def ensure_valid_hook_inputs(method_names, block, name:)
307
- return unless block && method_names.any?
308
-
309
- raise ArgumentError, "#{name} hooks accept either a block or method names, not both"
310
- end
107
+ # The methods below are all that Mu::Action adds to an action, with the
108
+ # call it implements. An action can override any of them and call super.
311
109
 
312
- def symbolize_hook_names(method_names, name:)
313
- raise ArgumentError, "#{name} hook requires a block or method name" if method_names.empty?
110
+ # The metadata of the action, which its result carries. It must be the
111
+ # same Hash on every call: hooks write to it and the result shares it.
112
+ def meta = @meta
314
113
 
315
- method_names.map do |method_name|
316
- unless method_name.respond_to?(:to_sym)
317
- raise ArgumentError, "Invalid #{name} hook identifier: #{method_name.inspect}"
318
- end
319
-
320
- method_name.to_sym
321
- end
322
- end
323
- end
114
+ # What the caller says about who is calling and from where.
115
+ def context = @context
324
116
 
325
117
  # rubocop:disable Naming/MethodName
118
+
119
+ # Builds the result of the action. This is what call must return.
326
120
  def Success(value = nil) = self.class.const_get(:Success).new(value, meta:)
327
121
 
122
+ # Fails the action: checks the failure against the declarations, then
123
+ # raises, so that nothing after it runs.
328
124
  def Failure(error, **details)
329
- check_failure(error, details)
125
+ Failures.check(self, error, details)
330
126
  raise FailureError.new(error, details:)
331
127
  end
332
128
  # rubocop:enable Naming/MethodName
333
129
 
130
+ # Runs the action and returns its result, a Success or a Failure: sets the
131
+ # context, then runs the hooks around the call.
334
132
  def run
335
- run!
133
+ Context.with(self) { Hooks.run(self) { Action.own_result(self, call, "call") } }
336
134
  rescue FailureError => e
337
- failure_from(e)
135
+ Failures.result_for(self, e)
338
136
  end
339
137
 
138
+ # Runs the action and returns its Success, or raises a FailureError that
139
+ # carries its Failure. An action that calls another one this way takes on
140
+ # its failure, as with the call! of the class.
340
141
  def run!
341
- with_context { with_hooks { call } }
342
- end
343
-
344
- protected
345
-
346
- def with_context
347
- previous = Fiber[CONTEXT_KEY]
348
- Fiber[CONTEXT_KEY] = context
349
- yield
350
- ensure
351
- Fiber[CONTEXT_KEY] = previous
352
- end
142
+ result = run
143
+ return result unless result.is_a?(Failure)
353
144
 
354
- def with_hooks(&)
355
- run_before_hooks
356
- call_chain = build_around_chain(&)
357
- result = call_chain.call
358
- run_after_hooks
359
- result
145
+ raise FailureError.new(result.error, details: result.details, failure: result), cause: result.meta[:failure_error]
360
146
  end
361
147
 
362
148
  private
363
149
 
364
- def run_before_hooks = self.class.before_hooks.each { execute_simple_hook(_1) }
365
- def run_after_hooks = self.class.after_hooks.each { execute_simple_hook(_1) }
366
-
367
- def build_around_chain(&block)
368
- chain = block
369
- self.class.around_hooks.reverse_each do |hook|
370
- previous = chain
371
- chain = build_around_wrapper(hook, previous)
372
- end
373
- chain
374
- end
375
-
376
- def execute_simple_hook(hook)
377
- if hook.is_a?(Proc)
378
- # @type var hook: ^(*untyped) -> untyped
379
- return instance_exec(&hook)
380
- end
381
-
382
- send(hook)
383
- end
384
-
385
- def build_around_wrapper(hook, previous)
386
- case hook
387
- when Proc
388
- lambda do
389
- # @type var hook: ^(*untyped) -> untyped
390
- instance_exec(self, previous, &hook)
391
- end
392
- else
393
- -> { invoke_around_method(hook, previous) }
394
- end
395
- end
396
-
397
- def invoke_around_method(hook, previous)
398
- method_name = hook.to_sym
399
- method_object = resolve_method(method_name)
400
- arguments = around_arguments(method_object, previous)
401
- method_object.bind(self).call(*arguments, &previous)
402
- end
403
-
404
- def around_arguments(method_object, previous)
405
- params = method_object.parameters.reject { _1.first == :block }
406
- return [] if params.empty?
407
- return [previous] if params.length == 1
408
-
409
- [self, previous]
410
- end
411
-
412
- def resolve_method(method_name)
413
- self.class.instance_method(method_name)
414
- rescue NameError
415
- raise NoMethodError, "Undefined hook method ##{method_name} for #{self.class}"
416
- end
417
-
418
150
  def call
419
151
  raise NotImplementedError, "You must implement the call method"
420
152
  end
153
+
154
+ # Fills in the metadata when the action is built. Override it, and call
155
+ # super, to record something else than the props.
156
+ def initialize_meta
157
+ meta[:class] = self.class
158
+ props = Metadata.recorded_props(self)
159
+ meta[:props] = props if props
160
+ meta[:context] = context unless context.nil?
161
+ end
421
162
  end
422
163
  end
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mu-action
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nicolas Buduroi
8
- bindir: exe
8
+ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - "~>"
17
17
  - !ruby/object:Gem::Version
18
- version: '1.7'
18
+ version: '1.9'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - "~>"
24
24
  - !ruby/object:Gem::Version
25
- version: '1.7'
25
+ version: '1.9'
26
26
  description: A Ruby gem providing interactor pattern implementation with enhanced
27
27
  type safety, metadata tracking, and hook system built on Literal gem
28
28
  email:
@@ -35,8 +35,13 @@ files:
35
35
  - LICENSE.txt
36
36
  - README.md
37
37
  - lib/mu/action.rb
38
+ - lib/mu/action/context.rb
39
+ - lib/mu/action/failure_error.rb
40
+ - lib/mu/action/failures.rb
41
+ - lib/mu/action/hooks.rb
42
+ - lib/mu/action/metadata.rb
43
+ - lib/mu/action/result.rb
38
44
  - lib/mu/action/version.rb
39
- - sig/mu/action.rbs
40
45
  homepage: https://github.com/budu/mu-action
41
46
  licenses:
42
47
  - MIT