|
| 1 | +""" |
| 2 | +Chain composition for ModuLink Next. |
| 3 | +
|
| 4 | +Defines the Chain class and its API for composing, connecting, and running links with middleware and error handling. |
| 5 | +See README.md section 2.2 for details. |
| 6 | +""" |
| 7 | + |
| 8 | +from .context import Context |
| 9 | +from .link import Link |
| 10 | +from typing import Any, Callable, Awaitable, Dict, List, Optional, Protocol |
| 11 | + |
| 12 | +class Chain: |
| 13 | + """ |
| 14 | + ModuLink Next Chain: Compose, connect, and run async workflows. |
| 15 | +
|
| 16 | + - Accepts any number of Link objects (async or sync functions) in order. |
| 17 | + - Supports explicit connections (branching, error handling) via .connect(). |
| 18 | + - Supports middleware for observability, logging, and metrics via .use(). |
| 19 | + - Runs the chain with .run(ctx), passing a Context through all links. |
| 20 | + - Provides .inspect() for structure introspection and dynamic docstring updates. |
| 21 | + - Designed for composable, testable, and debuggable async workflows. |
| 22 | + """ |
| 23 | + def __init__(self, *links: Link): |
| 24 | + """ |
| 25 | + Initialize a Chain with one or more Link objects. |
| 26 | + Links are auto-wired in sequence; use .connect() for custom flows. |
| 27 | + """ |
| 28 | + self._links = list(links) |
| 29 | + self._connections = [] |
| 30 | + self._middleware = [] |
| 31 | + self._update_doc() |
| 32 | + |
| 33 | + def _update_doc(self): |
| 34 | + """ |
| 35 | + Dynamically update the Chain's docstring to reflect its current structure. |
| 36 | + Lists all links, connections, and middleware attached to this chain. |
| 37 | + """ |
| 38 | + doc = (self.__class__.__doc__ or "") + "\n\n" |
| 39 | + doc += "Links:\n" |
| 40 | + for link in self._links: |
| 41 | + doc += f" - {getattr(link, '__name__', str(link))}: {getattr(link, '__doc__', '')}\n" |
| 42 | + doc += f"\nConnections: {self._connections}\n" |
| 43 | + doc += f"Middleware: {[type(m).__name__ for m in self._middleware]}" |
| 44 | + self.__doc__ = doc |
| 45 | + |
| 46 | + def add_link(self, link: Link): |
| 47 | + """ |
| 48 | + Add a Link to the end of the chain. |
| 49 | + Links must conform to the Link protocol (async or sync callable). |
| 50 | + """ |
| 51 | + self._links.append(link) |
| 52 | + self._update_doc() |
| 53 | + |
| 54 | + def use(self, middleware: Any, on_link: Link = None, position: str = None): |
| 55 | + """ |
| 56 | + Attach middleware to the chain or to a specific link. |
| 57 | + If on_link is None, attaches as chain-level middleware. |
| 58 | + If on_link is provided, attaches as link-level middleware (before/after). |
| 59 | + position: 'before' or 'after' for link-level middleware. |
| 60 | + """ |
| 61 | + if on_link is None: |
| 62 | + self._middleware.append(middleware) |
| 63 | + else: |
| 64 | + if not hasattr(on_link, "_before_middleware"): |
| 65 | + on_link._before_middleware = [] |
| 66 | + if not hasattr(on_link, "_after_middleware"): |
| 67 | + on_link._after_middleware = [] |
| 68 | + if position == 'before': |
| 69 | + on_link._before_middleware.append(middleware) |
| 70 | + elif position == 'after': |
| 71 | + on_link._after_middleware.append(middleware) |
| 72 | + else: |
| 73 | + raise ValueError("position must be 'before' or 'after' for link-level middleware") |
| 74 | + self._update_doc() |
| 75 | + |
| 76 | + def connect(self, source, target, condition): |
| 77 | + """ |
| 78 | + Explicitly connect a source Link (or Chain) to a target Link (or Chain) with a condition. |
| 79 | + Enables branching, error handling, and custom flows. |
| 80 | + - source: the Link (or Chain) to branch from (must be a specific link in the current chain) |
| 81 | + - target: the Link or Chain to branch to if condition(ctx) is True |
| 82 | + - condition: a callable that takes ctx and returns bool |
| 83 | + |
| 84 | + Note: The source must be a link in this chain, and the target can be either a single Link or another Chain. |
| 85 | + """ |
| 86 | + self._connections.append({"source": source, "target": target, "condition": condition}) |
| 87 | + self._update_doc() |
| 88 | + |
| 89 | + async def run(self, ctx: Context) -> Context: |
| 90 | + """ |
| 91 | + Execute the chain with the given Context. |
| 92 | + Passes the context through all links in order, applying middleware hooks. |
| 93 | + Handles errors and branching via .connect(). |
| 94 | + Returns the final Context after all processing. |
| 95 | + Middleware receives position, index, and mwctx. |
| 96 | + Supports both chain-level and link-level middleware. |
| 97 | + """ |
| 98 | + import inspect |
| 99 | + current_ctx = ctx |
| 100 | + mwctx = Context() # Shared middleware context for this run |
| 101 | + for link_index, link in enumerate(self._links): |
| 102 | + # Chain-level before middleware |
| 103 | + for mw_index, m in enumerate(self._middleware): |
| 104 | + if hasattr(m, "before"): |
| 105 | + m.link = link |
| 106 | + m.position = 'chain-before' |
| 107 | + m.index = mw_index |
| 108 | + await m.before(link, current_ctx, mwctx) |
| 109 | + # Link-level before middleware |
| 110 | + if hasattr(link, "_before_middleware"): |
| 111 | + for mw_index, m in enumerate(link._before_middleware): |
| 112 | + if hasattr(m, "before"): |
| 113 | + m.link = link |
| 114 | + m.position = 'link-before' |
| 115 | + m.index = mw_index |
| 116 | + await m.before(link, current_ctx, mwctx) |
| 117 | + try: |
| 118 | + if inspect.iscoroutinefunction(link): |
| 119 | + result = await link(current_ctx) |
| 120 | + else: |
| 121 | + result = link(current_ctx) |
| 122 | + except Exception as exc: |
| 123 | + current_ctx["exception"] = exc |
| 124 | + routed = False |
| 125 | + for conn in self._connections: |
| 126 | + if conn["source"] == link and callable(conn["condition"]): |
| 127 | + try: |
| 128 | + if conn["condition"](current_ctx): |
| 129 | + next_link = conn["target"] |
| 130 | + if inspect.iscoroutinefunction(next_link): |
| 131 | + result = await next_link(current_ctx) |
| 132 | + else: |
| 133 | + result = next_link(current_ctx) |
| 134 | + routed = True |
| 135 | + break |
| 136 | + except Exception: |
| 137 | + continue |
| 138 | + if not routed: |
| 139 | + break |
| 140 | + # Link-level after middleware |
| 141 | + if hasattr(link, "_after_middleware"): |
| 142 | + for mw_index, m in enumerate(link._after_middleware): |
| 143 | + if hasattr(m, "after"): |
| 144 | + m.link = link |
| 145 | + m.position = 'link-after' |
| 146 | + m.index = mw_index |
| 147 | + await m.after(link, current_ctx, result, mwctx) |
| 148 | + # Chain-level after middleware |
| 149 | + for mw_index, m in enumerate(self._middleware): |
| 150 | + if hasattr(m, "after"): |
| 151 | + m.link = link |
| 152 | + m.position = 'chain-after' |
| 153 | + m.index = mw_index |
| 154 | + await m.after(link, current_ctx, result, mwctx) |
| 155 | + current_ctx = result |
| 156 | + return current_ctx |
| 157 | + |
| 158 | + def inspect(self) -> dict: |
| 159 | + """ |
| 160 | + Return a dict representation of the chain's structure. |
| 161 | + Includes all links, connections, and middleware for debugging and introspection. |
| 162 | + """ |
| 163 | + return { |
| 164 | + "links": [getattr(link, "__name__", str(link)) for link in self._links], |
| 165 | + "connections": self._connections, |
| 166 | + "middleware": [type(m).__name__ for m in self._middleware] |
| 167 | + } |
0 commit comments