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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Procedural macros for the Tork web framework.
//!
//! Every macro here emits code that refers to the public API through the `tork`
//! facade crate (for example `::tork::Router`), never through `tork-core`
//! directly. This lets generated code compile inside user crates that depend
//! only on `tork`.
use TokenStream;
/// Marks the asynchronous entrypoint of a Tork application.
///
/// Rewrites an `async fn main` into a synchronous `main` that builds a
/// multi-threaded Tokio runtime and blocks on the original body. The function's
/// return type is preserved, so returning `tork::Result<()>` works as written.
///
/// # Example
///
/// ```ignore
/// #[tork::main]
/// async fn main() -> tork::Result<()> {
/// App::new().serve("0.0.0.0:8000").await
/// }
/// ```
/// Turns an inline module into a router.
///
/// Discovers the functions annotated with a route macro and generates a
/// `router()` function that mounts them under the given `prefix` and `tags`.
///
/// # Example
///
/// ```ignore
/// #[api_router(prefix = "/users", tags = ["users"])]
/// pub mod users_router {
/// use super::*;
///
/// #[get("/{user_id}", response_model = UserOut)]
/// pub async fn get_user(user_id: i64, service: UserService) -> tork::Result<UserOut> {
/// service.get_user(user_id).await
/// }
/// }
/// // `users_router::router()` is now available.
/// ```
/// Turns a type into a request dependency.
///
/// Applied to an `impl` block containing an async `resolve` function, it
/// generates a `FromRequest` implementation. Each parameter of `resolve` is
/// itself resolved through `FromRequest` (recursively), then `resolve` is called.
///
/// # Example
///
/// ```ignore
/// #[tork::dependency]
/// impl CurrentUser {
/// pub async fn resolve(token: BearerToken, users: UserRepository) -> tork::Result<Self> {
/// // ...resolve the current user from the token...
/// }
/// }
/// ```
/// Turns a struct into a validated, documented API model.
///
/// Derives serde (de)serialization, `garde` validation, and `schemars` JSON
/// Schema, and translates `#[field(...)]` constraints into the matching `garde`
/// and `schemars` attributes.
///
/// # Supported `#[field(...)]` constraints
///
/// - `min_length` / `max_length` — string length bounds
/// - `ge` / `le` — inclusive numeric bounds
/// - `gt` / `lt` — exclusive numeric bounds
/// - `title` / `description` — documentation metadata
/// - `custom` — a custom validator function (may be repeated); the function
/// performs the check and returns its own message, e.g.
/// `#[field(custom = validate_password)]`
///
/// # Example
///
/// ```ignore
/// #[api_model(rename_all = "camelCase")]
/// pub struct CreateOrderInput {
/// #[field(min_length = 1, max_length = 120)] pub name: String,
/// #[field(gt = 0, description = "The price must be greater than zero")] pub price: f64,
/// }
/// ```
/// Declares a typed application configuration.
///
/// Derives `serde` deserialization and `garde` validation, maps `#[setting(...)]`
/// constraints to validation rules, turns `#[setting(default = ...)]` into a serde
/// default, and generates a `load()` method that merges the configured sources
/// (`.env`, environment variables, config files, a secrets directory, overrides)
/// into a validated value. Loading is meant to run once at startup.
///
/// # Example
///
/// ```ignore
/// #[tork::settings(prefix = "APP", env_file = ".env")]
/// pub struct Config {
/// #[setting(default = "Awesome API")] pub app_name: String,
/// #[setting(email)] pub admin_email: String,
/// #[setting(default = 50, ge = 1, le = 500)] pub items_per_user: u32,
/// #[setting(secret)] pub jwt_secret: tork::SecretString,
/// }
/// // let config = Config::load()?;
/// ```
/// Declares an application lifespan on a resource container.
///
/// Applied to `impl T { async fn startup(ctx) -> tork::Result<Self>; async fn
/// shutdown(self) -> tork::Result<()> }`, it makes `T` a `Lifespan`. `shutdown`
/// is optional. `T` must also derive `Resources`.
///
/// # Example
///
/// ```ignore
/// #[tork::lifespan]
/// impl AppState {
/// async fn startup(ctx: tork::LifespanContext) -> tork::Result<Self> { /* ... */ }
/// async fn shutdown(self) -> tork::Result<()> { /* ... */ }
/// }
/// // App::new().lifespan::<AppState>()
/// ```
/// Declares a resource container.
///
/// Generates a `Resources` implementation that registers each `#[resource]`
/// field by type, and a `FromRequest` implementation for each resource type so
/// it can be injected directly.
/// Derives request-time construction by injecting each field.
///
/// Generates a `FromRequest` implementation that resolves every field through
/// `FromRequest` (a resource, another `Inject` service, or a built-in extractor).
/// Derives `FromMultipart` for a `multipart/form-data` model.
///
/// Each field binds from the parsed form: file fields (`FileBytes` / `UploadFile`,
/// optionally `Option` or `Vec`) are recognized by a `#[file]` attribute or their
/// type; every other field is a text field parsed from its string value.
/// `#[field(...)]` constraints validate text fields.
///
/// # Example
///
/// ```ignore
/// #[derive(FormModel)]
/// pub struct CreateFileForm {
/// #[file] pub file: FileBytes,
/// #[field(min_length = 16)] pub token: String,
/// }
/// ```
/// Derives `From<Self> for tork::Error`, storing the value as a typed source.
///
/// This lets a user error convert into a framework error through `?` while
/// preserving the original value, so a registered
/// `exception_handler::<Self>()` can recover and map it. A type-level
/// `#[status(...)]` attribute sets the default HTTP status (a status code such as
/// `503`, or an `ErrorKind` variant name); it defaults to `500`. The type must
/// implement `Display` and `std::error::Error`.
///
/// # Example
///
/// ```ignore
/// #[derive(Debug, tork::AppError)]
/// #[status(503)]
/// pub enum DbError { Timeout }
/// // impl Display + Error for DbError ...
/// // `repo.query()?` now converts DbError into tork::Error.
/// ```
/// Turns an async function into a middleware layer.
///
/// The function must be `async fn(request, next) -> tork::Result<tork::Response>`.
/// It is rewritten into a unit struct of the same name implementing the
/// `Middleware` trait, so it can be passed to `App::middleware`.
///
/// # Example
///
/// ```ignore
/// #[middleware]
/// pub async fn add_process_time_header(req: Request, next: Next) -> Result<Response> {
/// let mut res = next.run(req).await?;
/// // ...set a header on res...
/// Ok(res)
/// }
/// ```
/// Declares a `GET` route. See [`macro@get`] and the other method macros for the
/// supported attributes (`response_model`, `summary`, `description`,
/// `status_code`, `tags`).
/// Declares a `POST` route.
/// Declares a `PUT` route.
/// Declares a `PATCH` route.
/// Declares a `DELETE` route.
/// Declares a Server-Sent Events endpoint (default `GET`).
///
/// The handler returns `tork::Result<Sse<T>>`. Attributes: path (first), `method`,
/// `event` (default event name), `summary`, `description`, `tags`.
///
/// # Example
///
/// ```ignore
/// #[sse("/items/stream", event = "item_update")]
/// pub async fn stream_items(service: ItemService) -> tork::Result<Sse<ItemOut>> {
/// Ok(Sse::new(service.item_stream()))
/// }
/// ```
/// Declares a Server-Sent Events endpoint served over `POST`.
///
/// Shorthand for [`macro@sse`] with `method = POST`; useful for streaming a
/// response to a request that carries a body.
/// Declares a WebSocket endpoint.
///
/// The handler takes a `WebSocket` parameter (the upgrade handle) and returns
/// `tork::Result<()>`. Other parameters are path parameters or dependencies,
/// resolved before the upgrade. Attributes: path (first), `summary`,
/// `description`, `tags`.
///
/// # Example
///
/// ```ignore
/// #[websocket("/ws")]
/// pub async fn echo(socket: WebSocket) -> tork::Result<()> {
/// let mut socket = socket.accept().await?;
/// while let Some(message) = socket.recv().await? { /* ... */ }
/// Ok(())
/// }
/// ```