vyuh_macros/lib.rs
1mod assets;
2mod beacon;
3mod bundle;
4mod bundlepart;
5mod cron;
6mod mcp_resource;
7mod mcp_tool;
8mod migrations;
9mod multipart;
10mod openapi;
11mod periodic;
12mod pgnotify;
13mod route;
14mod schema;
15mod schemable;
16mod service;
17mod signal;
18mod task;
19mod test;
20mod url_info;
21mod validate;
22
23use proc_macro::TokenStream;
24extern crate proc_macro;
25
26/// Derives the Validate trait for data validation.
27///
28/// Generates validation logic based on `#[validate(...)]` attributes.
29///
30/// # Attributes
31///
32/// ## `#[validate(...)]`
33/// - `delegate` - Delegate validation to the field's type (must implement `Validate`)
34/// - `custom = "path"` - Call a custom validation function: `fn(&T) -> Result<(), ValidationError>`
35/// - `custom_schema = "name"` - Emit `x-vyuh-validators: ["name"]` for custom validation
36/// - String: `min_length`, `max_length`, `exact_length`, `pattern`
37/// - String formats: `email`, `url`, `uuid`, `phone_e164`, `ipv4`, `ipv6`, `date`, `datetime`
38/// - Numeric: `min`, `max`, `exclusive_min`, `exclusive_max`, `multiple_of`
39/// - Array: `min_items`, `max_items`, `unique_items`
40#[proc_macro_derive(Validate, attributes(validate))]
41pub fn derive_validate(input: TokenStream) -> TokenStream {
42 validate::derive_validate_impl(input)
43}
44
45/// Derives multipart form parsing for named structs.
46///
47/// Supports `String` text fields and `UploadedFile` file fields. File fields
48/// can use `#[upload(...)]` for content type, extension, sniffing, and size
49/// rules.
50#[proc_macro_derive(MultipartData, attributes(upload))]
51pub fn derive_multipart_data(input: TokenStream) -> TokenStream {
52 multipart::derive_multipart_data(input)
53}
54
55/// Defines a route handler with metadata for routing and OpenAPI documentation.
56///
57/// This macro is sugar over `vyuh::bundles::route(handler, RouteConf)`.
58/// Use the direct API when routes are generated conditionally or when macro
59/// syntax is not convenient.
60///
61/// # Required Attributes
62///
63/// - `path` - Axum path pattern with optional parameters in braces: `"/users/{id}"`
64///
65/// # Optional Attributes
66///
67/// - `method` - HTTP method. Defaults to `"GET"` and can be repeated for
68/// multi-method routes.
69/// - `name` - Route name for reverse routing (defaults to function name)
70/// - `trim` - Whether a slashless route accepts one trailing slash. Defaults to
71/// `true`; `false` is invalid when the declared path already ends in `/`.
72/// - `description` - Detailed description for OpenAPI. Defaults to doc comments.
73/// - `arg(...)` - Override OpenAPI argument metadata by position/name.
74/// - `returns(...)` - Override or append OpenAPI response metadata.
75///
76/// # Examples
77///
78/// ```ignore
79/// // Free function
80/// #[route(path = "/users/{id}")]
81/// async fn get_user(Path(id): Path<i32>) -> Json<User> {
82/// // ...
83/// }
84///
85/// // Multi-method route
86/// #[route(path = "/users", method = "GET", method = "HEAD")]
87/// async fn users() -> Json<Vec<User>> {
88/// // ...
89/// }
90///
91/// // OpenAPI metadata overrides
92/// #[route(
93/// path = "/users",
94/// method = "POST",
95/// returns(status = 201, description = "Created user")
96/// )]
97/// async fn create_user(Json(input): Json<CreateUser>) -> Json<User> {
98/// // ...
99/// }
100///
101/// ```
102#[proc_macro_attribute]
103pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
104 route::parse_route(attr, item)
105}
106
107/// Defines one declarative authenticated Beacon route.
108///
109/// This is sugar over `vyuh::bundles::beacon(factory(), BeaconConf::new(...))`.
110/// The factory returns a [`vyuh::channels::Beacon`] whose typed rules consume
111/// emitted signals. `path` is required; `modes = [ws, sse, poll]`, `name`, and
112/// `trim` are optional.
113///
114/// ```ignore
115/// #[bundles::beacon(path = "/live", modes = [ws, sse])]
116/// fn live() -> Beacon {
117/// Beacon::builder().rule::<NoteChanged>(["notes:read"]).build()
118/// }
119/// ```
120#[proc_macro_attribute]
121pub fn beacon(attr: TokenStream, item: TokenStream) -> TokenStream {
122 beacon::parse_beacon(attr, item)
123}
124
125/// Defines a semantic MCP-only tool backed by a typed Vyuh callable.
126///
127/// This macro is sugar over `vyuh::bundles::mcp_tool`. The handler must end in
128/// one `Data<T>` or `Valid<Data<T>>` object payload. Supported annotations are
129/// `read_only`, `destructive`, `idempotent`, `open_world`, and
130/// `ui_resource_uri = "ui://..."`.
131///
132/// ```ignore
133/// #[mcp_tool(read_only = true, idempotent = true)]
134/// async fn search_notes(
135/// _permit: Permit<ReadNotes>,
136/// input: Data<SearchNotesInput>,
137/// ) -> Result<Data<SearchNotesOutput>, Error> {
138/// // ...
139/// }
140/// ```
141#[proc_macro_attribute]
142pub fn mcp_tool(attr: TokenStream, item: TokenStream) -> TokenStream {
143 mcp_tool::parse_mcp_tool(attr, item)
144}
145
146/// Defines one static MCP resource factory.
147///
148/// This macro is sugar over `vyuh::bundles::mcp_resource("factory_name", factory())`.
149/// The factory name becomes the standard MCP resource name in `resources/list`.
150#[proc_macro_attribute]
151pub fn mcp_resource(attr: TokenStream, item: TokenStream) -> TokenStream {
152 mcp_resource::parse_mcp_resource(attr, item)
153}
154
155/// Collects bundle parts (routes, tasks, signals) into a Bundle for composition and registration.
156///
157/// Bundles are the primary unit for organizing and composing application components.
158/// Each handler must be annotated with appropriate macros (`#[route]`, `#[cron]`, `#[periodic]`, etc.).
159///
160/// # Syntax
161///
162/// ```ignore
163/// bundle! {
164/// handler1,
165/// handler2,
166/// ...,
167/// tags = ["tag1", "tag2"] // optional, applies only to routes
168/// }
169/// ```
170///
171/// # Options
172///
173/// - `tags` - Optional array of tags to apply to all routes in the bundle.
174/// These tags extend (not replace) any tags defined on individual routes.
175/// Note: tags only apply to route parts, not other bundle parts.
176///
177/// # Examples
178///
179/// ```ignore
180/// // Bundle without tags
181/// let user_bundle = bundle! {
182/// get_user, // #[route]
183/// create_user, // #[route]
184/// sync_users, // #[cron]
185/// };
186///
187/// // Bundle with tags - extends individual route tags
188/// let api_bundle = bundle! {
189/// tags = ["api", "v1"],
190/// get_user,
191/// create_user,
192/// };
193///
194/// // Compose bundles
195/// let all_bundles = bundle! {
196/// user_bundle,
197/// api_bundle,
198/// };
199/// ```
200///
201/// # Notes
202///
203/// - Handlers must be annotated with `#[route]`, `#[cron]`, `#[periodic]`, `#[pgnotify]`, or `#[signal]`
204/// - Handlers can be free functions or references to IntoBundle types
205/// - Tags are additive and only apply to route parts
206/// - Returns a `Bundle` that implements `IntoBundle`
207#[proc_macro]
208pub fn bundle(input: TokenStream) -> TokenStream {
209 bundle::parse_bundle(input)
210}
211
212/// Embeds YAML migrations using Vyuh's database facade.
213///
214/// The migration directory is resolved relative to the application crate's
215/// `CARGO_MANIFEST_DIR`. Generated types resolve through `vyuh::db`, so the
216/// application does not need a direct Mool dependency.
217#[proc_macro]
218pub fn embed_migrations(input: TokenStream) -> TokenStream {
219 mool_macros_impl::embed_migrations::expand(input.into(), quote::quote!(::vyuh::db)).into()
220}
221
222/// Embeds one asset directory using Vyuh's asset facade.
223///
224/// Generated asset runtime types resolve through `vyuh::embed`, so
225/// applications do not need a direct Rust Silos dependency.
226#[proc_macro]
227pub fn embed_assets(input: TokenStream) -> TokenStream {
228 let silo =
229 rust_silos_macros_impl::embed_silo::expand(input.into(), quote::quote!(::vyuh::embed));
230 quote::quote!(::vyuh::embed::Dir::new(#silo)).into()
231}
232
233#[proc_macro_derive(Record, attributes(field, column, table, db))]
234pub fn derive_record(input: TokenStream) -> TokenStream {
235 mool_macros_impl::record::derive_record(input.into(), quote::quote!(::vyuh::db)).into()
236}
237
238/// Derives physical-column mapping for migration-managed record values.
239///
240/// Generated implementations resolve through Vyuh's database facade, so an
241/// application does not need a direct Mool dependency.
242#[proc_macro_derive(ManagedRecord, attributes(column, table, db))]
243pub fn derive_managed_record(input: TokenStream) -> TokenStream {
244 mool_macros_impl::record::derive_managed_record(input.into(), quote::quote!(::vyuh::db)).into()
245}
246
247#[proc_macro_derive(Model, attributes(field, column, table, db))]
248pub fn derive_model(input: TokenStream) -> TokenStream {
249 mool_macros_impl::model::derive_model(input.into(), quote::quote!(::vyuh::db)).into()
250}
251
252#[proc_macro_derive(Filterable, attributes(filter, db))]
253pub fn derive_filterable(input: TokenStream) -> TokenStream {
254 mool_macros_impl::filterable::derive_filterable(input.into(), quote::quote!(::vyuh::db)).into()
255}
256
257#[proc_macro_derive(SortKey, attributes(sort, db))]
258pub fn derive_sort_key(input: TokenStream) -> TokenStream {
259 mool_macros_impl::sort_key::derive_sort_key(input.into(), quote::quote!(::vyuh::db)).into()
260}
261
262/// Derives a SQL-backed enum mapping through Vyuh's database facade.
263///
264/// Generated implementations resolve through `vyuh::db`, so an application
265/// does not need a direct Mool dependency.
266#[proc_macro_derive(SqlEnum, attributes(sql_enum, db))]
267pub fn derive_sql_enum(input: TokenStream) -> TokenStream {
268 mool_macros_impl::sql_enum::derive_sql_enum(input.into(), quote::quote!(::vyuh::db)).into()
269}
270
271/// Registers a cron emitter.
272///
273/// This macro is sugar over `vyuh::bundles::cron(handler, CronConf)`.
274/// The handler returns `Data<T>` and the emitted data is submitted to signals by
275/// default. `executor = "task"` submits it to a registered durable task with
276/// input type `T`.
277///
278/// # Attributes
279///
280/// - `expr` - Cron expression (required): `"0 0 * * * *"` (every minute)
281/// - `executor` - `"signal"` (default) or `"task"`
282/// - `schedule` - stable task cursor name (task executor only)
283/// - `start` - `"next"` (default) or `"immediately"` (task executor only)
284///
285/// # Examples
286///
287/// ```ignore
288/// // Free function
289/// #[cron(expr = "0 0 * * * *")]
290/// async fn publish_daily(site: Site) -> Data<DailyTick> {
291/// DailyTick.into()
292/// }
293///
294/// // Method in impl block
295/// impl SyncTasks {
296/// #[cron(expr = "0 */5 * * * *")]
297/// async fn publish_frequent(site: Site) -> Data<SyncTick> {
298/// SyncTick.into()
299/// }
300/// }
301/// ```
302#[proc_macro_attribute]
303pub fn cron(attr: TokenStream, item: TokenStream) -> TokenStream {
304 cron::parse_cron(attr, item)
305}
306
307/// Registers a fixed-interval emitter.
308///
309/// This macro is sugar over `vyuh::bundles::periodic(handler, PeriodicConf)`.
310/// The handler returns `Data<T>` and the emitted data is submitted to signals by
311/// default. `executor = "task"` submits it to a registered durable task with
312/// input type `T`.
313///
314/// # Attributes
315///
316/// - `secs` - Interval in seconds (optional)
317/// - `millis` - Interval in milliseconds (optional)
318/// - `executor` - `"signal"` (default) or `"task"`
319/// - `schedule` - stable task cursor name (task executor only)
320/// - `start` - `"next"` (default) or `"immediately"` (task executor only)
321///
322/// At least one of `secs` or `millis` must be specified. Both can be used together.
323///
324/// # Examples
325///
326/// ```ignore
327/// // Free function - runs every 30 seconds
328/// #[periodic(secs = 30)]
329/// async fn publish_health(site: Site) -> Data<HealthTick> {
330/// HealthTick.into()
331/// }
332///
333/// // Method - runs every 500ms
334/// impl Monitor {
335/// #[periodic(millis = 500)]
336/// async fn publish_metrics(site: Site) -> Data<MetricsTick> {
337/// MetricsTick.into()
338/// }
339/// }
340///
341/// // Combined - runs every 1.5 seconds
342/// #[periodic(secs = 1, millis = 500)]
343/// async fn publish_queue_tick(site: Site) -> Data<QueueTick> {
344/// QueueTick.into()
345/// }
346/// ```
347#[proc_macro_attribute]
348pub fn periodic(attr: TokenStream, item: TokenStream) -> TokenStream {
349 periodic::parse_periodic(attr, item)
350}
351
352/// Registers a PostgreSQL LISTEN/NOTIFY emitter.
353///
354/// This macro is sugar over `vyuh::bundles::pgnotify(handler, PgNotifyConf)`.
355/// The handler receives raw notification data with `Data<String>` and returns
356/// `Data<T>` for signal dispatch.
357///
358/// # Attributes
359///
360/// - `channel` - PostgreSQL channel name (required): `"user_updates"`
361/// - `debounce_millis` / `debounce_secs` - Optional debounce window.
362/// - `debounce` - Optional mode: `"leading"`, `"trailing"`, or
363/// `"leading_trailing"`. Defaults to `"trailing"` when a debounce window is
364/// configured.
365///
366/// # Examples
367///
368/// ```ignore
369/// // Free function
370/// #[pgnotify(channel = "user_updates")]
371/// async fn publish_user_update(Data(raw): Data<String>) -> Data<UserUpdate> {
372/// serde_json::from_str::<UserUpdate>(&raw).unwrap().into()
373/// }
374///
375/// // Debounced notifications. Runs immediately, then once more with the last
376/// // payload if more notifications arrive within 250ms.
377/// #[pgnotify(
378/// channel = "user_updates",
379/// debounce_millis = 250,
380/// debounce = "leading_trailing"
381/// )]
382/// async fn publish_debounced_user_update(Data(raw): Data<String>) -> Data<UserUpdate> {
383/// serde_json::from_str::<UserUpdate>(&raw).unwrap().into()
384/// }
385///
386/// // Method in impl block
387/// impl UserHandlers {
388/// #[pgnotify(channel = "notifications")]
389/// async fn publish_notification(Data(raw): Data<String>) -> Data<Notification> {
390/// serde_json::from_str::<Notification>(&raw).unwrap().into()
391/// }
392/// }
393/// ```
394#[proc_macro_attribute]
395pub fn pgnotify(attr: TokenStream, item: TokenStream) -> TokenStream {
396 pgnotify::parse_pgnotify(attr, item)
397}
398
399/// Registers a function as a typed signal handler.
400///
401/// This macro is sugar over `vyuh::bundles::signal(handler, SignalConf)`.
402/// Annotated functions are registered for the data type extracted with
403/// `Data<T>`. Signals are fire-and-forget in-process notifications; they do
404/// not guarantee delivery, ordering, retries, durability, or handler completion.
405///
406/// # Examples
407///
408/// ```ignore
409/// // Free function
410/// #[signal]
411/// async fn index_note_change(Data(event): Data<NoteChanged>) {
412/// // handle typed signal
413/// }
414///
415/// // Site can be extracted before the data.
416/// #[signal]
417/// async fn audit_note_change(site: Site, Data(event): Data<NoteChanged>) {
418/// // use site plus typed data
419/// }
420/// ```
421#[proc_macro_attribute]
422pub fn signal(attr: TokenStream, item: TokenStream) -> TokenStream {
423 signal::parse_signal(attr, item)
424}
425
426/// Registers an asynchronous Work task handler.
427///
428/// This macro is sugar over `vyuh::bundles::work(handler, TaskDefinition)`.
429/// Work handlers accept `Data<T>` as their submitted data argument and return
430/// serializable values, `WorkState<T>`, or their `Result<_, WorkError>` forms.
431///
432/// # Attributes
433///
434/// - `name` - Optional task name (defaults to function name)
435/// - `lane` - Optional static `TaskLane` descriptor (defaults to `default`)
436/// - `idempotency` - Optional static `TaskIdempotency<T>` key rule
437///
438/// # Examples
439///
440/// ```ignore
441/// // Free function with default name
442/// #[work]
443/// async fn send_email(Data(input): Data<EmailData>) -> Result<(), WorkError> {
444/// deliver(input).await?;
445/// Ok(())
446/// }
447///
448/// // Register associated functions through the direct API.
449/// impl TaskHandlers {
450/// async fn process_order(site: Site, Data(input): Data<Order>) -> Result<WorkState, WorkError> {
451/// // process order
452/// Ok(WorkState::complete(()))
453/// }
454/// }
455/// let part = vyuh::bundles::work(
456/// TaskHandlers::process_order,
457/// TaskDefinition::new("custom_task_name").lane(EMAIL),
458/// );
459/// ```
460#[proc_macro_attribute]
461pub fn work(attr: TokenStream, item: TokenStream) -> TokenStream {
462 task::parse_work(attr, item)
463}
464
465/// Registers a synchronous factory built once per site into an immutable Flow.
466/// Equivalent to `bundles::flow(factory, FlowConf::new(name))`. Accepts name,
467/// lane, idempotency, and optional `dispatch = Policy` configuration. The optional
468/// Pravah integration requires the `pravah` feature. Rust bounds reject async
469/// factories and runtime input/continuation extraction; no type syntax is inspected.
470#[proc_macro_attribute]
471pub fn flow(attr: TokenStream, item: TokenStream) -> TokenStream {
472 task::parse_flow(attr, item)
473}
474
475/// Registers a value-only local Work batch handler.
476///
477/// This macro is sugar over `vyuh::bundles::work_batch(handler, TaskDefinition)`.
478/// Batch handlers accept `Data<Batch<T>>` and return unit, uniform `WorkState<O>`,
479/// ordered `Batch<WorkState<O>>` / `Batch<Result<WorkState<O>, WorkError>>`,
480/// or an outer `Result<_, WorkError>`. Suspension is rejected per item.
481/// They do not expose task identity or continuation state, and cannot suspend
482/// or sleep individual tasks.
483///
484/// The supported attributes are `name`, `lane`, and `idempotency`, matching
485/// [`work`].
486///
487/// ```ignore
488/// #[work_batch]
489/// async fn index_documents(Data(items): Data<Batch<IndexDocument>>) -> Result<(), WorkError> {
490/// index_all(items.as_ref()).await?;
491/// Ok(())
492/// }
493/// ```
494#[proc_macro_attribute]
495pub fn work_batch(attr: TokenStream, item: TokenStream) -> TokenStream {
496 task::parse_work_batch(attr, item)
497}
498
499/// Builds an isolated `TestSite` around an async integration-test body.
500///
501/// This is syntax sugar over `vyuh::testing::test_site` and
502/// `TestSite::builder(...).without_migrations()`.
503#[proc_macro_attribute]
504pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
505 test::parse_test(attr, item)
506}
507
508// #[proc_macro_attribute]
509// pub fn fnspec(attr: TokenStream, item: TokenStream) -> TokenStream {
510// fnspec::parse_fnspec_input(attr, item, "fnspec")
511// }
512
513#[proc_macro_attribute]
514pub fn openapi(attr: TokenStream, item: TokenStream) -> TokenStream {
515 openapi::parse_openapi(attr, item)
516}
517
518#[proc_macro_attribute]
519pub fn service(attr: TokenStream, item: TokenStream) -> TokenStream {
520 service::parse_service(attr, item)
521}
522
523#[proc_macro_attribute]
524pub fn asset_dir(attr: TokenStream, item: TokenStream) -> TokenStream {
525 assets::parse_asset_dir(attr, item)
526}
527
528#[proc_macro_attribute]
529pub fn migrations(attr: TokenStream, item: TokenStream) -> TokenStream {
530 migrations::parse_migrations(attr, item)
531}
532
533#[proc_macro_attribute]
534pub fn schema(attr: TokenStream, item: TokenStream) -> TokenStream {
535 schema::parse_schema(attr, item)
536}
537
538#[proc_macro_attribute]
539pub fn url_info(attr: TokenStream, item: TokenStream) -> TokenStream {
540 url_info::parse_url_info(attr, item)
541}