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.
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mu
4
+ module Action
5
+ # The failures of an action: their declaration on the class, the check of
6
+ # each failure against the declarations, and the Failure result built
7
+ # from a FailureError.
8
+ #
9
+ # @api private Applications use what this module adds to action classes,
10
+ # never the module itself.
11
+ module Failures
12
+ # The instance variables of an action class that hold the failures it
13
+ # declares itself, and the actions it names with from:.
14
+ DECLARED = :@mu_action_failures
15
+ SOURCES = :@mu_action_failure_sources
16
+
17
+ def self.install(base)
18
+ base.extend(ClassMethods)
19
+ end
20
+
21
+ # The Failure result of an action, from the FailureError that stopped it.
22
+ # When the error comes from a call!, the failure of that other action is
23
+ # checked against the declarations and kept as the cause.
24
+ def self.result_for(action, exception)
25
+ cause = exception.failure
26
+ check(action, exception.error, exception.details, origin: cause.meta[:class]) if cause
27
+ # @type var failure_meta: ::Hash[Symbol, untyped]
28
+ failure_meta = { **action.meta, failure_error: exception }
29
+ failure_meta[:cause] = cause if cause
30
+ Failure.new(exception.error, details: exception.details, meta: failure_meta)
31
+ end
32
+
33
+ # Checks a failure against what the action declares, and hands one that is
34
+ # not allowed to Mu::Action.on_undeclared_failure.
35
+ def self.check(action, error, details, origin: nil)
36
+ return unless declared?(action.class)
37
+ return if origin && sources(action.class).any? { origin <= _1 }
38
+
39
+ problem = problem(of(action.class), error, details)
40
+ return unless problem
41
+
42
+ case (handler = Mu::Action.on_undeclared_failure)
43
+ when :raise then raise ArgumentError, "#{action.class}: #{problem}"
44
+ else handler.call(action, error, details)
45
+ end
46
+ end
47
+
48
+ # Declares failures on an action class. With codes, every keyword is a
49
+ # detail, including one named from. Without a code, from: names the
50
+ # actions whose failures the action can also return.
51
+ def self.declare(action_class, codes, details)
52
+ return declare_sources(action_class, **details) if codes.empty?
53
+ raise ArgumentError, "details can only be declared for a single failure" if codes.size > 1 && details.any?
54
+
55
+ declared = own(action_class).dup
56
+ codes.each { declared[_1] = details }
57
+ action_class.instance_variable_set(DECLARED, declared)
58
+ nil
59
+ end
60
+
61
+ # The failures an action class declares, including those of its parent
62
+ # class and of its from: actions, as a hash of error code to details
63
+ # types. They are worked out when read, so that a declaration added to a
64
+ # parent class reaches its subclasses whenever it is added.
65
+ def self.of(action_class)
66
+ lineage(action_class).map { own(_1) }.reduce({}, :merge)
67
+ end
68
+
69
+ # Class methods that declare and list the failures of an action.
70
+ #
71
+ # @api public
72
+ module ClassMethods
73
+ # Declares the failures this action can return. Once an action declares
74
+ # any, other failures are handled by Mu::Action.on_undeclared_failure.
75
+ #
76
+ # failure :site_disabled
77
+ # failure :invalid, errors: ActiveModel::Errors
78
+ # failure from: OtherAction
79
+ #
80
+ # With a code, every keyword is a detail, including one named +from+.
81
+ # Without a code, +from:+ names the actions whose failures this action
82
+ # can also return.
83
+ def failure(*codes, **details) = Failures.declare(self, codes, details)
84
+
85
+ # The declared failures, including those of the parent class and of the
86
+ # +from:+ actions, as a hash of error code to details types.
87
+ def failures = Failures.of(self)
88
+ end
89
+
90
+ class << self
91
+ private
92
+
93
+ def declared?(action_class) = sources(action_class).any? || of(action_class).any?
94
+ def own(action_class) = action_class.instance_variable_get(DECLARED) || {}
95
+ def own_sources(action_class) = action_class.instance_variable_get(SOURCES) || []
96
+
97
+ # The from: actions of an action class and of its parent classes.
98
+ def sources(action_class)
99
+ parent = Action.parent(action_class)
100
+ inherited = parent ? sources(parent) : [] #: ::Array[untyped]
101
+ inherited + own_sources(action_class)
102
+ end
103
+
104
+ # An action class preceded by its parent class and by the actions it
105
+ # takes failures from, each one once, so that actions that name each
106
+ # other do not recurse forever.
107
+ def lineage(action_class, seen = [])
108
+ return [] if seen.include?(action_class)
109
+
110
+ seen << action_class
111
+ ancestors = [Action.parent(action_class), *own_sources(action_class)].compact
112
+ ancestors.flat_map { lineage(_1, seen) } << action_class
113
+ end
114
+
115
+ def declare_sources(action_class, from: nil, **unexpected)
116
+ raise ArgumentError, "failure requires a code or from:" if from.nil? || unexpected.any?
117
+
118
+ # @type var sources: ::Array[untyped]
119
+ sources = Array(from)
120
+ invalid = sources.reject { _1.is_a?(Class) && _1.include?(Mu::Action) }
121
+ raise ArgumentError, "failure from: expects action classes, got #{invalid.inspect}" if invalid.any?
122
+
123
+ action_class.instance_variable_set(SOURCES, own_sources(action_class) + sources)
124
+ nil
125
+ end
126
+
127
+ def problem(failures, error, details)
128
+ return "undeclared failure #{error.inspect}" unless failures.key?(error)
129
+
130
+ types = failures[error]
131
+ unexpected = details.keys - types.keys
132
+ return "unexpected details #{unexpected.inspect} for failure #{error.inspect}" if unexpected.any?
133
+
134
+ detail_problem(error, types, details)
135
+ end
136
+
137
+ def detail_problem(error, types, details)
138
+ types.each do |key, type|
139
+ value = details[key]
140
+ next if type === value # rubocop:disable Style/CaseEquality
141
+
142
+ return "detail #{key.inspect} of failure #{error.inspect} must be #{type.inspect}, got #{value.inspect}"
143
+ end
144
+ nil
145
+ end
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mu
4
+ module Action
5
+ # The before, after and around hooks of an action: their registration on
6
+ # the class and their execution around the call.
7
+ #
8
+ # @api private Applications use what this module adds to action classes,
9
+ # never the module itself.
10
+ module Hooks
11
+ # The instance variable of an action class that holds the hooks it
12
+ # registers itself, by kind.
13
+ STORE = :@mu_action_hooks
14
+
15
+ def self.install(base)
16
+ base.extend(ClassMethods)
17
+ end
18
+
19
+ # Runs the hooks of an action around the block, which makes the call:
20
+ # the before hooks, the around hooks wrapped around the block, then the
21
+ # after hooks. Hooks run in the action, with instance_exec or send.
22
+ def self.run(action, &)
23
+ of(action.class, :before).each { run_hook(action, _1) }
24
+ # An around hook can replace the result, so what the chain returns is
25
+ # checked like what the call returns.
26
+ result = Action.own_result(action, around_chain(action, &).call, "an around hook")
27
+ of(action.class, :after).each { run_hook(action, _1) }
28
+ result
29
+ end
30
+
31
+ # The hooks of one kind of an action class: those of its parent class,
32
+ # followed by its own. They are worked out when read, so that a hook added
33
+ # to a parent class reaches its subclasses whenever it is added.
34
+ def self.of(action_class, kind)
35
+ parent = Action.parent(action_class)
36
+ inherited = parent ? of(parent, kind) : [] #: ::Array[untyped]
37
+ inherited + own(action_class, kind)
38
+ end
39
+
40
+ # Registers hooks of one kind on an action class: a block, or the names
41
+ # of methods of the action.
42
+ def self.register(action_class, kind, method_names, block)
43
+ hooks = block ? [checked_block(kind, method_names, block)] : hook_names(kind, method_names)
44
+ store = action_class.instance_variable_get(STORE) || {}
45
+ action_class.instance_variable_set(STORE, store.merge(kind => [*store[kind], *hooks]))
46
+ nil
47
+ end
48
+
49
+ # How many positional arguments a hook takes, from its parameters. A hook
50
+ # that takes any number of them counts as taking two.
51
+ def self.positional_arity(parameters)
52
+ return 2 if parameters.any? { |type, _| type == :rest }
53
+
54
+ parameters.count { |type, _| %i[req opt].include?(type) }
55
+ end
56
+
57
+ # Class methods that register hooks and list them.
58
+ #
59
+ # @api public
60
+ module ClassMethods
61
+ def before(*method_names, &block) = Hooks.register(self, :before, method_names, block)
62
+ def after(*method_names, &block) = Hooks.register(self, :after, method_names, block)
63
+
64
+ # An around hook takes the chain, or the action and the chain, and calls
65
+ # the chain to continue. A method can also take nothing and yield.
66
+ def around(*method_names, &block) = Hooks.register(self, :around, method_names, block)
67
+
68
+ # The hooks of the class, those of its parent class first. Each one is
69
+ # a block or the name of a method. They are for inspection: changing
70
+ # what these methods return does not change the hooks that run.
71
+ def before_hooks = Hooks.of(self, :before)
72
+ def after_hooks = Hooks.of(self, :after)
73
+ def around_hooks = Hooks.of(self, :around)
74
+ end
75
+
76
+ class << self
77
+ private
78
+
79
+ def own(action_class, kind)
80
+ action_class.instance_variable_get(STORE)&.fetch(kind, nil) || []
81
+ end
82
+
83
+ def checked_block(kind, method_names, block)
84
+ raise ArgumentError, "#{kind} hooks accept either a block or method names, not both" if method_names.any?
85
+ if kind == :around && positional_arity(block.parameters).zero?
86
+ raise ArgumentError, "an around block takes the chain, or the action and the chain"
87
+ end
88
+
89
+ block
90
+ end
91
+
92
+ def hook_names(kind, method_names)
93
+ raise ArgumentError, "#{kind} hook requires a block or method name" if method_names.empty?
94
+
95
+ method_names.map do |name|
96
+ raise ArgumentError, "Invalid #{kind} hook identifier: #{name.inspect}" unless name.respond_to?(:to_sym)
97
+
98
+ name.to_sym
99
+ end
100
+ end
101
+
102
+ def run_hook(action, hook)
103
+ if hook.is_a?(Proc)
104
+ # @type var hook: ^(*untyped) -> untyped
105
+ return action.instance_exec(&hook)
106
+ end
107
+
108
+ action.send(hook)
109
+ end
110
+
111
+ def around_chain(action, &block)
112
+ chain = block
113
+ of(action.class, :around).reverse_each do |hook|
114
+ previous = chain
115
+ chain = around_link(action, hook, previous)
116
+ end
117
+ chain
118
+ end
119
+
120
+ def around_link(action, hook, previous)
121
+ case hook
122
+ when Proc
123
+ arguments = around_arguments(action, hook.parameters, previous)
124
+ lambda do
125
+ # @type var hook: ^(*untyped) -> untyped
126
+ action.instance_exec(*arguments, &hook)
127
+ end
128
+ else
129
+ -> { call_around_method(action, hook, previous) }
130
+ end
131
+ end
132
+
133
+ def call_around_method(action, hook, previous)
134
+ method_object = around_method(action, hook.to_sym)
135
+ arguments = around_arguments(action, method_object.parameters, previous)
136
+ method_object.bind(action).call(*arguments, &previous)
137
+ end
138
+
139
+ # The arguments of an around hook, a block or a method: the chain when
140
+ # it takes one, the action and the chain when it takes two.
141
+ def around_arguments(action, parameters, previous)
142
+ case positional_arity(parameters)
143
+ when 0 then []
144
+ when 1 then [previous]
145
+ else [action, previous]
146
+ end
147
+ end
148
+
149
+ def around_method(action, method_name)
150
+ action.class.instance_method(method_name)
151
+ rescue NameError
152
+ raise NoMethodError, "Undefined hook method ##{method_name} for #{action.class}"
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mu
4
+ module Action
5
+ # The metadata of an action: diagnostic information such as its class and
6
+ # the values of its props, carried over to its result.
7
+ #
8
+ # @api private Applications use what this module adds to action classes,
9
+ # never the module itself.
10
+ module Metadata
11
+ # The instance variable of an action class that holds its own choice of
12
+ # the props to record.
13
+ RECORDING = :@mu_action_props_recording
14
+
15
+ def self.install(base)
16
+ base.extend(ClassMethods)
17
+ base.singleton_class.prepend(Lifecycle)
18
+ # The coercion copies the hash, so that one given by the caller is
19
+ # never modified.
20
+ base.prop(:meta, Hash, default: -> { {} }, &:dup) # steep:ignore UnannotatedEmptyCollection
21
+ end
22
+
23
+ # The props of an action to record in its metadata, by name, or nil when
24
+ # the action records none.
25
+ def self.recorded_props(action)
26
+ recording = recording(action.class)
27
+ return if recording == false
28
+
29
+ props = action.class.literal_properties.to_h do |prop|
30
+ [prop.name, action.instance_variable_get(:"@#{prop.name}")] #: [Symbol, untyped]
31
+ end.except(:meta, :context)
32
+
33
+ case recording
34
+ in { only: } then props.slice(*known_props(action, only, props))
35
+ in { except: } then props.except(*known_props(action, except, props))
36
+ else props
37
+ end
38
+ end
39
+
40
+ # Records the choice of an action class: every prop, none, or a subset.
41
+ def self.record(action_class, enabled, only, except)
42
+ action_class.instance_variable_set(RECORDING, build_recording(enabled, only, except))
43
+ nil
44
+ end
45
+
46
+ # Class methods that choose which props are recorded in the metadata.
47
+ #
48
+ # @api public
49
+ module ClassMethods
50
+ # Chooses which props are recorded in meta[:props]: all of them (the
51
+ # default), none, or a subset.
52
+ #
53
+ # record_props false
54
+ # record_props only: %i[site_id]
55
+ # record_props except: %i[payload]
56
+ #
57
+ # The names can be symbols or strings. Each one must be a prop of the
58
+ # action, and of every subclass that inherits the choice: this is checked
59
+ # when an action is instantiated, since props can be declared afterwards.
60
+ def record_props(enabled = true, only: nil, except: nil) # rubocop:disable Style/OptionalBooleanParameter
61
+ Metadata.record(self, enabled, only, except)
62
+ end
63
+ end
64
+
65
+ # Initializes the metadata of each new action.
66
+ module Lifecycle
67
+ # The metadata is initialized here and not in #initialize, because the
68
+ # initializer that Literal generates for a subclass with its own props
69
+ # does not call super.
70
+ def new(...)
71
+ instance = super
72
+ instance.send(:initialize_meta)
73
+ instance
74
+ end
75
+ end
76
+
77
+ class << self
78
+ private
79
+
80
+ # The choice of an action class, or else the one of its parent class.
81
+ # It is worked out when read, so that a choice made on a parent class
82
+ # reaches its subclasses whenever it is made.
83
+ def recording(action_class)
84
+ return action_class.instance_variable_get(RECORDING) if action_class.instance_variable_defined?(RECORDING)
85
+
86
+ parent = Action.parent(action_class)
87
+ parent ? recording(parent) : true
88
+ end
89
+
90
+ def build_recording(enabled, only, except)
91
+ unless [true, false].include?(enabled)
92
+ raise ArgumentError, "record_props takes true or false, got #{enabled.inspect}: " \
93
+ "name the props with only: or except:"
94
+ end
95
+ raise ArgumentError, "record_props accepts only: or except:, not both" if only && except
96
+
97
+ # @type var filter: ::Hash[Symbol, ::Array[Symbol]]
98
+ filter = { only:, except: }.compact.transform_values { symbolize(_1) }
99
+ return filter.empty? || filter if enabled
100
+ raise ArgumentError, "record_props false accepts no only: or except:" if filter.any?
101
+
102
+ false
103
+ end
104
+
105
+ def symbolize(names)
106
+ # @type var list: ::Array[untyped]
107
+ list = Array(names)
108
+ list.map(&:to_sym)
109
+ end
110
+
111
+ # The names, once each of them is known to be a prop. A name that
112
+ # matches no prop would otherwise be ignored, and a misspelled name in
113
+ # except: would leave the prop it meant to exclude recorded.
114
+ def known_props(action, names, props)
115
+ unknown = names - props.keys
116
+ return names if unknown.empty?
117
+
118
+ raise ArgumentError, "#{action.class}: record_props names props that do not exist: #{unknown.inspect}"
119
+ end
120
+ end
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mu
4
+ module Action
5
+ # Base result class that wraps action outcomes with success/failure state
6
+ # and metadata. Extended by Success and Failure classes for pattern matching.
7
+ #
8
+ # A result is immutable: it is frozen and has no writer. The hashes it
9
+ # holds are not frozen, as after hooks write to the metadata once the
10
+ # result is built.
11
+ class Result < Literal::Data
12
+ prop :meta, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
13
+
14
+ attr_reader :meta
15
+ end
16
+
17
+ # Success result class for pattern matching
18
+ class Success < Result
19
+ prop :value, _Nilable(_Any), :positional
20
+
21
+ attr_reader :value
22
+
23
+ def success? = true
24
+ def failure? = false
25
+ end
26
+
27
+ # Failure result class for pattern matching
28
+ class Failure < Result
29
+ prop :error, _Any, :positional
30
+ prop :details, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
31
+
32
+ attr_reader :error, :details
33
+
34
+ def success? = false
35
+ def failure? = true
36
+ end
37
+ end
38
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Mu
4
4
  module Action
5
- VERSION = "0.3.0"
5
+ VERSION = "0.4.0"
6
6
  end
7
7
  end