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`, with `asc` and
617    /// `desc` for each field whose `FilterField::orderable` is true.
618    #[must_use]
619    fn with_odata_orderby<T>(self) -> Self
620    where
621        T: toolkit_odata::filter::FilterField;
622}
623
624impl<S, H, R, A, L> OperationBuilderODataExt<S, H, R> for OperationBuilder<H, R, S, A, L>
625where
626    H: HandlerSlot<S>,
627    A: AuthState,
628    L: LicenseState,
629{
630    fn with_odata_filter<T>(mut self) -> Self
631    where
632        T: toolkit_odata::filter::FilterField,
633    {
634        use std::fmt::Write as _;
635        use toolkit_odata::filter::{FilterOp, published_ops_error};
636
637        // A field's list is a declaration; a wrong one is a bug at the
638        // declaring site, not a contract to publish narrowed.
639        if let Some(error) = published_ops_error::<T>() {
640            panic!(
641                "{} declares an invalid published_ops: {error}",
642                self.spec.path
643            );
644        }
645
646        let mut filter = self
647            .spec
648            .vendor_extensions
649            .x_odata_filter
650            .unwrap_or_default();
651
652        let mut description = "OData v4 filter expression".to_owned();
653        for field in T::FIELDS {
654            let name = field.name().to_owned();
655            let kind = field.kind();
656
657            // Published from the parser's own table, unless the field names the
658            // operators it serves; `parse_odata_filter` refuses the rest, so the
659            // contract and the parser hold to one set.
660            let ops: Vec<String> = match field.published_ops() {
661                Some(ops) => ops.iter().map(ToString::to_string).collect(),
662                None => [
663                    FilterOp::Eq,
664                    FilterOp::Ne,
665                    FilterOp::Gt,
666                    FilterOp::Ge,
667                    FilterOp::Lt,
668                    FilterOp::Le,
669                    FilterOp::Contains,
670                    FilterOp::StartsWith,
671                    FilterOp::EndsWith,
672                    FilterOp::In,
673                ]
674                .into_iter()
675                .filter(|op| kind.allows(*op))
676                .map(|op| op.to_string())
677                .collect(),
678            };
679
680            _ = write!(description, "\n- {}: {}", name, ops.join("|"));
681            filter.allowed_fields.insert(name.clone(), ops);
682        }
683        self.spec
684            .params
685            .push(ParamSpec::query("$filter").description(description));
686        self.spec.vendor_extensions.x_odata_filter = Some(filter);
687        self
688    }
689
690    fn with_odata_select(mut self) -> Self {
691        self.spec
692            .params
693            .push(ParamSpec::query("$select").description("OData v4 select expression"));
694        self
695    }
696
697    fn with_odata_orderby<T>(mut self) -> Self
698    where
699        T: toolkit_odata::filter::FilterField,
700    {
701        use std::fmt::Write as _;
702        let mut order_by = self
703            .spec
704            .vendor_extensions
705            .x_odata_orderby
706            .unwrap_or_default();
707        let mut description = "OData v4 orderby expression".to_owned();
708        // A filter-only field is refused in `$orderby` at request time, so the
709        // contract does not offer it.
710        for field in T::FIELDS.iter().filter(|field| field.orderable()) {
711            let name = field.name().to_owned();
712
713            // Add sort options (asc/desc)
714            let asc = format!("{name} asc");
715            let desc = format!("{name} desc");
716
717            _ = write!(description, "\n- {asc}\n- {desc}");
718            if !order_by.allowed_fields.contains(&asc) {
719                order_by.allowed_fields.push(asc);
720            }
721            if !order_by.allowed_fields.contains(&desc) {
722                order_by.allowed_fields.push(desc);
723            }
724        }
725        self.spec
726            .params
727            .push(ParamSpec::query("$orderby").description(description));
728        self.spec.vendor_extensions.x_odata_orderby = Some(order_by);
729        self
730    }
731}
732
733// Re-export from openapi_registry for backward compatibility
734pub use crate::api::openapi_registry::{OpenApiRegistry, ensure_schema};
735
736/// Type-safe operation builder with compile-time guarantees.
737///
738/// Generic parameters:
739/// - `H`: Handler state (Missing | Present)
740/// - `R`: Response state (Missing | Present)
741/// - `S`: Router state type (what you put into `Router::with_state(S)`).
742/// - `A`: Auth state (`AuthNotSet` | `AuthSet`)
743/// - `L`: License requirement state (`LicenseNotSet` | `LicenseSet`)
744#[must_use]
745pub struct OperationBuilder<H = Missing, R = Missing, S = (), A = AuthNotSet, L = LicenseNotSet>
746where
747    H: HandlerSlot<S>,
748    A: AuthState,
749    L: LicenseState,
750{
751    spec: OperationSpec,
752    method_router: <H as HandlerSlot<S>>::Slot,
753    _has_handler: PhantomData<H>,
754    _has_response: PhantomData<R>,
755    #[allow(clippy::type_complexity)]
756    _state: PhantomData<fn() -> S>, // Zero-sized marker for type-state pattern
757    _auth_state: PhantomData<A>,
758    _license_state: PhantomData<L>,
759}
760
761// -------------------------------------------------------------------------------------------------
762// Constructors — starts with both handler and response missing, auth not set
763// -------------------------------------------------------------------------------------------------
764impl<S> OperationBuilder<Missing, Missing, S, AuthNotSet> {
765    /// Create a new operation builder with an HTTP method and path
766    pub fn new(method: Method, path: impl Into<String>) -> Self {
767        let path_str = path.into();
768        let handler_id = format!(
769            "{}:{}",
770            method.as_str().to_lowercase(),
771            path_str.replace(['/', '{', '}'], "_")
772        );
773
774        Self {
775            spec: OperationSpec {
776                method,
777                path: path_str,
778                operation_id: None,
779                summary: None,
780                description: None,
781                tags: Vec::new(),
782                params: Vec::new(),
783                request_body: None,
784                responses: Vec::new(),
785                handler_id,
786                auth: RouteAuth::Anonymous,
787                exposed: false,
788                throttling: None,
789                allowed_request_content_types: None,
790                vendor_extensions: VendorExtensions::default(),
791                license_requirement: None,
792                request_timeout: RouteTimeout::Inherit,
793            },
794            method_router: (), // no router in Missing state
795            _has_handler: PhantomData,
796            _has_response: PhantomData,
797            _state: PhantomData,
798            _auth_state: PhantomData,
799            _license_state: PhantomData,
800        }
801    }
802
803    /// Convenience constructor for GET requests
804    pub fn get(path: impl Into<String>) -> Self {
805        let path_str = path.into();
806        Self::new(Method::GET, normalize_to_axum_path(&path_str))
807    }
808
809    /// Convenience constructor for POST requests
810    pub fn post(path: impl Into<String>) -> Self {
811        let path_str = path.into();
812        Self::new(Method::POST, normalize_to_axum_path(&path_str))
813    }
814
815    /// Convenience constructor for PUT requests
816    pub fn put(path: impl Into<String>) -> Self {
817        let path_str = path.into();
818        Self::new(Method::PUT, normalize_to_axum_path(&path_str))
819    }
820
821    /// Convenience constructor for DELETE requests
822    pub fn delete(path: impl Into<String>) -> Self {
823        let path_str = path.into();
824        Self::new(Method::DELETE, normalize_to_axum_path(&path_str))
825    }
826
827    /// Convenience constructor for PATCH requests
828    pub fn patch(path: impl Into<String>) -> Self {
829        let path_str = path.into();
830        Self::new(Method::PATCH, normalize_to_axum_path(&path_str))
831    }
832}
833
834// -------------------------------------------------------------------------------------------------
835// Descriptive methods — available at any stage
836// -------------------------------------------------------------------------------------------------
837impl<H, R, S, A, L> OperationBuilder<H, R, S, A, L>
838where
839    H: HandlerSlot<S>,
840    A: AuthState,
841    L: LicenseState,
842{
843    /// Inspect the spec (primarily for tests)
844    pub fn spec(&self) -> &OperationSpec {
845        &self.spec
846    }
847
848    /// Set the operation ID
849    pub fn operation_id(mut self, id: impl Into<String>) -> Self {
850        self.spec.operation_id = Some(id.into());
851        self
852    }
853
854    /// Attach zone-based throttling configuration to this operation.
855    ///
856    /// Binds the operation to gateway throttling zones (by name). The limits
857    /// themselves are defined in the gateway configuration.
858    pub fn with_throttling(mut self, spec: ThrottlingSpec) -> Self {
859        self.spec.throttling = Some(spec);
860        self
861    }
862
863    /// Give this operation its own request deadline, replacing the gateway's
864    /// `defaults.request_timeout` (e.g. a synchronous-publish route whose
865    /// handler legitimately holds the response longer than the default).
866    pub fn request_timeout(mut self, timeout: Duration) -> Self {
867        self.spec.request_timeout = RouteTimeout::Custom(timeout);
868        self
869    }
870
871    /// Exempt this operation from the gateway request timeout entirely; for
872    /// long-lived streaming routes (SSE, multipart streams) that a unary
873    /// deadline would truncate.
874    pub fn no_request_timeout(mut self) -> Self {
875        self.spec.request_timeout = RouteTimeout::Disabled;
876        self
877    }
878
879    /// Set the operation summary
880    pub fn summary(mut self, text: impl Into<String>) -> Self {
881        self.spec.summary = Some(text.into());
882        self
883    }
884
885    /// Set the operation description
886    pub fn description(mut self, text: impl Into<String>) -> Self {
887        self.spec.description = Some(text.into());
888        self
889    }
890
891    /// Add a tag to the operation
892    pub fn tag(mut self, tag: impl Into<String>) -> Self {
893        self.spec.tags.push(tag.into());
894        self
895    }
896
897    /// Add a parameter to the operation
898    pub fn param(mut self, param: ParamSpec) -> Self {
899        self.spec.params.push(param);
900        self
901    }
902
903    /// Add a path parameter with type inference (defaults to string)
904    pub fn path_param(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
905        self.spec
906            .params
907            .push(ParamSpec::path(name).description(description));
908        self
909    }
910
911    /// Add a query parameter (defaults to string)
912    pub fn query_param(
913        mut self,
914        name: impl Into<String>,
915        required: bool,
916        description: impl Into<String>,
917    ) -> Self {
918        self.spec.params.push(
919            ParamSpec::query(name)
920                .required(required)
921                .description(description),
922        );
923        self
924    }
925
926    /// Add a typed query parameter with explicit `OpenAPI` type
927    pub fn query_param_typed(
928        mut self,
929        name: impl Into<String>,
930        required: bool,
931        description: impl Into<String>,
932        param_type: impl Into<String>,
933    ) -> Self {
934        self.spec.params.push(
935            ParamSpec::query(name)
936                .required(required)
937                .description(description)
938                .param_type(param_type),
939        );
940        self
941    }
942
943    /// Add a string query parameter that only accepts `values`.
944    ///
945    /// The values reach the document as the parameter's `enum`, so a client
946    /// generated from the spec gets a closed set rather than a bare string,
947    /// and a caller reading the document can see what the endpoint takes
948    /// without trying one.
949    ///
950    /// The parameter stays a string; [`ParamSpec::enum_values`] is what
951    /// narrows it.
952    pub fn query_param_enum<V, I>(
953        mut self,
954        name: impl Into<String>,
955        required: bool,
956        description: impl Into<String>,
957        values: I,
958    ) -> Self
959    where
960        I: IntoIterator<Item = V>,
961        V: AsRef<str>,
962    {
963        self.spec.params.push(
964            ParamSpec::query(name)
965                .required(required)
966                .description(description)
967                .enum_values(values),
968        );
969        self
970    }
971
972    /// Register every query parameter declared by a
973    /// `#[derive(toolkit_contract::QueryParams)]` struct.
974    ///
975    /// The generated REST routes use this so the spec and the wire format come
976    /// from one declaration. Fields render as scalars or, for `Vec` fields, as
977    /// `style: form, explode: true` arrays.
978    pub fn query_params_from<T: toolkit_contract::query::QueryParams>(mut self) -> Self {
979        for p in T::openapi_params() {
980            self.spec.params.push(
981                ParamSpec::query(p.name)
982                    .required(p.required)
983                    .param_type(p.openapi_type)
984                    .array(p.array),
985            );
986        }
987        self
988    }
989
990    /// Add a repeating query parameter — `?tag=a&tag=b`.
991    ///
992    /// `item_type` is the `OpenAPI` type of one element; the parameter renders
993    /// as an array with `style: form, explode: true`, which is the encoding the
994    /// generated REST client and its server extractor agree on for a `Vec<T>`
995    /// field.
996    pub fn query_param_array(
997        mut self,
998        name: impl Into<String>,
999        required: bool,
1000        description: impl Into<String>,
1001        item_type: impl Into<String>,
1002    ) -> Self {
1003        self.spec.params.push(
1004            ParamSpec::query(name)
1005                .required(required)
1006                .description(description)
1007                .param_type(item_type)
1008                .array(true),
1009        );
1010        self
1011    }
1012
1013    /// Attach a JSON request body by *schema name* that you've already registered.
1014    /// This variant sets a description (`Some(desc)`) and marks the body as **required**.
1015    pub fn json_request_schema(
1016        mut self,
1017        schema_name: impl Into<String>,
1018        desc: impl Into<String>,
1019    ) -> Self {
1020        self.spec.request_body = Some(RequestBodySpec {
1021            content_type: "application/json",
1022            description: Some(desc.into()),
1023            schema: RequestBodySchema::Ref {
1024                schema_name: schema_name.into(),
1025            },
1026            required: true,
1027        });
1028        self
1029    }
1030
1031    /// Attach a JSON request body by *schema name* with **no** description (`None`).
1032    /// Marks the body as **required**.
1033    pub fn json_request_schema_no_desc(mut self, schema_name: impl Into<String>) -> Self {
1034        self.spec.request_body = Some(RequestBodySpec {
1035            content_type: "application/json",
1036            description: None,
1037            schema: RequestBodySchema::Ref {
1038                schema_name: schema_name.into(),
1039            },
1040            required: true,
1041        });
1042        self
1043    }
1044
1045    /// Attach a JSON request body and auto-register its schema using `utoipa`.
1046    /// This variant sets a description (`Some(desc)`) and marks the body as **required**.
1047    pub fn json_request<T>(
1048        mut self,
1049        registry: &dyn OpenApiRegistry,
1050        desc: impl Into<String>,
1051    ) -> Self
1052    where
1053        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
1054    {
1055        let name = ensure_schema::<T>(registry);
1056        self.spec.request_body = Some(RequestBodySpec {
1057            content_type: "application/json",
1058            description: Some(desc.into()),
1059            schema: RequestBodySchema::Ref { schema_name: name },
1060            required: true,
1061        });
1062        self
1063    }
1064
1065    /// Attach a JSON request body (auto-register schema) with **no** description (`None`).
1066    /// Marks the body as **required**.
1067    pub fn json_request_no_desc<T>(mut self, registry: &dyn OpenApiRegistry) -> Self
1068    where
1069        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::RequestApiDto + 'static,
1070    {
1071        let name = ensure_schema::<T>(registry);
1072        self.spec.request_body = Some(RequestBodySpec {
1073            content_type: "application/json",
1074            description: None,
1075            schema: RequestBodySchema::Ref { schema_name: name },
1076            required: true,
1077        });
1078        self
1079    }
1080
1081    /// Make the previously attached request body **optional** (if any).
1082    pub fn request_optional(mut self) -> Self {
1083        if let Some(rb) = &mut self.spec.request_body {
1084            rb.required = false;
1085        }
1086        self
1087    }
1088
1089    /// Configure a multipart/form-data file upload request.
1090    ///
1091    /// This is a convenience helper for file upload endpoints that:
1092    /// - Sets the request body content type to "multipart/form-data"
1093    /// - Sets a description for the request body
1094    /// - Configures an inline object schema with a binary file field
1095    /// - Restricts allowed Content-Type to only "multipart/form-data"
1096    ///
1097    /// The file field will be documented in `OpenAPI` as a binary string with the
1098    /// given field name. This generates the correct `OpenAPI` schema for UI tools
1099    /// like Stoplight to display a file upload control.
1100    ///
1101    /// # Arguments
1102    /// * `field_name` - Name of the multipart form field (e.g., "file")
1103    /// * `description` - Optional description for the request body
1104    ///
1105    /// # Example
1106    /// ```rust
1107    /// # use axum::Router;
1108    /// # use http::StatusCode;
1109    /// # use toolkit::api::{
1110    /// #     openapi_registry::OpenApiRegistryImpl,
1111    /// #     operation_builder::OperationBuilder,
1112    /// # };
1113    /// # async fn upload_handler() -> &'static str { "uploaded" }
1114    /// # let registry = OpenApiRegistryImpl::new();
1115    /// # let router: Router<()> = Router::new();
1116    /// let router = OperationBuilder::post("/files/v1/upload")
1117    ///     .operation_id("upload_file")
1118    ///     .summary("Upload a file")
1119    ///     .multipart_file_request("file", Some("File to upload"))
1120    ///     .anonymous()
1121    ///     .handler(upload_handler)
1122    ///     .json_response(StatusCode::OK, "Upload successful")
1123    ///     .register(router, &registry);
1124    /// # let _ = router;
1125    /// ```
1126    pub fn multipart_file_request(mut self, field_name: &str, description: Option<&str>) -> Self {
1127        // Set request body with multipart/form-data content type
1128        self.spec.request_body = Some(RequestBodySpec {
1129            content_type: "multipart/form-data",
1130            description: description
1131                .map(|s| format!("{s} (expects field '{field_name}' with file data)")),
1132            schema: RequestBodySchema::MultipartFile {
1133                field_name: field_name.to_owned(),
1134            },
1135            required: true,
1136        });
1137
1138        // Also configure MIME type validation
1139        self.spec.allowed_request_content_types = Some(vec!["multipart/form-data"]);
1140
1141        self
1142    }
1143
1144    /// Configure the request body as raw binary (application/octet-stream).
1145    ///
1146    /// This is intended for endpoints that accept the entire request body
1147    /// as a file or arbitrary bytes, without multipart form encoding.
1148    ///
1149    /// The `OpenAPI` schema will be:
1150    /// ```yaml
1151    /// requestBody:
1152    ///   required: true
1153    ///   content:
1154    ///     application/octet-stream:
1155    ///       schema:
1156    ///         type: string
1157    ///         format: binary
1158    /// ```
1159    ///
1160    /// Tools like Stoplight will render this as a single file upload control
1161    /// for the entire body.
1162    ///
1163    /// # Arguments
1164    /// * `description` - Optional description for the request body
1165    ///
1166    /// # Example
1167    /// ```rust
1168    /// # use axum::Router;
1169    /// # use http::StatusCode;
1170    /// # use toolkit::api::{
1171    /// #     openapi_registry::OpenApiRegistryImpl,
1172    /// #     operation_builder::OperationBuilder,
1173    /// # };
1174    /// # async fn upload_handler() -> &'static str { "uploaded" }
1175    /// # let registry = OpenApiRegistryImpl::new();
1176    /// # let router: Router<()> = Router::new();
1177    /// let router = OperationBuilder::post("/files/v1/upload")
1178    ///     .operation_id("upload_file")
1179    ///     .summary("Upload a file")
1180    ///     .octet_stream_request(Some("Raw file bytes to parse"))
1181    ///     .anonymous()
1182    ///     .handler(upload_handler)
1183    ///     .json_response(StatusCode::OK, "Upload successful")
1184    ///     .register(router, &registry);
1185    /// # let _ = router;
1186    /// ```
1187    pub fn octet_stream_request(mut self, description: Option<&str>) -> Self {
1188        self.spec.request_body = Some(RequestBodySpec {
1189            content_type: "application/octet-stream",
1190            description: description.map(str::to_owned),
1191            schema: RequestBodySchema::Binary,
1192            required: true,
1193        });
1194
1195        // Also configure MIME type validation
1196        self.spec.allowed_request_content_types = Some(vec!["application/octet-stream"]);
1197
1198        self
1199    }
1200
1201    /// Configure allowed request MIME types for this operation.
1202    ///
1203    /// This attaches a whitelist of allowed Content-Type values (without parameters),
1204    /// which will be enforced by gateway middleware. If a request arrives with a
1205    /// Content-Type that is not in this list, gateway will return HTTP 415.
1206    ///
1207    /// This is independent of the request body schema - it only configures gateway
1208    /// validation and does not affect `OpenAPI` request body specifications.
1209    ///
1210    /// # Example
1211    /// ```rust
1212    /// # use axum::Router;
1213    /// # use http::StatusCode;
1214    /// # use toolkit::api::{
1215    /// #     openapi_registry::OpenApiRegistryImpl,
1216    /// #     operation_builder::OperationBuilder,
1217    /// # };
1218    /// # async fn upload_handler() -> &'static str { "uploaded" }
1219    /// # let registry = OpenApiRegistryImpl::new();
1220    /// # let router: Router<()> = Router::new();
1221    /// let router = OperationBuilder::post("/files/v1/upload")
1222    ///     .operation_id("upload_file")
1223    ///     .allow_content_types(&["multipart/form-data", "application/pdf"])
1224    ///     .anonymous()
1225    ///     .handler(upload_handler)
1226    ///     .json_response(StatusCode::OK, "Upload successful")
1227    ///     .register(router, &registry);
1228    /// # let _ = router;
1229    /// ```
1230    pub fn allow_content_types(mut self, types: &[&'static str]) -> Self {
1231        self.spec.allowed_request_content_types = Some(types.to_vec());
1232        self
1233    }
1234
1235    /// Expose the route through the gateway, independently of authentication. Internal by
1236    /// default; callable at any stage. Platform auth suppresses exposure with a warning.
1237    pub fn exposed(mut self) -> Self {
1238        self.spec.exposed = true;
1239        self
1240    }
1241}
1242
1243/// License requirement setting — transitions `LicenseNotSet` -> `LicenseSet`
1244impl<H, R, S> OperationBuilder<H, R, S, AuthSet, LicenseNotSet>
1245where
1246    H: HandlerSlot<S>,
1247{
1248    /// Set (or explicitly clear) the license feature requirement for this operation.
1249    ///
1250    /// This method is only available after the auth requirement has been decided
1251    /// (i.e. after calling `authenticated()`).
1252    ///
1253    /// **Mandatory for authenticated endpoints:** operations configured with `authenticated()`
1254    /// must call `require_license_features(...)` before `register()`, because `register()` is only
1255    /// available once the license requirement state has transitioned to `LicenseSet`.
1256    ///
1257    /// **Not available for public endpoints:** public routes cannot (and do not need to) call this method.
1258    ///
1259    /// Pass an empty iterator (e.g. `[]`) to explicitly declare that no license feature is required.
1260    pub fn require_license_features<F>(
1261        mut self,
1262        licenses: impl IntoIterator<Item = F>,
1263    ) -> OperationBuilder<H, R, S, AuthSet, LicenseSet>
1264    where
1265        F: LicenseFeature,
1266    {
1267        let license_names: Vec<String> = licenses
1268            .into_iter()
1269            .map(|l| l.as_ref().to_owned())
1270            .collect();
1271
1272        self.spec.license_requirement =
1273            (!license_names.is_empty()).then_some(LicenseReqSpec { license_names });
1274
1275        OperationBuilder {
1276            spec: self.spec,
1277            method_router: self.method_router,
1278            _has_handler: self._has_handler,
1279            _has_response: self._has_response,
1280            _state: self._state,
1281            _auth_state: self._auth_state,
1282            _license_state: PhantomData,
1283        }
1284    }
1285
1286    /// Explicitly declare that this operation does not require any license.
1287    ///
1288    /// Use this for system/infrastructure endpoints that need authentication
1289    /// but are not gated behind application-level license features.
1290    ///
1291    /// This transitions from `LicenseNotSet` to `LicenseSet` without
1292    /// attaching any license requirement.
1293    pub fn no_license_required(self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1294        OperationBuilder {
1295            spec: self.spec,
1296            method_router: self.method_router,
1297            _has_handler: self._has_handler,
1298            _has_response: self._has_response,
1299            _state: self._state,
1300            _auth_state: self._auth_state,
1301            _license_state: PhantomData,
1302        }
1303    }
1304}
1305
1306// -------------------------------------------------------------------------------------------------
1307// Auth requirement setting — transitions AuthNotSet -> AuthSet
1308// -------------------------------------------------------------------------------------------------
1309impl<H, R, S, L> OperationBuilder<H, R, S, AuthNotSet, L>
1310where
1311    H: HandlerSlot<S>,
1312    L: LicenseState,
1313{
1314    /// Mark this route as requiring authentication.
1315    ///
1316    /// This is a binary marker — the route requires a valid bearer token.
1317    /// Scope enforcement (which scopes are needed) is configured at the
1318    /// gateway level, not per-route.
1319    ///
1320    /// This method transitions from `AuthNotSet` to `AuthSet` state.
1321    ///
1322    /// # Example
1323    /// ```rust
1324    /// # use toolkit::api::operation_builder::{
1325    /// #     OperationBuilder, LicenseFeature, CORE_GLOBAL_BASE_LICENSE_FEATURE,
1326    /// # };
1327    /// # use axum::{extract::Json, Router };
1328    /// # use serde::{Serialize};
1329    /// #
1330    /// # #[derive(Serialize)]
1331    /// # pub struct User;
1332    /// #
1333    /// enum License {
1334    ///     Base,
1335    /// }
1336    ///
1337    /// impl AsRef<str> for License {
1338    ///     fn as_ref(&self) -> &str {
1339    ///         match self {
1340    ///             License::Base => CORE_GLOBAL_BASE_LICENSE_FEATURE,
1341    ///         }
1342    ///     }
1343    /// }
1344    ///
1345    /// impl LicenseFeature for License {}
1346    ///
1347    /// #
1348    /// # fn register_rest(
1349    /// #   router: axum::Router,
1350    /// #   api: &dyn toolkit::api::OpenApiRegistry,
1351    /// # ) -> anyhow::Result<axum::Router> {
1352    /// let router = OperationBuilder::get("/users-info/v1/users")
1353    ///     .authenticated()
1354    ///     .require_license_features::<License>([])
1355    ///     .handler(list_users_handler)
1356    ///     .json_response(axum::http::StatusCode::OK, "List of users")
1357    ///     .register(router, api);
1358    /// #  Ok(router)
1359    /// # }
1360    ///
1361    /// # async fn list_users_handler() -> Json<Vec<User>> {
1362    /// #   unimplemented!()
1363    /// # }
1364    /// ```
1365    pub fn authenticated(mut self) -> OperationBuilder<H, R, S, AuthSet, L> {
1366        self.spec.auth = RouteAuth::Authenticated;
1367        OperationBuilder {
1368            spec: self.spec,
1369            method_router: self.method_router,
1370            _has_handler: self._has_handler,
1371            _has_response: self._has_response,
1372            _state: self._state,
1373            _auth_state: PhantomData,
1374            _license_state: self._license_state,
1375        }
1376    }
1377
1378    /// Require a validated `X-ToolKit-Internal-Token`; a bearer alone is never validated and
1379    /// yields 401, as do missing internal auth and a bearer beside the token. `OpenAPI` uses
1380    /// [`INTERNAL_TOKEN_SECURITY_SCHEME`]; discovery excludes the route. Handlers read
1381    /// `Extension<PlatformSecurityContext>`; a license decision is still required.
1382    pub fn platform_authenticated(mut self) -> OperationBuilder<H, R, S, AuthSet, L> {
1383        self.spec.auth = RouteAuth::Platform;
1384        OperationBuilder {
1385            spec: self.spec,
1386            method_router: self.method_router,
1387            _has_handler: self._has_handler,
1388            _has_response: self._has_response,
1389            _state: self._state,
1390            _auth_state: PhantomData,
1391            _license_state: self._license_state,
1392        }
1393    }
1394
1395    /// Mark this route as **anonymous** — no authentication required (the *auth*
1396    /// axis).
1397    ///
1398    /// A missing `Authorization: Bearer` header is allowed; a present bearer is
1399    /// still always re-validated. This explicitly opts out of the
1400    /// `require_auth_by_default` setting and maps to the `AnonymousRoute` marker
1401    /// in the `OoP` per-gear middleware. It is independent of visibility — use
1402    /// [`exposed`](Self::exposed) to also register the route in the gateway.
1403    /// This method transitions from `AuthNotSet` to `AuthSet` state.
1404    ///
1405    /// # Example
1406    /// ```rust
1407    /// # use axum::Router;
1408    /// # use http::StatusCode;
1409    /// # use toolkit::api::{
1410    /// #     openapi_registry::OpenApiRegistryImpl,
1411    /// #     operation_builder::OperationBuilder,
1412    /// # };
1413    /// # async fn health_check() -> &'static str { "OK" }
1414    /// # let registry = OpenApiRegistryImpl::new();
1415    /// # let router: Router<()> = Router::new();
1416    /// let router = OperationBuilder::get("/users-info/v1/health")
1417    ///     .anonymous()
1418    ///     .handler(health_check)
1419    ///     .json_response(StatusCode::OK, "OK")
1420    ///     .register(router, &registry);
1421    /// # let _ = router;
1422    /// ```
1423    pub fn anonymous(mut self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1424        self.spec.auth = RouteAuth::Anonymous;
1425        OperationBuilder {
1426            spec: self.spec,
1427            method_router: self.method_router,
1428            _has_handler: self._has_handler,
1429            _has_response: self._has_response,
1430            _state: self._state,
1431            _auth_state: PhantomData,
1432            _license_state: PhantomData,
1433        }
1434    }
1435
1436    /// Deprecated alias for the old single-axis `.public()`.
1437    ///
1438    /// The old `.public()` meant both **anonymous** (no auth) *and* **edge
1439    /// visible**. Those are now separate axes: [`anonymous`](Self::anonymous)
1440    /// (auth) and [`exposed`](Self::exposed) (visibility). This shim maps to
1441    /// `.anonymous().exposed()` so out-of-tree gears keep compiling for one
1442    /// release; a bare `.anonymous()` (the naive mechanical replacement) would
1443    /// silently drop the route from the edge, which this warning surfaces at
1444    /// compile time instead.
1445    #[deprecated(
1446        since = "0.6.21",
1447        note = "`.public()` split into two axes; use `.anonymous().exposed()` \
1448                (this alias forwards to exactly that)"
1449    )]
1450    pub fn public(self) -> OperationBuilder<H, R, S, AuthSet, LicenseSet> {
1451        self.anonymous().exposed()
1452    }
1453}
1454
1455// -------------------------------------------------------------------------------------------------
1456// Handler setting — transitions Missing -> Present for handler
1457// -------------------------------------------------------------------------------------------------
1458impl<R, S, A, L> OperationBuilder<Missing, R, S, A, L>
1459where
1460    S: Clone + Send + Sync + 'static,
1461    A: AuthState,
1462    L: LicenseState,
1463{
1464    /// Set the handler for this operation (function handlers are recommended).
1465    ///
1466    /// This transitions the builder from `Missing` to `Present` handler state.
1467    pub fn handler<F, T>(self, h: F) -> OperationBuilder<Present, R, S, A, L>
1468    where
1469        F: Handler<T, S> + Clone + Send + 'static,
1470        T: 'static,
1471    {
1472        let method_router = match self.spec.method {
1473            Method::GET => axum::routing::get(h),
1474            Method::POST => axum::routing::post(h),
1475            Method::PUT => axum::routing::put(h),
1476            Method::DELETE => axum::routing::delete(h),
1477            Method::PATCH => axum::routing::patch(h),
1478            _ => axum::routing::any(|| async { axum::http::StatusCode::METHOD_NOT_ALLOWED }),
1479        };
1480
1481        OperationBuilder {
1482            spec: self.spec,
1483            method_router, // concrete MethodRouter<S> in Present state
1484            _has_handler: PhantomData::<Present>,
1485            _has_response: self._has_response,
1486            _state: self._state,
1487            _auth_state: self._auth_state,
1488            _license_state: self._license_state,
1489        }
1490    }
1491
1492    /// Alternative path: provide a pre-composed `MethodRouter<S>` yourself
1493    /// (useful to attach per-route middleware/layers).
1494    pub fn method_router(self, mr: MethodRouter<S>) -> OperationBuilder<Present, R, S, A, L> {
1495        OperationBuilder {
1496            spec: self.spec,
1497            method_router: mr, // concrete MethodRouter<S> in Present state
1498            _has_handler: PhantomData::<Present>,
1499            _has_response: self._has_response,
1500            _state: self._state,
1501            _auth_state: self._auth_state,
1502            _license_state: self._license_state,
1503        }
1504    }
1505}
1506
1507// -------------------------------------------------------------------------------------------------
1508// Response setting — transitions Missing -> Present for response (first response)
1509// -------------------------------------------------------------------------------------------------
1510impl<H, S, A, L> OperationBuilder<H, Missing, S, A, L>
1511where
1512    H: HandlerSlot<S>,
1513    A: AuthState,
1514    L: LicenseState,
1515{
1516    /// Add a raw response spec (transitions from Missing to Present).
1517    pub fn response(mut self, resp: ResponseSpec) -> OperationBuilder<H, Present, S, A, L> {
1518        self.spec.responses.push(resp);
1519        OperationBuilder {
1520            spec: self.spec,
1521            method_router: self.method_router,
1522            _has_handler: self._has_handler,
1523            _has_response: PhantomData::<Present>,
1524            _state: self._state,
1525            _auth_state: self._auth_state,
1526            _license_state: self._license_state,
1527        }
1528    }
1529
1530    /// Add a JSON response (transitions from Missing to Present).
1531    pub fn json_response(
1532        mut self,
1533        status: http::StatusCode,
1534        description: impl Into<String>,
1535    ) -> OperationBuilder<H, Present, S, A, L> {
1536        self.spec.responses.push(ResponseSpec {
1537            status: status.as_u16(),
1538            content_type: "application/json",
1539            description: description.into(),
1540            schema: None,
1541            headers: Vec::new(),
1542        });
1543        OperationBuilder {
1544            spec: self.spec,
1545            method_router: self.method_router,
1546            _has_handler: self._has_handler,
1547            _has_response: PhantomData::<Present>,
1548            _state: self._state,
1549            _auth_state: self._auth_state,
1550            _license_state: self._license_state,
1551        }
1552    }
1553
1554    /// Add a body-less response (e.g. `204 No Content`) — transitions from
1555    /// Missing to Present.
1556    ///
1557    /// `OpenAPI` consumers and code-generators treat a `204` response with a
1558    /// `content` block as advertising a body, which is incorrect. Use this
1559    /// helper for any handler that intentionally returns no payload (typical
1560    /// for `DELETE` / `PUT` semantics).
1561    pub fn no_content_response(
1562        mut self,
1563        status: http::StatusCode,
1564        description: impl Into<String>,
1565    ) -> OperationBuilder<H, Present, S, A, L> {
1566        self.spec.responses.push(ResponseSpec {
1567            status: status.as_u16(),
1568            content_type: "",
1569            description: description.into(),
1570            schema: None,
1571            headers: Vec::new(),
1572        });
1573        OperationBuilder {
1574            spec: self.spec,
1575            method_router: self.method_router,
1576            _has_handler: self._has_handler,
1577            _has_response: PhantomData::<Present>,
1578            _state: self._state,
1579            _auth_state: self._auth_state,
1580            _license_state: self._license_state,
1581        }
1582    }
1583
1584    /// Add a JSON response with a registered schema (transitions from Missing to Present).
1585    pub fn json_response_with_schema<T>(
1586        mut self,
1587        registry: &dyn OpenApiRegistry,
1588        status: http::StatusCode,
1589        description: impl Into<String>,
1590    ) -> OperationBuilder<H, Present, S, A, L>
1591    where
1592        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1593    {
1594        let name = ensure_schema::<T>(registry);
1595        self.spec.responses.push(ResponseSpec {
1596            status: status.as_u16(),
1597            content_type: "application/json",
1598            description: description.into(),
1599            schema: Some(ResponseSchema::Ref { schema_name: name }),
1600            headers: Vec::new(),
1601        });
1602        OperationBuilder {
1603            spec: self.spec,
1604            method_router: self.method_router,
1605            _has_handler: self._has_handler,
1606            _has_response: PhantomData::<Present>,
1607            _state: self._state,
1608            _auth_state: self._auth_state,
1609            _license_state: self._license_state,
1610        }
1611    }
1612
1613    /// Add a JSON response whose body is a **top-level array** of `T`
1614    /// (transitions from Missing to Present).
1615    ///
1616    /// `T` is the *item* type — pass `GearDto`, not `Vec<GearDto>`. Registers
1617    /// `T` as a named component and emits an inline
1618    /// `{type: array, items: {$ref: T}}` schema for the response body.
1619    ///
1620    /// Never pass `Vec<T>` to [`Self::json_response_with_schema`]: utoipa's
1621    /// default `ToSchema::name()` strips generic arguments, so every `Vec<_>`
1622    /// registers under the single component name `Vec` and two such responses
1623    /// collide fatally in `OpenApiRegistryImpl::ensure_schema_raw`.
1624    pub fn json_array_response_with_schema<T>(
1625        mut self,
1626        registry: &dyn OpenApiRegistry,
1627        status: http::StatusCode,
1628        description: impl Into<String>,
1629    ) -> OperationBuilder<H, Present, S, A, L>
1630    where
1631        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1632    {
1633        let items_schema_name = ensure_schema::<T>(registry);
1634        self.spec.responses.push(ResponseSpec {
1635            status: status.as_u16(),
1636            content_type: "application/json",
1637            description: description.into(),
1638            schema: Some(ResponseSchema::Array { items_schema_name }),
1639            headers: Vec::new(),
1640        });
1641        OperationBuilder {
1642            spec: self.spec,
1643            method_router: self.method_router,
1644            _has_handler: self._has_handler,
1645            _has_response: PhantomData::<Present>,
1646            _state: self._state,
1647            _auth_state: self._auth_state,
1648            _license_state: self._license_state,
1649        }
1650    }
1651
1652    /// Add a text response with a custom content type (transitions from Missing to Present).
1653    ///
1654    /// # Arguments
1655    /// * `status` - HTTP status code
1656    /// * `description` - Description of the response
1657    /// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
1658    ///
1659    /// # Important
1660    /// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
1661    /// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
1662    /// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
1663    /// include the charset parameter.
1664    pub fn text_response(
1665        mut self,
1666        status: http::StatusCode,
1667        description: impl Into<String>,
1668        content_type: &'static str,
1669    ) -> OperationBuilder<H, Present, S, A, L> {
1670        self.spec.responses.push(ResponseSpec {
1671            status: status.as_u16(),
1672            content_type,
1673            description: description.into(),
1674            schema: None,
1675            headers: Vec::new(),
1676        });
1677        OperationBuilder {
1678            spec: self.spec,
1679            method_router: self.method_router,
1680            _has_handler: self._has_handler,
1681            _has_response: PhantomData::<Present>,
1682            _state: self._state,
1683            _auth_state: self._auth_state,
1684            _license_state: self._license_state,
1685        }
1686    }
1687
1688    /// Add an HTML response (transitions from Missing to Present).
1689    pub fn html_response(
1690        mut self,
1691        status: http::StatusCode,
1692        description: impl Into<String>,
1693    ) -> OperationBuilder<H, Present, S, A, L> {
1694        self.spec.responses.push(ResponseSpec {
1695            status: status.as_u16(),
1696            content_type: "text/html",
1697            description: description.into(),
1698            schema: None,
1699            headers: Vec::new(),
1700        });
1701        OperationBuilder {
1702            spec: self.spec,
1703            method_router: self.method_router,
1704            _has_handler: self._has_handler,
1705            _has_response: PhantomData::<Present>,
1706            _state: self._state,
1707            _auth_state: self._auth_state,
1708            _license_state: self._license_state,
1709        }
1710    }
1711
1712    /// Add an RFC 9457 `application/problem+json` response (transitions from Missing to Present).
1713    pub fn problem_response(
1714        mut self,
1715        registry: &dyn OpenApiRegistry,
1716        status: http::StatusCode,
1717        description: impl Into<String>,
1718    ) -> OperationBuilder<H, Present, S, A, L> {
1719        // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
1720        let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
1721        self.spec.responses.push(ResponseSpec {
1722            status: status.as_u16(),
1723            content_type: problem::APPLICATION_PROBLEM_JSON,
1724            description: description.into(),
1725            schema: Some(ResponseSchema::Ref {
1726                schema_name: problem_name,
1727            }),
1728            headers: Vec::new(),
1729        });
1730        OperationBuilder {
1731            spec: self.spec,
1732            method_router: self.method_router,
1733            _has_handler: self._has_handler,
1734            _has_response: PhantomData::<Present>,
1735            _state: self._state,
1736            _auth_state: self._auth_state,
1737            _license_state: self._license_state,
1738        }
1739    }
1740
1741    /// First response: SSE stream of JSON events (`text/event-stream`).
1742    pub fn sse_json<T>(
1743        mut self,
1744        openapi: &dyn OpenApiRegistry,
1745        description: impl Into<String>,
1746    ) -> OperationBuilder<H, Present, S, A, L>
1747    where
1748        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1749    {
1750        let name = ensure_schema::<T>(openapi);
1751        self.spec.responses.push(ResponseSpec {
1752            status: http::StatusCode::OK.as_u16(),
1753            content_type: "text/event-stream",
1754            description: description.into(),
1755            schema: Some(ResponseSchema::Ref { schema_name: name }),
1756            headers: Vec::new(),
1757        });
1758        OperationBuilder {
1759            spec: self.spec,
1760            method_router: self.method_router,
1761            _has_handler: self._has_handler,
1762            _has_response: PhantomData::<Present>,
1763            _state: self._state,
1764            _auth_state: self._auth_state,
1765            _license_state: self._license_state,
1766        }
1767    }
1768
1769    /// First response: `multipart/mixed` stream of JSON items, one item per
1770    /// body part — the server-to-server counterpart to [`Self::sse_json`].
1771    ///
1772    /// `T` is the *item* type, exactly as for SSE: the media-type key in the
1773    /// spec is the bare `multipart/mixed`, with no `boundary=` parameter,
1774    /// because the boundary is generated per response at runtime by
1775    /// [`crate::http::multipart::MultipartJsonStream`] and is not a property of
1776    /// the operation.
1777    pub fn multipart_json<T>(
1778        mut self,
1779        openapi: &dyn OpenApiRegistry,
1780        description: impl Into<String>,
1781    ) -> OperationBuilder<H, Present, S, A, L>
1782    where
1783        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1784    {
1785        let name = ensure_schema::<T>(openapi);
1786        self.spec.responses.push(ResponseSpec {
1787            status: http::StatusCode::OK.as_u16(),
1788            content_type: "multipart/mixed",
1789            description: description.into(),
1790            schema: Some(ResponseSchema::Ref { schema_name: name }),
1791            headers: Vec::new(),
1792        });
1793        OperationBuilder {
1794            spec: self.spec,
1795            method_router: self.method_router,
1796            _has_handler: self._has_handler,
1797            _has_response: PhantomData::<Present>,
1798            _state: self._state,
1799            _auth_state: self._auth_state,
1800            _license_state: self._license_state,
1801        }
1802    }
1803}
1804
1805// -------------------------------------------------------------------------------------------------
1806// Additional responses — for Present response state (additional responses)
1807// -------------------------------------------------------------------------------------------------
1808impl<H, S, A, L> OperationBuilder<H, Present, S, A, L>
1809where
1810    H: HandlerSlot<S>,
1811    A: AuthState,
1812    L: LicenseState,
1813{
1814    /// Declare a header on the most recently declared response.
1815    ///
1816    /// Call this immediately after the response declaration it describes.
1817    /// Consecutive calls attach multiple headers to that same response.
1818    ///
1819    /// # Panics
1820    /// Panics when the response status already has a header with the same
1821    /// case-insensitive name.
1822    pub fn response_header(mut self, header: ResponseHeaderSpec) -> Self {
1823        let Some(response) = self.spec.responses.last() else {
1824            unreachable!("Present response state guarantees a response");
1825        };
1826        let status = response.status;
1827        assert!(
1828            !self.spec.responses.iter().any(|response| {
1829                response.status == status
1830                    && response
1831                        .headers
1832                        .iter()
1833                        .any(|existing| existing.name.eq_ignore_ascii_case(&header.name))
1834            }),
1835            "response {status} already declares header '{}'",
1836            header.name
1837        );
1838        let Some(response) = self.spec.responses.last_mut() else {
1839            unreachable!("Present response state guarantees a response");
1840        };
1841        response.headers.push(header);
1842        self
1843    }
1844
1845    /// Add a JSON response (additional).
1846    pub fn json_response(
1847        mut self,
1848        status: http::StatusCode,
1849        description: impl Into<String>,
1850    ) -> Self {
1851        self.spec.upsert_response(ResponseSpec {
1852            status: status.as_u16(),
1853            content_type: "application/json",
1854            description: description.into(),
1855            schema: None,
1856            headers: Vec::new(),
1857        });
1858        self
1859    }
1860
1861    /// Add a body-less response (e.g. `204 No Content`) — additional variant.
1862    pub fn no_content_response(
1863        mut self,
1864        status: http::StatusCode,
1865        description: impl Into<String>,
1866    ) -> Self {
1867        self.spec.upsert_response(ResponseSpec {
1868            status: status.as_u16(),
1869            content_type: "",
1870            description: description.into(),
1871            schema: None,
1872            headers: Vec::new(),
1873        });
1874        self
1875    }
1876
1877    /// Add a JSON response with a registered schema (additional).
1878    pub fn json_response_with_schema<T>(
1879        mut self,
1880        registry: &dyn OpenApiRegistry,
1881        status: http::StatusCode,
1882        description: impl Into<String>,
1883    ) -> Self
1884    where
1885        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1886    {
1887        let name = ensure_schema::<T>(registry);
1888        self.spec.upsert_response(ResponseSpec {
1889            status: status.as_u16(),
1890            content_type: "application/json",
1891            description: description.into(),
1892            schema: Some(ResponseSchema::Ref { schema_name: name }),
1893            headers: Vec::new(),
1894        });
1895        self
1896    }
1897
1898    /// Add a JSON response whose body is a **top-level array** of `T` (additional).
1899    ///
1900    /// `T` is the *item* type — pass `GearDto`, not `Vec<GearDto>`. See
1901    /// [`OperationBuilder::json_array_response_with_schema`] on the
1902    /// `Missing`-response builder for why arrays are emitted inline.
1903    pub fn json_array_response_with_schema<T>(
1904        mut self,
1905        registry: &dyn OpenApiRegistry,
1906        status: http::StatusCode,
1907        description: impl Into<String>,
1908    ) -> Self
1909    where
1910        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1911    {
1912        let items_schema_name = ensure_schema::<T>(registry);
1913        self.spec.upsert_response(ResponseSpec {
1914            status: status.as_u16(),
1915            content_type: "application/json",
1916            description: description.into(),
1917            schema: Some(ResponseSchema::Array { items_schema_name }),
1918            headers: Vec::new(),
1919        });
1920        self
1921    }
1922
1923    /// Add a text response with a custom content type (additional).
1924    ///
1925    /// # Arguments
1926    /// * `status` - HTTP status code
1927    /// * `description` - Description of the response
1928    /// * `content_type` - **Pure media type without parameters** (e.g., `"text/plain"`, `"text/markdown"`)
1929    ///
1930    /// # Important
1931    /// The `content_type` must be a pure media type **without parameters** like `; charset=utf-8`.
1932    /// `OpenAPI` media type keys cannot include parameters. Use `"text/markdown"` instead of
1933    /// `"text/markdown; charset=utf-8"`. Actual HTTP response headers in handlers should still
1934    /// include the charset parameter.
1935    pub fn text_response(
1936        mut self,
1937        status: http::StatusCode,
1938        description: impl Into<String>,
1939        content_type: &'static str,
1940    ) -> Self {
1941        self.spec.upsert_response(ResponseSpec {
1942            status: status.as_u16(),
1943            content_type,
1944            description: description.into(),
1945            schema: None,
1946            headers: Vec::new(),
1947        });
1948        self
1949    }
1950
1951    /// Add an HTML response (additional).
1952    pub fn html_response(
1953        mut self,
1954        status: http::StatusCode,
1955        description: impl Into<String>,
1956    ) -> Self {
1957        self.spec.upsert_response(ResponseSpec {
1958            status: status.as_u16(),
1959            content_type: "text/html",
1960            description: description.into(),
1961            schema: None,
1962            headers: Vec::new(),
1963        });
1964        self
1965    }
1966
1967    /// Add an additional RFC 9457 `application/problem+json` response.
1968    pub fn problem_response(
1969        mut self,
1970        registry: &dyn OpenApiRegistry,
1971        status: http::StatusCode,
1972        description: impl Into<String>,
1973    ) -> Self {
1974        // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
1975        let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
1976        self.spec.upsert_response(ResponseSpec {
1977            status: status.as_u16(),
1978            content_type: problem::APPLICATION_PROBLEM_JSON,
1979            description: description.into(),
1980            schema: Some(ResponseSchema::Ref {
1981                schema_name: problem_name,
1982            }),
1983            headers: Vec::new(),
1984        });
1985        self
1986    }
1987
1988    /// Additional SSE response (if the operation already has a response).
1989    pub fn sse_json<T>(
1990        mut self,
1991        openapi: &dyn OpenApiRegistry,
1992        description: impl Into<String>,
1993    ) -> Self
1994    where
1995        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
1996    {
1997        let name = ensure_schema::<T>(openapi);
1998        self.spec.upsert_response(ResponseSpec {
1999            status: http::StatusCode::OK.as_u16(),
2000            content_type: "text/event-stream",
2001            description: description.into(),
2002            schema: Some(ResponseSchema::Ref { schema_name: name }),
2003            headers: Vec::new(),
2004        });
2005        self
2006    }
2007
2008    /// Additional `multipart/mixed` response (if the operation already has
2009    /// one). See [`OperationBuilder::multipart_json`] on the first-response
2010    /// builder for what `T` and the media-type key mean.
2011    pub fn multipart_json<T>(
2012        mut self,
2013        openapi: &dyn OpenApiRegistry,
2014        description: impl Into<String>,
2015    ) -> Self
2016    where
2017        T: utoipa::ToSchema + utoipa::PartialSchema + api_dto::ResponseApiDto + 'static,
2018    {
2019        let name = ensure_schema::<T>(openapi);
2020        self.spec.upsert_response(ResponseSpec {
2021            status: http::StatusCode::OK.as_u16(),
2022            content_type: "multipart/mixed",
2023            description: description.into(),
2024            schema: Some(ResponseSchema::Ref { schema_name: name }),
2025            headers: Vec::new(),
2026        });
2027        self
2028    }
2029
2030    /// Add standard error responses (400, 401, 403, 404, 409, 422, 429, 500).
2031    ///
2032    /// All responses reference the shared Problem schema (RFC 9457) for consistent
2033    /// error handling across your API. This is the recommended way to declare
2034    /// common error responses without repeating boilerplate.
2035    ///
2036    /// # Example
2037    ///
2038    /// ```rust
2039    /// # use axum::Router;
2040    /// # use http::StatusCode;
2041    /// # use toolkit::api::{
2042    /// #     openapi_registry::OpenApiRegistryImpl,
2043    /// #     operation_builder::OperationBuilder,
2044    /// # };
2045    /// # async fn list_users() -> &'static str { "[]" }
2046    /// # let registry = OpenApiRegistryImpl::new();
2047    /// # let router: Router<()> = Router::new();
2048    /// let op = OperationBuilder::get("/user-info/v1/users")
2049    ///     .anonymous()
2050    ///     .handler(list_users)
2051    ///     .json_response(StatusCode::OK, "List of users")
2052    ///     .standard_errors(&registry);
2053    ///
2054    /// let router = op.register(router, &registry);
2055    /// # let _ = router;
2056    /// ```
2057    ///
2058    /// This adds the following error responses:
2059    /// - 400 Bad Request
2060    /// - 401 Unauthorized
2061    /// - 403 Forbidden
2062    /// - 404 Not Found
2063    /// - 409 Conflict
2064    /// - 429 Too Many Requests
2065    /// - 500 Internal Server Error
2066    ///
2067    /// 413/415/422 are intentionally absent here: canonical `InvalidArgument`
2068    /// maps to 400 per `docs/arch/errors/DESIGN.md` §1.2, so no
2069    /// canonical-handler path alone produces those statuses. An operation
2070    /// whose handler takes `toolkit::api::rest::extract::Json<T>` can produce
2071    /// all three (oversized body, wrong `Content-Type`, schema violation) -
2072    /// add [`Self::error_413`]/[`Self::error_415`]/[`Self::error_422`]
2073    /// individually for such an operation.
2074    pub fn standard_errors(mut self, registry: &dyn OpenApiRegistry) -> Self {
2075        use http::StatusCode;
2076        // Canonical Problem schema (RFC 9457 + GTS-typed). Component name "Problem".
2077        let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
2078
2079        let standard_errors = [
2080            (StatusCode::BAD_REQUEST, "Bad Request"),
2081            (StatusCode::UNAUTHORIZED, "Unauthorized"),
2082            (StatusCode::FORBIDDEN, "Forbidden"),
2083            (StatusCode::NOT_FOUND, "Not Found"),
2084            (StatusCode::CONFLICT, "Conflict"),
2085            (StatusCode::TOO_MANY_REQUESTS, "Too Many Requests"),
2086            (StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"),
2087        ];
2088
2089        for (status, description) in standard_errors {
2090            self.spec.upsert_response(ResponseSpec {
2091                status: status.as_u16(),
2092                content_type: problem::APPLICATION_PROBLEM_JSON,
2093                description: description.to_owned(),
2094                schema: Some(ResponseSchema::Ref {
2095                    schema_name: problem_name.clone(),
2096                }),
2097                headers: Vec::new(),
2098            });
2099        }
2100
2101        self
2102    }
2103
2104    /// Add 400 validation error response using the canonical `Problem` schema.
2105    ///
2106    /// Field-level violations surface under `context.field_violations[]`
2107    /// (canonical `InvalidArgument` category, HTTP 400 per
2108    /// `docs/arch/errors/DESIGN.md` §1.2 / §3.5).
2109    ///
2110    /// # Example
2111    ///
2112    /// ```rust
2113    /// # use axum::Router;
2114    /// # use http::StatusCode;
2115    /// # use toolkit::api::{
2116    /// #     openapi_registry::OpenApiRegistryImpl,
2117    /// #     operation_builder::OperationBuilder,
2118    /// # };
2119    /// # use serde::{Deserialize, Serialize};
2120    /// # use utoipa::ToSchema;
2121    /// #
2122    /// #[toolkit_macros::api_dto(request)]
2123    /// struct CreateUserRequest {
2124    ///     email: String,
2125    /// }
2126    ///
2127    /// # async fn create_user() -> &'static str { "created" }
2128    /// # let registry = OpenApiRegistryImpl::new();
2129    /// # let router: Router<()> = Router::new();
2130    /// let op = OperationBuilder::post("/users-info/v1/users")
2131    ///     .anonymous()
2132    ///     .handler(create_user)
2133    ///     .json_request::<CreateUserRequest>(&registry, "User data")
2134    ///     .json_response(StatusCode::CREATED, "User created")
2135    ///     .with_400_validation_error(&registry);
2136    ///
2137    /// let router = op.register(router, &registry);
2138    /// # let _ = router;
2139    /// ```
2140    pub fn with_400_validation_error(mut self, registry: &dyn OpenApiRegistry) -> Self {
2141        let problem_name = ensure_schema::<toolkit_canonical_errors::Problem>(registry);
2142
2143        self.spec.upsert_response(ResponseSpec {
2144            status: http::StatusCode::BAD_REQUEST.as_u16(),
2145            content_type: problem::APPLICATION_PROBLEM_JSON,
2146            description: "Validation Error".to_owned(),
2147            schema: Some(ResponseSchema::Ref {
2148                schema_name: problem_name,
2149            }),
2150            headers: Vec::new(),
2151        });
2152
2153        self
2154    }
2155
2156    /// Add a 400 Bad Request error response.
2157    ///
2158    /// This is a convenience wrapper around `problem_response`.
2159    pub fn error_400(self, registry: &dyn OpenApiRegistry) -> Self {
2160        self.problem_response(registry, http::StatusCode::BAD_REQUEST, "Bad Request")
2161    }
2162
2163    /// Add a 401 Unauthorized error response.
2164    ///
2165    /// This is a convenience wrapper around `problem_response`.
2166    pub fn error_401(self, registry: &dyn OpenApiRegistry) -> Self {
2167        self.problem_response(registry, http::StatusCode::UNAUTHORIZED, "Unauthorized")
2168    }
2169
2170    /// Add a 403 Forbidden error response.
2171    ///
2172    /// This is a convenience wrapper around `problem_response`.
2173    pub fn error_403(self, registry: &dyn OpenApiRegistry) -> Self {
2174        self.problem_response(registry, http::StatusCode::FORBIDDEN, "Forbidden")
2175    }
2176
2177    /// Add a 404 Not Found error response.
2178    ///
2179    /// This is a convenience wrapper around `problem_response`.
2180    pub fn error_404(self, registry: &dyn OpenApiRegistry) -> Self {
2181        self.problem_response(registry, http::StatusCode::NOT_FOUND, "Not Found")
2182    }
2183
2184    /// Add a 409 Conflict error response.
2185    ///
2186    /// This is a convenience wrapper around `problem_response`.
2187    pub fn error_409(self, registry: &dyn OpenApiRegistry) -> Self {
2188        self.problem_response(registry, http::StatusCode::CONFLICT, "Conflict")
2189    }
2190
2191    /// Add a 413 Payload Too Large error response.
2192    ///
2193    /// This is a convenience wrapper around `problem_response`. Relevant to
2194    /// any operation whose handler takes
2195    /// [`toolkit::api::rest::extract::Json<T>`](crate::api::rest::extract::Json)
2196    /// as a parameter - an oversized request body produces this status.
2197    pub fn error_413(self, registry: &dyn OpenApiRegistry) -> Self {
2198        self.problem_response(
2199            registry,
2200            http::StatusCode::PAYLOAD_TOO_LARGE,
2201            "Payload Too Large",
2202        )
2203    }
2204
2205    /// Add a 415 Unsupported Media Type error response.
2206    ///
2207    /// This is a convenience wrapper around `problem_response`.
2208    pub fn error_415(self, registry: &dyn OpenApiRegistry) -> Self {
2209        self.problem_response(
2210            registry,
2211            http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
2212            "Unsupported Media Type",
2213        )
2214    }
2215
2216    /// Add a 422 Unprocessable Entity error response.
2217    ///
2218    /// This is a convenience wrapper around `problem_response`.
2219    pub fn error_422(self, registry: &dyn OpenApiRegistry) -> Self {
2220        self.problem_response(
2221            registry,
2222            http::StatusCode::UNPROCESSABLE_ENTITY,
2223            "Unprocessable Entity",
2224        )
2225    }
2226
2227    /// Add a 429 Too Many Requests error response.
2228    ///
2229    /// This is a convenience wrapper around `problem_response`.
2230    pub fn error_429(self, registry: &dyn OpenApiRegistry) -> Self {
2231        self.problem_response(
2232            registry,
2233            http::StatusCode::TOO_MANY_REQUESTS,
2234            "Too Many Requests",
2235        )
2236    }
2237
2238    /// Add a 500 Internal Server Error response.
2239    ///
2240    /// This is a convenience wrapper around `problem_response`.
2241    pub fn error_500(self, registry: &dyn OpenApiRegistry) -> Self {
2242        self.problem_response(
2243            registry,
2244            http::StatusCode::INTERNAL_SERVER_ERROR,
2245            "Internal Server Error",
2246        )
2247    }
2248
2249    /// Add a 502 Bad Gateway error response.
2250    ///
2251    /// This is a convenience wrapper around `problem_response`.
2252    pub fn error_502(self, registry: &dyn OpenApiRegistry) -> Self {
2253        self.problem_response(registry, http::StatusCode::BAD_GATEWAY, "Bad Gateway")
2254    }
2255
2256    /// Add a 503 Service Unavailable error response.
2257    ///
2258    /// This is a convenience wrapper around `problem_response`.
2259    pub fn error_503(self, registry: &dyn OpenApiRegistry) -> Self {
2260        self.problem_response(
2261            registry,
2262            http::StatusCode::SERVICE_UNAVAILABLE,
2263            "Service Unavailable",
2264        )
2265    }
2266
2267    /// Add a 504 Gateway Timeout error response.
2268    ///
2269    /// This is a convenience wrapper around `problem_response`.
2270    pub fn error_504(self, registry: &dyn OpenApiRegistry) -> Self {
2271        self.problem_response(
2272            registry,
2273            http::StatusCode::GATEWAY_TIMEOUT,
2274            "Gateway Timeout",
2275        )
2276    }
2277}
2278
2279// -------------------------------------------------------------------------------------------------
2280// Per-route request body limit — needs the handler (to layer) and the response stage (for 413)
2281// -------------------------------------------------------------------------------------------------
2282impl<S, A, L> OperationBuilder<Present, Present, S, A, L>
2283where
2284    S: Clone + Send + Sync + 'static,
2285    A: AuthState,
2286    L: LicenseState,
2287{
2288    /// Limit the request body of this route to `bytes` and document `413`.
2289    ///
2290    /// Applies [`axum::extract::DefaultBodyLimit`] to this route only, which
2291    /// overrides the gateway-wide body limit for body extractors such as
2292    /// `Json`; an over-limit body is rejected with `413 Payload Too Large`.
2293    /// Call it after the handler is set.
2294    pub fn body_limit(mut self, bytes: usize, registry: &dyn OpenApiRegistry) -> Self {
2295        self.method_router = self
2296            .method_router
2297            .layer(axum::extract::DefaultBodyLimit::max(bytes));
2298        self.error_413(registry)
2299    }
2300}
2301
2302/// Runtime options for the route registration that `#[toolkit::rest_contract]`
2303/// generates (`register_<trait>_routes_with`).
2304///
2305/// Values usually come from gear configuration, so they cannot be macro
2306/// attributes. Operations are named by their contract method (for example
2307/// `"evaluate_batch"`).
2308#[derive(Debug, Clone, Default)]
2309pub struct RestRouteOptions {
2310    body_limits: BTreeMap<String, usize>,
2311}
2312
2313impl RestRouteOptions {
2314    /// Limit the request body of `operation` to `bytes` (see
2315    /// [`OperationBuilder::body_limit`]).
2316    #[must_use]
2317    pub fn body_limit(mut self, operation: &str, bytes: usize) -> Self {
2318        self.body_limits.insert(operation.to_owned(), bytes);
2319        self
2320    }
2321
2322    /// The body limit configured for `operation`, if any.
2323    #[must_use]
2324    pub fn body_limit_for(&self, operation: &str) -> Option<usize> {
2325        self.body_limits.get(operation).copied()
2326    }
2327
2328    /// Check that every configured operation is in `known`: a typo would
2329    /// otherwise silently leave a route without its limit.
2330    ///
2331    /// # Errors
2332    ///
2333    /// [`UnknownOperations`] naming every configured operation not in `known`.
2334    pub fn check_operations(&self, known: &[&str]) -> Result<(), UnknownOperations> {
2335        let unknown: Vec<String> = self
2336            .body_limits
2337            .keys()
2338            .filter(|op| !known.contains(&op.as_str()))
2339            .cloned()
2340            .collect();
2341        if unknown.is_empty() {
2342            Ok(())
2343        } else {
2344            Err(UnknownOperations(unknown))
2345        }
2346    }
2347}
2348
2349/// [`RestRouteOptions`] name operations the contract does not register.
2350#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
2351#[error("REST route options name operations the contract does not register: {0:?}")]
2352pub struct UnknownOperations(pub Vec<String>);
2353
2354// -------------------------------------------------------------------------------------------------
2355// Registration — only available when handler, response, AND auth are all set
2356// -------------------------------------------------------------------------------------------------
2357impl<S> OperationBuilder<Present, Present, S, AuthSet, LicenseSet>
2358where
2359    S: Clone + Send + Sync + 'static,
2360{
2361    /// Register the operation with the router and `OpenAPI` registry.
2362    ///
2363    /// This method is only available when:
2364    /// - Handler is present
2365    /// - Response is present
2366    /// - Auth requirement is set (either `authenticated` or `public`)
2367    ///
2368    /// All conditions are enforced at compile time by the type system.
2369    pub fn register(self, router: Router<S>, openapi: &dyn OpenApiRegistry) -> Router<S> {
2370        // Inform the OpenAPI registry (the implementation will translate OperationSpec
2371        // into an OpenAPI Operation + RequestBody + Responses with component refs).
2372        openapi.register_operation(&self.spec);
2373
2374        // In Present state the method_router is guaranteed to be a real MethodRouter<S>.
2375        router.route(&self.spec.path, self.method_router)
2376    }
2377}
2378
2379// -------------------------------------------------------------------------------------------------
2380// Tests
2381// -------------------------------------------------------------------------------------------------
2382#[cfg(test)]
2383#[cfg_attr(coverage_nightly, coverage(off))]
2384#[path = "operation_builder_tests.rs"]
2385mod tests;