vespera_macro 0.1.17

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
Documentation
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::collections::BTreeMap;

use syn::{FnArg, PatType, Type};
use vespera_core::{
    route::{MediaType, Operation, Parameter, ParameterLocation, RequestBody, Response},
    schema::{Schema, SchemaRef},
};

use super::{
    parameters::parse_function_parameter, path::extract_path_parameters,
    request_body::parse_request_body, response::parse_return_type,
    schema::parse_type_to_schema_ref_with_schemas,
};

/// Build Operation from function signature
pub fn build_operation_from_function(
    sig: &syn::Signature,
    path: &str,
    known_schemas: &std::collections::HashMap<String, String>,
    struct_definitions: &std::collections::HashMap<String, String>,
    error_status: Option<&[u16]>,
    tags: Option<&[String]>,
) -> Operation {
    let path_params = extract_path_parameters(path);
    let mut parameters = Vec::new();
    let mut request_body = None;
    let mut path_extractor_type: Option<Type> = None;

    // First pass: find Path<T> extractor and extract its type
    for input in &sig.inputs {
        if let FnArg::Typed(PatType { ty, .. }) = input
            && let Type::Path(type_path) = ty.as_ref()
        {
            let path_segments = &type_path.path;
            if !path_segments.segments.is_empty() {
                let segment = path_segments.segments.last().unwrap();
                if segment.ident == "Path"
                    && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
                    && let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
                {
                    path_extractor_type = Some(inner_ty.clone());
                    break;
                }
            }
        }
    }

    // Generate path parameters from path string (not from function signature)
    // This is the primary source of truth for path parameters
    if !path_params.is_empty() {
        if let Some(ty) = path_extractor_type {
            // Check if it's a tuple type
            if let Type::Tuple(tuple) = ty {
                // For tuple types, match each path parameter with tuple element type
                for (idx, param_name) in path_params.iter().enumerate() {
                    if let Some(elem_ty) = tuple.elems.get(idx) {
                        parameters.push(Parameter {
                            name: param_name.clone(),
                            r#in: ParameterLocation::Path,
                            description: None,
                            required: Some(true),
                            schema: Some(parse_type_to_schema_ref_with_schemas(
                                elem_ty,
                                known_schemas,
                                struct_definitions,
                            )),
                            example: None,
                        });
                    } else {
                        // If tuple doesn't have enough elements, use String as default
                        parameters.push(Parameter {
                            name: param_name.clone(),
                            r#in: ParameterLocation::Path,
                            description: None,
                            required: Some(true),
                            schema: Some(parse_type_to_schema_ref_with_schemas(
                                &syn::parse_str::<Type>("String").unwrap(),
                                known_schemas,
                                struct_definitions,
                            )),
                            example: None,
                        });
                    }
                }
            } else {
                // Single path parameter
                if path_params.len() == 1 {
                    parameters.push(Parameter {
                        name: path_params[0].clone(),
                        r#in: ParameterLocation::Path,
                        description: None,
                        required: Some(true),
                        schema: Some(parse_type_to_schema_ref_with_schemas(
                            &ty,
                            known_schemas,
                            struct_definitions,
                        )),
                        example: None,
                    });
                } else {
                    // Multiple path parameters but single type - use String for all
                    for param_name in &path_params {
                        parameters.push(Parameter {
                            name: param_name.clone(),
                            r#in: ParameterLocation::Path,
                            description: None,
                            required: Some(true),
                            schema: Some(parse_type_to_schema_ref_with_schemas(
                                &ty,
                                known_schemas,
                                struct_definitions,
                            )),
                            example: None,
                        });
                    }
                }
            }
        } else {
            // No Path extractor found, but path has parameters - use String as default
            for param_name in &path_params {
                parameters.push(Parameter {
                    name: param_name.clone(),
                    r#in: ParameterLocation::Path,
                    description: None,
                    required: Some(true),
                    schema: Some(parse_type_to_schema_ref_with_schemas(
                        &syn::parse_str::<Type>("String").unwrap(),
                        known_schemas,
                        struct_definitions,
                    )),
                    example: None,
                });
            }
        }
    }

    // Parse function parameters (skip Path extractor as we already handled it)
    for input in &sig.inputs {
        // Check if it's a request body (Json<T>)
        if let Some(body) = parse_request_body(input, known_schemas, struct_definitions) {
            request_body = Some(body);
        } else {
            // Skip Path extractor - we already handled path parameters above
            let is_path_extractor = if let FnArg::Typed(PatType { ty, .. }) = input
                && let Type::Path(type_path) = ty.as_ref()
                && !&type_path.path.segments.is_empty()
            {
                let segment = &type_path.path.segments.last().unwrap();
                segment.ident == "Path"
            } else {
                false
            };

            if !is_path_extractor
                && let Some(params) =
                    parse_function_parameter(input, &path_params, known_schemas, struct_definitions)
            {
                parameters.extend(params);
            }
        }
    }

    // Fallback: if last arg is String/&str and no body yet, treat as text/plain body
    if request_body.is_none()
        && let Some(FnArg::Typed(PatType { ty, .. })) = sig.inputs.last()
    {
        let is_string = match ty.as_ref() {
            Type::Path(type_path) => type_path
                .path
                .segments
                .last()
                .map(|s| s.ident == "String" || s.ident == "str")
                .unwrap_or(false),
            Type::Reference(type_ref) => {
                if let Type::Path(p) = type_ref.elem.as_ref() {
                    p.path
                        .segments
                        .last()
                        .map(|s| s.ident == "String" || s.ident == "str")
                        .unwrap_or(false)
                } else {
                    false
                }
            }
            _ => false,
        };

        if is_string {
            let mut content = BTreeMap::new();
            content.insert(
                "text/plain".to_string(),
                MediaType {
                    schema: Some(SchemaRef::Inline(Box::new(Schema::string()))),
                    example: None,
                    examples: None,
                },
            );
            request_body = Some(RequestBody {
                description: None,
                content,
                required: Some(true),
            });
        }
    }

    // Parse return type - may return multiple responses (for Result types)
    let mut responses = parse_return_type(&sig.output, known_schemas, struct_definitions);

    // Add additional error status codes from error_status attribute
    if let Some(status_codes) = error_status {
        // Find the error response schema (usually 400 or the first error response)
        let error_schema = responses
            .iter()
            .find(|(code, _)| code != &&"200".to_string())
            .and_then(|(_, resp)| {
                resp.content
                    .as_ref()?
                    .get("application/json")?
                    .schema
                    .clone()
            });

        if let Some(schema) = error_schema {
            for &status_code in status_codes {
                let status_str = status_code.to_string();
                // Only add if not already present
                responses.entry(status_str).or_insert_with(|| {
                    let mut err_content = BTreeMap::new();
                    err_content.insert(
                        "application/json".to_string(),
                        MediaType {
                            schema: Some(schema.clone()),
                            example: None,
                            examples: None,
                        },
                    );

                    Response {
                        description: "Error response".to_string(),
                        headers: None,
                        content: Some(err_content),
                    }
                });
            }
        }
    }

    Operation {
        operation_id: Some(sig.ident.to_string()),
        tags: tags.map(|t| t.to_vec()),
        summary: None,
        description: None,
        parameters: if parameters.is_empty() {
            None
        } else {
            Some(parameters)
        },
        request_body,
        responses,
        security: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;
    use std::collections::HashMap;
    use vespera_core::schema::{SchemaRef, SchemaType};

    fn param_schema_type(param: &Parameter) -> Option<SchemaType> {
        match param.schema.as_ref()? {
            SchemaRef::Inline(schema) => schema.schema_type.clone(),
            SchemaRef::Ref(_) => None,
        }
    }

    fn build(sig_src: &str, path: &str, error_status: Option<&[u16]>) -> Operation {
        let sig: syn::Signature = syn::parse_str(sig_src).expect("signature parse failed");
        build_operation_from_function(
            &sig,
            path,
            &HashMap::new(),
            &HashMap::new(),
            error_status,
            None,
        )
    }

    #[derive(Clone, Debug)]
    struct ExpectedParam {
        name: &'static str,
        schema: Option<SchemaType>,
    }

    #[derive(Clone, Debug)]
    struct ExpectedBody {
        content_type: &'static str,
        schema: Option<SchemaType>,
    }

    #[derive(Clone, Debug)]
    struct ExpectedResp {
        status: &'static str,
        schema: Option<SchemaType>,
    }

    fn assert_body(op: &Operation, expected: &Option<ExpectedBody>) {
        match expected {
            None => assert!(op.request_body.is_none()),
            Some(exp) => {
                let body = op.request_body.as_ref().expect("request body expected");
                let media = body
                    .content
                    .get(exp.content_type)
                    .or_else(|| {
                        // allow fallback to the only available content type if expected is absent
                        if body.content.len() == 1 {
                            body.content.values().next()
                        } else {
                            None
                        }
                    })
                    .expect("expected content type");
                if let Some(schema_ty) = &exp.schema {
                    match media.schema.as_ref().expect("schema expected") {
                        SchemaRef::Inline(schema) => {
                            assert_eq!(schema.schema_type, Some(schema_ty.clone()));
                        }
                        SchemaRef::Ref(_) => panic!("expected inline schema"),
                    }
                }
            }
        }
    }

    fn assert_params(op: &Operation, expected: &[ExpectedParam]) {
        match op.parameters.as_ref() {
            None => assert!(expected.is_empty()),
            Some(params) => {
                assert_eq!(params.len(), expected.len());
                for (param, exp) in params.iter().zip(expected) {
                    assert_eq!(param.name, exp.name);
                    assert_eq!(param_schema_type(param), exp.schema);
                }
            }
        }
    }

    fn assert_responses(op: &Operation, expected: &[ExpectedResp]) {
        for exp in expected {
            let resp = op.responses.get(exp.status).expect("response missing");
            let media = resp
                .content
                .as_ref()
                .and_then(|c| c.get("application/json"))
                .or_else(|| resp.content.as_ref().and_then(|c| c.get("text/plain")))
                .expect("media type missing");
            if let Some(schema_ty) = &exp.schema {
                match media.schema.as_ref().expect("schema expected") {
                    SchemaRef::Inline(schema) => {
                        assert_eq!(schema.schema_type, Some(schema_ty.clone()));
                    }
                    SchemaRef::Ref(_) => panic!("expected inline schema"),
                }
            }
        }
    }

    #[rstest]
    #[case(
        "fn upload(data: String) -> String",
        "/upload",
        None::<&[u16]>,
        vec![],
        Some(ExpectedBody { content_type: "text/plain", schema: Some(SchemaType::String) }),
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn upload_ref(data: &str) -> String",
        "/upload",
        None::<&[u16]>,
        vec![],
        Some(ExpectedBody { content_type: "text/plain", schema: Some(SchemaType::String) }),
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn get(Path(params): Path<(i32,)>) -> String",
        "/users/{id}/{name}",
        None::<&[u16]>,
        vec![
            ExpectedParam { name: "id", schema: Some(SchemaType::Integer) },
            ExpectedParam { name: "name", schema: Some(SchemaType::String) },
        ],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn get() -> String",
        "/items/{item_id}",
        None::<&[u16]>,
        vec![ExpectedParam { name: "item_id", schema: Some(SchemaType::String) }],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn get(Path(id): Path<String>) -> String",
        "/shops/{shop_id}/items/{item_id}",
        None::<&[u16]>,
        vec![
            ExpectedParam { name: "shop_id", schema: Some(SchemaType::String) },
            ExpectedParam { name: "item_id", schema: Some(SchemaType::String) },
        ],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn create(Json(body): Json<User>) -> Result<String, String>",
        "/create",
        None::<&[u16]>,
        vec![],
        Some(ExpectedBody { content_type: "application/json", schema: None }),
        vec![
            ExpectedResp { status: "200", schema: Some(SchemaType::String) },
            ExpectedResp { status: "400", schema: Some(SchemaType::String) },
        ]
    )]
    #[case(
        "fn get(Path(params): Path<(i32,)>) -> String",
        "/users/{id}/{name}/{extra}",
        None::<&[u16]>,
        vec![
            ExpectedParam { name: "id", schema: Some(SchemaType::Integer) },
            ExpectedParam { name: "name", schema: Some(SchemaType::String) },
            ExpectedParam { name: "extra", schema: Some(SchemaType::String) },
        ],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn get() -> String",
        "/items/{item_id}/extra/{more}",
        None::<&[u16]>,
        vec![
            ExpectedParam { name: "item_id", schema: Some(SchemaType::String) },
            ExpectedParam { name: "more", schema: Some(SchemaType::String) },
        ],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn post(data: String) -> String",
        "/post",
        None::<&[u16]>,
        vec![],
        Some(ExpectedBody { content_type: "text/plain", schema: Some(SchemaType::String) }),
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn no_error_extra() -> String",
        "/plain",
        Some(&[500u16][..]),
        vec![],
        None,
        vec![ExpectedResp { status: "200", schema: Some(SchemaType::String) }]
    )]
    #[case(
        "fn create() -> Result<String, String>",
        "/create",
        Some(&[400u16, 500u16][..]),
        vec![],
        None,
        vec![
            ExpectedResp { status: "200", schema: Some(SchemaType::String) },
            ExpectedResp { status: "400", schema: Some(SchemaType::String) },
            ExpectedResp { status: "500", schema: Some(SchemaType::String) },
        ]
    )]
    #[case(
        "fn create() -> Result<String, String>",
        "/create",
        Some(&[401u16, 402u16][..]),
        vec![],
        None,
        vec![
            ExpectedResp { status: "200", schema: Some(SchemaType::String) },
            ExpectedResp { status: "400", schema: Some(SchemaType::String) },
            ExpectedResp { status: "401", schema: Some(SchemaType::String) },
            ExpectedResp { status: "402", schema: Some(SchemaType::String) },
        ]
    )]
    fn test_build_operation_cases(
        #[case] sig_src: &str,
        #[case] path: &str,
        #[case] extra_status: Option<&[u16]>,
        #[case] expected_params: Vec<ExpectedParam>,
        #[case] expected_body: Option<ExpectedBody>,
        #[case] expected_resps: Vec<ExpectedResp>,
    ) {
        let op = build(sig_src, path, extra_status);
        assert_params(&op, &expected_params);
        assert_body(&op, &expected_body);
        assert_responses(&op, &expected_resps);
    }
}