Skip to main content

wabot_macros/
lib.rs

1//! # wabot-macros
2//!
3//! Procedural macros that give wabot-rust a developer experience close to
4//! the TypeScript decorator syntax of wabot-ts. Each macro maps to a
5//! decorator family in the original framework — see the docstring on each
6//! one for the TS analogue.
7//!
8//! The macros emit code that depends on `wabot-core`. Re-exports flow
9//! through the `wabot` crate so users only need `use wabot::prelude::*`.
10
11extern crate proc_macro;
12
13use proc_macro::TokenStream;
14
15mod async_jobs;
16mod chat;
17mod injectable;
18mod mindset;
19mod rest;
20mod socket;
21mod ui;
22mod util;
23mod validate;
24
25/// `@injectable()` — emits a `Self::inject(&Container) -> Arc<Self>`
26/// constructor that resolves each `Arc<T>` field from the container and
27/// fills the rest from `Default`. Does **not** auto-register; pair with
28/// `#[singleton]` or call `container.register_*` manually.
29#[proc_macro_attribute]
30pub fn injectable(args: TokenStream, input: TokenStream) -> TokenStream {
31    injectable::expand_injectable(args, input)
32}
33
34/// `@singleton()` — like `#[injectable]`, but additionally registers the
35/// type as a singleton via `inventory`. Equivalent to writing
36/// `container.register_singleton_factory::<Self, _>(|c| Self::inject(c))`
37/// at framework startup, except the registration is collected at compile
38/// time so a fresh `Container::new()` already knows about it.
39#[proc_macro_attribute]
40pub fn singleton(args: TokenStream, input: TokenStream) -> TokenStream {
41    injectable::expand_singleton(args, input)
42}
43
44/// `@description("...")` — attaches a human-readable description to a
45/// field or method. On struct fields it is consumed by
46/// `#[derive(Validate)]` and folded into [`PropertyInfo::description`].
47/// On methods it is consumed by mindset macros (later phase). Used
48/// standalone, the attribute is a no-op so it never appears as
49/// "unknown attribute".
50#[proc_macro_attribute]
51pub fn description(_args: TokenStream, input: TokenStream) -> TokenStream {
52    // Inert on its own — enclosing macros (`#[derive(Validate)]`,
53    // `#[mindset_module]`) read it. Returning `input` unchanged means
54    // ordering with other attributes doesn't matter.
55    input
56}
57
58/// `#[derive(Validate)]` — generates a `Validate` impl that owns a
59/// `ModelInfo` describing the struct and a `validate()` that runs every
60/// declared constraint against an instance.
61///
62/// Recognized field attributes:
63///
64/// | Attribute              | TS analogue                  | Effect                                          |
65/// | ---------------------- | ---------------------------- | ----------------------------------------------- |
66/// | `#[description("…")]`  | `@description`               | Attached to `PropertyInfo::description`         |
67/// | `#[min(n)]`            | `@min(n)`                    | Numeric lower bound                             |
68/// | `#[max(n)]`            | `@max(n)`                    | Numeric upper bound                             |
69/// | `#[min_length(n)]`     | `@isString` + check          | String length lower bound                       |
70/// | `#[max_length(n)]`     | `@isString` + check          | String length upper bound                       |
71/// | `#[is_not_empty]`      | `@isNotEmpty()`              | Non-blank string / non-empty collection         |
72/// | `#[is_in("a", "b")]`   | `@isIn(['a','b'])`           | Membership check                                |
73/// | `#[pattern("regex")]`  | (custom)                     | Regex match (regex check left to user runtime)  |
74///
75/// Field type, optionality, and primitive class (`is_string`, `is_number`,
76/// etc.) are inferred from the Rust type and don't need attributes.
77#[proc_macro_derive(
78    Validate,
79    attributes(
80        description,
81        min,
82        max,
83        min_length,
84        max_length,
85        is_not_empty,
86        is_in,
87        pattern,
88    )
89)]
90pub fn derive_validate(input: TokenStream) -> TokenStream {
91    validate::expand_derive(input)
92}
93
94// ----- REST controller macros ----------------------------------------------
95
96/// `@restController('/path')` — apply to an `impl Controller` block. The
97/// macro walks every method, finds the `#[get]` / `#[post]` / `#[put]` /
98/// `#[delete]` / `#[middleware]` attributes, and emits a
99/// `Self::register_routes(&Container, axum::Router) -> axum::Router`
100/// function that adds every endpoint nested under the controller's
101/// base path.
102///
103/// Each endpoint method must:
104///
105/// * take `&self` and at most one typed argument (the request);
106/// * return `RestResult<T: Serialize>`;
107/// * be `async`.
108///
109/// The struct itself should also be marked `#[singleton]` so the
110/// container can resolve a controller instance per request.
111#[proc_macro_attribute]
112pub fn rest_controller(args: TokenStream, input: TokenStream) -> TokenStream {
113    rest::expand_rest_controller(args, input)
114}
115
116/// `@onGet(...)` — marks a method inside a `#[rest_controller]` impl
117/// block as an HTTP GET endpoint. Inert when used outside such a block.
118#[proc_macro_attribute]
119pub fn get(args: TokenStream, input: TokenStream) -> TokenStream {
120    rest::passthrough(args, input)
121}
122
123/// `@onPost(...)` — see [`get`].
124#[proc_macro_attribute]
125pub fn post(args: TokenStream, input: TokenStream) -> TokenStream {
126    rest::passthrough(args, input)
127}
128
129/// `@onPut(...)` — see [`get`].
130#[proc_macro_attribute]
131pub fn put(args: TokenStream, input: TokenStream) -> TokenStream {
132    rest::passthrough(args, input)
133}
134
135/// `@onDelete(...)` — see [`get`].
136#[proc_macro_attribute]
137pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
138    rest::passthrough(args, input)
139}
140
141/// `#[patch("…")]` — a partial update. See [`get`].
142#[proc_macro_attribute]
143pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
144    rest::passthrough(args, input)
145}
146
147/// `#[head("…")]` — the headers a GET would answer with, and no body.
148///
149/// Its own endpoint rather than something derived from the `#[get]`
150/// beside it: a HEAD that means "do you have this" is often far
151/// cheaper than the GET that would send it, and deriving one from the
152/// other would throw that away.
153#[proc_macro_attribute]
154pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
155    rest::passthrough(args, input)
156}
157
158/// `@middleware(MyMiddleware)` — attaches a middleware to the next
159/// endpoint method. Multiple `#[middleware(...)]` attributes stack;
160/// they run in source order before the handler. Inert outside a
161/// `#[rest_controller]` impl block.
162#[proc_macro_attribute]
163pub fn middleware(args: TokenStream, input: TokenStream) -> TokenStream {
164    rest::passthrough(args, input)
165}
166
167/// `#[max_body(N)]` — how many bytes this endpoint buffers before
168/// refusing the request. Defaults to `DEFAULT_MAX_BODY` (1 MiB), which
169/// is generous for a REST payload and mean for a file upload.
170///
171/// Any const-evaluable expression, so `#[max_body(64 * 1024 * 1024)]`
172/// reads the way you would say it. Inert outside a
173/// `#[rest_controller]` impl block.
174#[proc_macro_attribute]
175pub fn max_body(args: TokenStream, input: TokenStream) -> TokenStream {
176    rest::passthrough(args, input)
177}
178
179/// `#[raw]` — take the `Request` and return the `Response` untouched.
180///
181/// The escape hatch from the framework's request/response shape, for
182/// the cases where that shape is the wrong one: a body too large to
183/// hold in memory, a response that is not JSON, or one that streams —
184/// a file download, an SSE feed, an OCI blob.
185///
186/// ```ignore
187/// #[put("/blobs/uploads/:id")]
188/// #[raw]
189/// async fn upload(&self, req: Request) -> RestResult<Response> { … }
190/// ```
191///
192/// The method keeps dependency injection, its middlewares still run,
193/// and a `RestError` still renders the framework's error body — only
194/// the buffering and the JSON serialization are skipped. Path
195/// parameters come from `path_param(&req, "id")`.
196///
197/// Mutually exclusive with `#[max_body]`: nothing is buffered, so
198/// there is no size to limit. Inert outside a `#[rest_controller]`
199/// impl block.
200#[proc_macro_attribute]
201pub fn raw(args: TokenStream, input: TokenStream) -> TokenStream {
202    rest::passthrough(args, input)
203}
204
205// ----- Chat controller macros ----------------------------------------------
206
207/// `@chatController()` — apply to an `impl Controller` block. Walks
208/// every method; methods carrying a channel marker (`#[cmd]`, future
209/// `#[telegram]` / `#[socket]`, …) are wired into a per-channel
210/// dispatch closure, and a `Self::register_channels(&Container,
211/// Arc<ChatResolver>)` function is emitted that hands each channel
212/// its dispatch via `listen`.
213///
214/// The struct must also be marked `#[injectable]` so the dispatch can
215/// build a fresh controller from the per-message child container.
216#[proc_macro_attribute]
217pub fn chat_controller(args: TokenStream, input: TokenStream) -> TokenStream {
218    chat::expand_chat_controller(args, input)
219}
220
221/// `@cmd()` — marks a method inside a `#[chat_controller]` impl block
222/// as the handler for the CLI (`CmdChannel`) channel. Inert outside a
223/// `#[chat_controller]` impl block.
224#[proc_macro_attribute]
225pub fn cmd(args: TokenStream, input: TokenStream) -> TokenStream {
226    chat::passthrough(args, input)
227}
228
229/// `@telegram()` — marks a method as the handler for the Telegram
230/// (`TelegramChannel`) channel. The bot token is supplied at runtime
231/// via a registered `Arc<TelegramChannelConfig>` singleton, not as an
232/// attribute argument. Inert outside a `#[chat_controller]` impl block.
233#[proc_macro_attribute]
234pub fn telegram(args: TokenStream, input: TokenStream) -> TokenStream {
235    chat::passthrough(args, input)
236}
237
238/// `@socket()` — marks a method as the handler for the Socket.IO
239/// (`SocketChannel`) channel. Namespace + bind address come from the
240/// runtime-registered `SocketChannelConfig` singleton. Inert outside a
241/// `#[chat_controller]` impl block.
242#[proc_macro_attribute]
243pub fn socket(args: TokenStream, input: TokenStream) -> TokenStream {
244    chat::passthrough(args, input)
245}
246
247// ----- Tool macros -------------------------------------------------------
248
249/// `@tools()` — apply to an `impl MyTools` block. Walks every method,
250/// finds those carrying `#[tool("description")]`, and emits a
251/// `Self::register_tools(&Container) -> Vec<ToolDefinition>` helper.
252/// The struct must be `#[injectable]` (or `#[singleton]`) so dispatch
253/// can resolve it from the container.
254///
255/// Both mindsets and agents consume the result.
256///
257/// ```ignore
258/// #[tools(language = "spanish", expose_to_mindsets = false)]
259/// impl RefundTools {
260///     #[tool("Issue a refund for an order.")]
261///     async fn issue_refund(&self, args: RefundArgs) -> String { … }
262/// }
263/// ```
264///
265/// * `language` — the language the descriptions are written in
266///   (default `"english"`); a method may override it with
267///   `#[tool_lang("…")]`.
268/// * `expose_to_mindsets` — `false` marks the set agent-only, so a
269///   mindset delegating to an agent can't reach it unless the
270///   delegation allow-lists the tool by name.
271#[proc_macro_attribute]
272pub fn tools(args: TokenStream, input: TokenStream) -> TokenStream {
273    mindset::expand_tools(args, input)
274}
275
276/// `#[tool("description")]` — marker on one method inside a `#[tools]`
277/// impl block. Inert outside such a block — the enclosing macro reads
278/// it and strips it.
279#[proc_macro_attribute]
280pub fn tool(args: TokenStream, input: TokenStream) -> TokenStream {
281    mindset::passthrough(args, input)
282}
283
284/// `#[tool_lang("english")]` — per-method language override, when one
285/// tool's description is written in a different language from the rest
286/// of its set. Inert outside a `#[tools]` impl block.
287#[proc_macro_attribute]
288pub fn tool_lang(args: TokenStream, input: TokenStream) -> TokenStream {
289    mindset::passthrough(args, input)
290}
291
292/// Deprecated alias of [`macro@tools`], from when tool sets were a
293/// mindset-only concept.
294#[proc_macro_attribute]
295pub fn mindset_module(args: TokenStream, input: TokenStream) -> TokenStream {
296    mindset::expand_tools(args, input)
297}
298
299/// Deprecated alias of [`macro@tool`].
300#[proc_macro_attribute]
301pub fn mindset_tool(args: TokenStream, input: TokenStream) -> TokenStream {
302    mindset::passthrough(args, input)
303}
304
305/// Deprecated alias of [`macro@tool_lang`].
306#[proc_macro_attribute]
307pub fn mindset_lang(args: TokenStream, input: TokenStream) -> TokenStream {
308    mindset::passthrough(args, input)
309}
310
311// ----- Socket controller macros -----------------------------------------
312
313/// `@socketController('/ns')` — apply to an `impl MyController` block.
314/// Walks every method, finds those carrying
315/// `#[on_socket_event("name")]`, and emits
316/// `Self::register_socket_handlers(&Container, &SocketIo)`.
317///
318/// ```ignore
319/// #[socket_controller("/rooms", handshake(ApiKeyHandshake))]
320/// impl RoomController {
321///     #[on_socket_event("join")]
322///     async fn join(&self, req: JoinRoom, socket: SocketRef) -> SocketResult<Joined> { … }
323/// }
324/// ```
325///
326/// * the namespace defaults to `"/"`;
327/// * `handshake(A, B)` names middlewares that run before the
328///   connection is accepted — one that errors refuses it;
329/// * a method takes `&self`, at most one validated payload, and
330///   optionally a `SocketRef`, in either order;
331/// * whatever it returns goes back through the client's ack callback.
332///   The `"connection"` event has no ack, so its return value is
333///   dropped.
334///
335/// The struct must also be `#[injectable]` (or `#[singleton]`) so the
336/// connection container can resolve it.
337#[proc_macro_attribute]
338pub fn socket_controller(args: TokenStream, input: TokenStream) -> TokenStream {
339    socket::expand_socket_controller(args, input)
340}
341
342/// `#[on_socket_event("name")]` — marker on one method inside a
343/// `#[socket_controller]` impl block. Inert outside such a block.
344#[proc_macro_attribute]
345pub fn on_socket_event(args: TokenStream, input: TokenStream) -> TokenStream {
346    socket::passthrough(args, input)
347}
348
349// ----- UI controller macros ---------------------------------------------
350
351/// `@uiController({ path, app, layout })` — apply to the controller's
352/// `impl` block. Walks every method, interprets `#[view]`, `#[action]`
353/// and `#[middleware]`, and emits `Self::register_ui_routes`.
354///
355/// Options after the path:
356///
357/// * `app` — enable boosted navigation: the client runtime is injected
358///   and in-scope link clicks swap the outlet instead of reloading.
359/// * `layout` — the impl block defines
360///   `fn layout(&self, outlet: ViewBody) -> ViewBody`, used for full
361///   document loads (fragments render the view alone).
362/// * `styles = ["/app.css"]` / `scripts = ["/app.js"]` — assets every
363///   view of this controller needs.
364///
365/// ```ignore
366/// #[ui_controller("/panel", app, layout, styles = ["/static/app.css"])]
367/// impl PanelController { … }
368/// ```
369#[proc_macro_attribute]
370pub fn ui_controller(args: TokenStream, input: TokenStream) -> TokenStream {
371    ui::expand_ui_controller(args, input)
372}
373
374/// `@view('/path')` — marker on a method inside a `#[ui_controller]`
375/// impl block. The method takes `&self` plus at most one typed request
376/// and returns `UiResult<ViewBody>` (or `UiResult<ViewOutcome>` to
377/// redirect).
378///
379/// Options after the path:
380///
381/// * `title = "…"` — document `<title>` (a `set_title` during render wins).
382/// * `max_age = 30` — seconds a boosted-nav client may serve its cached
383///   fragment before revalidating.
384/// * `static` — render once and serve from `StaticPageCache`. Cannot be
385///   combined with `#[middleware]`: the cached page is shared across
386///   visitors, so the guard would be bypassed (compile error).
387/// * `revalidate = 60` — with `static`, ISR: past 60s the next visitor
388///   gets the cached copy while a fresh one renders in the background.
389/// * `version = "method"` — name a `async fn(&self) -> UiResult<String>`
390///   on the impl block. It runs before rendering, and a matching
391///   `If-None-Match` is answered 304 without calling the view at all.
392///
393/// ```ignore
394/// #[view("/", title = "Home", static, revalidate = 60)]
395/// #[view("/feed", version = "feed_revision")]
396/// ```
397///
398/// Bare `#[view]` means the controller's own path.
399#[proc_macro_attribute]
400pub fn view(args: TokenStream, input: TokenStream) -> TokenStream {
401    ui::passthrough(args, input)
402}
403
404/// `@action('name')` — marker on a method inside a `#[ui_controller]`
405/// impl block. Becomes `POST <controller>/_action/<name>` returning
406/// JSON; the name defaults to the method name.
407#[proc_macro_attribute]
408pub fn action(args: TokenStream, input: TokenStream) -> TokenStream {
409    ui::passthrough(args, input)
410}
411
412// ----- Async / cron macros ----------------------------------------------
413
414/// `@command('name')` — apply to a command-payload struct. Bakes
415/// `Self::COMMAND_NAME = "name"` and an `impl CommandData` so the
416/// typed `run_command` / `schedule_command` helpers can find the name.
417/// The struct must also derive `Serialize + Deserialize`.
418#[proc_macro_attribute]
419pub fn command(args: TokenStream, input: TokenStream) -> TokenStream {
420    async_jobs::expand_command(args, input)
421}
422
423/// `@commandHandler({ command, ...options })` — apply to a handler
424/// struct. Emits `Self::__handler_entry(&Container) ->
425/// CommandHandlerEntry` so the runtime can dispatch by `COMMAND_NAME`.
426/// The handler must implement `async fn handle(&self, cmd: MyCommand)
427/// -> Result<(), E: Display>` on a separate inherent impl, and the
428/// struct itself must be `#[injectable]`.
429///
430/// Options (all optional, after the command type):
431///
432/// * `retry_delays = [5, 30, 120]` — seconds to wait before each retry;
433///   running out of entries fails the job for good.
434/// * `acceptable_running_time = 60` — seconds before the watchdog
435///   treats a running job as stuck (default 15).
436/// * `stuck_retry_attempts = 3` — how many stuck recoveries to allow
437///   (default 2).
438/// * `dedup = 300` / `dedup = "forever"` — collapse identical payloads
439///   enqueued within the window (or ever) onto one job.
440///
441/// ```ignore
442/// #[injectable]
443/// #[command_handler(SendEmail, retry_delays = [5, 30], dedup = 300)]
444/// pub struct SendEmailHandler { mailer: Arc<Mailer> }
445/// ```
446#[proc_macro_attribute]
447pub fn command_handler(args: TokenStream, input: TokenStream) -> TokenStream {
448    async_jobs::expand_command_handler(args, input)
449}
450
451/// `@cronCommand({ name, cron })` — apply to a command struct that's
452/// fired periodically. Bakes `COMMAND_NAME` + `CRON_SCHEDULE`.
453///
454/// Usage: `#[cron_command("daily-cleanup", schedule = "0 0 2 * * *")]`
455#[proc_macro_attribute]
456pub fn cron_command(args: TokenStream, input: TokenStream) -> TokenStream {
457    async_jobs::expand_cron_command(args, input)
458}
459
460/// `@cronHandler({ ...config })` — apply to a handler struct. Emits
461/// `Self::__cron_entry(&Container) -> CronHandlerEntry`. The handler
462/// must implement `async fn handle(&self) -> Result<(), E: Display>`
463/// (cron handlers carry no arguments) and the struct must be
464/// `#[injectable]`.
465///
466/// Takes the same `retry_delays` / `acceptable_running_time` /
467/// `stuck_retry_attempts` options as `#[command_handler]`, plus:
468///
469/// * `max_running_jobs = 1` — skip a tick while that many jobs for
470///   this command are still running (default 1).
471/// * `misfire = "RUN_ONCE" | "RUN_ALL" | "SKIP"` — what to do with
472///   ticks missed while the process was down (default `RUN_ONCE`).
473/// * `disabled` — register the schedule but don't fire it.
474///
475/// ```ignore
476/// #[injectable]
477/// #[cron_handler(NightlyCleanup, misfire = "SKIP", max_running_jobs = 1)]
478/// pub struct NightlyCleanupHandler { db: Arc<Db> }
479/// ```
480#[proc_macro_attribute]
481pub fn cron_handler(args: TokenStream, input: TokenStream) -> TokenStream {
482    async_jobs::expand_cron_handler(args, input)
483}