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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
use super::*;
use utoipa::openapi::path::{
HttpMethod, OperationBuilder, Parameter, ParameterBuilder, ParameterIn, Paths,
};
use utoipa::openapi::response::ResponseBuilder;
use utoipa::openapi::schema::{ObjectBuilder, SchemaFormat, SchemaType, Type};
use utoipa::openapi::{Info, InfoBuilder, OpenApi, Required};
impl OpenApiPathParam {
/// Construct a new path parameter descriptor.
pub const fn new(
name: &'static str,
description: &'static str,
required: bool,
schema_type: &'static str,
schema_format: &'static str,
) -> Self {
Self {
name,
description,
required,
schema_type,
schema_format,
}
}
/// Build a utoipa [`Parameter`] from this static descriptor.
///
/// Path parameters are always marked `Required::True` regardless of the
/// `required` field, per the OpenAPI specification (path params MUST be
/// required).
pub fn to_parameter(&self) -> Parameter {
let schema_type = match self.schema_type {
"integer" => SchemaType::Type(Type::Integer),
"number" => SchemaType::Type(Type::Number),
"boolean" => SchemaType::Type(Type::Boolean),
"string" => SchemaType::Type(Type::String),
_ => SchemaType::Type(Type::String),
};
let format = if self.schema_format.is_empty() {
None
} else {
Some(SchemaFormat::Custom(self.schema_format.to_string()))
};
let schema = ObjectBuilder::new()
.schema_type(schema_type)
.format(format)
.build();
let desc = if self.description.is_empty() {
None
} else {
Some(self.description.to_string())
};
ParameterBuilder::new()
.name(self.name)
.parameter_in(ParameterIn::Path)
.required(Required::True)
.description(desc)
.schema(Some(schema))
.build()
}
}
impl OpenApiRouteInfo {
/// Construct a new route info entry with no path parameters. Used by
/// manual `inventory::submit!` calls and tests.
pub const fn new(
path: &'static str,
method: &'static str,
summary: &'static str,
description: &'static str,
version: &'static str,
tags: &'static [&'static str],
) -> Self {
Self {
path,
method,
summary,
description,
version,
tags,
path_params: &[],
success_status: None,
}
}
/// Construct a new route info entry with explicit path parameters.
/// Used by the `#[forge]` macro to pass auto-extracted path
/// params (name + schema type/format derived from the Rust handler
/// signature).
pub const fn with_path_params(
path: &'static str,
method: &'static str,
summary: &'static str,
description: &'static str,
version: &'static str,
tags: &'static [&'static str],
path_params: &'static [OpenApiPathParam],
) -> Self {
Self {
path,
method,
summary,
description,
version,
tags,
path_params,
success_status: None,
}
}
/// Construct a new route info entry with path parameters and an explicit
/// success status code (from `#[forge(status = <code>)]`).
///
/// When `success_status` is `Some(code)`, the OpenAPI response key uses
/// that code (e.g. `"201"`) instead of the default `"200"`.
//
// All 8 parameters map 1:1 to `OpenApiRouteInfo` fields. This is a `const
// fn` invoked from macro-generated `inventory::submit!` call sites (see
// `macros/src/lib.rs`) and const-context tests, where a builder or params
// struct cannot be used. Refactoring to a struct parameter would change the
// public API and require regenerating the proc-macro call sites, so the
// argument count is accepted here.
#[allow(clippy::too_many_arguments)]
pub const fn with_path_params_and_status(
path: &'static str,
method: &'static str,
summary: &'static str,
description: &'static str,
version: &'static str,
tags: &'static [&'static str],
path_params: &'static [OpenApiPathParam],
success_status: Option<u16>,
) -> Self {
Self {
path,
method,
summary,
description,
version,
tags,
path_params,
success_status,
}
}
/// Map the string method to utoipa's [`HttpMethod`] enum.
///
/// Unknown methods fall back to [`HttpMethod::Get`] to keep the spec valid;
/// callers are expected to use canonical uppercase method names.
pub fn http_method(&self) -> HttpMethod {
match self.method.to_ascii_uppercase().as_str() {
"GET" => HttpMethod::Get,
"POST" => HttpMethod::Post,
"PUT" => HttpMethod::Put,
"DELETE" => HttpMethod::Delete,
"PATCH" => HttpMethod::Patch,
"HEAD" => HttpMethod::Head,
"OPTIONS" => HttpMethod::Options,
"TRACE" => HttpMethod::Trace,
_ => HttpMethod::Get,
}
}
}
impl OpenApiBuilder {
/// Create a new builder with empty fields.
pub fn new() -> Self {
Self::default()
}
/// Set the API title. Chainable.
pub fn title<S: Into<String>>(mut self, title: S) -> Self {
self.title = title.into();
self
}
/// Set the API version. Chainable.
pub fn version<S: Into<String>>(mut self, version: S) -> Self {
self.version = version.into();
self
}
/// Set the optional API description. Chainable.
pub fn description<S: Into<String>>(mut self, description: S) -> Self {
self.description = Some(description.into());
self
}
/// Build the final [`OpenApi`] spec, collecting all registered routes from
/// the `inventory` registry.
///
/// Each registered [`OpenApiRouteInfo`] becomes a path operation with its
/// `summary`, `description`, `tags`, a synthesized `operation_id` of the
/// form `{version}_{path}`, and one [`Parameter`] per entry in
/// [`OpenApiRouteInfo::path_params`] (auto-extracted path parameters with
/// name/in(path)/required/schema).
pub fn build(&self) -> OpenApi {
let mut info_builder = InfoBuilder::new()
.title(self.title.clone())
.version(self.version.clone());
if let Some(desc) = &self.description {
info_builder = info_builder.description(Some(desc.clone()));
}
let info: Info = info_builder.build();
let mut paths = Paths::new();
for route in inventory::iter::<OpenApiRouteInfo> {
// Translate description at runtime using i18n registry.
// OpenApiRouteInfo doesn't carry i18n_key directly; the
// translation is keyed by description content when the
// route was generated from a #[forge] macro with i18n_key.
// For now, the English default is used (OpenAPI specs are
// typically generated once at build time, not per-request).
let mut operation_builder = OperationBuilder::new()
.summary(Some(route.summary.to_string()))
.description(Some(route.description.to_string()))
.tags(Some(
route
.tags
.iter()
.map(|t| (*t).to_string())
.collect::<Vec<_>>(),
))
.operation_id(Some(format!("{}_{}", route.version, route.path)));
for param in route.path_params {
operation_builder = operation_builder.parameter(param.to_parameter());
}
// forge-success-status-code: emit a response entry keyed by the
// declared success status (from `#[forge(status = <code>)]`) or
// default `200` when not specified. This makes the OpenAPI doc
// accurately reflect the HTTP success code clients will receive.
let status_code = route.success_status.unwrap_or(200);
let response = ResponseBuilder::new()
.description("Successful response")
.build();
operation_builder = operation_builder.response(status_code.to_string(), response);
let operation = operation_builder.build();
paths.add_path_operation(route.path, vec![route.http_method()], operation);
}
OpenApi::new(info, paths)
}
}
/// Generate a complete OpenAPI spec from all registered routes.
///
/// Uses the default title `"SDForge API"` and the crate version. For custom
/// metadata use [`OpenApiBuilder`] directly.
pub fn generate_openapi_spec() -> OpenApi {
OpenApiBuilder::new()
.title("SDForge API")
.version(env!("CARGO_PKG_VERSION"))
.build()
}