1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//! Modulink-RS Macro Implementations
//
// This file implements all macros and patterns described in the macro reference and documentation.
// Each macro is annotated with usage and rationale. See docs/MODULINK_MACROS.md for details.
// ---
// 1. Context Macro
//
// Purpose: Define or initialize a context (can be `Context`, `MutableContext`, or custom type).
//
/*
/// Macro to define a context struct with named fields.
///
/// # Example
/// ```rust
/// define_context! {
/// user_id: u64,
/// data: String,
/// }
/// let ctx = Context::new();
/// ```
///
/// Use this macro to quickly define a context type for your chain.
#[macro_export]
macro_rules! define_context {
( $( $field:ident : $ty:ty ),* $(,)? ) => {
#[derive(Debug, Clone, Default)]
pub struct Context {
$( pub $field: $ty, )*
}
impl Context {
pub fn new() -> Self { Self { $( $field: Default::default(), )* } }
}
};
}
*/
// ---
// 2. Link Macro
//
// Purpose: Define a link as a pure async function or closure.
//
/*
/// Macro to define a link as a pure async function or closure.
///
/// # Function-style Example
/// ```rust
/// link! {
/// fn add_user_id(ctx: Context) -> Context {
/// ctx.insert("user_id", 42)
/// }
/// }
/// ```
///
/// # Closure-style Example
/// ```rust
/// let link = link!(|ctx: Context| async move { ctx.insert("user_id", 42) });
/// ```
///
/// Use this macro to define composable steps in your chain.
#[macro_export]
macro_rules! link {
// Function-style link
(fn $name:ident ( $ctx:ident : $ctx_ty:ty ) -> $ret:ty $body:block) => {
pub async fn $name($ctx: $ctx_ty) -> $ret $body
};
// Closure-style link
(|$ctx:ident : $ctx_ty:ty| $body:expr) => {
Box::new(move |$ctx: $ctx_ty| Box::pin(async move { $body }))
};
}
*/
// ---
// 3. Chain Macro (active)
//
// Purpose: Compose a sequence of links into a chain.
//
/// Macro to compose a sequence of links into a chain.
///
/// # Example
/// ```rust
/// use modulink_rs::chain;
/// use std::sync::Arc;
/// use std::future::Future;
/// use std::pin::Pin;
/// use modulink_rs::context::Context;
/// // Example async link type for Chain
/// let link1: Arc<dyn Fn(Context) -> Pin<Box<dyn Future<Output = Context> + Send>> + Send + Sync> = Arc::new(|ctx: Context| Box::pin(async move { ctx }));
/// let link2 = link1.clone();
/// let link3 = link1.clone();
/// // Comma-separated syntax
/// let my_chain = chain!(link1.clone(), link2.clone(), link3.clone());
/// // Array-like syntax
/// let my_chain2 = chain![link1.clone(), link2.clone(), link3.clone()];
/// // my_chain can now be executed with .run(ctx).await
/// ```
///
/// Use this macro to build a pipeline of links.
};
// Generic: explicit type parameter (comma syntax)
=> ;
// Ergonomic: default Context (comma-separated list)
=> ;
// Ergonomic: default Context (array-like syntax)
=> ;
}
// ---
// 4. Add Link Macro (method pattern)
//
// Purpose: Add a link to an existing chain.
//
// Usage:
// my_chain.add_link(link!(|ctx| async move { ctx }));
//
// Rationale: Enables dynamic or incremental chain construction.
// ---
// 5. Use Middleware Macro (method pattern)
//
// Purpose: Attach middleware for logging, metrics, or side effects.
//
// Usage:
// my_chain.use_middleware(middleware!(Logging));
//
// Rationale: Middleware provides observability and cross-cutting concerns.
// ---
// 6. Connect Macro (Branching)
//
// Purpose: Add conditional branches between links or chains, using a macro syntax that clarifies intent and supports both link and chain connections.
//
/*
/// Macro to add conditional branches between links or chains.
///
/// # Syntax
/// - Connect a link:
/// ```rust
/// my_chain.connect![
/// link: my_link,
/// to: link_in_og_chain,
/// when: condition!(|ctx| ctx.get::<bool>("skip").unwrap_or(false)),
/// ]
/// ```
/// - Connect a chain:
/// ```rust
/// my_chain.connect![
/// chain: my_other_chain,
/// to: link_in_og_chain,
/// when: condition!(|ctx| ctx.get::<bool>("should_branch").unwrap_or(false)),
/// ]
/// ```
///
/// Use this macro to enable advanced graph topologies, error routing, and dynamic control flow.
#[macro_export]
macro_rules! connect {
(
link: $link:expr,
to: $to:expr,
when: $when:expr $(,)?
) => {
.connect_link($link, $to, $when)
};
(
chain: $chain:expr,
to: $to:expr,
when: $when:expr $(,)?
) => {
.connect_chain($chain, $to, $when)
};
}
*/
// ---
// 7. Run Macro (method pattern)
//
// Purpose: Execute the chain with a given context.
//
// Usage:
// let result = my_chain.run(ctx).await;
//
// Rationale: Runs the pipeline. Async for concurrency.
// ---
// 8. Condition Macro
//
// Purpose: Define a branching condition as a closure.
//
/*
/// Macro to define a branching condition as a closure.
///
/// # Example
/// ```rust
/// let cond = condition!(|ctx: &Context| ctx.get::<bool>("flag").unwrap_or(false));
/// ```
///
/// Use this macro for branching and control flow in chains.
#[macro_export]
macro_rules! condition {
(|$ctx:ident : $ctx_ty:ty| $body:expr) => {
Box::new(move |$ctx: &$ctx_ty| $body)
};
(|$ctx:ident| $body:expr) => {
Box::new(move |$ctx| $body)
};
}
*/
// ---
// 9. Middleware Macro
//
// Purpose: Define custom middleware with before/after hooks.
//
/*
/// Macro to define custom middleware with before/after hooks.
///
/// # Example
/// ```rust
/// middleware! {
/// struct MyLogger;
/// impl Middleware for MyLogger {
/// async fn before(&self, ctx: &dyn std::any::Any) {
/// println!("Before link");
/// }
/// async fn after(&self, ctx: &dyn std::any::Any) {
/// println!("After link");
/// }
/// }
/// }
/// ```
///
/// Use this macro to add observability, metrics, or side effects.
#[macro_export]
macro_rules! middleware {
// Struct + impl block
(struct $name:ident; impl Middleware for $name2:ident { $($body:tt)* }) => {
pub struct $name;
#[async_trait::async_trait]
impl ::modulink_rs::middleware::Middleware for $name2 {
$($body)*
}
};
}
*/
// ---
// 10. Listener Macro
//
// Purpose: Define a listener for triggers (HTTP, CLI, etc.).
//
/*
/// Macro to define a listener for triggers (HTTP, CLI, etc.).
///
/// # Example
/// ```rust
/// listener! {
/// struct MyHttpListener;
/// // ... implement listener trait ...
/// }
/// ```
///
/// Use this macro to integrate chains with external systems.
#[macro_export]
macro_rules! listener {
(struct $name:ident; $($body:tt)*) => {
pub struct $name;
$($body)*
};
}
*/
// ---
// Notes:
// - All macros are sketches; adapt as needed for your codebase.
// - Use shadowing (`let ctx = ...`) for ergonomic APIs; use `mut` only for advanced/generic APIs and document the tradeoff.
// - Maximize type safety, extensibility, and modularity as God wills.
// - See docs/CHAIN_MACRO_PATTERNS.md and docs/CHEATSHEET_ADVANCED.md for more.