Skip to main content

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