skyzen 0.3.0

A fast, ergonomic HTTP framework that works everywhere
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! OpenAPI helpers powered by `utoipa` schemas.

use core::future::{ready, Future};
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::{
    fmt::{self, Debug},
    sync::Arc,
};

use crate::{
    extract::Extractor,
    responder::Responder,
    routing::{IntoRouteNode, MethodFilter, RouteNode},
    Body, Endpoint, Request, Response, Route,
};
use http_kit::{header, http_error, Method, StatusCode};
use utoipa::openapi::{
    content::Content,
    info::Info,
    path::{
        HttpMethod, Operation, OperationBuilder, Parameter, ParameterBuilder, ParameterIn,
        PathItemBuilder, Paths, PathsBuilder,
    },
    request_body::RequestBodyBuilder,
    response::{ResponseBuilder, ResponsesBuilder},
    schema::{ComponentsBuilder, ObjectBuilder, Schema, SchemaType, Type},
    Deprecated, OpenApi as UtoipaSpec, RefOr, Required,
};
use utoipa_redoc::Redoc;
use utoipa_scalar::Scalar;

/// `OpenAPI` schema reference type alias.
pub type SchemaRef = RefOr<Schema>;

#[cfg(feature = "openapi")]
pub use skyzen_core::openapi::{
    ExtractorSchema, ParameterLocation, ResponseSchema, SchemaCollector,
};

#[cfg(not(feature = "openapi"))]
/// Where an extractor reads its data from (stubbed when `openapi` is disabled).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParameterLocation {
    /// Read from the request body.
    Body,
    /// Read from the URL query string.
    Query,
    /// Read from a request header.
    Header,
    /// Read from the route's captured `{name}` path segments.
    Path,
}

#[cfg(not(feature = "openapi"))]
/// Schema information captured for an extractor argument (stubbed when `openapi` is disabled).
#[derive(Clone)]
pub struct ExtractorSchema {
    /// Where the extractor sources its data.
    pub location: ParameterLocation,
    /// Content type associated with the extractor, if any.
    pub content_type: Option<&'static str>,
    /// JSON schema describing the extractor payload.
    pub schema: Option<SchemaRef>,
}

#[cfg(not(feature = "openapi"))]
/// Schema information captured for a responder (stubbed when `openapi` is disabled).
#[derive(Clone)]
pub struct ResponseSchema {
    /// HTTP status code returned by the responder (or [`StatusCode::OK`] by default).
    pub status: Option<StatusCode>,
    /// Description associated with the response.
    pub description: Option<&'static str>,
    /// JSON schema describing the response payload.
    pub schema: Option<SchemaRef>,
    /// Content type returned by the responder, if known.
    pub content_type: Option<&'static str>,
}

#[cfg(not(feature = "openapi"))]
impl fmt::Debug for ExtractorSchema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExtractorSchema")
            .field("location", &self.location)
            .field("content_type", &self.content_type)
            .field("has_schema", &self.schema.is_some())
            .finish()
    }
}

#[cfg(not(feature = "openapi"))]
impl fmt::Debug for ResponseSchema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResponseSchema")
            .field("status", &self.status)
            .field("description", &self.description)
            .field("content_type", &self.content_type)
            .field("has_schema", &self.schema.is_some())
            .finish()
    }
}

#[cfg(not(feature = "openapi"))]
/// Function type that collects `OpenAPI` schemas into a definitions map.
pub type SchemaCollector = fn(&mut BTreeMap<String, SchemaRef>);

pub mod registry;

mod builtins;
pub use builtins::IgnoreOpenApi;

/// Strip the crate prefix from a module path, e.g. `my_crate::users::get` -> `users::get`.
#[must_use]
pub fn trim_crate(path: &str) -> &str {
    path.split_once("::").map_or(path, |(_, rest)| rest)
}

/// Function pointer used to lazily build an extractor schema.
pub type ExtractorSchemaFn = fn() -> Option<ExtractorSchema>;
/// Function pointer used to lazily build responder schemas.
pub type ResponderSchemaFn = fn() -> Option<Vec<ResponseSchema>>;

/// Return the schema for a `ToSchema` type.
#[must_use]
pub fn schema_of<T>() -> Option<SchemaRef>
where
    T: crate::ToSchema,
{
    Some(<T as crate::PartialSchema>::schema())
}

/// Return the extractor schema for `T` if it exposes `OpenAPI` metadata.
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn extractor_schema_of<T>() -> Option<ExtractorSchema>
where
    T: Extractor,
{
    #[cfg(feature = "openapi")]
    {
        <T as Extractor>::openapi()
    }

    #[cfg(not(feature = "openapi"))]
    {
        let _ = core::marker::PhantomData::<T>;
        None
    }
}

/// Return the responder schemas for `T` if it exposes `OpenAPI` metadata.
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn responder_schemas_of<T>() -> Option<Vec<ResponseSchema>>
where
    T: Responder,
{
    #[cfg(feature = "openapi")]
    {
        <T as Responder>::openapi()
    }

    #[cfg(not(feature = "openapi"))]
    {
        let _ = core::marker::PhantomData::<T>;
        None
    }
}

/// Register dependent schemas for the extractor type if `OpenAPI` metadata is available.
#[allow(clippy::missing_const_for_fn)]
pub fn register_extractor_schemas_for<T>(defs: &mut BTreeMap<String, SchemaRef>)
where
    T: Extractor,
{
    #[cfg(feature = "openapi")]
    {
        <T as Extractor>::register_openapi_schemas(defs);
    }

    #[cfg(not(feature = "openapi"))]
    {
        let _ = (core::marker::PhantomData::<T>, defs);
    }
}

/// Register dependent schemas for the responder type if `OpenAPI` metadata is available.
#[allow(clippy::missing_const_for_fn)]
pub fn register_responder_schemas_for<T>(defs: &mut BTreeMap<String, SchemaRef>)
where
    T: Responder,
{
    #[cfg(feature = "openapi")]
    {
        <T as Responder>::register_openapi_schemas(defs);
    }

    #[cfg(not(feature = "openapi"))]
    {
        let _ = (core::marker::PhantomData::<T>, defs);
    }
}

#[derive(Debug, Clone, Copy)]
/// Metadata captured for every handler annotated with `#[skyzen::openapi]`.
pub struct HandlerSpec {
    /// Fully-qualified handler name (module + function).
    pub type_name: &'static str,
    /// Default display name derived from the module path (without the crate prefix).
    pub operation_name: &'static str,
    /// Documentation collected from the handler's doc comments.
    pub docs: Option<&'static str>,
    /// Deprecation flag extracted from handler attributes.
    pub deprecated: bool,
    /// Schema generators for each extractor argument.
    pub parameters: &'static [ExtractorSchemaFn],
    /// Names of each documented extractor argument (aligned with `parameters`).
    pub parameter_names: &'static [&'static str],
    /// Schema generators for the responder type, if any.
    pub response: Option<ResponderSchemaFn>,
    /// Schema collectors for parameters and responders, including their transitive dependencies.
    pub schemas: &'static [SchemaCollector],
}

#[cfg(feature = "openapi")]
fn find_handler_spec(type_name: &str) -> Option<&'static HandlerSpec> {
    registry::iter().find(|spec| spec.type_name == type_name)
}

#[cfg(feature = "openapi")]
fn register_type<T>(defs: &mut BTreeMap<String, SchemaRef>)
where
    T: crate::PartialSchema + crate::ToSchema,
{
    let name = <T as crate::ToSchema>::name().into_owned();
    defs.entry(name)
        .or_insert_with(<T as crate::PartialSchema>::schema);
    let mut nested = Vec::new();
    <T as crate::ToSchema>::schemas(&mut nested);
    for (dep_name, schema) in nested {
        defs.entry(dep_name).or_insert(schema);
    }
}

/// Asks "does `T` describe itself?" without requiring that it does.
///
/// The answer is decided by method resolution: [`SchemaProbe::maybe_schema`] is an *inherent*
/// method that only exists when `T: ToSchema`, and inherent methods win over the trait method of
/// the same name on `&SchemaProbe<T>`, so a self-describing type takes the first and everything
/// else falls through to the second.
///
/// The choice is made where the call is written, so it only discriminates when `T` is concrete
/// there. Calling it from a function generic over `T` always yields the fallback, silently — so
/// this is reachable from exactly one place, `#[skyzen::openapi]`'s expansion, where the payload
/// type is spelled out and the answer is therefore real.
///
/// It exists for one caller: [`Path<T>`](crate::extract::Path), whose payload is legitimately
/// allowed not to describe itself. A multi-segment route is extracted as `Path<(String, u32)>`,
/// tuples have no `ToSchema`, and the route pattern already names those parameters — so the
/// payload only supplies types, and its absence costs a type rather than failing the build. Every
/// *body* payload takes the opposite route and requires the bound outright: see
/// [`Json`](crate::utils::Json), whose schema is the documented contract rather than a bonus.
///
/// There is deliberately no generic `maybe_schema_of<T>()` wrapper around this. Such a function
/// can only ever return `None`, and having one meant six extractors and responders reported no
/// schema while looking as though they reported one.
#[doc(hidden)]
#[derive(Debug, Default)]
pub struct SchemaProbe<T>(PhantomData<T>);

impl<T> SchemaProbe<T> {
    /// Build a probe for `T`.
    #[doc(hidden)]
    #[must_use]
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

/// The fallback half of [`SchemaProbe`]: any type at all, describing nothing.
#[doc(hidden)]
pub trait MaybeSchemaProbe {
    /// No schema, because `T` does not implement `ToSchema`.
    fn maybe_schema(self) -> Option<SchemaRef>;
    /// Nothing to register, for the same reason.
    fn maybe_register(self, defs: &mut BTreeMap<String, SchemaRef>);
}

impl<T> MaybeSchemaProbe for &SchemaProbe<T> {
    fn maybe_schema(self) -> Option<SchemaRef> {
        None
    }

    fn maybe_register(self, _defs: &mut BTreeMap<String, SchemaRef>) {}
}

/// The specialized half of [`SchemaProbe`], reached only when `T` really does describe itself.
impl<T> SchemaProbe<T>
where
    T: crate::PartialSchema + crate::ToSchema,
{
    /// The schema `T` declares.
    #[doc(hidden)]
    #[must_use]
    pub fn maybe_schema(&self) -> Option<SchemaRef> {
        Some(<T as crate::PartialSchema>::schema())
    }

    /// Register `T` and its dependencies into the components map.
    #[doc(hidden)]
    #[cfg(feature = "openapi")]
    pub fn maybe_register(&self, defs: &mut BTreeMap<String, SchemaRef>) {
        register_type::<T>(defs);
    }

    /// Registering is a no-op without the `openapi` feature: nothing ever reads the components
    /// map, so the probe keeps its signature and does nothing.
    ///
    /// This is a separate `const` definition rather than one body holding a `#[cfg]`ed statement
    /// so the feature-off form is genuinely const, which is what `clippy::missing_const_for_fn`
    /// asks for on the wasm builds that turn `openapi` off.
    #[doc(hidden)]
    #[cfg(not(feature = "openapi"))]
    pub const fn maybe_register(&self, defs: &mut BTreeMap<String, SchemaRef>) {
        let _ = defs;
    }
}

/// Register a schema and its dependencies when `OpenAPI` is enabled.
#[allow(clippy::missing_const_for_fn)]
pub fn register_schema_for<T>(defs: &mut BTreeMap<String, SchemaRef>)
where
    T: crate::PartialSchema + crate::ToSchema,
{
    #[cfg(feature = "openapi")]
    register_type::<T>(defs);
    let _ = defs;
}

#[cfg(feature = "openapi")]
/// Registers types and their dependencies into the `OpenAPI` components map.
pub trait RegisterSchemas {
    /// Insert the type's schema and dependent schemas into the provided map.
    fn register(defs: &mut BTreeMap<String, SchemaRef>);
}

#[cfg(feature = "openapi")]
impl<T> RegisterSchemas for T
where
    T: crate::PartialSchema + crate::ToSchema,
{
    fn register(defs: &mut BTreeMap<String, SchemaRef>) {
        register_type::<T>(defs);
    }
}

#[cfg(feature = "openapi")]
fn collect_schemas(collectors: &[SchemaCollector], defs: &mut BTreeMap<String, SchemaRef>) {
    for collector in collectors {
        collector(defs);
    }
}

/// Handler metadata attached to each endpoint.
#[derive(Clone, Copy, Debug)]
pub struct RouteHandlerDoc {
    #[cfg(feature = "openapi")]
    type_name: &'static str,
    #[cfg(feature = "openapi")]
    spec: Option<&'static HandlerSpec>,
}

impl RouteHandlerDoc {
    #[cfg(feature = "openapi")]
    const fn new(type_name: &'static str, spec: Option<&'static HandlerSpec>) -> Self {
        Self { type_name, spec }
    }

    #[cfg(not(feature = "openapi"))]
    const fn new() -> Self {
        Self {}
    }
}

/// Describe the provided handler type, registering metadata when `OpenAPI` support is enabled.
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn describe_handler<H: 'static>() -> RouteHandlerDoc {
    #[cfg(feature = "openapi")]
    {
        let type_name = std::any::type_name::<H>();
        let spec = find_handler_spec(type_name);
        RouteHandlerDoc::new(type_name, spec)
    }

    #[cfg(not(feature = "openapi"))]
    {
        let _ = ::core::marker::PhantomData::<H>;
        RouteHandlerDoc::new()
    }
}

#[cfg(feature = "openapi")]
#[derive(Debug, Clone)]
/// Route metadata stored when `OpenAPI` instrumentation is enabled.
pub struct RouteOpenApiEntry {
    /// HTTP path served by the handler.
    pub path: String,
    /// HTTP method associated with the handler.
    pub method: Method,
    /// Handler documentation collected from the distributed registry.
    pub handler: RouteHandlerDoc,
}

#[cfg(feature = "openapi")]
impl RouteOpenApiEntry {
    #[must_use]
    /// Construct a new entry describing a route + handler pair.
    pub const fn new(path: String, method: Method, handler: RouteHandlerDoc) -> Self {
        Self {
            path,
            method,
            handler,
        }
    }
}

/// Who the document is about: the application's own name, version and description.
///
/// Applications do not normally construct one. `#[skyzen::main]` expands in the application's
/// crate, where `env!("CARGO_PKG_NAME")` reads the application rather than skyzen, and registers
/// this there — so a document is titled correctly with nothing passed through the routing API.
/// Build one by hand, or with [`app_info!`](crate::app_info), only to override that: see
/// [`OpenApi::with_info`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AppInfo {
    /// The application's package name, shown as the document title.
    pub name: &'static str,
    /// The application's package version.
    pub version: &'static str,
    /// The application's package description, if it declares one.
    pub description: Option<&'static str>,
}

/// Build an [`AppInfo`] describing the crate this macro is written in.
///
/// `#[skyzen::main]` already does this for the application it is attached to, so this is for the
/// cases that have no `#[skyzen::main]` to do it — a document built in a test, or an application
/// embedding skyzen behind its own runtime:
///
/// ```rust
/// # use skyzen::routing::{CreateRouteNode, Route};
/// # async fn health() -> &'static str { "OK" }
/// let api = Route::new(("/health".at(health),));
/// let docs = api
///     .openapi()
///     .with_info(skyzen::app_info!())
///     .scalar_route("/docs");
/// ```
#[macro_export]
macro_rules! app_info {
    () => {
        $crate::openapi::AppInfo {
            name: env!("CARGO_PKG_NAME"),
            version: env!("CARGO_PKG_VERSION"),
            description: option_env!("CARGO_PKG_DESCRIPTION"),
        }
    };
}

/// Minimal `OpenAPI` representation for Skyzen routers.
#[derive(Clone, Default)]
pub struct OpenApi {
    info: Option<AppInfo>,
    #[cfg(feature = "openapi")]
    operations: Vec<OpenApiOperation>,
    #[cfg(feature = "openapi")]
    schemas: Vec<(String, SchemaRef)>,
}

impl Debug for OpenApi {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenApi")
            .field("operations", &"[..]")
            .field("schemas", &"[..]")
            .finish()
    }
}

impl OpenApi {
    /// Build an [`OpenApi`] instance from the collected route metadata.
    #[cfg(feature = "openapi")]
    #[must_use]
    pub(crate) fn from_entries(entries: &[RouteOpenApiEntry]) -> Self {
        let mut schema_defs = BTreeMap::new();
        let operations = entries
            .iter()
            .map(|entry| {
                let handler_type = entry.handler.type_name;
                entry.handler.spec.map_or_else(
                    || OpenApiOperation {
                        path: entry.path.clone(),
                        method: entry.method.clone(),
                        handler_type,
                        operation_id: trim_crate(handler_type).to_owned(),
                        docs: None,
                        deprecated: false,
                        parameters: Vec::new(),
                        responses: Vec::new(),
                    },
                    |spec| {
                        collect_schemas(spec.schemas, &mut schema_defs);
                        let docs = spec.docs;
                        let mut parameters = Vec::new();
                        for (idx, schema_fn) in spec.parameters.iter().enumerate() {
                            if let Some(schema) = schema_fn() {
                                let name =
                                    spec.parameter_names.get(idx).copied().unwrap_or("param");
                                parameters.push(NamedExtractorSchema {
                                    name: name.to_string(),
                                    schema,
                                });
                            }
                        }
                        let responses = spec
                            .response
                            .and_then(|schema| schema())
                            .unwrap_or_default();
                        OpenApiOperation {
                            path: entry.path.clone(),
                            method: entry.method.clone(),
                            handler_type,
                            operation_id: spec.operation_name.to_owned(),
                            docs,
                            deprecated: spec.deprecated,
                            parameters,
                            responses,
                        }
                    },
                )
            })
            .collect();
        let schemas = schema_defs.into_iter().collect();
        Self {
            info: None,
            operations,
            schemas,
        }
    }

    /// Build an empty `OpenAPI` definition when `OpenAPI` support is disabled.
    #[cfg(not(feature = "openapi"))]
    #[must_use]
    #[allow(dead_code)]
    pub(crate) const fn from_entries(_: &[()]) -> Self {
        Self { info: None }
    }

    /// Inspect the registered operations.
    ///
    /// Empty without the `openapi` feature, which is the only thing that varies: the signature is
    /// the same in every build, so calling code never has to be written twice.
    #[must_use]
    // Deliberately not `const` in the feature-off arm. It could be, but then the two arms would
    // differ in a way a caller can observe, and one signature everywhere is worth more than a
    // `const fn` returning an empty slice.
    #[allow(clippy::missing_const_for_fn)]
    pub fn operations(&self) -> &[OpenApiOperation] {
        #[cfg(feature = "openapi")]
        {
            &self.operations
        }

        #[cfg(not(feature = "openapi"))]
        {
            &[]
        }
    }

    /// Indicates whether `OpenAPI` instrumentation is active.
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        cfg!(feature = "openapi")
    }

    /// Convert the collected spec to a [`Scalar`](utoipa_scalar::Scalar) endpoint.
    ///
    /// This is the recommended interactive documentation UI.
    #[must_use]
    pub fn scalar(&self) -> OpenApiUiEndpoint {
        self.ui_endpoint(|| Scalar::new(self.to_utoipa_spec()).to_html())
    }

    /// Build a [`RouteNode`] that serves the generated `OpenAPI` document via Scalar at `mount_path`.
    #[must_use]
    pub fn scalar_route(&self, mount_path: impl Into<String>) -> RouteNode {
        ui_route(self.scalar(), mount_path.into())
    }

    /// Convert the collected spec to a [`Redoc`](utoipa_redoc::Redoc) endpoint.
    #[must_use]
    pub fn redoc(&self) -> OpenApiUiEndpoint {
        self.ui_endpoint(|| Redoc::new(self.to_utoipa_spec()).to_html())
    }

    /// Build a [`RouteNode`] that serves the generated `OpenAPI` document via Redoc at `mount_path`.
    #[must_use]
    pub fn redoc_route(&self, mount_path: impl Into<String>) -> RouteNode {
        ui_route(self.redoc(), mount_path.into())
    }

    /// Convert the collected spec to an endpoint serving the raw `OpenAPI` JSON document.
    ///
    /// The counterpart to [`scalar`](Self::scalar): the same document, for a client generator or
    /// another tool rather than a reader.
    ///
    /// # Panics
    ///
    /// If the document cannot be serialized, which would mean `utoipa` produced a structure serde
    /// cannot write — a bug in a dependency rather than anything an application can cause.
    #[must_use]
    pub fn json(&self) -> OpenApiUiEndpoint {
        self.rendered(JSON_CONTENT_TYPE, || {
            serde_json::to_string(&self.to_utoipa_spec())
                .expect("an OpenAPI document is always serializable")
        })
    }

    /// Build a [`RouteNode`] serving the raw `OpenAPI` JSON document at `mount_path`.
    ///
    /// Unlike [`scalar_route`](Self::scalar_route) this mounts one exact path, not a subtree: a
    /// specification is a single file, and `/openapi.json/anything` is not it.
    #[must_use]
    pub fn json_route(&self, mount_path: impl Into<String>) -> RouteNode {
        RouteNode::new_endpoint(
            mount_path.into(),
            MethodFilter::Exact(Method::GET),
            self.json(),
            None,
            Vec::new(),
        )
    }

    fn ui_endpoint(&self, html: impl FnOnce() -> String) -> OpenApiUiEndpoint {
        self.rendered(HTML_CONTENT_TYPE, html)
    }

    fn rendered(
        &self,
        content_type: &'static str,
        body: impl FnOnce() -> String,
    ) -> OpenApiUiEndpoint {
        if self.is_enabled() {
            OpenApiUiEndpoint::enabled(body(), content_type)
        } else {
            OpenApiUiEndpoint::disabled()
        }
    }

    /// Convert collected operations to a fully hydrated [`utoipa::openapi::OpenApi`] document.
    #[must_use]
    pub fn to_utoipa_spec(&self) -> UtoipaSpec {
        UtoipaSpec::builder()
            .info(self.info())
            .paths(self.build_paths())
            .components(Some(self.build_components()))
            .build()
    }

    /// Name the application this document describes, overriding what `#[skyzen::main]` registered.
    ///
    /// Rarely needed: an application built the ordinary way is already titled after its own crate.
    /// Reach for this when the API's public name is not the crate's — `orders-service` the crate,
    /// "Orders API" the product — or when building a document outside an application entirely.
    #[must_use]
    pub const fn with_info(mut self, info: AppInfo) -> Self {
        self.info = Some(info);
        self
    }

    /// The application's identity: what [`with_info`](Self::with_info) was told, else what
    /// `#[skyzen::main]` registered for this binary, else an anonymous placeholder.
    ///
    /// The placeholder is reached only by a document built outside an application — a library
    /// under test, or a binary that embeds skyzen behind its own runtime. It is deliberately
    /// anonymous rather than skyzen's own package metadata: a document announcing itself as
    /// `skyzen 0.2.1` in every application is worse than one that admits it was never told.
    fn info(&self) -> Info {
        self.info
            .or_else(|| registry::app_info().copied())
            .map_or_else(
                || Info::new("API", "0.0.0"),
                |app| {
                    let mut info = Info::new(app.name, app.version);
                    // A package with no `description` still yields `Some("")` from `option_env!`, and
                    // an empty description in the document is worse than none.
                    info.description = app
                        .description
                        .filter(|text| !text.is_empty())
                        .map(ToOwned::to_owned);
                    info
                },
            )
    }

    fn build_paths(&self) -> Paths {
        self.operations()
            .iter()
            .fold(PathsBuilder::new(), |builder, op| {
                if let Some(http_method) = method_to_http_method(&op.method) {
                    let operation = build_operation(op);
                    let path_item = PathItemBuilder::new()
                        .operation(http_method, operation)
                        .build();
                    builder.path(op.path.clone(), path_item)
                } else {
                    builder
                }
            })
            .build()
    }

    #[cfg(feature = "openapi")]
    fn build_components(&self) -> utoipa::openapi::schema::Components {
        self.schemas
            .iter()
            .cloned()
            .fold(ComponentsBuilder::new(), |builder, (name, schema)| {
                builder.schema(name, schema)
            })
            .build()
    }

    #[cfg(not(feature = "openapi"))]
    #[allow(clippy::unused_self)]
    fn build_components(&self) -> utoipa::openapi::schema::Components {
        ComponentsBuilder::new().build()
    }
}

/// Description of a parameter along with its schema metadata.
#[derive(Clone, Debug)]
pub struct NamedExtractorSchema {
    /// Parameter name as captured from the handler signature.
    pub name: String,
    /// Schema metadata for the extractor.
    pub schema: ExtractorSchema,
}

/// Description of a single handler operation.
#[derive(Clone)]
pub struct OpenApiOperation {
    /// Path served by the handler.
    pub path: String,
    /// HTTP method for the handler.
    pub method: Method,
    /// Handler type name.
    pub handler_type: &'static str,
    /// Operation identifier used in the `OpenAPI` document.
    pub operation_id: String,
    /// Documentation extracted from the handler's doc comments.
    pub docs: Option<&'static str>,
    /// Whether the handler is deprecated.
    pub deprecated: bool,
    /// Schemas describing the extractor arguments.
    pub parameters: Vec<NamedExtractorSchema>,
    /// Schemas describing all potential responses.
    pub responses: Vec<ResponseSchema>,
}

impl fmt::Debug for OpenApiOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OpenApiOperation")
            .field("path", &self.path)
            .field("method", &self.method)
            .field("handler_type", &self.handler_type)
            .field("operation_id", &self.operation_id)
            .field("docs", &self.docs)
            .field("deprecated", &self.deprecated)
            .field("parameters", &self.parameters.len())
            .field("responses", &self.responses.len())
            .finish()
    }
}

#[derive(Clone, Debug)]
/// Endpoint that serves a pre-rendered `OpenAPI` document — a documentation page, or the raw
/// specification.
///
/// The body is rendered once when the route is built, so serving it is a header and a `memcpy`.
pub struct OpenApiUiEndpoint {
    body: Option<Arc<String>>,
    content_type: &'static str,
}

impl OpenApiUiEndpoint {
    fn enabled(body: String, content_type: &'static str) -> Self {
        Self {
            body: Some(Arc::new(body)),
            content_type,
        }
    }

    const fn disabled() -> Self {
        Self {
            body: None,
            content_type: HTML_CONTENT_TYPE,
        }
    }
}

const HTML_CONTENT_TYPE: &str = "text/html; charset=utf-8";
const JSON_CONTENT_TYPE: &str = "application/json";

http_error!(
    /// Error returned when OpenAPI support is disabled.
    pub OpenApiUiDisabledError, StatusCode::NOT_IMPLEMENTED, "OpenAPI support is disabled for this build");

impl Endpoint for OpenApiUiEndpoint {
    type Error = OpenApiUiDisabledError;
    // The document is rendered at build time, so the future is ready on creation rather than an
    // `async` block with nothing to await.
    fn respond(
        &mut self,
        _request: &mut Request,
    ) -> impl Future<Output = Result<Response, Self::Error>> + Send {
        let content_type = self.content_type;
        ready(self.body.as_ref().map_or_else(
            || Err(OpenApiUiDisabledError::new()),
            |body| {
                let mut response = Response::new(Body::from(body.as_bytes().to_vec()));
                response.headers_mut().insert(
                    header::CONTENT_TYPE,
                    header::HeaderValue::from_static(content_type),
                );
                Ok(response)
            },
        ))
    }
}

fn ui_route(endpoint: OpenApiUiEndpoint, mount_path: String) -> RouteNode {
    let wildcard_suffix = "/{*path}";
    let route = Route::new((
        RouteNode::new_endpoint(
            "",
            MethodFilter::Exact(Method::GET),
            endpoint.clone(),
            None,
            Vec::new(),
        ),
        RouteNode::new_endpoint(
            wildcard_suffix,
            MethodFilter::Exact(Method::GET),
            endpoint,
            None,
            Vec::new(),
        ),
    ));

    RouteNode::new_route(mount_path, route)
}

/// Default mount path for the generated API documentation page.
pub const DEFAULT_API_DOCS_MOUNT: &str = "/api-docs";

impl IntoRouteNode for OpenApiUiEndpoint {
    fn into_route_node(self) -> RouteNode {
        ui_route(self, DEFAULT_API_DOCS_MOUNT.to_string())
    }
}

fn method_to_http_method(method: &Method) -> Option<HttpMethod> {
    match method.as_str() {
        "GET" => Some(HttpMethod::Get),
        "POST" => Some(HttpMethod::Post),
        "PUT" => Some(HttpMethod::Put),
        "DELETE" => Some(HttpMethod::Delete),
        "PATCH" => Some(HttpMethod::Patch),
        "OPTIONS" => Some(HttpMethod::Options),
        "HEAD" => Some(HttpMethod::Head),
        "TRACE" => Some(HttpMethod::Trace),
        _ => None,
    }
}

fn build_operation(op: &OpenApiOperation) -> Operation {
    let summary = op
        .docs
        .and_then(doc_summary)
        .or_else(|| Some(op.operation_id.clone()));
    let mut builder = OperationBuilder::new()
        .operation_id(Some(op.operation_id.clone()))
        .summary(summary)
        .responses(build_responses(op));

    if op.deprecated {
        builder = builder.deprecated(Some(Deprecated::True));
    }

    let parameters = build_parameters(op);
    if !parameters.is_empty() {
        builder = builder.parameters(Some(parameters));
    }

    if let Some(body) = build_request_body(op) {
        builder = builder.request_body(Some(body));
    }

    if let Some(docs) = op.docs {
        builder = builder.description(Some(docs.to_owned()));
    }

    builder.build()
}

/// A minimal `string` schema used as a default for path/query/header parameters that don't carry
/// their own typed schema.
fn string_param_schema() -> RefOr<Schema> {
    RefOr::T(Schema::Object(
        ObjectBuilder::new()
            .schema_type(SchemaType::from(Type::String))
            .build(),
    ))
}

/// Extract the names of `{name}` / `{*wildcard}` segments from a route path.
fn path_parameter_names(path: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut rest = path;
    while let Some(start) = rest.find('{') {
        let after = &rest[start + 1..];
        let Some(end) = after.find('}') else { break };
        let raw = &after[..end];
        let name = raw.strip_prefix('*').unwrap_or(raw);
        if !name.is_empty() {
            names.push(name.to_owned());
        }
        rest = &after[end + 1..];
    }
    names
}

/// Build the `OpenAPI` `parameters` list: path parameters (from the route pattern) plus query and
/// header parameters (from the handler's extractor schemas). Body extractors are handled separately
/// by [`build_request_body`].
fn build_parameters(op: &OpenApiOperation) -> Vec<Parameter> {
    let mut parameters = Vec::new();

    // The route pattern is what names the path parameters; a `Path<T>` extractor only supplies
    // their types, so the two are merged rather than both emitted.
    let names = path_parameter_names(&op.path);
    let typed = typed_path_schemas(op, &names);
    for name in names {
        let schema = typed.get(&name).cloned();
        parameters.push(
            ParameterBuilder::new()
                .name(name)
                .parameter_in(ParameterIn::Path)
                .required(Required::True)
                .schema(Some(schema.unwrap_or_else(string_param_schema)))
                .build(),
        );
    }

    for named in &op.parameters {
        match named.schema.location {
            ParameterLocation::Query => append_query_parameters(&mut parameters, named),
            ParameterLocation::Header => parameters.push(
                ParameterBuilder::new()
                    .name(named.name.clone())
                    .parameter_in(ParameterIn::Header)
                    .required(Required::False)
                    .schema(Some(
                        named
                            .schema
                            .schema
                            .clone()
                            .unwrap_or_else(string_param_schema),
                    ))
                    .build(),
            ),
            // Path parameters were emitted above, merged with the route pattern's names; body
            // extractors are handled by `build_request_body`.
            ParameterLocation::Path | ParameterLocation::Body => {}
        }
    }

    parameters
}

/// The schemas a `Path<T>` extractor contributes, keyed by path parameter name.
///
/// A struct or map payload names its own fields; a tuple or a bare primitive does not, so its
/// schema is matched positionally against the route pattern — which for the single-parameter case
/// is exactly what `Path<u64>` means.
fn typed_path_schemas(op: &OpenApiOperation, names: &[String]) -> BTreeMap<String, RefOr<Schema>> {
    let mut typed = BTreeMap::new();
    for named in &op.parameters {
        if named.schema.location != ParameterLocation::Path {
            continue;
        }
        let Some(schema) = &named.schema.schema else {
            continue;
        };
        match schema {
            RefOr::T(Schema::Object(object)) if !object.properties.is_empty() => {
                for (field, field_schema) in &object.properties {
                    typed.insert(field.clone(), field_schema.clone());
                }
            }
            _ => {
                if let [only] = names {
                    typed.insert(only.clone(), schema.clone());
                }
            }
        }
    }
    typed
}

/// Append query parameters for a `Query<T>` extractor. When the schema is an inline object its
/// fields become individual query parameters (the conventional `OpenAPI` representation); otherwise
/// the whole schema is exposed under the argument name.
fn append_query_parameters(out: &mut Vec<Parameter>, named: &NamedExtractorSchema) {
    if let Some(RefOr::T(Schema::Object(object))) = &named.schema.schema {
        for (name, schema) in &object.properties {
            let required = object.required.iter().any(|field| field == name);
            out.push(
                ParameterBuilder::new()
                    .name(name.clone())
                    .parameter_in(ParameterIn::Query)
                    .required(if required {
                        Required::True
                    } else {
                        Required::False
                    })
                    .schema(Some(schema.clone()))
                    .build(),
            );
        }
    } else {
        out.push(
            ParameterBuilder::new()
                .name(named.name.clone())
                .parameter_in(ParameterIn::Query)
                .required(Required::False)
                .schema(Some(
                    named
                        .schema
                        .schema
                        .clone()
                        .unwrap_or_else(string_param_schema),
                ))
                .build(),
        );
    }
}

fn build_responses(op: &OpenApiOperation) -> utoipa::openapi::response::Responses {
    if op.responses.is_empty() {
        let response = ResponseBuilder::new()
            .description("Successful response")
            .build();
        return ResponsesBuilder::new()
            .response(StatusCode::OK.as_str(), response)
            .build();
    }

    let mut builder = ResponsesBuilder::new();
    for response in &op.responses {
        let status = response.status.unwrap_or(StatusCode::OK);
        let mut response_builder =
            ResponseBuilder::new().description(response.description.unwrap_or("Response"));

        if let Some(schema) = &response.schema {
            let content_type = response.content_type.unwrap_or("application/json");
            response_builder =
                response_builder.content(content_type, Content::new(Some(schema.clone())));
        }

        builder = builder.response(status.as_str(), response_builder.build());
    }

    builder.build()
}

fn build_request_body(op: &OpenApiOperation) -> Option<utoipa::openapi::request_body::RequestBody> {
    let mut by_content_type: BTreeMap<&str, Vec<(String, RefOr<Schema>)>> = BTreeMap::new();

    for param in &op.parameters {
        // Only body-sourced extractors contribute to the request body; query/header/path
        // parameters are emitted as `parameters` by `build_parameters`.
        if param.schema.location != ParameterLocation::Body {
            continue;
        }

        let Some(content_type) = param.schema.content_type else {
            continue;
        };

        let schema = param
            .schema
            .schema
            .clone()
            .unwrap_or_else(|| utoipa::openapi::schema::empty().into());
        by_content_type
            .entry(content_type)
            .or_default()
            .push((param.name.clone(), schema));
    }

    if by_content_type.is_empty() {
        return None;
    }

    let mut builder = RequestBodyBuilder::new()
        .description(Some("Extractor arguments"))
        .required(Some(Required::True));

    for (content_type, schemas) in by_content_type {
        let schema = aggregate_parameter_schema(&schemas);
        builder = builder.content(content_type, Content::new(Some(schema)));
    }

    Some(builder.build())
}

fn aggregate_parameter_schema(parameters: &[(String, RefOr<Schema>)]) -> RefOr<Schema> {
    if parameters.len() == 1 {
        return parameters[0].1.clone();
    }

    let object = parameters.iter().fold(
        ObjectBuilder::new().schema_type(SchemaType::from(Type::Object)),
        |builder, (name, schema)| {
            builder
                .property(name.clone(), schema.clone())
                .required(name.clone())
        },
    );

    RefOr::T(Schema::from(object.build()))
}

fn doc_summary(docs: &str) -> Option<String> {
    let lines = docs.lines();
    let mut paragraph = Vec::new();
    for line in lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            if !paragraph.is_empty() {
                break;
            }
            continue;
        }
        paragraph.push(trimmed);
    }
    if paragraph.is_empty() {
        None
    } else {
        Some(paragraph.join(" "))
    }
}

#[cfg(test)]
mod tests {
    use super::OpenApi;

    #[test]
    fn a_document_with_no_registered_identity_is_anonymous_rather_than_skyzen() {
        // Reachable from a library under test or a binary that embeds skyzen behind its own
        // runtime — anything with no `#[skyzen::main]` to register an identity. This crate's own
        // test binary is exactly that case.
        //
        // `default_info` used to answer with skyzen's own `CARGO_PKG_*` here, which titled every
        // application's document `skyzen 0.2.1`. Admitting it was never told is better than
        // confidently naming the wrong crate. `tests/openapi_app_info.rs` covers the other side.
        let spec = OpenApi::default().to_utoipa_spec();

        assert_eq!(spec.info.title, "API");
        assert_eq!(spec.info.version, "0.0.0");
        assert_ne!(spec.info.title, env!("CARGO_PKG_NAME"));
    }
}