sdforge 0.5.0-rc.2

Multi-protocol SDK framework with unified macro configuration
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! OpenAPI 3.1 specification generation.
//!
//! This module provides runtime OpenAPI spec generation from routes registered
//! via the `inventory` crate. Each `#[forge]` macro invocation emits an
//! `OpenApiRouteInfo` entry when the `openapi` feature is enabled; the entries
//! are collected at link time and iterated by [`generate_openapi_spec`] to
//! build a complete [`utoipa::openapi::OpenApi`].
//!
//! # Example
//!
//! ```ignore
//! use sdforge::openapi::{generate_openapi_spec, OpenApiBuilder};
//!
//! // Default spec from all registered routes
//! let spec = generate_openapi_spec();
//!
//! // Customized spec
//! let spec = OpenApiBuilder::new()
//!     .title("My Service")
//!     .version("2.0.0")
//!     .description("User-facing API")
//!     .build();
//! ```
//!
//! # Feature Flag
//!
//! This module is only available when the `openapi` feature is enabled.

mod openapi_impl;
pub use openapi_impl::generate_openapi_spec;

/// Static metadata for a single OpenAPI path parameter, embedded in
/// [`OpenApiRouteInfo`].
///
/// The `#[forge]` macro emits one `OpenApiPathParam` per path segment
/// (e.g. `/users/{id}` yields a param with `name = "id"`). The schema type and
/// format are derived from the Rust parameter type at macro-expansion time so
/// the runtime can build a fully-populated OpenAPI operation without relying
/// on utoipa's `ToSchema` derive on handler return types.
#[derive(Debug, Clone, Copy)]
pub struct OpenApiPathParam {
    /// Parameter name (matches the `{name}` placeholder in the path).
    pub name: &'static str,
    /// Human-readable description; empty string when unspecified.
    pub description: &'static str,
    /// Whether the parameter is required. Path parameters are always
    /// required per the OpenAPI spec; this field is kept for future
    /// flexibility (query/header params).
    pub required: bool,
    /// OpenAPI schema type (`"integer"`, `"string"`, `"number"`,
    /// `"boolean"`).
    pub schema_type: &'static str,
    /// OpenAPI schema format (`"uint64"`, `"int64"`, `"float"`, `""` for
    /// none). Uses custom format strings (e.g. `"uint64"`) to match the
    /// Rust type precisely.
    pub schema_format: &'static str,
}

/// Static metadata for an OpenAPI route, registered via `inventory::submit!`.
///
/// The `#[forge]` macro generates one `OpenApiRouteInfo` entry per route
/// when the `openapi` feature is enabled. Users may also submit entries
/// manually for routes not declared via the macro.
#[derive(Debug, Clone, Copy)]
pub struct OpenApiRouteInfo {
    /// Route path (e.g. `/users/{id}`). OpenAPI path templating is supported.
    pub path: &'static str,
    /// HTTP method in uppercase (`"GET"`, `"POST"`, ...).
    pub method: &'static str,
    /// Short summary of the operation.
    pub summary: &'static str,
    /// Long description of the operation.
    pub description: &'static str,
    /// API version this route belongs to (e.g. `"v1"`).
    pub version: &'static str,
    /// Tags for grouping operations in the rendered spec.
    pub tags: &'static [&'static str],
    /// Path parameters auto-extracted from the route path by the
    /// `#[forge]` macro. Empty for routes without path params.
    pub path_params: &'static [OpenApiPathParam],
    /// Explicit success status code from `#[forge(status = <code>)]`.
    /// When `Some`, the OpenAPI response key uses this code (e.g. `201`)
    /// instead of the default `200`. `None` keeps backward-compatible `200`.
    pub success_status: Option<u16>,
}

inventory::collect!(OpenApiRouteInfo);

/// Builder for constructing an `OpenApi` specification with custom metadata.
///
/// Routes are always collected from the global `inventory` registry; the
/// builder only controls the top-level `info` section (title, version,
/// description).
#[derive(Debug, Clone, Default)]
pub struct OpenApiBuilder {
    title: String,
    version: String,
    description: Option<String>,
}

// Register a test-only route so inventory-driven tests have a known entry to
// assert against. The entry is collected only when tests are compiled.
#[cfg(test)]
inventory::submit!(OpenApiRouteInfo::new(
    "/__openapi_test_marker__",
    "GET",
    "OpenAPI module test marker",
    "Sentinel route registered by src/openapi/mod.rs tests to verify inventory collection.",
    "test",
    &["test"],
));

// Register a test-only route WITH path parameters to verify that path_params
// are emitted as OpenAPI `parameters` entries in the generated spec.
#[cfg(test)]
inventory::submit!(OpenApiRouteInfo::with_path_params(
    "/__openapi_path_param_test__/{id}",
    "GET",
    "Path param test marker",
    "Route with a u64 path param registered by src/openapi/mod.rs tests.",
    "test",
    &["test"],
    &[OpenApiPathParam::new(
        "id", "User ID", true, "integer", "uint64"
    ),],
));

// forge-success-status-code: Register a test-only route with an explicit
// success status code (201) to verify that the OpenAPI spec emits a `"201"`
// response key instead of the default `"200"`.
#[cfg(test)]
inventory::submit!(OpenApiRouteInfo::with_path_params_and_status(
    "/__openapi_status_201_test__",
    "POST",
    "Status 201 test marker",
    "Route with success_status=Some(201) registered by src/openapi/mod.rs tests.",
    "test",
    &["test"],
    &[],
    Some(201u16),
));

#[cfg(test)]
mod tests {
    use super::*;
    use utoipa::openapi::path::HttpMethod;

    /// `OpenApiBuilder::new()` should produce a builder with empty fields.
    #[test]
    fn builder_new_yields_empty_fields() {
        let builder = OpenApiBuilder::new();
        assert!(builder.title.is_empty());
        assert!(builder.version.is_empty());
        assert!(builder.description.is_none());
    }

    /// `title`, `version`, and `description` should be chainable and store
    /// the provided values.
    #[test]
    fn builder_chain_sets_all_fields() {
        let builder = OpenApiBuilder::new()
            .title("My API")
            .version("9.9.9")
            .description("hello");
        assert_eq!(builder.title, "My API");
        assert_eq!(builder.version, "9.9.9");
        assert_eq!(builder.description.as_deref(), Some("hello"));
    }

    /// `OpenApiBuilder::default()` should equal `new()` (Default impl).
    #[test]
    fn builder_default_matches_new() {
        let a = OpenApiBuilder::new();
        let b = OpenApiBuilder::default();
        assert_eq!(a.title, b.title);
        assert_eq!(a.version, b.version);
        assert_eq!(a.description, b.description);
    }

    /// `build()` should populate `info.title` and `info.version` from the
    /// builder, and leave `info.description` as `None` when unset.
    #[test]
    fn build_propagates_info_fields_without_description() {
        let spec = OpenApiBuilder::new()
            .title("Title X")
            .version("0.0.1")
            .build();
        assert_eq!(spec.info.title, "Title X");
        assert_eq!(spec.info.version, "0.0.1");
        assert!(spec.info.description.is_none());
    }

    /// `build()` should set `info.description` when provided.
    #[test]
    fn build_propagates_description_when_set() {
        let spec = OpenApiBuilder::new()
            .title("T")
            .version("1")
            .description("desc")
            .build();
        assert_eq!(spec.info.description.as_deref(), Some("desc"));
    }

    /// `to_parameter()` with an unknown schema_type falls back to
    /// `Type::String` (line 93 — the `_` match arm).
    #[test]
    fn to_parameter_unknown_schema_type_falls_back_to_string() {
        let param = OpenApiPathParam::new("id", "", true, "object", "");
        let parameter = param.to_parameter();
        assert_eq!(parameter.name, "id");
    }

    /// `with_path_params()` constructs a route info with explicit path
    /// parameters (line 171 — the const fn body). Called at runtime (not
    /// const context) so tarpaulin attributes the coverage.
    #[test]
    fn with_path_params_constructs_route_info() {
        const PARAMS: &[OpenApiPathParam] = &[OpenApiPathParam::new(
            "id", "user id", true, "integer", "int64",
        )];
        let route = OpenApiRouteInfo::with_path_params(
            "/users/{id}",
            "GET",
            "Get user",
            "Retrieve a user by id",
            "v1",
            &["users"],
            PARAMS,
        );
        assert_eq!(route.path, "/users/{id}");
        assert_eq!(route.method, "GET");
        assert_eq!(route.path_params.len(), 1);
        assert_eq!(route.path_params[0].name, "id");
    }

    /// `generate_openapi_spec()` should always use the crate title and the
    /// compile-time crate version, regardless of registered routes.
    #[test]
    fn generate_openapi_spec_uses_crate_identity() {
        let spec = generate_openapi_spec();
        assert_eq!(spec.info.title, "SDForge API");
        assert_eq!(spec.info.version, env!("CARGO_PKG_VERSION"));
    }

    /// The test-marker route registered above must be discoverable in the
    /// generated spec's paths. This validates the `inventory` -> `Paths`
    /// pipeline end-to-end.
    #[test]
    fn generated_spec_contains_test_marker_route() {
        let spec = generate_openapi_spec();
        let paths_json = serde_json::to_value(&spec.paths).expect("paths serialize");
        let paths_obj = paths_json
            .as_object()
            .expect("paths is a JSON object")
            .keys()
            .cloned()
            .collect::<Vec<_>>();
        assert!(
            paths_obj.iter().any(|p| p == "/__openapi_test_marker__"),
            "expected /__openapi_test_marker__ in paths, got {:?}",
            paths_obj
        );
    }

    /// `OpenApiRouteInfo::http_method()` should map every supported method
    /// string to the correct `HttpMethod` variant.
    #[test]
    fn http_method_maps_all_canonical_variants() {
        let cases = [
            ("GET", HttpMethod::Get),
            ("POST", HttpMethod::Post),
            ("PUT", HttpMethod::Put),
            ("DELETE", HttpMethod::Delete),
            ("PATCH", HttpMethod::Patch),
            ("HEAD", HttpMethod::Head),
            ("OPTIONS", HttpMethod::Options),
            ("TRACE", HttpMethod::Trace),
        ];
        for (s, expected) in cases {
            let info = OpenApiRouteInfo::new("/", s, "", "", "", &[]);
            assert!(
                info.http_method() == expected,
                "method={} did not map to expected variant",
                s
            );
        }
    }

    /// `http_method()` should be case-insensitive (lowercase input).
    #[test]
    fn http_method_is_case_insensitive() {
        let info = OpenApiRouteInfo::new("/", "get", "", "", "", &[]);
        assert!(info.http_method() == HttpMethod::Get);
    }

    /// Unknown method strings should fall back to `HttpMethod::Get`.
    #[test]
    fn http_method_unknown_falls_back_to_get() {
        let info = OpenApiRouteInfo::new("/", "CONNECT", "", "", "", &[]);
        assert!(info.http_method() == HttpMethod::Get);
    }

    /// `OpenApiRouteInfo::new()` should populate every field verbatim.
    #[test]
    fn route_info_new_populates_fields() {
        let info = OpenApiRouteInfo::new(
            "/users/{id}",
            "GET",
            "Fetch user",
            "Fetch a user by id",
            "v2",
            &["users", "v2"],
        );
        assert_eq!(info.path, "/users/{id}");
        assert_eq!(info.method, "GET");
        assert_eq!(info.summary, "Fetch user");
        assert_eq!(info.description, "Fetch a user by id");
        assert_eq!(info.version, "v2");
        assert_eq!(info.tags, &["users", "v2"]);
    }

    /// `OpenApiRouteInfo` should be `Clone + Copy`, allowing cheap duplication
    /// for inventory iteration.
    #[test]
    fn route_info_is_copy() {
        let info = OpenApiRouteInfo::new("/x", "GET", "s", "d", "v1", &[]);
        let copied = info;
        assert_eq!(info.path, copied.path);
        assert_eq!(info.method, copied.method);
    }

    /// `build()` with no routes registered should still succeed and produce
    /// an empty `paths` map. The test-marker route is always present, so we
    /// check that the paths map is a valid (possibly empty) object.
    #[test]
    fn build_succeeds_with_empty_inventory() {
        // We cannot unregister inventory entries, so this test verifies that
        // build() returns a well-formed OpenApi even when called standalone.
        let spec = OpenApiBuilder::new().title("T").version("0").build();
        let json = serde_json::to_value(&spec.paths).expect("serialize");
        assert!(json.is_object(), "paths must be a JSON object");
    }

    /// `OpenApiBuilder` should be `Clone + Debug` to support ergonomics.
    #[test]
    fn builder_implements_clone_and_debug() {
        let b = OpenApiBuilder::new().title("t").version("1");
        let cloned = b.clone();
        assert_eq!(b.title, cloned.title);
        let debug = format!("{:?}", b);
        assert!(debug.contains("OpenApiBuilder"));
    }

    /// `OpenApiPathParam::new()` should populate every field verbatim.
    #[test]
    fn path_param_new_populates_fields() {
        let p = OpenApiPathParam::new("id", "User ID", true, "integer", "uint64");
        assert_eq!(p.name, "id");
        assert_eq!(p.description, "User ID");
        assert!(p.required);
        assert_eq!(p.schema_type, "integer");
        assert_eq!(p.schema_format, "uint64");
    }

    /// `OpenApiPathParam::to_parameter()` should produce a `Parameter` with
    /// `name`, `parameter_in = Path`, `required = True`, and a schema
    /// containing the configured type and format.
    #[test]
    fn path_param_to_parameter_builds_correct_parameter() {
        let p = OpenApiPathParam::new("id", "User ID", true, "integer", "uint64");
        let param = p.to_parameter();
        assert_eq!(param.name, "id");
        assert!(
            matches!(param.parameter_in, utoipa::openapi::path::ParameterIn::Path),
            "parameter_in must be Path"
        );
        assert!(
            matches!(param.required, utoipa::openapi::Required::True),
            "path parameter must be required"
        );
        let schema = param.schema.expect("schema must be present");
        let json = serde_json::to_value(&schema).expect("schema serialize");
        assert_eq!(json["type"], "integer", "schema type must be integer");
        assert_eq!(json["format"], "uint64", "schema format must be uint64");
    }

    /// `OpenApiPathParam::to_parameter()` with empty format should omit the
    /// `format` field from the serialized schema (string type, no format).
    #[test]
    fn path_param_to_parameter_omits_empty_format() {
        let p = OpenApiPathParam::new("name", "", true, "string", "");
        let param = p.to_parameter();
        let schema = param.schema.expect("schema present");
        let json = serde_json::to_value(&schema).expect("serialize");
        assert_eq!(json["type"], "string");
        assert!(
            json.get("format").is_none() || json["format"].is_null(),
            "format must be absent for empty schema_format"
        );
    }

    /// `OpenApiRouteInfo::with_path_params()` should store the provided
    /// path_params slice. Uses a `const` declaration because
    /// `with_path_params` requires `&'static` data (it is designed for
    /// macro-generated static registration, not runtime construction).
    #[test]
    fn with_path_params_stores_params() {
        const PARAMS: &[OpenApiPathParam] =
            &[OpenApiPathParam::new("id", "", true, "integer", "uint64")];
        const INFO: OpenApiRouteInfo =
            OpenApiRouteInfo::with_path_params("/x/{id}", "GET", "s", "d", "v1", &[], PARAMS);
        assert_eq!(INFO.path_params.len(), 1);
        assert_eq!(INFO.path_params[0].name, "id");
        assert_eq!(INFO.path_params[0].schema_type, "integer");
        assert_eq!(INFO.path_params[0].schema_format, "uint64");
    }

    /// `generate_openapi_spec()` should emit a `parameters` array on the
    /// operation of a route registered with `path_params`. This is the
    /// end-to-end T094 verification: the generated OpenAPI operation for
    /// `/__openapi_path_param_test__/{id}` MUST contain a parameter
    /// `{name: "id", in: "path", required: true, schema: {type: "integer",
    /// format: "uint64"}}`.
    #[test]
    fn generated_spec_contains_path_param_operation() {
        let spec = generate_openapi_spec();
        let paths_json = serde_json::to_value(&spec.paths).expect("paths serialize");
        let paths_obj = paths_json
            .as_object()
            .expect("paths is a JSON object")
            .clone();
        let route_key = "/__openapi_path_param_test__/{id}";
        let route = paths_obj
            .get(route_key)
            .unwrap_or_else(|| panic!("expected route {} in paths", route_key));
        let get_op = route
            .get("get")
            .unwrap_or_else(|| panic!("expected GET operation on {}", route_key));
        let params = get_op
            .get("parameters")
            .and_then(|p| p.as_array())
            .unwrap_or_else(|| panic!("expected parameters array on {}", route_key));
        assert_eq!(
            params.len(),
            1,
            "expected exactly 1 parameter on {}",
            route_key
        );
        let id_param = &params[0];
        assert_eq!(id_param["name"], "id", "parameter name must be id");
        assert_eq!(id_param["in"], "path", "parameter in must be path");
        assert_eq!(
            id_param["required"], true,
            "path parameter must be required"
        );
        assert_eq!(
            id_param["schema"]["type"], "integer",
            "schema type must be integer"
        );
        assert_eq!(
            id_param["schema"]["format"], "uint64",
            "schema format must be uint64"
        );
    }

    // ========================================================================
    // forge-success-status-code: OpenAPI response code generation tests
    // ========================================================================

    /// `OpenApiRouteInfo::new()` should default `success_status` to `None`.
    #[test]
    fn new_defaults_success_status_to_none() {
        let info = OpenApiRouteInfo::new("/x", "GET", "s", "d", "v1", &[]);
        assert!(
            info.success_status.is_none(),
            "new() must default success_status to None"
        );
    }

    /// `OpenApiRouteInfo::with_path_params()` should default `success_status`
    /// to `None` (backward-compatible with pre-status-code routes).
    #[test]
    fn with_path_params_defaults_success_status_to_none() {
        const PARAMS: &[OpenApiPathParam] =
            &[OpenApiPathParam::new("id", "", true, "integer", "uint64")];
        const INFO: OpenApiRouteInfo =
            OpenApiRouteInfo::with_path_params("/x/{id}", "GET", "s", "d", "v1", &[], PARAMS);
        assert!(
            INFO.success_status.is_none(),
            "with_path_params must default success_status to None"
        );
    }

    /// `OpenApiRouteInfo::with_path_params_and_status()` should store the
    /// provided `success_status`.
    #[test]
    fn with_path_params_and_status_stores_status() {
        const PARAMS: &[OpenApiPathParam] = &[];
        const INFO: OpenApiRouteInfo = OpenApiRouteInfo::with_path_params_and_status(
            "/create",
            "POST",
            "s",
            "d",
            "v1",
            &[],
            PARAMS,
            Some(201u16),
        );
        assert_eq!(
            INFO.success_status,
            Some(201),
            "with_path_params_and_status must store success_status"
        );
    }

    /// `with_path_params_and_status()` with `None` should behave like
    /// `with_path_params()` (backward-compatible default).
    #[test]
    fn with_path_params_and_status_none_is_default() {
        const INFO: OpenApiRouteInfo = OpenApiRouteInfo::with_path_params_and_status(
            "/x",
            "GET",
            "s",
            "d",
            "v1",
            &[],
            &[],
            None,
        );
        assert!(INFO.success_status.is_none());
    }

    /// R-openapi-generation-001: `#[forge(status = 201)]` should produce an
    /// OpenAPI spec where the route's `responses` object contains a `"201"`
    /// key (not `"200"`).
    ///
    /// Uses the test-only route `/__openapi_status_201_test__` registered
    /// above with `success_status: Some(201)`.
    #[test]
    fn generated_spec_contains_201_response_for_status_route() {
        let spec = generate_openapi_spec();
        let paths_json = serde_json::to_value(&spec.paths).expect("paths serialize");
        let paths_obj = paths_json
            .as_object()
            .expect("paths is a JSON object")
            .clone();
        let route_key = "/__openapi_status_201_test__";
        let route = paths_obj
            .get(route_key)
            .unwrap_or_else(|| panic!("expected route {} in paths", route_key));
        let post_op = route
            .get("post")
            .unwrap_or_else(|| panic!("expected POST operation on {}", route_key));
        let responses = post_op
            .get("responses")
            .unwrap_or_else(|| panic!("expected responses object on {}", route_key));
        assert!(
            responses.get("201").is_some(),
            "expected \"201\" response key on {}, got: {}",
            route_key,
            serde_json::to_string_pretty(&responses).unwrap()
        );
        assert!(
            responses.get("200").is_none(),
            "must NOT have \"200\" response key when status=201 is declared, got: {}",
            serde_json::to_string_pretty(&responses).unwrap()
        );
    }

    /// R-openapi-generation-002: Routes without `status` should produce a
    /// `"200"` response key (backward-compatible with pre-change behavior).
    ///
    /// Uses the test-only route `/__openapi_test_marker__` registered above
    /// with default `success_status: None`.
    #[test]
    fn generated_spec_contains_200_response_for_default_route() {
        let spec = generate_openapi_spec();
        let paths_json = serde_json::to_value(&spec.paths).expect("paths serialize");
        let paths_obj = paths_json
            .as_object()
            .expect("paths is a JSON object")
            .clone();
        let route_key = "/__openapi_test_marker__";
        let route = paths_obj
            .get(route_key)
            .unwrap_or_else(|| panic!("expected route {} in paths", route_key));
        let get_op = route
            .get("get")
            .unwrap_or_else(|| panic!("expected GET operation on {}", route_key));
        let responses = get_op
            .get("responses")
            .unwrap_or_else(|| panic!("expected responses object on {}", route_key));
        assert!(
            responses.get("200").is_some(),
            "expected \"200\" response key on {} (default), got: {}",
            route_key,
            serde_json::to_string_pretty(&responses).unwrap()
        );
    }
}