falyx 0.1.37__py3-none-any.whl → 0.1.39__py3-none-any.whl
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.
- falyx/__init__.py +0 -11
- falyx/action/__init__.py +9 -9
- falyx/action/action.py +4 -724
- falyx/action/action_factory.py +1 -1
- falyx/action/action_group.py +170 -0
- falyx/action/base.py +156 -0
- falyx/action/chained_action.py +208 -0
- falyx/action/fallback_action.py +49 -0
- falyx/action/io_action.py +1 -1
- falyx/action/literal_input_action.py +47 -0
- falyx/action/menu_action.py +1 -1
- falyx/action/mixins.py +33 -0
- falyx/action/process_action.py +128 -0
- falyx/action/process_pool_action.py +166 -0
- falyx/action/prompt_menu_action.py +1 -1
- falyx/action/select_file_action.py +1 -1
- falyx/action/selection_action.py +1 -2
- falyx/action/user_input_action.py +1 -1
- falyx/command.py +2 -1
- falyx/config.py +2 -1
- falyx/falyx.py +21 -13
- falyx/menu.py +1 -1
- falyx/parsers/argparse.py +152 -53
- falyx/parsers/utils.py +1 -1
- falyx/protocols.py +1 -1
- falyx/retry_utils.py +2 -1
- falyx/utils.py +1 -1
- falyx/version.py +1 -1
- {falyx-0.1.37.dist-info → falyx-0.1.39.dist-info}/METADATA +6 -5
- falyx-0.1.39.dist-info/RECORD +61 -0
- falyx-0.1.37.dist-info/RECORD +0 -53
- {falyx-0.1.37.dist-info → falyx-0.1.39.dist-info}/LICENSE +0 -0
- {falyx-0.1.37.dist-info → falyx-0.1.39.dist-info}/WHEEL +0 -0
- {falyx-0.1.37.dist-info → falyx-0.1.39.dist-info}/entry_points.txt +0 -0
falyx/action/action_factory.py
CHANGED
@@ -4,7 +4,7 @@ from typing import Any, Callable
|
|
4
4
|
|
5
5
|
from rich.tree import Tree
|
6
6
|
|
7
|
-
from falyx.action.
|
7
|
+
from falyx.action.base import BaseAction
|
8
8
|
from falyx.context import ExecutionContext
|
9
9
|
from falyx.execution_registry import ExecutionRegistry as er
|
10
10
|
from falyx.hook_manager import HookType
|
@@ -0,0 +1,170 @@
|
|
1
|
+
import asyncio
|
2
|
+
import random
|
3
|
+
from typing import Any, Callable
|
4
|
+
|
5
|
+
from rich.tree import Tree
|
6
|
+
|
7
|
+
from falyx.action.action import Action
|
8
|
+
from falyx.action.base import BaseAction
|
9
|
+
from falyx.action.mixins import ActionListMixin
|
10
|
+
from falyx.context import ExecutionContext, SharedContext
|
11
|
+
from falyx.execution_registry import ExecutionRegistry as er
|
12
|
+
from falyx.hook_manager import Hook, HookManager, HookType
|
13
|
+
from falyx.logger import logger
|
14
|
+
from falyx.parsers.utils import same_argument_definitions
|
15
|
+
from falyx.themes.colors import OneColors
|
16
|
+
|
17
|
+
|
18
|
+
class ActionGroup(BaseAction, ActionListMixin):
|
19
|
+
"""
|
20
|
+
ActionGroup executes multiple actions concurrently in parallel.
|
21
|
+
|
22
|
+
It is ideal for independent tasks that can be safely run simultaneously,
|
23
|
+
improving overall throughput and responsiveness of workflows.
|
24
|
+
|
25
|
+
Core features:
|
26
|
+
- Parallel execution of all contained actions.
|
27
|
+
- Shared last_result injection across all actions if configured.
|
28
|
+
- Aggregated collection of individual results as (name, result) pairs.
|
29
|
+
- Hook lifecycle support (before, on_success, on_error, after, on_teardown).
|
30
|
+
- Error aggregation: captures all action errors and reports them together.
|
31
|
+
|
32
|
+
Behavior:
|
33
|
+
- If any action fails, the group collects the errors but continues executing
|
34
|
+
other actions without interruption.
|
35
|
+
- After all actions complete, ActionGroup raises a single exception summarizing
|
36
|
+
all failures, or returns all results if successful.
|
37
|
+
|
38
|
+
Best used for:
|
39
|
+
- Batch processing multiple independent tasks.
|
40
|
+
- Reducing latency for workflows with parallelizable steps.
|
41
|
+
- Isolating errors while maximizing successful execution.
|
42
|
+
|
43
|
+
Args:
|
44
|
+
name (str): Name of the chain.
|
45
|
+
actions (list): List of actions or literals to execute.
|
46
|
+
hooks (HookManager, optional): Hooks for lifecycle events.
|
47
|
+
inject_last_result (bool, optional): Whether to inject last results into kwargs
|
48
|
+
by default.
|
49
|
+
inject_into (str, optional): Key name for injection.
|
50
|
+
"""
|
51
|
+
|
52
|
+
def __init__(
|
53
|
+
self,
|
54
|
+
name: str,
|
55
|
+
actions: list[BaseAction] | None = None,
|
56
|
+
*,
|
57
|
+
hooks: HookManager | None = None,
|
58
|
+
inject_last_result: bool = False,
|
59
|
+
inject_into: str = "last_result",
|
60
|
+
):
|
61
|
+
super().__init__(
|
62
|
+
name,
|
63
|
+
hooks=hooks,
|
64
|
+
inject_last_result=inject_last_result,
|
65
|
+
inject_into=inject_into,
|
66
|
+
)
|
67
|
+
ActionListMixin.__init__(self)
|
68
|
+
if actions:
|
69
|
+
self.set_actions(actions)
|
70
|
+
|
71
|
+
def _wrap_if_needed(self, action: BaseAction | Any) -> BaseAction:
|
72
|
+
if isinstance(action, BaseAction):
|
73
|
+
return action
|
74
|
+
elif callable(action):
|
75
|
+
return Action(name=action.__name__, action=action)
|
76
|
+
else:
|
77
|
+
raise TypeError(
|
78
|
+
"ActionGroup only accepts BaseAction or callable, got "
|
79
|
+
f"{type(action).__name__}"
|
80
|
+
)
|
81
|
+
|
82
|
+
def add_action(self, action: BaseAction | Any) -> None:
|
83
|
+
action = self._wrap_if_needed(action)
|
84
|
+
super().add_action(action)
|
85
|
+
if hasattr(action, "register_teardown") and callable(action.register_teardown):
|
86
|
+
action.register_teardown(self.hooks)
|
87
|
+
|
88
|
+
def get_infer_target(self) -> tuple[Callable[..., Any] | None, dict[str, Any] | None]:
|
89
|
+
arg_defs = same_argument_definitions(self.actions)
|
90
|
+
if arg_defs:
|
91
|
+
return self.actions[0].get_infer_target()
|
92
|
+
logger.debug(
|
93
|
+
"[%s] auto_args disabled: mismatched ActionGroup arguments",
|
94
|
+
self.name,
|
95
|
+
)
|
96
|
+
return None, None
|
97
|
+
|
98
|
+
async def _run(self, *args, **kwargs) -> list[tuple[str, Any]]:
|
99
|
+
shared_context = SharedContext(name=self.name, action=self, is_parallel=True)
|
100
|
+
if self.shared_context:
|
101
|
+
shared_context.set_shared_result(self.shared_context.last_result())
|
102
|
+
updated_kwargs = self._maybe_inject_last_result(kwargs)
|
103
|
+
context = ExecutionContext(
|
104
|
+
name=self.name,
|
105
|
+
args=args,
|
106
|
+
kwargs=updated_kwargs,
|
107
|
+
action=self,
|
108
|
+
extra={"results": [], "errors": []},
|
109
|
+
shared_context=shared_context,
|
110
|
+
)
|
111
|
+
|
112
|
+
async def run_one(action: BaseAction):
|
113
|
+
try:
|
114
|
+
prepared = action.prepare(shared_context, self.options_manager)
|
115
|
+
result = await prepared(*args, **updated_kwargs)
|
116
|
+
shared_context.add_result((action.name, result))
|
117
|
+
context.extra["results"].append((action.name, result))
|
118
|
+
except Exception as error:
|
119
|
+
shared_context.add_error(shared_context.current_index, error)
|
120
|
+
context.extra["errors"].append((action.name, error))
|
121
|
+
|
122
|
+
context.start_timer()
|
123
|
+
try:
|
124
|
+
await self.hooks.trigger(HookType.BEFORE, context)
|
125
|
+
await asyncio.gather(*[run_one(a) for a in self.actions])
|
126
|
+
|
127
|
+
if context.extra["errors"]:
|
128
|
+
context.exception = Exception(
|
129
|
+
f"{len(context.extra['errors'])} action(s) failed: "
|
130
|
+
f"{' ,'.join(name for name, _ in context.extra['errors'])}"
|
131
|
+
)
|
132
|
+
await self.hooks.trigger(HookType.ON_ERROR, context)
|
133
|
+
raise context.exception
|
134
|
+
|
135
|
+
context.result = context.extra["results"]
|
136
|
+
await self.hooks.trigger(HookType.ON_SUCCESS, context)
|
137
|
+
return context.result
|
138
|
+
|
139
|
+
except Exception as error:
|
140
|
+
context.exception = error
|
141
|
+
raise
|
142
|
+
finally:
|
143
|
+
context.stop_timer()
|
144
|
+
await self.hooks.trigger(HookType.AFTER, context)
|
145
|
+
await self.hooks.trigger(HookType.ON_TEARDOWN, context)
|
146
|
+
er.record(context)
|
147
|
+
|
148
|
+
def register_hooks_recursively(self, hook_type: HookType, hook: Hook):
|
149
|
+
"""Register a hook for all actions and sub-actions."""
|
150
|
+
super().register_hooks_recursively(hook_type, hook)
|
151
|
+
for action in self.actions:
|
152
|
+
action.register_hooks_recursively(hook_type, hook)
|
153
|
+
|
154
|
+
async def preview(self, parent: Tree | None = None):
|
155
|
+
label = [f"[{OneColors.MAGENTA_b}]⏩ ActionGroup (parallel)[/] '{self.name}'"]
|
156
|
+
if self.inject_last_result:
|
157
|
+
label.append(f" [dim](receives '{self.inject_into}')[/dim]")
|
158
|
+
tree = parent.add("".join(label)) if parent else Tree("".join(label))
|
159
|
+
actions = self.actions.copy()
|
160
|
+
random.shuffle(actions)
|
161
|
+
await asyncio.gather(*(action.preview(parent=tree) for action in actions))
|
162
|
+
if not parent:
|
163
|
+
self.console.print(tree)
|
164
|
+
|
165
|
+
def __str__(self):
|
166
|
+
return (
|
167
|
+
f"ActionGroup(name={self.name!r}, actions={[a.name for a in self.actions]!r},"
|
168
|
+
f" inject_last_result={self.inject_last_result}, "
|
169
|
+
f"inject_into={self.inject_into!r})"
|
170
|
+
)
|
falyx/action/base.py
ADDED
@@ -0,0 +1,156 @@
|
|
1
|
+
# Falyx CLI Framework — (c) 2025 rtj.dev LLC — MIT Licensed
|
2
|
+
"""base.py
|
3
|
+
|
4
|
+
Core action system for Falyx.
|
5
|
+
|
6
|
+
This module defines the building blocks for executable actions and workflows,
|
7
|
+
providing a structured way to compose, execute, recover, and manage sequences of
|
8
|
+
operations.
|
9
|
+
|
10
|
+
All actions are callable and follow a unified signature:
|
11
|
+
result = action(*args, **kwargs)
|
12
|
+
|
13
|
+
Core guarantees:
|
14
|
+
- Full hook lifecycle support (before, on_success, on_error, after, on_teardown).
|
15
|
+
- Consistent timing and execution context tracking for each run.
|
16
|
+
- Unified, predictable result handling and error propagation.
|
17
|
+
- Optional last_result injection to enable flexible, data-driven workflows.
|
18
|
+
- Built-in support for retries, rollbacks, parallel groups, chaining, and fallback
|
19
|
+
recovery.
|
20
|
+
|
21
|
+
Key components:
|
22
|
+
- Action: wraps a function or coroutine into a standard executable unit.
|
23
|
+
- ChainedAction: runs actions sequentially, optionally injecting last results.
|
24
|
+
- ActionGroup: runs actions in parallel and gathers results.
|
25
|
+
- ProcessAction: executes CPU-bound functions in a separate process.
|
26
|
+
- LiteralInputAction: injects static values into workflows.
|
27
|
+
- FallbackAction: gracefully recovers from failures or missing data.
|
28
|
+
|
29
|
+
This design promotes clean, fault-tolerant, modular CLI and automation systems.
|
30
|
+
"""
|
31
|
+
from __future__ import annotations
|
32
|
+
|
33
|
+
from abc import ABC, abstractmethod
|
34
|
+
from typing import Any, Callable
|
35
|
+
|
36
|
+
from rich.console import Console
|
37
|
+
from rich.tree import Tree
|
38
|
+
|
39
|
+
from falyx.context import SharedContext
|
40
|
+
from falyx.debug import register_debug_hooks
|
41
|
+
from falyx.execution_registry import ExecutionRegistry as er
|
42
|
+
from falyx.hook_manager import Hook, HookManager, HookType
|
43
|
+
from falyx.logger import logger
|
44
|
+
from falyx.options_manager import OptionsManager
|
45
|
+
|
46
|
+
|
47
|
+
class BaseAction(ABC):
|
48
|
+
"""
|
49
|
+
Base class for actions. Actions can be simple functions or more
|
50
|
+
complex actions like `ChainedAction` or `ActionGroup`. They can also
|
51
|
+
be run independently or as part of Falyx.
|
52
|
+
|
53
|
+
inject_last_result (bool): Whether to inject the previous action's result
|
54
|
+
into kwargs.
|
55
|
+
inject_into (str): The name of the kwarg key to inject the result as
|
56
|
+
(default: 'last_result').
|
57
|
+
"""
|
58
|
+
|
59
|
+
def __init__(
|
60
|
+
self,
|
61
|
+
name: str,
|
62
|
+
*,
|
63
|
+
hooks: HookManager | None = None,
|
64
|
+
inject_last_result: bool = False,
|
65
|
+
inject_into: str = "last_result",
|
66
|
+
never_prompt: bool = False,
|
67
|
+
logging_hooks: bool = False,
|
68
|
+
) -> None:
|
69
|
+
self.name = name
|
70
|
+
self.hooks = hooks or HookManager()
|
71
|
+
self.is_retryable: bool = False
|
72
|
+
self.shared_context: SharedContext | None = None
|
73
|
+
self.inject_last_result: bool = inject_last_result
|
74
|
+
self.inject_into: str = inject_into
|
75
|
+
self._never_prompt: bool = never_prompt
|
76
|
+
self._skip_in_chain: bool = False
|
77
|
+
self.console = Console(color_system="auto")
|
78
|
+
self.options_manager: OptionsManager | None = None
|
79
|
+
|
80
|
+
if logging_hooks:
|
81
|
+
register_debug_hooks(self.hooks)
|
82
|
+
|
83
|
+
async def __call__(self, *args, **kwargs) -> Any:
|
84
|
+
return await self._run(*args, **kwargs)
|
85
|
+
|
86
|
+
@abstractmethod
|
87
|
+
async def _run(self, *args, **kwargs) -> Any:
|
88
|
+
raise NotImplementedError("_run must be implemented by subclasses")
|
89
|
+
|
90
|
+
@abstractmethod
|
91
|
+
async def preview(self, parent: Tree | None = None):
|
92
|
+
raise NotImplementedError("preview must be implemented by subclasses")
|
93
|
+
|
94
|
+
@abstractmethod
|
95
|
+
def get_infer_target(self) -> tuple[Callable[..., Any] | None, dict[str, Any] | None]:
|
96
|
+
"""
|
97
|
+
Returns the callable to be used for argument inference.
|
98
|
+
By default, it returns None.
|
99
|
+
"""
|
100
|
+
raise NotImplementedError("get_infer_target must be implemented by subclasses")
|
101
|
+
|
102
|
+
def set_options_manager(self, options_manager: OptionsManager) -> None:
|
103
|
+
self.options_manager = options_manager
|
104
|
+
|
105
|
+
def set_shared_context(self, shared_context: SharedContext) -> None:
|
106
|
+
self.shared_context = shared_context
|
107
|
+
|
108
|
+
def get_option(self, option_name: str, default: Any = None) -> Any:
|
109
|
+
"""
|
110
|
+
Resolve an option from the OptionsManager if present, otherwise use the fallback.
|
111
|
+
"""
|
112
|
+
if self.options_manager:
|
113
|
+
return self.options_manager.get(option_name, default)
|
114
|
+
return default
|
115
|
+
|
116
|
+
@property
|
117
|
+
def last_result(self) -> Any:
|
118
|
+
"""Return the last result from the shared context."""
|
119
|
+
if self.shared_context:
|
120
|
+
return self.shared_context.last_result()
|
121
|
+
return None
|
122
|
+
|
123
|
+
@property
|
124
|
+
def never_prompt(self) -> bool:
|
125
|
+
return self.get_option("never_prompt", self._never_prompt)
|
126
|
+
|
127
|
+
def prepare(
|
128
|
+
self, shared_context: SharedContext, options_manager: OptionsManager | None = None
|
129
|
+
) -> BaseAction:
|
130
|
+
"""
|
131
|
+
Prepare the action specifically for sequential (ChainedAction) execution.
|
132
|
+
Can be overridden for chain-specific logic.
|
133
|
+
"""
|
134
|
+
self.set_shared_context(shared_context)
|
135
|
+
if options_manager:
|
136
|
+
self.set_options_manager(options_manager)
|
137
|
+
return self
|
138
|
+
|
139
|
+
def _maybe_inject_last_result(self, kwargs: dict[str, Any]) -> dict[str, Any]:
|
140
|
+
if self.inject_last_result and self.shared_context:
|
141
|
+
key = self.inject_into
|
142
|
+
if key in kwargs:
|
143
|
+
logger.warning("[%s] Overriding '%s' with last_result", self.name, key)
|
144
|
+
kwargs = dict(kwargs)
|
145
|
+
kwargs[key] = self.shared_context.last_result()
|
146
|
+
return kwargs
|
147
|
+
|
148
|
+
def register_hooks_recursively(self, hook_type: HookType, hook: Hook):
|
149
|
+
"""Register a hook for all actions and sub-actions."""
|
150
|
+
self.hooks.register(hook_type, hook)
|
151
|
+
|
152
|
+
async def _write_stdout(self, data: str) -> None:
|
153
|
+
"""Override in subclasses that produce terminal output."""
|
154
|
+
|
155
|
+
def __repr__(self) -> str:
|
156
|
+
return str(self)
|
@@ -0,0 +1,208 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
from typing import Any, Callable
|
4
|
+
|
5
|
+
from rich.tree import Tree
|
6
|
+
|
7
|
+
from falyx.action.action import Action
|
8
|
+
from falyx.action.base import BaseAction
|
9
|
+
from falyx.action.fallback_action import FallbackAction
|
10
|
+
from falyx.action.literal_input_action import LiteralInputAction
|
11
|
+
from falyx.action.mixins import ActionListMixin
|
12
|
+
from falyx.context import ExecutionContext, SharedContext
|
13
|
+
from falyx.exceptions import EmptyChainError
|
14
|
+
from falyx.execution_registry import ExecutionRegistry as er
|
15
|
+
from falyx.hook_manager import Hook, HookManager, HookType
|
16
|
+
from falyx.logger import logger
|
17
|
+
from falyx.themes import OneColors
|
18
|
+
|
19
|
+
|
20
|
+
class ChainedAction(BaseAction, ActionListMixin):
|
21
|
+
"""
|
22
|
+
ChainedAction executes a sequence of actions one after another.
|
23
|
+
|
24
|
+
Features:
|
25
|
+
- Supports optional automatic last_result injection (auto_inject).
|
26
|
+
- Recovers from intermediate errors using FallbackAction if present.
|
27
|
+
- Rolls back all previously executed actions if a failure occurs.
|
28
|
+
- Handles literal values with LiteralInputAction.
|
29
|
+
|
30
|
+
Best used for defining robust, ordered workflows where each step can depend on
|
31
|
+
previous results.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
name (str): Name of the chain.
|
35
|
+
actions (list): List of actions or literals to execute.
|
36
|
+
hooks (HookManager, optional): Hooks for lifecycle events.
|
37
|
+
inject_last_result (bool, optional): Whether to inject last results into kwargs
|
38
|
+
by default.
|
39
|
+
inject_into (str, optional): Key name for injection.
|
40
|
+
auto_inject (bool, optional): Auto-enable injection for subsequent actions.
|
41
|
+
return_list (bool, optional): Whether to return a list of all results. False
|
42
|
+
returns the last result.
|
43
|
+
"""
|
44
|
+
|
45
|
+
def __init__(
|
46
|
+
self,
|
47
|
+
name: str,
|
48
|
+
actions: list[BaseAction | Any] | None = None,
|
49
|
+
*,
|
50
|
+
hooks: HookManager | None = None,
|
51
|
+
inject_last_result: bool = False,
|
52
|
+
inject_into: str = "last_result",
|
53
|
+
auto_inject: bool = False,
|
54
|
+
return_list: bool = False,
|
55
|
+
) -> None:
|
56
|
+
super().__init__(
|
57
|
+
name,
|
58
|
+
hooks=hooks,
|
59
|
+
inject_last_result=inject_last_result,
|
60
|
+
inject_into=inject_into,
|
61
|
+
)
|
62
|
+
ActionListMixin.__init__(self)
|
63
|
+
self.auto_inject = auto_inject
|
64
|
+
self.return_list = return_list
|
65
|
+
if actions:
|
66
|
+
self.set_actions(actions)
|
67
|
+
|
68
|
+
def _wrap_if_needed(self, action: BaseAction | Any) -> BaseAction:
|
69
|
+
if isinstance(action, BaseAction):
|
70
|
+
return action
|
71
|
+
elif callable(action):
|
72
|
+
return Action(name=action.__name__, action=action)
|
73
|
+
else:
|
74
|
+
return LiteralInputAction(action)
|
75
|
+
|
76
|
+
def add_action(self, action: BaseAction | Any) -> None:
|
77
|
+
action = self._wrap_if_needed(action)
|
78
|
+
if self.actions and self.auto_inject and not action.inject_last_result:
|
79
|
+
action.inject_last_result = True
|
80
|
+
super().add_action(action)
|
81
|
+
if hasattr(action, "register_teardown") and callable(action.register_teardown):
|
82
|
+
action.register_teardown(self.hooks)
|
83
|
+
|
84
|
+
def get_infer_target(self) -> tuple[Callable[..., Any] | None, dict[str, Any] | None]:
|
85
|
+
if self.actions:
|
86
|
+
return self.actions[0].get_infer_target()
|
87
|
+
return None, None
|
88
|
+
|
89
|
+
def _clear_args(self):
|
90
|
+
return (), {}
|
91
|
+
|
92
|
+
async def _run(self, *args, **kwargs) -> list[Any]:
|
93
|
+
if not self.actions:
|
94
|
+
raise EmptyChainError(f"[{self.name}] No actions to execute.")
|
95
|
+
|
96
|
+
shared_context = SharedContext(name=self.name, action=self)
|
97
|
+
if self.shared_context:
|
98
|
+
shared_context.add_result(self.shared_context.last_result())
|
99
|
+
updated_kwargs = self._maybe_inject_last_result(kwargs)
|
100
|
+
context = ExecutionContext(
|
101
|
+
name=self.name,
|
102
|
+
args=args,
|
103
|
+
kwargs=updated_kwargs,
|
104
|
+
action=self,
|
105
|
+
extra={"results": [], "rollback_stack": []},
|
106
|
+
shared_context=shared_context,
|
107
|
+
)
|
108
|
+
context.start_timer()
|
109
|
+
try:
|
110
|
+
await self.hooks.trigger(HookType.BEFORE, context)
|
111
|
+
|
112
|
+
for index, action in enumerate(self.actions):
|
113
|
+
if action._skip_in_chain:
|
114
|
+
logger.debug(
|
115
|
+
"[%s] Skipping consumed action '%s'", self.name, action.name
|
116
|
+
)
|
117
|
+
continue
|
118
|
+
shared_context.current_index = index
|
119
|
+
prepared = action.prepare(shared_context, self.options_manager)
|
120
|
+
try:
|
121
|
+
result = await prepared(*args, **updated_kwargs)
|
122
|
+
except Exception as error:
|
123
|
+
if index + 1 < len(self.actions) and isinstance(
|
124
|
+
self.actions[index + 1], FallbackAction
|
125
|
+
):
|
126
|
+
logger.warning(
|
127
|
+
"[%s] Fallback triggered: %s, recovering with fallback "
|
128
|
+
"'%s'.",
|
129
|
+
self.name,
|
130
|
+
error,
|
131
|
+
self.actions[index + 1].name,
|
132
|
+
)
|
133
|
+
shared_context.add_result(None)
|
134
|
+
context.extra["results"].append(None)
|
135
|
+
fallback = self.actions[index + 1].prepare(shared_context)
|
136
|
+
result = await fallback()
|
137
|
+
fallback._skip_in_chain = True
|
138
|
+
else:
|
139
|
+
raise
|
140
|
+
args, updated_kwargs = self._clear_args()
|
141
|
+
shared_context.add_result(result)
|
142
|
+
context.extra["results"].append(result)
|
143
|
+
context.extra["rollback_stack"].append(prepared)
|
144
|
+
|
145
|
+
all_results = context.extra["results"]
|
146
|
+
assert (
|
147
|
+
all_results
|
148
|
+
), f"[{self.name}] No results captured. Something seriously went wrong."
|
149
|
+
context.result = all_results if self.return_list else all_results[-1]
|
150
|
+
await self.hooks.trigger(HookType.ON_SUCCESS, context)
|
151
|
+
return context.result
|
152
|
+
|
153
|
+
except Exception as error:
|
154
|
+
context.exception = error
|
155
|
+
shared_context.add_error(shared_context.current_index, error)
|
156
|
+
await self._rollback(context.extra["rollback_stack"], *args, **kwargs)
|
157
|
+
await self.hooks.trigger(HookType.ON_ERROR, context)
|
158
|
+
raise
|
159
|
+
finally:
|
160
|
+
context.stop_timer()
|
161
|
+
await self.hooks.trigger(HookType.AFTER, context)
|
162
|
+
await self.hooks.trigger(HookType.ON_TEARDOWN, context)
|
163
|
+
er.record(context)
|
164
|
+
|
165
|
+
async def _rollback(self, rollback_stack, *args, **kwargs):
|
166
|
+
"""
|
167
|
+
Roll back all executed actions in reverse order.
|
168
|
+
|
169
|
+
Rollbacks run even if a fallback recovered from failure,
|
170
|
+
ensuring consistent undo of all side effects.
|
171
|
+
|
172
|
+
Actions without rollback handlers are skipped.
|
173
|
+
|
174
|
+
Args:
|
175
|
+
rollback_stack (list): Actions to roll back.
|
176
|
+
*args, **kwargs: Passed to rollback handlers.
|
177
|
+
"""
|
178
|
+
for action in reversed(rollback_stack):
|
179
|
+
rollback = getattr(action, "rollback", None)
|
180
|
+
if rollback:
|
181
|
+
try:
|
182
|
+
logger.warning("[%s] Rolling back...", action.name)
|
183
|
+
await action.rollback(*args, **kwargs)
|
184
|
+
except Exception as error:
|
185
|
+
logger.error("[%s] Rollback failed: %s", action.name, error)
|
186
|
+
|
187
|
+
def register_hooks_recursively(self, hook_type: HookType, hook: Hook):
|
188
|
+
"""Register a hook for all actions and sub-actions."""
|
189
|
+
self.hooks.register(hook_type, hook)
|
190
|
+
for action in self.actions:
|
191
|
+
action.register_hooks_recursively(hook_type, hook)
|
192
|
+
|
193
|
+
async def preview(self, parent: Tree | None = None):
|
194
|
+
label = [f"[{OneColors.CYAN_b}]⛓ ChainedAction[/] '{self.name}'"]
|
195
|
+
if self.inject_last_result:
|
196
|
+
label.append(f" [dim](injects '{self.inject_into}')[/dim]")
|
197
|
+
tree = parent.add("".join(label)) if parent else Tree("".join(label))
|
198
|
+
for action in self.actions:
|
199
|
+
await action.preview(parent=tree)
|
200
|
+
if not parent:
|
201
|
+
self.console.print(tree)
|
202
|
+
|
203
|
+
def __str__(self):
|
204
|
+
return (
|
205
|
+
f"ChainedAction(name={self.name!r}, "
|
206
|
+
f"actions={[a.name for a in self.actions]!r}, "
|
207
|
+
f"auto_inject={self.auto_inject}, return_list={self.return_list})"
|
208
|
+
)
|
@@ -0,0 +1,49 @@
|
|
1
|
+
from functools import cached_property
|
2
|
+
from typing import Any
|
3
|
+
|
4
|
+
from rich.tree import Tree
|
5
|
+
|
6
|
+
from falyx.action.action import Action
|
7
|
+
from falyx.themes import OneColors
|
8
|
+
|
9
|
+
|
10
|
+
class FallbackAction(Action):
|
11
|
+
"""
|
12
|
+
FallbackAction provides a default value if the previous action failed or
|
13
|
+
returned None.
|
14
|
+
|
15
|
+
It injects the last result and checks:
|
16
|
+
- If last_result is not None, it passes it through unchanged.
|
17
|
+
- If last_result is None (e.g., due to failure), it replaces it with a fallback value.
|
18
|
+
|
19
|
+
Used in ChainedAction pipelines to gracefully recover from errors or missing data.
|
20
|
+
When activated, it consumes the preceding error and allows the chain to continue
|
21
|
+
normally.
|
22
|
+
|
23
|
+
Args:
|
24
|
+
fallback (Any): The fallback value to use if last_result is None.
|
25
|
+
"""
|
26
|
+
|
27
|
+
def __init__(self, fallback: Any):
|
28
|
+
self._fallback = fallback
|
29
|
+
|
30
|
+
async def _fallback_logic(last_result):
|
31
|
+
return last_result if last_result is not None else fallback
|
32
|
+
|
33
|
+
super().__init__(name="Fallback", action=_fallback_logic, inject_last_result=True)
|
34
|
+
|
35
|
+
@cached_property
|
36
|
+
def fallback(self) -> Any:
|
37
|
+
"""Return the fallback value."""
|
38
|
+
return self._fallback
|
39
|
+
|
40
|
+
async def preview(self, parent: Tree | None = None):
|
41
|
+
label = [f"[{OneColors.LIGHT_RED}]🛟 Fallback[/] '{self.name}'"]
|
42
|
+
label.append(f" [dim](uses fallback = {repr(self.fallback)})[/dim]")
|
43
|
+
if parent:
|
44
|
+
parent.add("".join(label))
|
45
|
+
else:
|
46
|
+
self.console.print(Tree("".join(label)))
|
47
|
+
|
48
|
+
def __str__(self) -> str:
|
49
|
+
return f"FallbackAction(fallback={self.fallback!r})"
|
falyx/action/io_action.py
CHANGED
@@ -23,7 +23,7 @@ from typing import Any, Callable
|
|
23
23
|
|
24
24
|
from rich.tree import Tree
|
25
25
|
|
26
|
-
from falyx.action.
|
26
|
+
from falyx.action.base import BaseAction
|
27
27
|
from falyx.context import ExecutionContext
|
28
28
|
from falyx.exceptions import FalyxError
|
29
29
|
from falyx.execution_registry import ExecutionRegistry as er
|
@@ -0,0 +1,47 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
from functools import cached_property
|
4
|
+
from typing import Any
|
5
|
+
|
6
|
+
from rich.tree import Tree
|
7
|
+
|
8
|
+
from falyx.action.action import Action
|
9
|
+
from falyx.themes import OneColors
|
10
|
+
|
11
|
+
|
12
|
+
class LiteralInputAction(Action):
|
13
|
+
"""
|
14
|
+
LiteralInputAction injects a static value into a ChainedAction.
|
15
|
+
|
16
|
+
This allows embedding hardcoded values mid-pipeline, useful when:
|
17
|
+
- Providing default or fallback inputs.
|
18
|
+
- Starting a pipeline with a fixed input.
|
19
|
+
- Supplying missing context manually.
|
20
|
+
|
21
|
+
Args:
|
22
|
+
value (Any): The static value to inject.
|
23
|
+
"""
|
24
|
+
|
25
|
+
def __init__(self, value: Any):
|
26
|
+
self._value = value
|
27
|
+
|
28
|
+
async def literal(*_, **__):
|
29
|
+
return value
|
30
|
+
|
31
|
+
super().__init__("Input", literal)
|
32
|
+
|
33
|
+
@cached_property
|
34
|
+
def value(self) -> Any:
|
35
|
+
"""Return the literal value."""
|
36
|
+
return self._value
|
37
|
+
|
38
|
+
async def preview(self, parent: Tree | None = None):
|
39
|
+
label = [f"[{OneColors.LIGHT_YELLOW}]📥 LiteralInput[/] '{self.name}'"]
|
40
|
+
label.append(f" [dim](value = {repr(self.value)})[/dim]")
|
41
|
+
if parent:
|
42
|
+
parent.add("".join(label))
|
43
|
+
else:
|
44
|
+
self.console.print(Tree("".join(label)))
|
45
|
+
|
46
|
+
def __str__(self) -> str:
|
47
|
+
return f"LiteralInputAction(value={self.value!r})"
|
falyx/action/menu_action.py
CHANGED
@@ -7,7 +7,7 @@ from rich.console import Console
|
|
7
7
|
from rich.table import Table
|
8
8
|
from rich.tree import Tree
|
9
9
|
|
10
|
-
from falyx.action.
|
10
|
+
from falyx.action.base import BaseAction
|
11
11
|
from falyx.context import ExecutionContext
|
12
12
|
from falyx.execution_registry import ExecutionRegistry as er
|
13
13
|
from falyx.hook_manager import HookType
|