Skip to main content

sololc_webhook_macros/
lib.rs

1//! # Sololc Webhook Macros
2//!
3//! Provides high-performance, zero-dependency procedural macro attributes for 
4//! compile-time static routing configuration within the Sololc Webhook ecosystem.
5//!
6//! This crate works closely with `sololc-webhook-sdk` to expand declarative attributes
7//! into standard WASI-HTTP component model `wasi:http/incoming-handler` exports.
8
9extern crate proc_macro;
10use proc_macro::TokenStream;
11
12/// Routes an incoming HTTP `GET` request to the annotated handler function.
13///
14/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
15///
16/// # Examples
17///
18/// ```ignore
19/// use sololc_webhook_sdk::{get, Request, Response};
20///
21/// #[get("/api/v1/webhook")]
22/// async fn my_handler(req: Request) -> Response {
23///     Response::json(200, r#"{"status": "ok"}"#)
24/// }
25/// ```
26#[proc_macro_attribute]
27pub fn get(attr: TokenStream, item: TokenStream) -> TokenStream {
28    generate_webhook_route("GET", attr, item)
29}
30
31/// Routes an incoming HTTP `POST` request to the annotated handler function.
32///
33/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
34///
35/// # Examples
36///
37/// ```ignore
38/// use sololc_webhook_sdk::{post, Request, Response};
39///
40/// #[post("/api/v1/events")]
41/// async fn process_event(req: Request) -> Response {
42///     Response::json(201, r#"{"event": "accepted"}"#)
43/// }
44/// ```
45#[proc_macro_attribute]
46pub fn post(attr: TokenStream, item: TokenStream) -> TokenStream {
47    generate_webhook_route("POST", attr, item)
48}
49
50/// Routes an incoming HTTP `PUT` request to the annotated handler function.
51///
52/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
53#[proc_macro_attribute]
54pub fn put(attr: TokenStream, item: TokenStream) -> TokenStream {
55    generate_webhook_route("PUT", attr, item)
56}
57
58/// Routes an incoming HTTP `DELETE` request to the annotated handler function.
59///
60/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
61#[proc_macro_attribute]
62pub fn delete(attr: TokenStream, item: TokenStream) -> TokenStream {
63    generate_webhook_route("DELETE", attr, item)
64}
65
66/// Routes an incoming HTTP `PATCH` request to the annotated handler function.
67///
68/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
69#[proc_macro_attribute]
70pub fn patch(attr: TokenStream, item: TokenStream) -> TokenStream {
71    generate_webhook_route("PATCH", attr, item)
72}
73
74/// Routes an incoming HTTP `HEAD` request to the annotated handler function.
75///
76/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
77#[proc_macro_attribute]
78pub fn head(attr: TokenStream, item: TokenStream) -> TokenStream {
79    generate_webhook_route("HEAD", attr, item)
80}
81
82/// Routes an incoming HTTP `OPTIONS` request to the annotated handler function.
83///
84/// Generates the static routing glue code at compile-time to match the URI path and HTTP method.
85#[proc_macro_attribute]
86pub fn options(attr: TokenStream, item: TokenStream) -> TokenStream {
87    generate_webhook_route("OPTIONS", attr, item)
88}
89
90/// Generates the comprehensive WASI-HTTP proxy boilerplate from raw attributes and tokens.
91///
92/// Extracts the target handler identifier dynamically from the `item` stream, wraps it 
93/// inside a standard `futures::executor::block_on` runtime sequence, and welds it directly
94/// to the underlying guest capabilities export layer.
95fn generate_webhook_route(method: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
96    let path_str = attr.to_string();
97    let func_str = item.to_string();
98    let expected_method = method.to_uppercase();
99
100    // 🌟 动态命名提取算法:在无需 syn 库的极轻量模式下,精准捕获开发者的原始异步函数标识符
101    let func_name = func_str
102        .split_whitespace()
103        .skip_while(|&token| token != "fn")
104        .nth(1)
105        .and_then(|name| name.split('(').next())
106        .unwrap_or("handle_webhook")
107        .trim();
108
109    let code_template = format!(
110        "
111        // Emits the original developer-defined asynchronous block seamlessly.
112        {}
113
114        struct WitProxyImpl;
115
116        impl sololc_webhook_sdk::Guest for WitProxyImpl {{
117            fn handle(
118                wasi_req: sololc_webhook_sdk::IncomingRequest,
119                wasi_outparam: sololc_webhook_sdk::ResponseOutparam,
120            ) {{
121                let current_path = wasi_req.path_with_query().unwrap_or_default();
122                let current_method_raw = wasi_req.method();
123                let current_method = format!(\"{{:?}}\", current_method_raw).to_uppercase();
124
125                if current_path.starts_with({}) && current_method == \"{}\" {{
126                    let req_wrapper = sololc_webhook_sdk::Request::from_wasi(wasi_req);
127                    
128                    // Invokes the dynamically resolved handler identifier function.
129                    let future = {}(req_wrapper); 
130                    let app_resp = futures::executor::block_on(future);
131                    
132                    sololc_webhook_sdk::ResponseOutparam::set(wasi_outparam, Ok(app_resp.into_wasi()));
133                }} else if current_path.starts_with({}) && current_method != \"{}\" {{
134                    let fields = sololc_webhook_sdk::Fields::new();
135                    let resp = sololc_webhook_sdk::OutgoingResponse::new(fields);
136                    resp.set_status_code(405).unwrap();
137                    sololc_webhook_sdk::ResponseOutparam::set(wasi_outparam, Ok(resp));
138                }} else {{
139                    let fields = sololc_webhook_sdk::Fields::new();
140                    let resp = sololc_webhook_sdk::OutgoingResponse::new(fields);
141                    resp.set_status_code(404).unwrap();
142                    sololc_webhook_sdk::ResponseOutparam::set(wasi_outparam, Ok(resp));
143                }}
144            }}
145        }}
146
147        sololc_webhook_sdk::export!(WitProxyImpl);
148        ",
149        func_str, path_str, expected_method, func_name, path_str, expected_method
150    );
151
152    code_template.parse().expect("Failed to parse generated webhook glue code")
153}