toolkit/api/operation_builder.rs
1// Updated: 2026-04-28 by Constructor Tech
2//! Type-safe API operation builder with compile-time guarantees
3//!
4//! This gear implements a type-state builder pattern that ensures:
5//! - `register()` cannot be called unless a handler is set
6//! - `register()` cannot be called unless at least one response is declared
7//! - Descriptive methods remain available at any stage
8//! - No panics or unwraps in production hot paths
9//! - Request body support (`json_request`, `json_request_schema`) so POST/PUT calls are invokable in UI
10//! - Schema-aware responses (`json_response_with_schema`)
11//! - Typed Router state `S` usage pattern: pass a state type once via `Router::with_state`,
12//! then use plain function handlers (no per-route closures that capture/clones).
13//! - Optional `method_router(...)` for advanced use (layers/middleware on route level).
14
15use crate::api::api_dto;
16use axum::{Router, handler::Handler, routing::MethodRouter};
17use http::Method;
18use serde::{Deserialize, Serialize};
19use std::collections::BTreeMap;
20use std::marker::PhantomData;
21use toolkit_canonical_errors::problem;
22use toolkit_gts::gts_id;
23
24/// Convert OpenAPI-style path placeholders to Axum 0.8+ style path parameters.
25///
26/// Axum 0.8+ uses `{id}` for path parameters and `{*path}` for wildcards, which is the same as `OpenAPI`.
27/// However, `OpenAPI` wildcards are just `{path}` without the asterisk.
28/// This function converts `OpenAPI` wildcards to Axum wildcards by detecting common wildcard names.
29///
30/// # Examples
31///
32/// ```
33/// # use toolkit::api::operation_builder::normalize_to_axum_path;
34/// assert_eq!(normalize_to_axum_path("/users/{id}"), "/users/{id}");
35/// assert_eq!(normalize_to_axum_path("/projects/{project_id}/items/{item_id}"), "/projects/{project_id}/items/{item_id}");
36/// // Note: Most paths don't need normalization in Axum 0.8+
37/// ```
38#[must_use]
39pub fn normalize_to_axum_path(path: &str) -> String {
40 // In Axum 0.8+, the path syntax is {param} for parameters and {*wildcard} for wildcards
41 // which is the same as OpenAPI except wildcards need the asterisk prefix.
42 // For now, we just pass through the path as-is since OpenAPI and Axum 0.8 use the same syntax
43 // for regular parameters. Wildcards need special handling if used.
44 path.to_owned()
45}
46
47/// Convert Axum 0.8+ style path parameters to OpenAPI-style placeholders.
48///
49/// Removes the asterisk prefix from Axum wildcards `{*path}` to make them OpenAPI-compatible `{path}`.
50///
51/// # Examples
52///
53/// ```
54/// # use toolkit::api::operation_builder::axum_to_openapi_path;
55/// assert_eq!(axum_to_openapi_path("/users/{id}"), "/users/{id}");
56/// assert_eq!(axum_to_openapi_path("/static/{*path}"), "/static/{path}");
57/// ```
58#[must_use]
59pub fn axum_to_openapi_path(path: &str) -> String {
60 // In Axum 0.8+, wildcards are {*name} but OpenAPI expects {name}
61 // Regular parameters are the same in both
62 path.replace("{*", "{")
63}
64
65/// Canonical base license feature used by the example gears.
66pub const CORE_GLOBAL_BASE_LICENSE_FEATURE: &str =
67 gts_id!("cf.core.lic.feat.v1~cf.core.global.base.v1");
68
69/// Type-state markers for compile-time enforcement
70pub mod state {
71 /// Marker for missing required components
72 #[derive(Debug, Clone, Copy)]
73 pub struct Missing;
74
75 /// Marker for present required components
76 #[derive(Debug, Clone, Copy)]
77 pub struct Present;
78
79 /// Marker for auth requirement not yet set
80 #[derive(Debug, Clone, Copy)]
81 pub struct AuthNotSet;
82
83 /// Marker for auth requirement set (either `authenticated` or public)
84 #[derive(Debug, Clone, Copy)]
85 pub struct AuthSet;
86
87 /// Marker for license requirement not yet set
88 #[derive(Debug, Clone, Copy)]
89 pub struct LicenseNotSet;
90
91 /// Marker for license requirement set
92 #[derive(Debug, Clone, Copy)]
93 pub struct LicenseSet;
94}
95
96/// Internal trait mapping handler state to the concrete router slot type.
97/// For `Missing` there is no router slot; for `Present` it is `MethodRouter<S>`.
98/// Private sealed trait to enforce the implementation is only visible within this gear.
99mod sealed {
100 pub trait Sealed {}
101 pub trait SealedAuth {}
102 pub trait SealedLicenseReq {}
103}
104
105pub trait HandlerSlot<S>: sealed::Sealed {
106 type Slot;
107}
108
109/// Sealed trait for auth state markers
110pub trait AuthState: sealed::SealedAuth {}
111
112impl sealed::Sealed for Missing {}
113impl sealed::Sealed for Present {}
114
115impl sealed::SealedAuth for state::AuthNotSet {}
116impl sealed::SealedAuth for state::AuthSet {}
117
118impl AuthState for state::AuthNotSet {}
119impl AuthState for state::AuthSet {}
120
121pub trait LicenseState: sealed::SealedLicenseReq {}
122
123impl sealed::SealedLicenseReq for state::LicenseNotSet {}
124impl sealed::SealedLicenseReq for state::LicenseSet {}
125
126impl LicenseState for state::LicenseNotSet {}
127impl LicenseState for state::LicenseSet {}
128
129impl<S> HandlerSlot<S> for Missing {
130 type Slot = ();
131}
132impl<S> HandlerSlot<S> for Present {
133 type Slot = MethodRouter<S>;
134}
135
136pub use state::{AuthNotSet, AuthSet, LicenseNotSet, LicenseSet, Missing, Present};
137
138/// Parameter specification built with location constructors and fluent setters.
139/// `#[non_exhaustive]` allows new schema keywords without changing call sites.
140///
141/// ```
142/// # use toolkit::api::operation_builder::{ParamLocation, ParamSpec};
143/// let version = ParamSpec::query("expected_resource_version")
144/// .required(true)
145/// .param_type("integer")
146/// .format("int64")
147/// .minimum(1.0);
148/// assert_eq!(version.location, ParamLocation::Query);
149/// assert_eq!(version.format.as_deref(), Some("int64"));
150/// ```
151#[derive(Clone, Debug)]
152#[non_exhaustive]
153pub struct ParamSpec {
154 pub name: String,
155 pub location: ParamLocation,
156 pub required: bool,
157 pub description: Option<String>,
158 pub param_type: String, // JSON Schema type (string, integer, etc.)
159 /// Whether the parameter repeats. When set, `param_type` describes the
160 /// *item* type and the parameter renders as `type: array` with
161 /// `style: form, explode: true` — i.e. `?tag=a&tag=b`, which is how the
162 /// generated REST client encodes a `Vec<T>` query field.
163 pub array: bool,
164 /// Optional JSON Schema format token, kept independent of `utoipa` types.
165 pub format: Option<String>,
166 /// Optional JSON Schema `minimum`.
167 pub minimum: Option<f64>,
168 /// The only values this parameter accepts, rendered as the schema's
169 /// `enum`. Empty means any value of `param_type` will do.
170 pub enum_values: Vec<String>,
171}
172
173impl ParamSpec {
174 /// A required path parameter — `string` unless [`Self::param_type`] says
175 /// otherwise.
176 #[must_use]
177 pub fn path(name: impl Into<String>) -> Self {
178 Self::new(name, ParamLocation::Path, true)
179 }
180
181 /// An optional query parameter.
182 #[must_use]
183 pub fn query(name: impl Into<String>) -> Self {
184 Self::new(name, ParamLocation::Query, false)
185 }
186
187 /// An optional header parameter.
188 #[must_use]
189 pub fn header(name: impl Into<String>) -> Self {
190 Self::new(name, ParamLocation::Header, false)
191 }
192
193 /// An optional cookie parameter.
194 #[must_use]
195 pub fn cookie(name: impl Into<String>) -> Self {
196 Self::new(name, ParamLocation::Cookie, false)
197 }
198
199 fn new(name: impl Into<String>, location: ParamLocation, required: bool) -> Self {
200 Self {
201 name: name.into(),
202 location,
203 required,
204 description: None,
205 param_type: "string".to_owned(),
206 array: false,
207 format: None,
208 minimum: None,
209 enum_values: Vec::new(),
210 }
211 }
212
213 /// Whether the caller must send this parameter; path parameters are always required.
214 #[must_use]
215 pub fn required(mut self, required: bool) -> Self {
216 self.required = required;
217 self
218 }
219
220 /// The closed set of values this parameter accepts.
221 ///
222 /// They reach the document as the schema's `enum`, so a client generated
223 /// from the spec gets the set rather than a bare string, and a caller
224 /// reading the document can see what the endpoint takes without trying a
225 /// value to find out.
226 #[must_use]
227 pub fn enum_values<V, I>(mut self, values: I) -> Self
228 where
229 I: IntoIterator<Item = V>,
230 V: AsRef<str>,
231 {
232 self.enum_values = values
233 .into_iter()
234 .map(|value| value.as_ref().to_owned())
235 .collect();
236 self
237 }
238
239 /// The description a generated client's documentation carries.
240 #[must_use]
241 pub fn description(mut self, description: impl Into<String>) -> Self {
242 self.description = Some(description.into());
243 self
244 }
245
246 /// JSON Schema type, or item type for arrays.
247 #[must_use]
248 pub fn param_type(mut self, param_type: impl Into<String>) -> Self {
249 self.param_type = param_type.into();
250 self
251 }
252
253 /// Whether the parameter repeats — see [`Self::array`](#structfield.array).
254 #[must_use]
255 pub fn array(mut self, array: bool) -> Self {
256 self.array = array;
257 self
258 }
259
260 /// The JSON Schema `format` token, e.g. `int64`.
261 #[must_use]
262 pub fn format(mut self, format: impl Into<String>) -> Self {
263 self.format = Some(format.into());
264 self
265 }
266
267 /// The JSON Schema `minimum`.
268 #[must_use]
269 pub fn minimum(mut self, minimum: f64) -> Self {
270 self.minimum = Some(minimum);
271 self
272 }
273}
274
275pub trait LicenseFeature: AsRef<str> {}
276
277impl<T: LicenseFeature + ?Sized> LicenseFeature for &T {}
278
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub enum ParamLocation {
281 Path,
282 Query,
283 Header,
284 Cookie,
285}
286
287/// Request body schema variants for different kinds of request bodies
288#[derive(Clone, Debug, PartialEq, Eq)]
289pub enum RequestBodySchema {
290 /// Reference to a component schema in `#/components/schemas/{schema_name}`
291 Ref { schema_name: String },
292 /// Multipart form with a single file field
293 MultipartFile { field_name: String },
294 /// Raw binary body (e.g. application/octet-stream), represented as
295 /// type: string, format: binary in `OpenAPI`.
296 Binary,
297 /// A generic inline object schema with no predefined properties
298 InlineObject,
299}
300
301/// Request body specification for API operations
302#[derive(Clone, Debug)]
303pub struct RequestBodySpec {
304 pub content_type: &'static str,
305 pub description: Option<String>,
306 /// The schema for this request body
307 pub schema: RequestBodySchema,
308 /// Whether request body is required (`OpenAPI` default is `false`).
309 pub required: bool,
310}
311
312/// Response body schema variants.
313///
314/// Mirrors [`RequestBodySchema`]. `Array` exists because utoipa's default
315/// `ToSchema::name()` strips generic arguments, so `Vec<A>` and `Vec<B>` both
316/// resolve to the component name `Vec` and clobber each other in
317/// `components.schemas`. A top-level array is therefore emitted **inline** —
318/// `{type: array, items: {$ref: T}}` — registering only the item type as a
319/// named component. That is both the `OpenAPI` norm and what utoipa's own
320/// `#[utoipa::path]` produces for a `Vec<T>` body.
321#[derive(Clone, Debug, PartialEq, Eq)]
322pub enum ResponseSchema {
323 /// Reference to a component schema in `#/components/schemas/{schema_name}`
324 Ref { schema_name: String },
325 /// Inline array whose items `$ref` the named item component.
326 Array { items_schema_name: String },
327}
328
329impl ResponseSchema {
330 /// The component name this response ultimately references: the type itself
331 /// for [`Self::Ref`], the item type for [`Self::Array`].
332 #[must_use]
333 pub fn schema_name(&self) -> &str {
334 match self {
335 Self::Ref { schema_name } => schema_name,
336 Self::Array { items_schema_name } => items_schema_name,
337 }
338 }
339}
340
341/// Response specification for API operations
342#[non_exhaustive]
343#[derive(Clone, Debug)]
344pub struct ResponseSpec {
345 pub status: u16,
346 pub content_type: &'static str,
347 pub description: String,
348 /// Schema of the response body (if any).
349 pub schema: Option<ResponseSchema>,
350 /// Headers that may be returned with this response.
351 pub headers: Vec<ResponseHeaderSpec>,
352}
353
354impl ResponseSpec {
355 /// Create a response specification without declared headers.
356 #[must_use]
357 pub fn new(
358 status: u16,
359 content_type: &'static str,
360 description: impl Into<String>,
361 schema: Option<ResponseSchema>,
362 ) -> Self {
363 Self {
364 status,
365 content_type,
366 description: description.into(),
367 schema,
368 headers: Vec::new(),
369 }
370 }
371
372 /// Add headers to this response specification.
373 ///
374 /// # Panics
375 /// Panics when the response already has, or the supplied headers contain,
376 /// a header with the same case-insensitive name.
377 #[must_use]
378 pub fn with_headers(mut self, headers: impl IntoIterator<Item = ResponseHeaderSpec>) -> Self {
379 let headers: Vec<_> = headers.into_iter().collect();
380 for (index, header) in headers.iter().enumerate() {
381 assert!(
382 !self
383 .headers
384 .iter()
385 .chain(headers[..index].iter())
386 .any(|existing| existing.name.eq_ignore_ascii_case(&header.name)),
387 "response {} already declares header '{}'",
388 self.status,
389 header.name
390 );
391 }
392 self.headers.extend(headers);
393 self
394 }
395
396 /// Name of the component schema this response references, if any.
397 ///
398 /// For an array response this is the **item** component, not the array.
399 #[must_use]
400 pub fn schema_name(&self) -> Option<&str> {
401 self.schema.as_ref().map(ResponseSchema::schema_name)
402 }
403}
404
405/// JSON Schema scalar type of a response header.
406#[non_exhaustive]
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum ResponseHeaderType {
409 String,
410 Integer,
411 Boolean,
412}
413
414/// Header declared on one API response.
415#[non_exhaustive]
416#[derive(Clone, Debug, PartialEq, Eq)]
417pub struct ResponseHeaderSpec {
418 pub name: String,
419 pub description: Option<String>,
420 pub header_type: ResponseHeaderType,
421}
422
423impl ResponseHeaderSpec {
424 /// Create a response header with a description.
425 #[must_use]
426 pub fn new(
427 name: impl Into<String>,
428 description: impl Into<String>,
429 header_type: ResponseHeaderType,
430 ) -> Self {
431 Self {
432 name: name.into(),
433 description: Some(description.into()),
434 header_type,
435 }
436 }
437
438 /// Create a response header without a description.
439 #[must_use]
440 pub fn without_description(name: impl Into<String>, header_type: ResponseHeaderType) -> Self {
441 Self {
442 name: name.into(),
443 description: None,
444 header_type,
445 }
446 }
447}
448
449/// License requirement specification for an operation
450#[derive(Clone, Debug)]
451pub struct LicenseReqSpec {
452 pub license_names: Vec<String>,
453}
454
455/// Name of the platform `OpenAPI` apiKey scheme.
456pub use super::openapi_registry::INTERNAL_TOKEN_SECURITY_SCHEME;
457
458/// Per-route credential requirement, shared with listeners and the gateway.
459pub use toolkit_security::RouteAuth;
460
461/// Simplified operation specification for the type-safe builder
462#[derive(Clone, Debug)]
463pub struct OperationSpec {
464 pub method: Method,
465 pub path: String,
466 pub operation_id: Option<String>,
467 pub summary: Option<String>,
468 pub description: Option<String>,
469 pub tags: Vec<String>,
470 pub params: Vec<ParamSpec>,
471 pub request_body: Option<RequestBodySpec>,
472 pub responses: Vec<ResponseSpec>,
473 /// Internal handler id; can be used by registry/generator to map a handler identity
474 pub handler_id: String,
475 /// Auth axis: which credential this operation requires. Set by the builder's
476 /// `.authenticated()`, `.anonymous()` or `.platform_authenticated()`. Independent of
477 /// [`exposed`](Self::exposed).
478 pub auth: RouteAuth,
479 /// Visibility axis: whether this route is registered in the gateway for
480 /// external access (`true`) or is internal-only, reachable only via
481 /// inter-gear communication (`false`). Defaults to `false` (internal).
482 /// Independent of [`auth`](Self::auth) — an exposed route may still require a JWT.
483 pub exposed: bool,
484 /// Optional zone-based throttling configuration for this operation.
485 /// Binds the operation to gateway throttling zones and carries the
486 /// `require_security_context` / `dry_run` flags. Zone keying is decided by
487 /// the zone config, not here.
488 pub throttling: Option<ThrottlingSpec>,
489 /// Optional whitelist of allowed request Content-Type values (without parameters).
490 /// Example: Some(vec!["application/json", "multipart/form-data", "application/pdf"])
491 /// When set, gateway middleware will enforce these types and return HTTP 415 for
492 /// requests with disallowed Content-Type headers. This is independent of the
493 /// request body schema and should not be used to create synthetic request bodies.
494 pub allowed_request_content_types: Option<Vec<&'static str>>,
495 /// `OpenAPI` vendor extensions (x-*)
496 pub vendor_extensions: VendorExtensions,
497 pub license_requirement: Option<LicenseReqSpec>,
498}
499
500impl OperationSpec {
501 /// Replace a response with the same status and content type while retaining
502 /// headers that were already declared for that response. The declared
503 /// response becomes the most recent response so subsequent headers attach
504 /// to it.
505 ///
506 /// Different content types for the same status are kept as separate specs;
507 /// the `OpenAPI` registry combines them into one response object.
508 fn upsert_response(&mut self, mut response: ResponseSpec) {
509 let Some(index) = self.responses.iter().position(|existing| {
510 existing.status == response.status && existing.content_type == response.content_type
511 }) else {
512 self.responses.push(response);
513 return;
514 };
515
516 let mut existing = self.responses.remove(index);
517 response.headers.append(&mut existing.headers);
518 self.responses.push(response);
519 }
520}
521
522#[derive(Clone, Debug, Default, Deserialize, Serialize)]
523pub struct VendorExtensions {
524 #[serde(rename = "x-odata-filter", skip_serializing_if = "Option::is_none")]
525 pub x_odata_filter: Option<ODataPagination<BTreeMap<String, Vec<String>>>>,
526 #[serde(rename = "x-odata-orderby", skip_serializing_if = "Option::is_none")]
527 pub x_odata_orderby: Option<ODataPagination<Vec<String>>>,
528}
529
530#[derive(Clone, Debug, Default, Deserialize, Serialize)]
531pub struct ODataPagination<T> {
532 #[serde(rename = "allowedFields")]
533 pub allowed_fields: T,
534}
535
536/// Per-operation throttling specification.
537///
538/// References throttling zones (defined in the API gateway configuration) by
539/// name. Limits themselves live in config (zones are the primary source of
540/// truth); this struct only binds an operation to zones and provides the
541/// code-side behavior that config cannot express.
542#[derive(Clone, Debug, Default)]
543pub struct ThrottlingSpec {
544 /// Name of the rate-limit zone this operation participates in, or `None`
545 /// when the operation is not rate-limited.
546 pub rate_limit_zone: Option<String>,
547 /// Name of the in-flight-limit zone this operation participates in, or
548 /// `None` when the operation has no in-flight limit.
549 pub in_flight_limit_zone: Option<String>,
550 /// Whether this operation's throttling must run after authentication
551 /// (so the identity validated by the operation's auth plane is available).
552 ///
553 /// - `false` (default): the operation is throttled *before* auth, using
554 /// IP-keyed zones only.
555 /// - `true`: the operation is throttled *after* auth, allowing
556 /// identity-keyed zones: keyed by the tenant subject id on an
557 /// `.authenticated()` operation, or by the calling workload on a
558 /// `.platform_authenticated()` one.
559 pub require_security_context: bool,
560 /// Observe-but-don't-enforce mode.
561 ///
562 /// - `false` (default): limits are enforced normally (over-limit requests
563 /// are rejected).
564 /// - `true`: requests are never rejected by this operation's rate-limit or
565 /// in-flight limits. Instead, whenever a limit *would* have triggered, the
566 /// gateway emits a `warn` log (with the offending key) and serves the
567 /// request. Useful for tuning zones before enabling enforcement.
568 pub dry_run: bool,
569}
570
571#[derive(Clone, Debug, Deserialize, Serialize, Default)]
572#[serde(rename_all = "camelCase")]
573pub struct XPagination {
574 pub filter_fields: BTreeMap<String, Vec<String>>,
575 pub order_by: Vec<String>,
576}
577
578//
579pub trait OperationBuilderODataExt<S, H, R> {
580 /// Adds optional `$filter` query parameter to `OpenAPI`.
581 ///
582 /// # Panics
583 /// Panics when a field's `published_ops` is empty, repeats an operator,
584 /// or names one its kind does not allow (see
585 /// `toolkit_odata::filter::published_ops_error`).
586 #[must_use]
587 fn with_odata_filter<T>(self) -> Self
588 where
589 T: toolkit_odata::filter::FilterField;
590
591 /// Adds optional `$select` query parameter to `OpenAPI`.
592 #[must_use]
593 fn with_odata_select(self) -> Self;
594
595 /// Adds optional `$orderby` query parameter to `OpenAPI`.
596 #[must_use]
597 fn with_odata_orderby<T>(self) -> Self
598 where
599 T: toolkit_odata::filter::FilterField;
600}
601
602impl<S, H, R, A, L> OperationBuilderODataExt<S, H, R> for OperationBuilder<H, R, S, A, L>
603where
604 H: HandlerSlot<S>,
605 A: AuthState,
606 L: LicenseState,
607{
608 fn with_odata_filter<T>(mut self) -> Self
609 where
610 T: toolkit_odata::filter::FilterField,
611 {
612 use std::fmt::Write as _;
613 use toolkit_odata::filter::{FilterOp, published_ops_error};
614
615 // A field's list is a declaration; a wrong one is a bug at the
616 // declaring site, not a contract to publish narrowed.
617 if let Some(error) = published_ops_error::<T>() {
618 panic!(
619 "{} declares an invalid published_ops: {error}",
620 self.spec.path
621 );
622 }
623
624 let mut filter = self
625 .spec
626 .vendor_extensions
627 .x_odata_filter
628 .unwrap_or_default();
629
630 let mut description = "OData v4 filter expression".to_owned();
631 for field in T::FIELDS {
632 let name = field.name().to_owned();
633 let kind = field.kind();
634
635 // Published from the parser's own table, unless the field names the
636 // operators it serves; `parse_odata_filter` refuses the rest, so the
637 // contract and the parser hold to one set.
638 let ops: Vec<String> = match field.published_ops() {
639 Some(ops) => ops.iter().map(ToString::to_string).collect(),
640 None => [
641 FilterOp::Eq,
642 FilterOp::Ne,
643 FilterOp::Gt,
644 FilterOp::Ge,
645 FilterOp::Lt,
646 FilterOp::Le,
647 FilterOp::Contains,
648 FilterOp::StartsWith,
649 FilterOp::EndsWith,
650 FilterOp::In,
651 ]
652 .into_iter()
653 .filter(|op| kind.allows(*op))
654 .map(|op| op.to_string())
655 .collect(),
656 };
657
658 _ = write!(description, "\n- {}: {}", name, ops.join("|"));
659 filter.allowed_fields.insert(name.clone(), ops);
660 }
661 self.spec
662 .params
663 .push(ParamSpec::query("$filter").description(description));
664 self.spec.vendor_extensions.x_odata_filter = Some(filter);
665 self
666 }
667
668 fn with_odata_select(mut self) -> Self {
669 self.spec
670 .params
671 .push(ParamSpec::query("$select").description("OData v4 select expression"));
672 self
673 }
674
675 fn with_odata_orderby<T>(mut self) -> Self
676 where
677 T: toolkit_odata::filter::FilterField,
678 {
679 use std::fmt::Write as _;
680 let mut order_by = self
681 .spec
682 .vendor_extensions
683 .x_odata_orderby
684 .unwrap_or_default();
685 let mut description = "OData v4 orderby expression".to_owned();
686 for field in T::FIELDS {
687 let name = field.name().to_owned();
688
689 // Add sort options (asc/desc)
690 let asc = format!("{name} asc");
691 let desc = format!("{name} desc");
692
693 _ = write!(description, "\n- {asc}\n- {desc}");
694 if !order_by.allowed_fields.contains(&asc) {
695 order_by.allowed_fields.push(asc);
696 }
697 if !order_by.allowed_fields.contains(&desc) {
698 order_by.allowed_fields.push(desc);
699 }
700 }
701 self.spec
702 .params
703 .push(ParamSpec::query("$orderby").description(description));
704 self.spec.vendor_extensions.x_odata_orderby = Some(order_by);
705 self
706 }
707}
708
709// Re-export from openapi_registry for backward compatibility
710pub use crate::api::openapi_registry::{OpenApiRegistry, ensure_schema};
711
712/// Type-safe operation builder with compile-time guarantees.
713///
714/// Generic parameters:
715/// - `H`: Handler state (Missing | Present)
716/// - `R`: Response state (Missing | Present)
717/// - `S`: Router state type (what you put into `Router::with_state(S)`).
718/// - `A`: Auth state (`AuthNotSet` | `AuthSet`)
719/// - `L`: License requirement state (`LicenseNotSet` | `LicenseSet`)
720#[must_use]
721pub struct OperationBuilder<H = Missing, R = Missing, S = (), A = AuthNotSet, L = LicenseNotSet>
722where
723 H: HandlerSlot<S>,
724 A: AuthState,
725 L: LicenseState,
726{
727 spec: OperationSpec,
728 method_router: <H as HandlerSlot<S>>::Slot,
729 _has_handler: PhantomData<H>,
730 _has_response: PhantomData<R>,
731 #[allow(clippy::type_complexity)]
732 _state: PhantomData<fn() -> S>, // Zero-sized marker for type-state pattern
733 _auth_state: PhantomData<A>,
734 _license_state: PhantomData<L>,
735}
736
737// -------------------------------------------------------------------------------------------------
738// Constructors — starts with both handler and response missing, auth not set
739// -------------------------------------------------------------------------------------------------
740impl<S> OperationBuilder<Missing, Missing, S, AuthNotSet> {
741 /// Create a new operation builder with an HTTP method and path
742 pub fn new(method: Method, path: impl Into<String>) -> Self {
743 let path_str = path.into();
744 let handler_id = format!(
745 "{}:{}",
746 method.as_str().to_lowercase(),
747 path_str.replace(['/', '{', '}'], "_")
748 );
749
750 Self {
751 spec: OperationSpec {
752 method,
753 path: path_str,
754 operation_id: None,
755 summary: None,
756 description: None,
757 tags: Vec::new(),
758 params: Vec::new(),
759 request_body: None,
760 responses: Vec::new(),
761 handler_id,
762 auth: RouteAuth::Anonymous,
763 exposed: false,
764 throttling: None,
765 allowed_request_content_types: None,
766 vendor_extensions: VendorExtensions::default(),
767 license_requirement: None,
768 },
769 method_router: (), // no router in Missing state
770 _has_handler: PhantomData,
771 _has_response: PhantomData,
772 _state: PhantomData,
773 _auth_state: PhantomData,
774 _license_state: PhantomData,
775 }
776 }
777
778 /// Convenience constructor for GET requests
779 pub fn get(path: impl Into<String>) -> Self {
780 let path_str = path.into();
781 Self::new(Method::GET, normalize_to_axum_path(&path_str))
782 }
783
784 /// Convenience constructor for POST requests
785 pub fn post(path: impl Into<String>) -> Self {
786 let path_str = path.into();
787 Self::new(Method::POST, normalize_to_axum_path(&path_str))
788 }
789
790 /// Convenience constructor for PUT requests
791 pub fn put(path: impl Into<String>) -> Self {
792 let path_str = path.into();
793 Self::new(Method::PUT, normalize_to_axum_path(&path_str))
794 }
795
796 /// Convenience constructor for DELETE requests
797 pub fn delete(path: impl Into<String>) -> Self {
798 let path_str = path.into();
799 Self::new(Method::DELETE, normalize_to_axum_path(&path_str))
800 }
801
802 /// Convenience constructor for PATCH requests
803 pub fn patch(path: impl Into<String>) -> Self {
804 let path_str = path.into();
805 Self::new(Method::PATCH, normalize_to_axum_path(&path_str))
806 }
807}
808
809// -------------------------------------------------------------------------------------------------
810// Descriptive methods — available at any stage
811// -------------------------------------------------------------------------------------------------
812impl<H, R, S, A, L> OperationBuilder<H, R, S, A, L>
813where
814 H: HandlerSlot<S>,
815 A: AuthState,
816 L: LicenseState,
817{
818 /// Inspect the spec (primarily for tests)
819 pub fn spec(&self) -> &OperationSpec {
820 &self.spec
821 }
822
823 /// Set the operation ID
824 pub fn operation_id(mut self, id: impl Into<String>) -> Self {
825 self.spec.operation_id = Some(id.into());
826 self
827 }
828
829 /// Attach zone-based throttling configuration to this operation.
830 ///
831 /// Binds the operation to gateway throttling zones (by name). The limits
832 /// themselves are defined in the gateway configuration.
833 pub fn with_throttling(mut self, spec: ThrottlingSpec) -> Self {
834 self.spec.throttling = Some(spec);
835 self
836 }
837
838 /// Set the operation summary
839 pub fn summary(mut self, text: impl Into<String>) -> Self {
840 self.spec.summary = Some(text.into());
841 self
842 }
843
844 /// Set the operation description
845 pub fn description(mut self, text: impl Into<String>) -> Self {
846 self.spec.description = Some(text.into());
847 self
848 }
849
850 /// Add a tag to the operation
851 pub fn tag(mut self, tag: impl Into<String>) -> Self {
852 self.spec.tags.push(tag.into());
853 self
854 }
855
856 /// Add a parameter to the operation
857 pub fn param(mut self, param: ParamSpec) -> Self {
858 self.spec.params.push(param);
859 self
860 }
861
862 /// Add a path parameter with type inference (defaults to string)
863 pub fn path_param(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
864 self.spec
865 .params
866 .push(ParamSpec::path(name).description(description));
867 self
868 }
869
870 /// Add a query parameter (defaults to string)
871 pub fn query_param(
872 mut self,
873 name: impl Into<String>,
874 required: bool,
875 description: impl Into<String>,
876 ) -> Self {
877 self.spec.params.push(
878 ParamSpec::query(name)
879 .required(required)
880 .description(description),
881 );
882 self
883 }
884
885 /// Add a typed query parameter with explicit `OpenAPI` type
886 pub fn query_param_typed(
887 mut self,
888 name: impl Into<String>,
889 required: bool,
890 description: impl Into<String>,
891 param_type: impl Into<String>,
892 ) -> Self {
893 self.spec.params.push(
894 ParamSpec::query(name)
895 .required(required)
896 .description(description)
897 .param_type(param_type),
898 );
899 self
900 }
901
902 /// Add a string query parameter that only accepts `values`.
903 ///
904 /// The values reach the document as the parameter's `enum`, so a client
905 /// generated from the spec gets a closed set rather than a bare string,
906 /// and a caller reading the document can see what the endpoint takes
907 /// without trying one.
908 ///
909 /// The parameter stays a string; [`ParamSpec::enum_values`] is what
910 /// narrows it.
911 pub fn query_param_enum<V, I>(
912 mut self,
913 name: impl Into<String>,
914 required: bool,
915 description: impl Into<String>,
916 values: I,
917 ) -> Self
918 where
919 I: IntoIterator<Item = V>,
920 V: AsRef<str>,
921 {
922 self.spec.params.push(
923 ParamSpec::query(name)
924 .required(required)
925 .description(description)
926 .enum_values(values),
927 );
928 self
929 }
930
931 /// Register every query parameter declared by a
932 /// `#[derive(toolkit_contract::QueryParams)]` struct.
933 ///
934 /// The generated REST routes use this so the spec and the wire format come
935 /// from one declaration. Fields render as scalars or, for `Vec` fields, as
936 /// `style: form, explode: true` arrays.
937 pub fn query_params_from<T: toolkit_contract::query::QueryParams>(mut self) -> Self {
938 for p in T::openapi_params() {
939 self.spec.params.push(
940 ParamSpec::query(p.name)
941 .required(p.required)
942 .param_type(p.openapi_type)
943 .array(p.array),
944 );
945 }
946 self
947 }
948
949 /// Add a repeating query parameter — `?tag=a&tag=b`.
950 ///
951 /// `item_type` is the `OpenAPI` type of one element; the parameter renders
952 /// as an array with `style: form, explode: true`, which is the encoding the
953 /// generated REST client and its server extractor agree on for a `Vec<T>`
954 /// field.
955 pub fn query_param_array(
956 mut self,
957 name: impl Into<String>,
958 required: bool,
959 description: impl Into<String>,
960 item_type: impl Into<String>,
961 ) -> Self {
962 self.spec.params.push(
963 ParamSpec::query(name)
964 .required(required)
965 .description(description)
966 .param_type(item_type)
967 .array(true),
968 );
969 self
970 }
971
972 /// Attach a JSON request body by *schema name* that you've already registered.
973 /// This variant sets a description (`Some(desc)`) and marks the body as **required**.
974 pub fn json_request_schema(
975 mut self,
976 schema_name: impl Into<String>,
977 desc: impl Into<String>,
978 ) -> Self {
979 self.spec.request_body = Some(RequestBodySpec {
980 content_type: "application/json",
981 description: Some(desc.into()),
982 schema: RequestBodySchema::Ref {
983 schema_name: schema_name.into(),
984 },
985 required: true,
986 });
987 self
988 }
989
990 /// Attach a JSON request body by *schema name* with **no** description (`None`).
991 /// Marks the body as **required**.
992 pub fn json_request_schema_no_desc(mut self, schema_name: impl Into<String>) -> Self {
993 self.spec.request_body = Some(RequestBodySpec {
994 content_type: "application/json",
995 description: None,
996 schema: RequestBodySchema::Ref {
997 schema_name: schema_name.into(),
998 },
999 required: true,
1000 });
1001 self
1002 }
1003
1004 /// Attach a JSON request body and auto-register its schema using `utoipa`.
1005 /// This variant sets a description (`Some(desc)`) and marks the body as **required**.
1006 pub fn json_request<T>(
1007 mut self,
1008 registry: &dyn OpenApiRegistry,
1009 desc: impl Into<String>,
1010 ) -> Self
1011 where
1012 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
1013 {
1014 let name = ensure_schema::<T>(registry);
1015 self.spec.request_body = Some(RequestBodySpec {
1016 content_type: "application/json",
1017 description: Some(desc.into()),
1018 schema: RequestBodySchema::Ref { schema_name: name },
1019 required: true,
1020 });
1021 self
1022 }
1023
1024 /// Attach a JSON request body (auto-register schema) with **no** description (`None`).
1025 /// Marks the body as **required**.
1026 pub fn json_request_no_desc<T>(mut self, registry: &dyn OpenApiRegistry) -> Self
1027 where
1028 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
1029 {
1030 let name = ensure_schema::<T>(registry);
1031 self.spec.request_body = Some(RequestBodySpec {
1032 content_type: "application/json",
1033 description: None,
1034 schema: RequestBodySchema::Ref { schema_name: name },
1035 required: true,
1036 });
1037 self
1038 }
1039
1040 /// Make the previously attached request body **optional** (if any).
1041 pub fn request_optional(mut self) -> Self {
1042 if let Some(rb) = &mut self.spec.request_body {
1043 rb.required = false;
1044 }
1045 self
1046 }
1047
1048 /// Configure a multipart/form-data file upload request.
1049 ///
1050 /// This is a convenience helper for file upload endpoints that:
1051 /// - Sets the request body content type to "multipart/form-data"
1052 /// - Sets a description for the request body
1053 /// - Configures an inline object schema with a binary file field
1054 /// - Restricts allowed Content-Type to only "multipart/form-data"
1055 ///
1056 /// The file field will be documented in `OpenAPI` as a binary string with the
1057 /// given field name. This generates the correct `OpenAPI` schema for UI tools
1058 /// like Stoplight to display a file upload control.
1059 ///
1060 /// # Arguments
1061 /// * `field_name` - Name of the multipart form field (e.g., "file")
1062 /// * `description` - Optional description for the request body
1063 ///
1064 /// # Example
1065 /// ```rust
1066 /// # use axum::Router;
1067 /// # use http::StatusCode;
1068 /// # use toolkit::api::{
1069 /// # openapi_registry::OpenApiRegistryImpl,
1070 /// # operation_builder::OperationBuilder,
1071 /// # };
1072 /// # async fn upload_handler() -> &'static str { "uploaded" }
1073 /// # let registry = OpenApiRegistryImpl::new();
1074 /// # let router: Router<()> = Router::new();
1075 /// let router = OperationBuilder::post("/files/v1/upload")
1076 /// .operation_id("upload_file")
1077 /// .summary("Upload a file")
1078 /// .multipart_file_request("file", Some("File to upload"))
1079 /// .anonymous()
1080 /// .handler(upload_handler)
1081 /// .json_response(StatusCode::OK, "Upload successful")
1082 /// .register(router, ®istry);
1083 /// # let _ = router;
1084 /// ```
1085 pub fn multipart_file_request(mut self, field_name: &str, description: Option<&str>) -> Self {
1086 // Set request body with multipart/form-data content type
1087 self.spec.request_body = Some(RequestBodySpec {
1088 content_type: "multipart/form-data",
1089 description: description
1090 .map(|s| format!("{s} (expects field '{field_name}' with file data)")),
1091 schema: RequestBodySchema::MultipartFile {
1092 field_name: field_name.to_owned(),
1093 },
1094 required: true,
1095 });
1096
1097 // Also configure MIME type validation
1098 self.spec.allowed_request_content_types = Some(vec!["multipart/form-data"]);
1099
1100 self
1101 }
1102
1103 /// Configure the request body as raw binary (application/octet-stream).
1104 ///
1105 /// This is intended for endpoints that accept the entire request body
1106 /// as a file or arbitrary bytes, without multipart form encoding.
1107 ///
1108 /// The `OpenAPI` schema will be:
1109 /// ```yaml
1110 /// requestBody:
1111 /// required: true
1112 /// content:
1113 /// application/octet-stream:
1114 /// schema:
1115 /// type: string
1116 /// format: binary
1117 /// ```
1118 ///
1119 /// Tools like Stoplight will render this as a single file upload control
1120 /// for the entire body.
1121 ///
1122 /// # Arguments
1123 /// * `description` - Optional description for the request body
1124 ///
1125 /// # Example
1126 /// ```rust
1127 /// # use axum::Router;
1128 /// # use http::StatusCode;
1129 /// # use toolkit::api::{
1130 /// # openapi_registry::OpenApiRegistryImpl,
1131 /// # operation_builder::OperationBuilder,
1132 /// # };
1133 /// # async fn upload_handler() -> &'static str { "uploaded" }
1134 /// # let registry = OpenApiRegistryImpl::new();
1135 /// # let router: Router<()> = Router::new();
1136 /// let router = OperationBuilder::post("/files/v1/upload")
1137 /// .operation_id("upload_file")
1138 /// .summary("Upload a file")
1139 /// .octet_stream_request(Some("Raw file bytes to parse"))
1140 /// .anonymous()
1141 /// .handler(upload_handler)
1142 /// .json_response(StatusCode::OK, "Upload successful")
1143 /// .register(router, ®istry);
1144 /// # let _ = router;
1145 /// ```
1146 pub fn octet_stream_request(mut self, description: Option<&str>) -> Self {
1147 self.spec.request_body = Some(RequestBodySpec {
1148 content_type: "application/octet-stream",
1149 description: description.map(str::to_owned),
1150 schema: RequestBodySchema::Binary,
1151 required: true,
1152 });
1153
1154 // Also configure MIME type validation
1155 self.spec.allowed_request_content_types = Some(vec!["application/octet-stream"]);
1156
1157 self
1158 }
1159
1160 /// Configure allowed request MIME types for this operation.
1161 ///
1162 /// This attaches a whitelist of allowed Content-Type values (without parameters),
1163 /// which will be enforced by gateway middleware. If a request arrives with a
1164 /// Content-Type that is not in this list, gateway will return HTTP 415.
1165 ///
1166 /// This is independent of the request body schema - it only configures gateway
1167 /// validation and does not affect `OpenAPI` request body specifications.
1168 ///
1169 /// # Example
1170 /// ```rust
1171 /// # use axum::Router;
1172 /// # use http::StatusCode;
1173 /// # use toolkit::api::{
1174 /// # openapi_registry::OpenApiRegistryImpl,
1175 /// # operation_builder::OperationBuilder,
1176 /// # };
1177 /// # async fn upload_handler() -> &'static str { "uploaded" }
1178 /// # let registry = OpenApiRegistryImpl::new();
1179 /// # let router: Router<()> = Router::new();
1180 /// let router = OperationBuilder::post("/files/v1/upload")
1181 /// .operation_id("upload_file")
1182 /// .allow_content_types(&["multipart/form-data", "application/pdf"])
1183 /// .anonymous()
1184 /// .handler(upload_handler)
1185 /// .json_response(StatusCode::OK, "Upload successful")
1186 /// .register(router, ®istry);
1187 /// # let _ = router;
1188 /// ```
1189 pub fn allow_content_types(mut self, types: &[&'static str]) -> Self {
1190 self.spec.allowed_request_content_types = Some(types.to_vec());
1191 self
1192 }
1193
1194 /// Expose the route through the gateway, independently of authentication. Internal by
1195 /// default; callable at any stage. Platform auth suppresses exposure with a warning.
1196 pub fn exposed(mut self) -> Self {
1197 self.spec.exposed = true;
1198 self
1199 }
1200}
1201
1202/// License requirement setting — transitions `LicenseNotSet` -> `LicenseSet`
1203impl<H, R, S> OperationBuilder<H, R, S, AuthSet, LicenseNotSet>
1204where
1205 H: HandlerSlot<S>,
1206{
1207 /// Set (or explicitly clear) the license feature requirement for this operation.
1208 ///
1209 /// This method is only available after the auth requirement has been decided
1210 /// (i.e. after calling `authenticated()`).
1211 ///
1212 /// **Mandatory for authenticated endpoints:** operations configured with `authenticated()`
1213 /// must call `require_license_features(...)` before `register()`, because `register()` is only
1214 /// available once the license requirement state has transitioned to `LicenseSet`.
1215 ///
1216 /// **Not available for public endpoints:** public routes cannot (and do not need to) call this method.
1217 ///
1218 /// Pass an empty iterator (e.g. `[]`) to explicitly declare that no license feature is required.
1219 pub fn require_license_features<F>(
1220 mut self,
1221 licenses: impl IntoIterator<Item = F>,
1222 ) -> OperationBuilder<H, R, S, AuthSet, LicenseSet>
1223 where
1224 F: LicenseFeature,
1225 {
1226 let license_names: Vec<String> = licenses
1227 .into_iter()
1228 .map(|l| l.as_ref().to_owned())
1229 .collect();
1230
1231 self.spec.license_requirement =
1232 (!license_names.is_empty()).then_some(LicenseReqSpec { license_names });
1233
1234 OperationBuilder {
1235 spec: self.spec,
1236 method_router: self.method_router,
1237 _has_handler: self._has_handler,
1238 _has_response: self._has_response,
1239 _state: self._state,
1240 _auth_state: self._auth_state,
1241 _license_state: PhantomData,
1242 }
1243 }
1244
1245 /// Explicitly declare that this operation does not require any license.
1246 ///
1247 /// Use this for system/infrastructure endpoints that need authentication
1248 /// but are not gated behind application-level license features.
1249 ///
1250 /// This transitions from `LicenseNotSet` to `LicenseSet` without
1251 /// attaching any license requirement.
1252 pub fn no_license_required(self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1253 OperationBuilder {
1254 spec: self.spec,
1255 method_router: self.method_router,
1256 _has_handler: self._has_handler,
1257 _has_response: self._has_response,
1258 _state: self._state,
1259 _auth_state: self._auth_state,
1260 _license_state: PhantomData,
1261 }
1262 }
1263}
1264
1265// -------------------------------------------------------------------------------------------------
1266// Auth requirement setting — transitions AuthNotSet -> AuthSet
1267// -------------------------------------------------------------------------------------------------
1268impl<H, R, S, L> OperationBuilder<H, R, S, AuthNotSet, L>
1269where
1270 H: HandlerSlot<S>,
1271 L: LicenseState,
1272{
1273 /// Mark this route as requiring authentication.
1274 ///
1275 /// This is a binary marker — the route requires a valid bearer token.
1276 /// Scope enforcement (which scopes are needed) is configured at the
1277 /// gateway level, not per-route.
1278 ///
1279 /// This method transitions from `AuthNotSet` to `AuthSet` state.
1280 ///
1281 /// # Example
1282 /// ```rust
1283 /// # use toolkit::api::operation_builder::{
1284 /// # OperationBuilder, LicenseFeature, CORE_GLOBAL_BASE_LICENSE_FEATURE,
1285 /// # };
1286 /// # use axum::{extract::Json, Router };
1287 /// # use serde::{Serialize};
1288 /// #
1289 /// # #[derive(Serialize)]
1290 /// # pub struct User;
1291 /// #
1292 /// enum License {
1293 /// Base,
1294 /// }
1295 ///
1296 /// impl AsRef<str> for License {
1297 /// fn as_ref(&self) -> &str {
1298 /// match self {
1299 /// License::Base => CORE_GLOBAL_BASE_LICENSE_FEATURE,
1300 /// }
1301 /// }
1302 /// }
1303 ///
1304 /// impl LicenseFeature for License {}
1305 ///
1306 /// #
1307 /// # fn register_rest(
1308 /// # router: axum::Router,
1309 /// # api: &dyn toolkit::api::OpenApiRegistry,
1310 /// # ) -> anyhow::Result<axum::Router> {
1311 /// let router = OperationBuilder::get("/users-info/v1/users")
1312 /// .authenticated()
1313 /// .require_license_features::<License>([])
1314 /// .handler(list_users_handler)
1315 /// .json_response(axum::http::StatusCode::OK, "List of users")
1316 /// .register(router, api);
1317 /// # Ok(router)
1318 /// # }
1319 ///
1320 /// # async fn list_users_handler() -> Json<Vec<User>> {
1321 /// # unimplemented!()
1322 /// # }
1323 /// ```
1324 pub fn authenticated(mut self) -> OperationBuilder<H, R, S, AuthSet, L> {
1325 self.spec.auth = RouteAuth::Authenticated;
1326 OperationBuilder {
1327 spec: self.spec,
1328 method_router: self.method_router,
1329 _has_handler: self._has_handler,
1330 _has_response: self._has_response,
1331 _state: self._state,
1332 _auth_state: PhantomData,
1333 _license_state: self._license_state,
1334 }
1335 }
1336
1337 /// Require a validated `X-ToolKit-Internal-Token`; a bearer alone is never validated and
1338 /// yields 401, as do missing internal auth and a bearer beside the token. `OpenAPI` uses
1339 /// [`INTERNAL_TOKEN_SECURITY_SCHEME`]; discovery excludes the route. Handlers read
1340 /// `Extension<PlatformSecurityContext>`; a license decision is still required.
1341 pub fn platform_authenticated(mut self) -> OperationBuilder<H, R, S, AuthSet, L> {
1342 self.spec.auth = RouteAuth::Platform;
1343 OperationBuilder {
1344 spec: self.spec,
1345 method_router: self.method_router,
1346 _has_handler: self._has_handler,
1347 _has_response: self._has_response,
1348 _state: self._state,
1349 _auth_state: PhantomData,
1350 _license_state: self._license_state,
1351 }
1352 }
1353
1354 /// Mark this route as **anonymous** — no authentication required (the *auth*
1355 /// axis).
1356 ///
1357 /// A missing `Authorization: Bearer` header is allowed; a present bearer is
1358 /// still always re-validated. This explicitly opts out of the
1359 /// `require_auth_by_default` setting and maps to the `AnonymousRoute` marker
1360 /// in the `OoP` per-gear middleware. It is independent of visibility — use
1361 /// [`exposed`](Self::exposed) to also register the route in the gateway.
1362 /// This method transitions from `AuthNotSet` to `AuthSet` state.
1363 ///
1364 /// # Example
1365 /// ```rust
1366 /// # use axum::Router;
1367 /// # use http::StatusCode;
1368 /// # use toolkit::api::{
1369 /// # openapi_registry::OpenApiRegistryImpl,
1370 /// # operation_builder::OperationBuilder,
1371 /// # };
1372 /// # async fn health_check() -> &'static str { "OK" }
1373 /// # let registry = OpenApiRegistryImpl::new();
1374 /// # let router: Router<()> = Router::new();
1375 /// let router = OperationBuilder::get("/users-info/v1/health")
1376 /// .anonymous()
1377 /// .handler(health_check)
1378 /// .json_response(StatusCode::OK, "OK")
1379 /// .register(router, ®istry);
1380 /// # let _ = router;
1381 /// ```
1382 pub fn anonymous(mut self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1383 self.spec.auth = RouteAuth::Anonymous;
1384 OperationBuilder {
1385 spec: self.spec,
1386 method_router: self.method_router,
1387 _has_handler: self._has_handler,
1388 _has_response: self._has_response,
1389 _state: self._state,
1390 _auth_state: PhantomData,
1391 _license_state: PhantomData,
1392 }
1393 }
1394
1395 /// Deprecated alias for the old single-axis `.public()`.
1396 ///
1397 /// The old `.public()` meant both **anonymous** (no auth) *and* **edge
1398 /// visible**. Those are now separate axes: [`anonymous`](Self::anonymous)
1399 /// (auth) and [`exposed`](Self::exposed) (visibility). This shim maps to
1400 /// `.anonymous().exposed()` so out-of-tree gears keep compiling for one
1401 /// release; a bare `.anonymous()` (the naive mechanical replacement) would
1402 /// silently drop the route from the edge, which this warning surfaces at
1403 /// compile time instead.
1404 #[deprecated(
1405 since = "0.6.21",
1406 note = "`.public()` split into two axes; use `.anonymous().exposed()` \
1407 (this alias forwards to exactly that)"
1408 )]
1409 pub fn public(self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1410 self.anonymous().exposed()
1411 }
1412}
1413
1414// -------------------------------------------------------------------------------------------------
1415// Handler setting — transitions Missing -> Present for handler
1416// -------------------------------------------------------------------------------------------------
1417impl<R, S, A, L> OperationBuilder<Missing, R, S, A, L>
1418where
1419 S: Clone + Send + Sync + 'static,
1420 A: AuthState,
1421 L: LicenseState,
1422{
1423 /// Set the handler for this operation (function handlers are recommended).
1424 ///
1425 /// This transitions the builder from `Missing` to `Present` handler state.
1426 pub fn handler<F, T>(self, h: F) -> OperationBuilder<Present, R, S, A, L>
1427 where
1428 F: Handler<T, S> + Clone + Send + 'static,
1429 T: 'static,
1430 {
1431 let method_router = match self.spec.method {
1432 Method::GET => axum::routing::get(h),
1433 Method::POST => axum::routing::post(h),
1434 Method::PUT => axum::routing::put(h),
1435 Method::DELETE => axum::routing::delete(h),
1436 Method::PATCH => axum::routing::patch(h),
1437 _ => axum::routing::any(|| async { axum::http::StatusCode::METHOD_NOT_ALLOWED }),
1438 };
1439
1440 OperationBuilder {
1441 spec: self.spec,
1442 method_router, // concrete MethodRouter<S> in Present state
1443 _has_handler: PhantomData::<Present>,
1444 _has_response: self._has_response,
1445 _state: self._state,
1446 _auth_state: self._auth_state,
1447 _license_state: self._license_state,
1448 }
1449 }
1450
1451 /// Alternative path: provide a pre-composed `MethodRouter<S>` yourself
1452 /// (useful to attach per-route middleware/layers).
1453 pub fn method_router(self, mr: MethodRouter<S>) -> OperationBuilder<Present, R, S, A, L> {
1454 OperationBuilder {
1455 spec: self.spec,
1456 method_router: mr, // concrete MethodRouter<S> in Present state
1457 _has_handler: PhantomData::<Present>,
1458 _has_response: self._has_response,
1459 _state: self._state,
1460 _auth_state: self._auth_state,
1461 _license_state: self._license_state,
1462 }
1463 }
1464}
1465
1466// -------------------------------------------------------------------------------------------------
1467// Response setting — transitions Missing -> Present for response (first response)
1468// -------------------------------------------------------------------------------------------------
1469impl<H, S, A, L> OperationBuilder<H, Missing, S, A, L>
1470where
1471 H: HandlerSlot<S>,
1472 A: AuthState,
1473 L: LicenseState,
1474{
1475 /// Add a raw response spec (transitions from Missing to Present).
1476 pub fn response(mut self, resp: ResponseSpec) -> OperationBuilder<H, Present, S, A, L> {
1477 self.spec.responses.push(resp);
1478 OperationBuilder {
1479 spec: self.spec,
1480 method_router: self.method_router,
1481 _has_handler: self._has_handler,
1482 _has_response: PhantomData::<Present>,
1483 _state: self._state,
1484 _auth_state: self._auth_state,
1485 _license_state: self._license_state,
1486 }
1487 }
1488
1489 /// Add a JSON response (transitions from Missing to Present).
1490 pub fn json_response(
1491 mut self,
1492 status: http::StatusCode,
1493 description: impl Into<String>,
1494 ) -> OperationBuilder<H, Present, S, A, L> {
1495 self.spec.responses.push(ResponseSpec {
1496 status: status.as_u16(),
1497 content_type: "application/json",
1498 description: description.into(),
1499 schema: None,
1500 headers: Vec::new(),
1501 });
1502 OperationBuilder {
1503 spec: self.spec,
1504 method_router: self.method_router,
1505 _has_handler: self._has_handler,
1506 _has_response: PhantomData::<Present>,
1507 _state: self._state,
1508 _auth_state: self._auth_state,
1509 _license_state: self._license_state,
1510 }
1511 }
1512
1513 /// Add a body-less response (e.g. `204 No Content`) — transitions from
1514 /// Missing to Present.
1515 ///
1516 /// `OpenAPI` consumers and code-generators treat a `204` response with a
1517 /// `content` block as advertising a body, which is incorrect. Use this
1518 /// helper for any handler that intentionally returns no payload (typical
1519 /// for `DELETE` / `PUT` semantics).
1520 pub fn no_content_response(
1521 mut self,
1522 status: http::StatusCode,
1523 description: impl Into<String>,
1524 ) -> OperationBuilder<H, Present, S, A, L> {
1525 self.spec.responses.push(ResponseSpec {
1526 status: status.as_u16(),
1527 content_type: "",
1528 description: description.into(),
1529 schema: None,
1530 headers: Vec::new(),
1531 });
1532 OperationBuilder {
1533 spec: self.spec,
1534 method_router: self.method_router,
1535 _has_handler: self._has_handler,
1536 _has_response: PhantomData::<Present>,
1537 _state: self._state,
1538 _auth_state: self._auth_state,
1539 _license_state: self._license_state,
1540 }
1541 }
1542
1543 /// Add a JSON response with a registered schema (transitions from Missing to Present).
1544 pub fn json_response_with_schema<T>(
1545 mut self,
1546 registry: &dyn OpenApiRegistry,
1547 status: http::StatusCode,
1548 description: impl Into<String>,
1549 ) -> OperationBuilder<H, Present, S, A, L>
1550 where
1551 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1552 {
1553 let name = ensure_schema::<T>(registry);
1554 self.spec.responses.push(ResponseSpec {
1555 status: status.as_u16(),
1556 content_type: "application/json",
1557 description: description.into(),
1558 schema: Some(ResponseSchema::Ref { schema_name: name }),
1559 headers: Vec::new(),
1560 });
1561 OperationBuilder {
1562 spec: self.spec,
1563 method_router: self.method_router,
1564 _has_handler: self._has_handler,
1565 _has_response: PhantomData::<Present>,
1566 _state: self._state,
1567 _auth_state: self._auth_state,
1568 _license_state: self._license_state,
1569 }
1570 }
1571
1572 /// Add a JSON response whose body is a **top-level array** of `T`
1573 /// (transitions from Missing to Present).
1574 ///
1575 /// `T` is the *item* type — pass `GearDto`, not `Vec<GearDto>`. Registers
1576 /// `T` as a named component and emits an inline
1577 /// `{type: array, items: {$ref: T}}` schema for the response body.
1578 ///
1579 /// Never pass `Vec<T>` to [`Self::json_response_with_schema`]: utoipa's
1580 /// default `ToSchema::name()` strips generic arguments, so every `Vec<_>`
1581 /// registers under the single component name `Vec` and two such responses
1582 /// collide fatally in `OpenApiRegistryImpl::ensure_schema_raw`.
1583 pub fn json_array_response_with_schema<T>(
1584 mut self,
1585 registry: &dyn OpenApiRegistry,
1586 status: http::StatusCode,
1587 description: impl Into<String>,
1588 ) -> OperationBuilder<H, Present, S, A, L>
1589 where
1590 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1591 {
1592 let items_schema_name = ensure_schema::<T>(registry);
1593 self.spec.responses.push(ResponseSpec {
1594 status: status.as_u16(),
1595 content_type: "application/json",
1596 description: description.into(),
1597 schema: Some(ResponseSchema::Array { items_schema_name }),
1598 headers: Vec::new(),
1599 });
1600 OperationBuilder {
1601 spec: self.spec,
1602 method_router: self.method_router,
1603 _has_handler: self._has_handler,
1604 _has_response: PhantomData::<Present>,
1605 _state: self._state,
1606 _auth_state: self._auth_state,
1607 _license_state: self._license_state,
1608 }
1609 }
1610
1611 /// Add a text response with a custom content type (transitions from Missing to Present).
1612 ///
1613 /// # Arguments
1614 /// * `status` - HTTP status code
1615 /// * `description` - Description of the response
1616 /// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
1617 ///
1618 /// # Important
1619 /// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
1620 /// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
1621 /// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
1622 /// include the charset parameter.
1623 pub fn text_response(
1624 mut self,
1625 status: http::StatusCode,
1626 description: impl Into<String>,
1627 content_type: &'static str,
1628 ) -> OperationBuilder<H, Present, S, A, L> {
1629 self.spec.responses.push(ResponseSpec {
1630 status: status.as_u16(),
1631 content_type,
1632 description: description.into(),
1633 schema: None,
1634 headers: Vec::new(),
1635 });
1636 OperationBuilder {
1637 spec: self.spec,
1638 method_router: self.method_router,
1639 _has_handler: self._has_handler,
1640 _has_response: PhantomData::<Present>,
1641 _state: self._state,
1642 _auth_state: self._auth_state,
1643 _license_state: self._license_state,
1644 }
1645 }
1646
1647 /// Add an HTML response (transitions from Missing to Present).
1648 pub fn html_response(
1649 mut self,
1650 status: http::StatusCode,
1651 description: impl Into<String>,
1652 ) -> OperationBuilder<H, Present, S, A, L> {
1653 self.spec.responses.push(ResponseSpec {
1654 status: status.as_u16(),
1655 content_type: "text/html",
1656 description: description.into(),
1657 schema: None,
1658 headers: Vec::new(),
1659 });
1660 OperationBuilder {
1661 spec: self.spec,
1662 method_router: self.method_router,
1663 _has_handler: self._has_handler,
1664 _has_response: PhantomData::<Present>,
1665 _state: self._state,
1666 _auth_state: self._auth_state,
1667 _license_state: self._license_state,
1668 }
1669 }
1670
1671 /// Add an RFC 9457 `application/problem+json` response (transitions from Missing to Present).
1672 pub fn problem_response(
1673 mut self,
1674 registry: &dyn OpenApiRegistry,
1675 status: http::StatusCode,
1676 description: impl Into<String>,
1677 ) -> OperationBuilder<H, Present, S, A, L> {
1678 // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
1679 let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
1680 self.spec.responses.push(ResponseSpec {
1681 status: status.as_u16(),
1682 content_type: problem::APPLICATION_PROBLEM_JSON,
1683 description: description.into(),
1684 schema: Some(ResponseSchema::Ref {
1685 schema_name: problem_name,
1686 }),
1687 headers: Vec::new(),
1688 });
1689 OperationBuilder {
1690 spec: self.spec,
1691 method_router: self.method_router,
1692 _has_handler: self._has_handler,
1693 _has_response: PhantomData::<Present>,
1694 _state: self._state,
1695 _auth_state: self._auth_state,
1696 _license_state: self._license_state,
1697 }
1698 }
1699
1700 /// First response: SSE stream of JSON events (`text/event-stream`).
1701 pub fn sse_json<T>(
1702 mut self,
1703 openapi: &dyn OpenApiRegistry,
1704 description: impl Into<String>,
1705 ) -> OperationBuilder<H, Present, S, A, L>
1706 where
1707 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1708 {
1709 let name = ensure_schema::<T>(openapi);
1710 self.spec.responses.push(ResponseSpec {
1711 status: http::StatusCode::OK.as_u16(),
1712 content_type: "text/event-stream",
1713 description: description.into(),
1714 schema: Some(ResponseSchema::Ref { schema_name: name }),
1715 headers: Vec::new(),
1716 });
1717 OperationBuilder {
1718 spec: self.spec,
1719 method_router: self.method_router,
1720 _has_handler: self._has_handler,
1721 _has_response: PhantomData::<Present>,
1722 _state: self._state,
1723 _auth_state: self._auth_state,
1724 _license_state: self._license_state,
1725 }
1726 }
1727
1728 /// First response: `multipart/mixed` stream of JSON items, one item per
1729 /// body part — the server-to-server counterpart to [`Self::sse_json`].
1730 ///
1731 /// `T` is the *item* type, exactly as for SSE: the media-type key in the
1732 /// spec is the bare `multipart/mixed`, with no `boundary=` parameter,
1733 /// because the boundary is generated per response at runtime by
1734 /// [`crate::http::multipart::MultipartJsonStream`] and is not a property of
1735 /// the operation.
1736 pub fn multipart_json<T>(
1737 mut self,
1738 openapi: &dyn OpenApiRegistry,
1739 description: impl Into<String>,
1740 ) -> OperationBuilder<H, Present, S, A, L>
1741 where
1742 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1743 {
1744 let name = ensure_schema::<T>(openapi);
1745 self.spec.responses.push(ResponseSpec {
1746 status: http::StatusCode::OK.as_u16(),
1747 content_type: "multipart/mixed",
1748 description: description.into(),
1749 schema: Some(ResponseSchema::Ref { schema_name: name }),
1750 headers: Vec::new(),
1751 });
1752 OperationBuilder {
1753 spec: self.spec,
1754 method_router: self.method_router,
1755 _has_handler: self._has_handler,
1756 _has_response: PhantomData::<Present>,
1757 _state: self._state,
1758 _auth_state: self._auth_state,
1759 _license_state: self._license_state,
1760 }
1761 }
1762}
1763
1764// -------------------------------------------------------------------------------------------------
1765// Additional responses — for Present response state (additional responses)
1766// -------------------------------------------------------------------------------------------------
1767impl<H, S, A, L> OperationBuilder<H, Present, S, A, L>
1768where
1769 H: HandlerSlot<S>,
1770 A: AuthState,
1771 L: LicenseState,
1772{
1773 /// Declare a header on the most recently declared response.
1774 ///
1775 /// Call this immediately after the response declaration it describes.
1776 /// Consecutive calls attach multiple headers to that same response.
1777 ///
1778 /// # Panics
1779 /// Panics when the response status already has a header with the same
1780 /// case-insensitive name.
1781 pub fn response_header(mut self, header: ResponseHeaderSpec) -> Self {
1782 let Some(response) = self.spec.responses.last() else {
1783 unreachable!("Present response state guarantees a response");
1784 };
1785 let status = response.status;
1786 assert!(
1787 !self.spec.responses.iter().any(|response| {
1788 response.status == status
1789 && response
1790 .headers
1791 .iter()
1792 .any(|existing| existing.name.eq_ignore_ascii_case(&header.name))
1793 }),
1794 "response {status} already declares header '{}'",
1795 header.name
1796 );
1797 let Some(response) = self.spec.responses.last_mut() else {
1798 unreachable!("Present response state guarantees a response");
1799 };
1800 response.headers.push(header);
1801 self
1802 }
1803
1804 /// Add a JSON response (additional).
1805 pub fn json_response(
1806 mut self,
1807 status: http::StatusCode,
1808 description: impl Into<String>,
1809 ) -> Self {
1810 self.spec.upsert_response(ResponseSpec {
1811 status: status.as_u16(),
1812 content_type: "application/json",
1813 description: description.into(),
1814 schema: None,
1815 headers: Vec::new(),
1816 });
1817 self
1818 }
1819
1820 /// Add a body-less response (e.g. `204 No Content`) — additional variant.
1821 pub fn no_content_response(
1822 mut self,
1823 status: http::StatusCode,
1824 description: impl Into<String>,
1825 ) -> Self {
1826 self.spec.upsert_response(ResponseSpec {
1827 status: status.as_u16(),
1828 content_type: "",
1829 description: description.into(),
1830 schema: None,
1831 headers: Vec::new(),
1832 });
1833 self
1834 }
1835
1836 /// Add a JSON response with a registered schema (additional).
1837 pub fn json_response_with_schema<T>(
1838 mut self,
1839 registry: &dyn OpenApiRegistry,
1840 status: http::StatusCode,
1841 description: impl Into<String>,
1842 ) -> Self
1843 where
1844 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1845 {
1846 let name = ensure_schema::<T>(registry);
1847 self.spec.upsert_response(ResponseSpec {
1848 status: status.as_u16(),
1849 content_type: "application/json",
1850 description: description.into(),
1851 schema: Some(ResponseSchema::Ref { schema_name: name }),
1852 headers: Vec::new(),
1853 });
1854 self
1855 }
1856
1857 /// Add a JSON response whose body is a **top-level array** of `T` (additional).
1858 ///
1859 /// `T` is the *item* type — pass `GearDto`, not `Vec<GearDto>`. See
1860 /// [`OperationBuilder::json_array_response_with_schema`] on the
1861 /// `Missing`-response builder for why arrays are emitted inline.
1862 pub fn json_array_response_with_schema<T>(
1863 mut self,
1864 registry: &dyn OpenApiRegistry,
1865 status: http::StatusCode,
1866 description: impl Into<String>,
1867 ) -> Self
1868 where
1869 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1870 {
1871 let items_schema_name = ensure_schema::<T>(registry);
1872 self.spec.upsert_response(ResponseSpec {
1873 status: status.as_u16(),
1874 content_type: "application/json",
1875 description: description.into(),
1876 schema: Some(ResponseSchema::Array { items_schema_name }),
1877 headers: Vec::new(),
1878 });
1879 self
1880 }
1881
1882 /// Add a text response with a custom content type (additional).
1883 ///
1884 /// # Arguments
1885 /// * `status` - HTTP status code
1886 /// * `description` - Description of the response
1887 /// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
1888 ///
1889 /// # Important
1890 /// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
1891 /// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
1892 /// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
1893 /// include the charset parameter.
1894 pub fn text_response(
1895 mut self,
1896 status: http::StatusCode,
1897 description: impl Into<String>,
1898 content_type: &'static str,
1899 ) -> Self {
1900 self.spec.upsert_response(ResponseSpec {
1901 status: status.as_u16(),
1902 content_type,
1903 description: description.into(),
1904 schema: None,
1905 headers: Vec::new(),
1906 });
1907 self
1908 }
1909
1910 /// Add an HTML response (additional).
1911 pub fn html_response(
1912 mut self,
1913 status: http::StatusCode,
1914 description: impl Into<String>,
1915 ) -> Self {
1916 self.spec.upsert_response(ResponseSpec {
1917 status: status.as_u16(),
1918 content_type: "text/html",
1919 description: description.into(),
1920 schema: None,
1921 headers: Vec::new(),
1922 });
1923 self
1924 }
1925
1926 /// Add an additional RFC 9457 `application/problem+json` response.
1927 pub fn problem_response(
1928 mut self,
1929 registry: &dyn OpenApiRegistry,
1930 status: http::StatusCode,
1931 description: impl Into<String>,
1932 ) -> Self {
1933 // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
1934 let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
1935 self.spec.upsert_response(ResponseSpec {
1936 status: status.as_u16(),
1937 content_type: problem::APPLICATION_PROBLEM_JSON,
1938 description: description.into(),
1939 schema: Some(ResponseSchema::Ref {
1940 schema_name: problem_name,
1941 }),
1942 headers: Vec::new(),
1943 });
1944 self
1945 }
1946
1947 /// Additional SSE response (if the operation already has a response).
1948 pub fn sse_json<T>(
1949 mut self,
1950 openapi: &dyn OpenApiRegistry,
1951 description: impl Into<String>,
1952 ) -> Self
1953 where
1954 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1955 {
1956 let name = ensure_schema::<T>(openapi);
1957 self.spec.upsert_response(ResponseSpec {
1958 status: http::StatusCode::OK.as_u16(),
1959 content_type: "text/event-stream",
1960 description: description.into(),
1961 schema: Some(ResponseSchema::Ref { schema_name: name }),
1962 headers: Vec::new(),
1963 });
1964 self
1965 }
1966
1967 /// Additional `multipart/mixed` response (if the operation already has
1968 /// one). See [`OperationBuilder::multipart_json`] on the first-response
1969 /// builder for what `T` and the media-type key mean.
1970 pub fn multipart_json<T>(
1971 mut self,
1972 openapi: &dyn OpenApiRegistry,
1973 description: impl Into<String>,
1974 ) -> Self
1975 where
1976 T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1977 {
1978 let name = ensure_schema::<T>(openapi);
1979 self.spec.upsert_response(ResponseSpec {
1980 status: http::StatusCode::OK.as_u16(),
1981 content_type: "multipart/mixed",
1982 description: description.into(),
1983 schema: Some(ResponseSchema::Ref { schema_name: name }),
1984 headers: Vec::new(),
1985 });
1986 self
1987 }
1988
1989 /// Add standard error responses (400, 401, 403, 404, 409, 422, 429, 500).
1990 ///
1991 /// All responses reference the shared Problem schema (RFC 9457) for consistent
1992 /// error handling across your API. This is the recommended way to declare
1993 /// common error responses without repeating boilerplate.
1994 ///
1995 /// # Example
1996 ///
1997 /// ```rust
1998 /// # use axum::Router;
1999 /// # use http::StatusCode;
2000 /// # use toolkit::api::{
2001 /// # openapi_registry::OpenApiRegistryImpl,
2002 /// # operation_builder::OperationBuilder,
2003 /// # };
2004 /// # async fn list_users() -> &'static str { "[]" }
2005 /// # let registry = OpenApiRegistryImpl::new();
2006 /// # let router: Router<()> = Router::new();
2007 /// let op = OperationBuilder::get("/user-info/v1/users")
2008 /// .anonymous()
2009 /// .handler(list_users)
2010 /// .json_response(StatusCode::OK, "List of users")
2011 /// .standard_errors(®istry);
2012 ///
2013 /// let router = op.register(router, ®istry);
2014 /// # let _ = router;
2015 /// ```
2016 ///
2017 /// This adds the following error responses:
2018 /// - 400 Bad Request
2019 /// - 401 Unauthorized
2020 /// - 403 Forbidden
2021 /// - 404 Not Found
2022 /// - 409 Conflict
2023 /// - 429 Too Many Requests
2024 /// - 500 Internal Server Error
2025 ///
2026 /// 413/415/422 are intentionally absent here: canonical `InvalidArgument`
2027 /// maps to 400 per `docs/arch/errors/DESIGN.md` §1.2, so no
2028 /// canonical-handler path alone produces those statuses. An operation
2029 /// whose handler takes `toolkit::api::rest::extract::Json<T>` can produce
2030 /// all three (oversized body, wrong `Content-Type`, schema violation) -
2031 /// add [`Self::error_413`]/[`Self::error_415`]/[`Self::error_422`]
2032 /// individually for such an operation.
2033 pub fn standard_errors(mut self, registry: &dyn OpenApiRegistry) -> Self {
2034 use http::StatusCode;
2035 // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
2036 let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
2037
2038 let standard_errors = [
2039 (StatusCode::BAD_REQUEST, "Bad Request"),
2040 (StatusCode::UNAUTHORIZED, "Unauthorized"),
2041 (StatusCode::FORBIDDEN, "Forbidden"),
2042 (StatusCode::NOT_FOUND, "Not Found"),
2043 (StatusCode::CONFLICT, "Conflict"),
2044 (StatusCode::TOO_MANY_REQUESTS, "Too Many Requests"),
2045 (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"),
2046 ];
2047
2048 for (status, description) in standard_errors {
2049 self.spec.upsert_response(ResponseSpec {
2050 status: status.as_u16(),
2051 content_type: problem::APPLICATION_PROBLEM_JSON,
2052 description: description.to_owned(),
2053 schema: Some(ResponseSchema::Ref {
2054 schema_name: problem_name.clone(),
2055 }),
2056 headers: Vec::new(),
2057 });
2058 }
2059
2060 self
2061 }
2062
2063 /// Add 400 validation error response using the canonical `Problem` schema.
2064 ///
2065 /// Field-level violations surface under `context.field_violations[]`
2066 /// (canonical `InvalidArgument` category, HTTP 400 per
2067 /// `docs/arch/errors/DESIGN.md` §1.2 / §3.5).
2068 ///
2069 /// # Example
2070 ///
2071 /// ```rust
2072 /// # use axum::Router;
2073 /// # use http::StatusCode;
2074 /// # use toolkit::api::{
2075 /// # openapi_registry::OpenApiRegistryImpl,
2076 /// # operation_builder::OperationBuilder,
2077 /// # };
2078 /// # use serde::{Deserialize, Serialize};
2079 /// # use utoipa::ToSchema;
2080 /// #
2081 /// #[toolkit_macros::api_dto(request)]
2082 /// struct CreateUserRequest {
2083 /// email: String,
2084 /// }
2085 ///
2086 /// # async fn create_user() -> &'static str { "created" }
2087 /// # let registry = OpenApiRegistryImpl::new();
2088 /// # let router: Router<()> = Router::new();
2089 /// let op = OperationBuilder::post("/users-info/v1/users")
2090 /// .anonymous()
2091 /// .handler(create_user)
2092 /// .json_request::<CreateUserRequest>(®istry, "User data")
2093 /// .json_response(StatusCode::CREATED, "User created")
2094 /// .with_400_validation_error(®istry);
2095 ///
2096 /// let router = op.register(router, ®istry);
2097 /// # let _ = router;
2098 /// ```
2099 pub fn with_400_validation_error(mut self, registry: &dyn OpenApiRegistry) -> Self {
2100 let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
2101
2102 self.spec.upsert_response(ResponseSpec {
2103 status: http::StatusCode::BAD_REQUEST.as_u16(),
2104 content_type: problem::APPLICATION_PROBLEM_JSON,
2105 description: "Validation Error".to_owned(),
2106 schema: Some(ResponseSchema::Ref {
2107 schema_name: problem_name,
2108 }),
2109 headers: Vec::new(),
2110 });
2111
2112 self
2113 }
2114
2115 /// Add a 400 Bad Request error response.
2116 ///
2117 /// This is a convenience wrapper around `problem_response`.
2118 pub fn error_400(self, registry: &dyn OpenApiRegistry) -> Self {
2119 self.problem_response(registry, http::StatusCode::BAD_REQUEST, "Bad Request")
2120 }
2121
2122 /// Add a 401 Unauthorized error response.
2123 ///
2124 /// This is a convenience wrapper around `problem_response`.
2125 pub fn error_401(self, registry: &dyn OpenApiRegistry) -> Self {
2126 self.problem_response(registry, http::StatusCode::UNAUTHORIZED, "Unauthorized")
2127 }
2128
2129 /// Add a 403 Forbidden error response.
2130 ///
2131 /// This is a convenience wrapper around `problem_response`.
2132 pub fn error_403(self, registry: &dyn OpenApiRegistry) -> Self {
2133 self.problem_response(registry, http::StatusCode::FORBIDDEN, "Forbidden")
2134 }
2135
2136 /// Add a 404 Not Found error response.
2137 ///
2138 /// This is a convenience wrapper around `problem_response`.
2139 pub fn error_404(self, registry: &dyn OpenApiRegistry) -> Self {
2140 self.problem_response(registry, http::StatusCode::NOT_FOUND, "Not Found")
2141 }
2142
2143 /// Add a 409 Conflict error response.
2144 ///
2145 /// This is a convenience wrapper around `problem_response`.
2146 pub fn error_409(self, registry: &dyn OpenApiRegistry) -> Self {
2147 self.problem_response(registry, http::StatusCode::CONFLICT, "Conflict")
2148 }
2149
2150 /// Add a 413 Payload Too Large error response.
2151 ///
2152 /// This is a convenience wrapper around `problem_response`. Relevant to
2153 /// any operation whose handler takes
2154 /// [`toolkit::api::rest::extract::Json<T>`](crate::api::rest::extract::Json)
2155 /// as a parameter - an oversized request body produces this status.
2156 pub fn error_413(self, registry: &dyn OpenApiRegistry) -> Self {
2157 self.problem_response(
2158 registry,
2159 http::StatusCode::PAYLOAD_TOO_LARGE,
2160 "Payload Too Large",
2161 )
2162 }
2163
2164 /// Add a 415 Unsupported Media Type error response.
2165 ///
2166 /// This is a convenience wrapper around `problem_response`.
2167 pub fn error_415(self, registry: &dyn OpenApiRegistry) -> Self {
2168 self.problem_response(
2169 registry,
2170 http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
2171 "Unsupported Media Type",
2172 )
2173 }
2174
2175 /// Add a 422 Unprocessable Entity error response.
2176 ///
2177 /// This is a convenience wrapper around `problem_response`.
2178 pub fn error_422(self, registry: &dyn OpenApiRegistry) -> Self {
2179 self.problem_response(
2180 registry,
2181 http::StatusCode::UNPROCESSABLE_ENTITY,
2182 "Unprocessable Entity",
2183 )
2184 }
2185
2186 /// Add a 429 Too Many Requests error response.
2187 ///
2188 /// This is a convenience wrapper around `problem_response`.
2189 pub fn error_429(self, registry: &dyn OpenApiRegistry) -> Self {
2190 self.problem_response(
2191 registry,
2192 http::StatusCode::TOO_MANY_REQUESTS,
2193 "Too Many Requests",
2194 )
2195 }
2196
2197 /// Add a 500 Internal Server Error response.
2198 ///
2199 /// This is a convenience wrapper around `problem_response`.
2200 pub fn error_500(self, registry: &dyn OpenApiRegistry) -> Self {
2201 self.problem_response(
2202 registry,
2203 http::StatusCode::INTERNAL_SERVER_ERROR,
2204 "Internal Server Error",
2205 )
2206 }
2207
2208 /// Add a 502 Bad Gateway error response.
2209 ///
2210 /// This is a convenience wrapper around `problem_response`.
2211 pub fn error_502(self, registry: &dyn OpenApiRegistry) -> Self {
2212 self.problem_response(registry, http::StatusCode::BAD_GATEWAY, "Bad Gateway")
2213 }
2214
2215 /// Add a 503 Service Unavailable error response.
2216 ///
2217 /// This is a convenience wrapper around `problem_response`.
2218 pub fn error_503(self, registry: &dyn OpenApiRegistry) -> Self {
2219 self.problem_response(
2220 registry,
2221 http::StatusCode::SERVICE_UNAVAILABLE,
2222 "Service Unavailable",
2223 )
2224 }
2225
2226 /// Add a 504 Gateway Timeout error response.
2227 ///
2228 /// This is a convenience wrapper around `problem_response`.
2229 pub fn error_504(self, registry: &dyn OpenApiRegistry) -> Self {
2230 self.problem_response(
2231 registry,
2232 http::StatusCode::GATEWAY_TIMEOUT,
2233 "Gateway Timeout",
2234 )
2235 }
2236}
2237
2238// -------------------------------------------------------------------------------------------------
2239// Registration — only available when handler, response, AND auth are all set
2240// -------------------------------------------------------------------------------------------------
2241impl<S> OperationBuilder<Present, Present, S, AuthSet, LicenseSet>
2242where
2243 S: Clone + Send + Sync + 'static,
2244{
2245 /// Register the operation with the router and `OpenAPI` registry.
2246 ///
2247 /// This method is only available when:
2248 /// - Handler is present
2249 /// - Response is present
2250 /// - Auth requirement is set (either `authenticated` or `public`)
2251 ///
2252 /// All conditions are enforced at compile time by the type system.
2253 pub fn register(self, router: Router<S>, openapi: &dyn OpenApiRegistry) -> Router<S> {
2254 // Inform the OpenAPI registry (the implementation will translate OperationSpec
2255 // into an OpenAPI Operation + RequestBody + Responses with component refs).
2256 openapi.register_operation(&self.spec);
2257
2258 // In Present state the method_router is guaranteed to be a real MethodRouter<S>.
2259 router.route(&self.spec.path, self.method_router)
2260 }
2261}
2262
2263// -------------------------------------------------------------------------------------------------
2264// Tests
2265// -------------------------------------------------------------------------------------------------
2266#[cfg(test)]
2267#[cfg_attr(coverage_nightly, coverage(off))]
2268#[path = "operation_builder_tests.rs"]
2269mod tests;