cf-gears-toolkit 0.10.0

Core ToolKit library
Documentation
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
// Updated: 2026-04-28 by Constructor Tech
//! `OpenAPI` registry for schema and operation management
//!
//! This gear provides a standalone `OpenAPI` registry that collects operation specs
//! and schemas, and builds a complete `OpenAPI` document from them.

use anyhow::Result;
use arc_swap::ArcSwap;
use dashmap::DashMap;
use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
use utoipa::openapi::{
    OpenApi, OpenApiBuilder, Ref, RefOr, Required,
    content::ContentBuilder,
    header::HeaderBuilder,
    info::InfoBuilder,
    path::{
        HttpMethod, OperationBuilder as UOperationBuilder, ParameterBuilder, ParameterIn,
        PathItemBuilder, PathsBuilder,
    },
    request_body::RequestBodyBuilder,
    response::{Response, ResponsesBuilder},
    schema::{ArrayBuilder, ComponentsBuilder, ObjectBuilder, Schema, SchemaFormat, SchemaType},
    security::{HttpAuthScheme, HttpBuilder, SecurityScheme},
    server::Server,
};

use crate::api::operation_builder;
use toolkit_canonical_errors::problem;
use toolkit_contract::StreamFraming;

/// Type alias for schema collections used in API operations.
type SchemaCollection = Vec<(String, RefOr<Schema>)>;

/// `OpenAPI` document metadata (title, version, description)
#[derive(Debug, Clone)]
pub struct OpenApiInfo {
    pub title: String,
    pub version: String,
    pub description: Option<String>,
    pub servers: Vec<String>,
}

impl Default for OpenApiInfo {
    fn default() -> Self {
        Self {
            title: "API Documentation".to_owned(),
            version: "0.1.0".to_owned(),
            description: None,
            servers: Vec::new(),
        }
    }
}

/// `OpenAPI` registry trait for operation and schema registration
pub trait OpenApiRegistry: Send + Sync {
    /// Register an API operation specification
    fn register_operation(&self, spec: &operation_builder::OperationSpec);

    /// Ensure schema for a type (including transitive dependencies) is registered
    /// under components and return the canonical component name for `$ref`.
    /// This is a type-erased version for dyn compatibility.
    fn ensure_schema_raw(&self, name: &str, schemas: SchemaCollection) -> String;

    /// Downcast support for accessing the concrete implementation if needed.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// Helper function to call `ensure_schema` with proper type information
///
/// # Panics
/// Panics if `T` is a `Vec<_>`. utoipa names every `Vec<_>` `Vec`, so
/// registering one as a component would collide with every other list
/// response; use
/// [`OperationBuilder::json_array_response_with_schema`](crate::api::operation_builder::OperationBuilder::json_array_response_with_schema)
/// instead. Also panics if `T`'s name is already registered with a different
/// definition (see `ensure_schema_raw`).
pub fn ensure_schema<T: utoipa::ToSchema + utoipa::PartialSchema + 'static>(
    registry: &dyn OpenApiRegistry,
) -> String {
    use utoipa::PartialSchema;

    // 1) Canonical component name for T as seen by utoipa
    let root_name = T::name().to_string();

    // utoipa's default `ToSchema::name()` drops generic arguments, so every
    // `Vec<_>` collapses to the single name `Vec` and distinct list responses
    // clobber each other (or, since M-14, panic on collision). `Vec` is a std
    // type, so `#[schema(as = "...")]` cannot rescue it — the caller has to use
    // the array-aware builder instead. Guard only this one name: a legitimate
    // user DTO could plausibly be called `Option`, `Page`, or `Map`.
    assert!(
        root_name != "Vec",
        "ensure_schema::<Vec<_>>() would register the component name `Vec`, which every other \
         Vec<T> also resolves to. Use `OperationBuilder::json_array_response_with_schema::<Item>()` \
         to emit an inline array with only the item type named."
    );

    // 2) Always insert T's own schema first (actual object, not a ref)
    //    This avoids self-referential components.
    let mut collected: SchemaCollection = vec![(root_name.clone(), <T as PartialSchema>::schema())];

    // 3) Collect and append all referenced schemas (dependencies) of T
    T::schemas(&mut collected);

    // 4) Pass to registry for insertion
    registry.ensure_schema_raw(&root_name, collected)
}

/// Build the `x-*` vendor extensions for one operation.
fn operation_vendor_extensions(
    spec: &operation_builder::OperationSpec,
) -> utoipa::openapi::extensions::Extensions {
    let mut ext = utoipa::openapi::extensions::Extensions::default();

    // Pagination
    if let Some(pagination) = spec.vendor_extensions.x_odata_filter.as_ref()
        && let Ok(value) = serde_json::to_value(pagination)
    {
        ext.insert("x-odata-filter".to_owned(), value);
    }
    if let Some(pagination) = spec.vendor_extensions.x_odata_orderby.as_ref()
        && let Ok(value) = serde_json::to_value(pagination)
    {
        ext.insert("x-odata-orderby".to_owned(), value);
    }

    // Visibility axis (`OperationSpec.exposed`): mark routes that are
    // registered in the gateway for external access. The `GatewayProvider`
    // reads this vendor extension to select which routes to reverse-proxy.
    // The key is mirrored as a constant in `cf-gears-toolkit-gateway`.
    if spec.exposed {
        ext.insert(
            "x-toolkit-visibility".to_owned(),
            serde_json::Value::String("exposed".to_owned()),
        );
    }

    // Throttling zone bindings. The contract layer only knows zone
    // *names*; the API gateway enriches these operations with the
    // zones' numeric limits (`x-rate-limit-rps` / `x-rate-limit-burst`)
    // when it builds the final document, using the zone name emitted
    // here as the join key.
    if let Some(throttling) = spec.throttling.as_ref() {
        if let Some(zone) = throttling.rate_limit_zone.as_ref() {
            ext.insert(
                "x-throttling-rate-limit-zone".to_owned(),
                serde_json::Value::String(zone.clone()),
            );
        }
        if let Some(zone) = throttling.in_flight_limit_zone.as_ref() {
            ext.insert(
                "x-throttling-in-flight-limit-zone".to_owned(),
                serde_json::Value::String(zone.clone()),
            );
        }
    }

    ext
}

/// Build a scalar parameter schema, preserving its format and minimum.
///
/// `format` is the token as the document carries it. `SchemaFormat::Custom`
/// serializes it verbatim, which is what a `KnownFormat` serializes to as well
/// — `"int64"` here and `SchemaFormat::KnownFormat(KnownFormat::Int64)` build
/// the same document — so a declaration site states the token and takes no
/// `utoipa` dependency for it.
fn param_schema_object(
    schema_type: SchemaType,
    format: Option<&str>,
    minimum: Option<f64>,
) -> utoipa::openapi::schema::Object {
    ObjectBuilder::new()
        .schema_type(schema_type)
        .format(format.map(|format| SchemaFormat::Custom(format.to_owned())))
        .minimum(minimum)
        .build()
}

/// Implementation of `OpenAPI` registry with lock-free data structures
pub struct OpenApiRegistryImpl {
    /// Store operation specs keyed by "METHOD:path"
    pub operation_specs: DashMap<String, operation_builder::OperationSpec>,
    /// Store schema components using arc-swap for lock-free reads
    /// `BTreeMap` ensures deterministic ordering of schemas in the `OpenAPI` document
    pub components_registry: ArcSwap<BTreeMap<String, RefOr<Schema>>>,
}

impl OpenApiRegistryImpl {
    /// Create a new empty registry
    #[must_use]
    pub fn new() -> Self {
        Self {
            operation_specs: DashMap::new(),
            components_registry: ArcSwap::from_pointee(BTreeMap::new()),
        }
    }

    /// Build `OpenAPI` specification from registered operations and components.
    ///
    /// # Arguments
    /// * `info` - `OpenAPI` document metadata (title, version, description)
    ///
    /// # Errors
    /// Returns an error if the `OpenAPI` specification cannot be built.
    #[allow(unknown_lints, de0205_operation_builder)]
    pub fn build_openapi(&self, info: &OpenApiInfo) -> Result<OpenApi> {
        use http::Method;

        // Log operation count for visibility
        let op_count = self.operation_specs.len();
        tracing::info!("Building OpenAPI: found {op_count} registered operations");

        // 1) Paths
        let mut paths = PathsBuilder::new();

        for spec in self.operation_specs.iter().map(|e| e.value().clone()) {
            let mut op = UOperationBuilder::new()
                .operation_id(spec.operation_id.clone().or(Some(spec.handler_id.clone())))
                .summary(spec.summary.clone())
                .description(spec.description.clone());

            for tag in &spec.tags {
                op = op.tag(tag.clone());
            }

            let ext = operation_vendor_extensions(&spec);
            if !ext.is_empty() {
                op = op.extensions(Some(ext));
            }

            // Parameters
            for p in &spec.params {
                let in_ = match p.location {
                    operation_builder::ParamLocation::Path => ParameterIn::Path,
                    operation_builder::ParamLocation::Query => ParameterIn::Query,
                    operation_builder::ParamLocation::Header => ParameterIn::Header,
                    operation_builder::ParamLocation::Cookie => ParameterIn::Cookie,
                };
                let required =
                    if matches!(p.location, operation_builder::ParamLocation::Path) || p.required {
                        Required::True
                    } else {
                        Required::False
                    };

                let schema_type = match p.param_type.as_str() {
                    "integer" => SchemaType::Type(utoipa::openapi::schema::Type::Integer),
                    "number" => SchemaType::Type(utoipa::openapi::schema::Type::Number),
                    "boolean" => SchemaType::Type(utoipa::openapi::schema::Type::Boolean),
                    _ => SchemaType::Type(utoipa::openapi::schema::Type::String),
                };
                let item_object = param_schema_object(schema_type, p.format.as_deref(), p.minimum);

                let mut builder = ParameterBuilder::new()
                    .name(&p.name)
                    .parameter_in(in_)
                    .required(required)
                    .description(p.description.clone());

                if p.array {
                    // `style: form, explode: true` is the repeated-key encoding
                    // (`?tag=a&tag=b`). Spelling it out matters: the OpenAPI
                    // default for a query array is `form` with `explode: true`,
                    // but generators differ on whether they assume it, and the
                    // wire format has to be unambiguous for a client written
                    // against this spec to interoperate.
                    builder = builder
                        .style(Some(utoipa::openapi::path::ParameterStyle::Form))
                        .explode(Some(true))
                        .schema(Some(Schema::Array(
                            utoipa::openapi::schema::ArrayBuilder::new()
                                .items(item_object)
                                .build(),
                        )));
                } else {
                    builder = builder.schema(Some(Schema::Object(item_object)));
                }

                op = op.parameter(builder.build());
            }

            // Request body
            if let Some(rb) = &spec.request_body {
                let content = build_request_body_content(&rb.schema);
                let mut rbld = RequestBodyBuilder::new()
                    .description(rb.description.clone())
                    .content(rb.content_type.to_owned(), content);
                if rb.required {
                    rbld = rbld.required(Some(Required::True));
                }
                op = op.request_body(Some(rbld.build()));
            }

            // Responses
            let mut responses_by_status = BTreeMap::<u16, Response>::new();
            for r in &spec.responses {
                let response = responses_by_status
                    .entry(r.status)
                    .or_insert_with(|| Response::new(&r.description));
                // Preserve the historical last-declaration-wins behavior for
                // the status-level description while merging media types.
                response.description.clone_from(&r.description);

                // Body-less response (e.g. 204 No Content) is signalled by an
                // empty `content_type`. Emit just `description` — attaching a
                // `content` block would make code-generators expect a body.
                if !r.content_type.is_empty() {
                    // Streaming media types are json-like here too: their
                    // declared schema is the *item* type, so it must render as
                    // a `$ref` rather than as an opaque string blob. Derived
                    // from `StreamFraming` rather than hard-coded, so a new
                    // framing variant is covered automatically instead of
                    // silently falling through to the opaque-string branch.
                    let is_json_like = r.content_type == "application/json"
                        || r.content_type == problem::APPLICATION_PROBLEM_JSON
                        || StreamFraming::is_stream_media_type(r.content_type);
                    let content = if is_json_like {
                        // Manually build content to preserve the correct content type.
                        ContentBuilder::new()
                            .schema(Some(build_response_schema(r.schema.as_ref())))
                            .build()
                    } else {
                        let schema = Schema::Object(
                            ObjectBuilder::new()
                                .schema_type(SchemaType::Type(
                                    utoipa::openapi::schema::Type::String,
                                ))
                                .format(Some(SchemaFormat::Custom(r.content_type.into())))
                                .build(),
                        );
                        ContentBuilder::new().schema(Some(schema)).build()
                    };
                    response.content.insert(r.content_type.to_owned(), content);
                }

                for header in &r.headers {
                    let schema_type = match header.header_type {
                        operation_builder::ResponseHeaderType::String => {
                            SchemaType::Type(utoipa::openapi::schema::Type::String)
                        }
                        operation_builder::ResponseHeaderType::Integer => {
                            SchemaType::Type(utoipa::openapi::schema::Type::Integer)
                        }
                        operation_builder::ResponseHeaderType::Boolean => {
                            SchemaType::Type(utoipa::openapi::schema::Type::Boolean)
                        }
                    };
                    let declared = HeaderBuilder::new()
                        .description(header.description.clone())
                        .schema(ObjectBuilder::new().schema_type(schema_type).build())
                        .build();
                    response.headers.insert(header.name.clone(), declared);
                }
            }
            let responses = ResponsesBuilder::new().responses_from_iter(
                responses_by_status
                    .into_iter()
                    .map(|(status, response)| (status.to_string(), response)),
            );
            op = op.responses(responses.build());

            // Add security requirement if operation requires authentication
            if spec.authenticated {
                let sec_req = utoipa::openapi::security::SecurityRequirement::new(
                    "bearerAuth",
                    Vec::<String>::new(),
                );
                op = op.security(sec_req);
            }

            let method = match spec.method {
                Method::POST => HttpMethod::Post,
                Method::PUT => HttpMethod::Put,
                Method::DELETE => HttpMethod::Delete,
                Method::PATCH => HttpMethod::Patch,
                // GET and any other method default to Get
                _ => HttpMethod::Get,
            };

            let item = PathItemBuilder::new().operation(method, op.build()).build();
            // Convert Axum-style path to OpenAPI-style path
            let openapi_path = operation_builder::axum_to_openapi_path(&spec.path);
            paths = paths.path(openapi_path, item);
        }

        // 2) Components (from our registry)
        let reg = self.components_registry.load();
        let mut components = ComponentsBuilder::new();
        for (name, schema) in reg.iter() {
            components = components.schema(name.clone(), schema.clone());
        }

        // Add bearer auth security scheme
        components = components.security_scheme(
            "bearerAuth",
            SecurityScheme::Http(
                HttpBuilder::new()
                    .scheme(HttpAuthScheme::Bearer)
                    .bearer_format("JWT")
                    .build(),
            ),
        );

        // 3) Info & final OpenAPI doc
        let openapi_info = InfoBuilder::new()
            .title(&info.title)
            .version(&info.version)
            .description(info.description.clone())
            .build();

        let servers = (!info.servers.is_empty()).then(|| {
            info.servers
                .iter()
                .cloned()
                .map(Server::new)
                .collect::<Vec<_>>()
        });

        let mut openapi = OpenApiBuilder::new()
            .info(openapi_info)
            .servers(servers)
            .paths(paths.build())
            .components(Some(components.build()))
            .build();

        // Document-level vendor extension: this spec is generated from Rust
        // contract traits + `schemars`/`utoipa` schemas, which cover a deliberate
        // subset of REST (ADR-0002). It is the MINIMUM conformance contract —
        // remote services may expose strictly more, never less. Downstream
        // directory validators key their superset semantics off this marker.
        let mut ext = utoipa::openapi::extensions::Extensions::default();
        ext.insert(
            "x-toolkit-spec-scope".to_owned(),
            serde_json::json!("minimum-conformance"),
        );
        openapi.extensions = Some(ext);

        warn_dangling_refs_in_openapi(&openapi);

        Ok(openapi)
    }
}

impl Default for OpenApiRegistryImpl {
    fn default() -> Self {
        Self::new()
    }
}

impl OpenApiRegistry for OpenApiRegistryImpl {
    fn register_operation(&self, spec: &operation_builder::OperationSpec) {
        let operation_key = format!("{}:{}", spec.method.as_str(), spec.path);
        // Surface duplicate (method, path) registrations — e.g. a generated
        // `register_<trait>_routes()` colliding with a hand-written route, or two
        // SDKs registering the same path (M-13). Silently overwriting the earlier
        // operation's OpenAPI spec is a hard-to-diagnose drift; the axum router
        // itself will also panic on the duplicate route at bind time.
        if let Some(prev) = self
            .operation_specs
            .insert(operation_key.clone(), spec.clone())
            && prev.handler_id != spec.handler_id
        {
            tracing::warn!(
                operation_key = %operation_key,
                previous_handler = %prev.handler_id,
                new_handler = %spec.handler_id,
                "duplicate OpenAPI operation registration; the earlier operation spec was \
                 overwritten - generated and manual routes must not share a (method, path)"
            );
        }

        tracing::debug!(
            handler_id = %spec.handler_id,
            method = %spec.method.as_str(),
            path = %spec.path,
            summary = %spec.summary.as_deref().unwrap_or("No summary"),
            operation_key = %operation_key,
            "Registered API operation in registry"
        );
    }

    fn ensure_schema_raw(&self, root_name: &str, schemas: SchemaCollection) -> String {
        // Snapshot & copy-on-write
        let current = self.components_registry.load();
        let mut reg = (**current).clone();

        for (name, schema) in schemas {
            // Conflict policy: identical → no-op; different → HARD ERROR. Two
            // distinct types resolving to the same schema name (utoipa uses the
            // bare type ident by default) would otherwise silently clobber each
            // other in `components.schemas`, producing a spec where one type
            // masquerades under another's name — a hard-to-diagnose wire
            // mismatch. Fail fast at registration instead.
            if let Some(existing) = reg.get(&name) {
                let a = serde_json::to_value(existing).ok();
                let b = serde_json::to_value(&schema).ok();
                if a == b {
                    continue; // Skip identical schemas
                }
                panic!(
                    "OpenAPI schema name collision: `{name}` is registered with two different \
                     definitions. Two distinct types share the same schema name — rename one, or \
                     give it a distinct `#[schema(as = \"...\")]` alias. For a `Vec<T>` response \
                     use `OperationBuilder::json_array_response_with_schema::<T>()`, which emits \
                     an inline array instead of registering a component named `Vec`. \
                     existing={}, new={}",
                    a.map(|v| truncate_json(&v)).unwrap_or_default(),
                    b.map(|v| truncate_json(&v)).unwrap_or_default(),
                );
            }
            reg.insert(name, schema);
        }

        self.components_registry.store(Arc::new(reg));
        root_name.to_owned()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Render a JSON value to a compact, length-bounded string for diagnostics.
/// Bounded by character count (char-boundary safe) rather than bytes.
fn truncate_json(v: &serde_json::Value) -> String {
    const MAX: usize = 200;
    let s = v.to_string();
    if s.chars().count() > MAX {
        let mut out: String = s.chars().take(MAX).collect();
        out.push('\u{2026}');
        out
    } else {
        s
    }
}

/// Build the `OpenAPI` content object for a request body schema variant.
fn build_request_body_content(
    schema: &operation_builder::RequestBodySchema,
) -> utoipa::openapi::content::Content {
    match schema {
        operation_builder::RequestBodySchema::Ref { schema_name } => ContentBuilder::new()
            .schema(Some(RefOr::Ref(Ref::from_schema_name(schema_name.clone()))))
            .build(),
        operation_builder::RequestBodySchema::MultipartFile { field_name } => {
            // Build multipart/form-data schema with a single binary file field
            // type: object
            // properties:
            //   {field_name}: { type: string, format: binary }
            // required: [ field_name ]
            let file_schema = Schema::Object(
                ObjectBuilder::new()
                    .schema_type(SchemaType::Type(utoipa::openapi::schema::Type::String))
                    .format(Some(SchemaFormat::Custom("binary".into())))
                    .build(),
            );
            let obj = ObjectBuilder::new()
                .property(field_name.clone(), file_schema)
                .required(field_name.clone());
            ContentBuilder::new()
                .schema(Some(Schema::Object(obj.build())))
                .build()
        }
        operation_builder::RequestBodySchema::Binary => {
            // Represent raw binary body as type string, format binary.
            // This is used for application/octet-stream and similar raw binary content.
            let schema = Schema::Object(
                ObjectBuilder::new()
                    .schema_type(SchemaType::Type(utoipa::openapi::schema::Type::String))
                    .format(Some(SchemaFormat::Custom("binary".into())))
                    .build(),
            );
            ContentBuilder::new().schema(Some(schema)).build()
        }
        operation_builder::RequestBodySchema::InlineObject => {
            // Preserve previous behavior for inline object bodies
            ContentBuilder::new()
                .schema(Some(Schema::Object(ObjectBuilder::new().build())))
                .build()
        }
    }
}

/// Build the response body schema for a [`operation_builder::ResponseSchema`].
///
/// `None` — a JSON response with no declared schema — yields a free-form
/// object, preserving the previous behaviour.
fn build_response_schema(schema: Option<&operation_builder::ResponseSchema>) -> RefOr<Schema> {
    match schema {
        Some(operation_builder::ResponseSchema::Ref { schema_name }) => {
            RefOr::Ref(Ref::from_schema_name(schema_name.clone()))
        }
        // Top-level arrays are emitted INLINE, with only the item type
        // registered as a named component. Naming the array itself would use
        // utoipa's `Vec` (generics are stripped from `ToSchema::name()`), so
        // every list endpoint in the process would fight over one component.
        Some(operation_builder::ResponseSchema::Array { items_schema_name }) => {
            RefOr::T(Schema::Array(
                ArrayBuilder::new()
                    .items(RefOr::Ref(Ref::from_schema_name(items_schema_name.clone())))
                    .build(),
            ))
        }
        None => RefOr::T(Schema::Object(ObjectBuilder::new().build())),
    }
}

/// Walk the finalized `OpenAPI` document and warn about dangling `$ref` targets.
///
/// Scans the entire document (operations, request bodies, responses, and schemas)
/// so that `$ref`s emitted outside `components.schemas` are also caught.
fn warn_dangling_refs_in_openapi(openapi: &OpenApi) {
    for ref_name in &collect_all_dangling_refs_in_openapi(openapi) {
        tracing::warn!(
            schema = %ref_name,
            "Dangling $ref: schema '{}' is referenced but not registered. \
             Add an explicit `ensure_schema::<T>(registry)` call.",
            ref_name,
        );
    }
}

/// Serialize the full `OpenAPI` document to JSON, collect every
/// `#/components/schemas/{name}` reference, and return those not defined
/// in `components.schemas`.
fn collect_all_dangling_refs_in_openapi(openapi: &OpenApi) -> Vec<String> {
    let value = match serde_json::to_value(openapi) {
        Ok(v) => v,
        Err(err) => {
            tracing::debug!(error = %err, "Failed to serialize OpenAPI doc for dangling $ref check");
            return Vec::new();
        }
    };

    let mut all_refs = HashSet::new();
    collect_refs_from_json(&value, &mut all_refs);

    // Defined schema names live under components.schemas keys
    let defined: HashSet<&str> = value
        .pointer("/components/schemas")
        .and_then(|v| v.as_object())
        .map(|obj| obj.keys().map(String::as_str).collect())
        .unwrap_or_default();

    all_refs
        .into_iter()
        .filter(|name| !defined.contains(name.as_str()))
        .collect()
}

/// Recursively extract `#/components/schemas/{name}` targets from a JSON value.
fn collect_refs_from_json(value: &serde_json::Value, refs: &mut HashSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(serde_json::Value::String(ref_str)) = map.get("$ref")
                && let Some(name) = ref_str.strip_prefix("#/components/schemas/")
            {
                refs.insert(name.to_owned());
            }
            for v in map.values() {
                collect_refs_from_json(v, refs);
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                collect_refs_from_json(v, refs);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use crate::api::operation_builder::{
        OperationSpec, ParamSpec, ResponseHeaderSpec, ResponseHeaderType, ResponseSchema,
        ResponseSpec, VendorExtensions,
    };
    use http::Method;

    /// Minimal `OperationSpec` carrying a single 200 response with `schema`.
    fn spec_with_response(
        path: &str,
        handler: &str,
        schema: Option<ResponseSchema>,
    ) -> OperationSpec {
        OperationSpec {
            method: Method::GET,
            path: path.to_owned(),
            operation_id: Some(handler.to_owned()),
            summary: None,
            description: None,
            tags: vec![],
            params: vec![],
            request_body: None,
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "OK".to_owned(),
                schema,
                headers: vec![],
            }],
            handler_id: handler.to_owned(),
            authenticated: false,
            exposed: false,
            throttling: None,
            allowed_request_content_types: None,
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        }
    }

    /// The 200 response schema for `path`, as JSON.
    fn response_schema_json(doc: &serde_json::Value, path: &str) -> serde_json::Value {
        doc["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
            .clone()
    }

    fn test_info() -> OpenApiInfo {
        OpenApiInfo {
            title: "T".to_owned(),
            version: "1".to_owned(),
            description: None,
            servers: Vec::new(),
        }
    }

    #[test]
    fn throttling_zone_names_are_emitted_as_vendor_extensions() {
        use crate::api::operation_builder::ThrottlingSpec;

        let registry = OpenApiRegistryImpl::new();
        let mut spec = spec_with_response("/throttled", "throttled_op", None);
        spec.throttling = Some(ThrottlingSpec {
            rate_limit_zone: Some("rl_zone".to_owned()),
            in_flight_limit_zone: Some("ifl_zone".to_owned()),
            require_security_context: false,
            dry_run: false,
        });
        registry.register_operation(&spec);
        // An operation without throttling must not carry the extensions.
        registry.register_operation(&spec_with_response("/plain", "plain_op", None));

        let doc = registry.build_openapi(&test_info()).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        let throttled = &json["paths"]["/throttled"]["get"];
        assert_eq!(
            throttled["x-throttling-rate-limit-zone"],
            serde_json::json!("rl_zone")
        );
        assert_eq!(
            throttled["x-throttling-in-flight-limit-zone"],
            serde_json::json!("ifl_zone")
        );

        let plain = &json["paths"]["/plain"]["get"];
        assert!(plain.get("x-throttling-rate-limit-zone").is_none());
        assert!(plain.get("x-throttling-in-flight-limit-zone").is_none());
    }

    #[test]
    fn test_registry_creation() {
        let registry = OpenApiRegistryImpl::new();
        assert_eq!(registry.operation_specs.len(), 0);
        assert_eq!(registry.components_registry.load().len(), 0);
    }

    #[test]
    fn parameter_formats_are_preserved_in_scalar_and_array_schemas() {
        use serde_json::json;

        // `int64` is a format `utoipa` knows and `resource-version` is not:
        // both reach the document as the token the declaration spelled, which
        // is what lets `ParamSpec::format` be a plain string.
        for (format, param_type, expected) in [
            (
                Some("int64"),
                "integer",
                json!({"type": "integer", "format": "int64", "minimum": 1}),
            ),
            (
                Some("resource-version"),
                "integer",
                json!({"type": "integer", "format": "resource-version", "minimum": 1}),
            ),
            (None, "integer", json!({"type": "integer", "minimum": 1})),
        ] {
            for array in [false, true] {
                let registry = OpenApiRegistryImpl::new();
                let mut spec = spec_with_response("/test", "get_test", None);
                let mut param = ParamSpec::query("version")
                    .required(true)
                    .param_type(param_type)
                    .array(array)
                    .minimum(1.0);
                if let Some(format) = format {
                    param = param.format(format);
                }
                spec.params.push(param);
                registry.register_operation(&spec);
                let doc = registry.build_openapi(&test_info()).expect("build OpenAPI");
                let json = serde_json::to_value(doc).expect("serialize OpenAPI");
                let schema = &json["paths"]["/test"]["get"]["parameters"][0]["schema"];
                let expected_schema = if array {
                    json!({"type": "array", "items": expected})
                } else {
                    expected.clone()
                };
                assert_eq!(schema, &expected_schema, "format={format:?}, array={array}");
            }
        }
    }

    #[test]
    fn test_register_operation() {
        let registry = OpenApiRegistryImpl::new();
        let spec = OperationSpec {
            method: Method::GET,
            path: "/test".to_owned(),
            operation_id: Some("test_op".to_owned()),
            summary: Some("Test operation".to_owned()),
            description: None,
            tags: vec![],
            params: vec![],
            request_body: None,
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "Success".to_owned(),
                schema: None,
                headers: vec![],
            }],
            handler_id: "get_test".to_owned(),
            authenticated: false,
            exposed: false,
            throttling: None,
            allowed_request_content_types: None,
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        };

        registry.register_operation(&spec);
        assert_eq!(registry.operation_specs.len(), 1);
    }

    #[test]
    fn response_headers_are_emitted_with_their_declared_types() {
        let registry = OpenApiRegistryImpl::new();
        let mut spec = spec_with_response("/submit", "submit", None);
        spec.responses[0].headers = vec![
            ResponseHeaderSpec::new(
                "Location",
                "Operation resource URI",
                ResponseHeaderType::String,
            ),
            ResponseHeaderSpec::new(
                "Retry-After",
                "Retry delay in seconds",
                ResponseHeaderType::Integer,
            ),
            ResponseHeaderSpec::new(
                "Idempotency-Replayed",
                "Whether this is a replay",
                ResponseHeaderType::Boolean,
            ),
        ];
        registry.register_operation(&spec);

        let doc = registry.build_openapi(&test_info()).unwrap();
        let json = serde_json::to_value(doc).unwrap();
        let headers = &json["paths"]["/submit"]["get"]["responses"]["200"]["headers"];
        assert_eq!(headers["Location"]["schema"]["type"], "string");
        assert_eq!(headers["Location"]["description"], "Operation resource URI");
        assert_eq!(headers["Retry-After"]["schema"]["type"], "integer");
        assert_eq!(headers["Idempotency-Replayed"]["schema"]["type"], "boolean");
    }

    #[test]
    fn response_content_types_with_the_same_status_are_combined() {
        let registry = OpenApiRegistryImpl::new();
        let mut spec = spec_with_response("/document", "document", None);
        spec.responses[0].content_type = "text/plain";
        spec.responses[0].description = "Plain document".to_owned();
        spec.responses[0].headers = vec![ResponseHeaderSpec::new(
            "X-Plain-Document",
            "Whether plain text is available",
            ResponseHeaderType::Boolean,
        )];
        spec.responses.push(
            ResponseSpec::new(
                http::StatusCode::OK.as_u16(),
                "text/html",
                "HTML document",
                None,
            )
            .with_headers([ResponseHeaderSpec::new(
                "X-HTML-Document",
                "Whether HTML is available",
                ResponseHeaderType::Boolean,
            )]),
        );
        registry.register_operation(&spec);

        let doc = registry.build_openapi(&test_info()).unwrap();
        let json = serde_json::to_value(doc).unwrap();
        let response = &json["paths"]["/document"]["get"]["responses"]["200"];
        assert_eq!(response["description"], "HTML document");
        assert_eq!(
            response["content"]["text/plain"]["schema"]["format"],
            "text/plain"
        );
        assert_eq!(
            response["content"]["text/html"]["schema"]["format"],
            "text/html"
        );
        assert_eq!(
            response["headers"]["X-Plain-Document"]["schema"]["type"],
            "boolean"
        );
        assert_eq!(
            response["headers"]["X-HTML-Document"]["schema"]["type"],
            "boolean"
        );
    }

    #[test]
    fn bodyless_response_can_declare_headers_without_content() {
        let registry = OpenApiRegistryImpl::new();
        let mut spec = spec_with_response("/jobs", "jobs", None);
        spec.responses[0].content_type = "";
        spec.responses[0].schema = None;
        spec.responses[0].headers = vec![ResponseHeaderSpec::without_description(
            "Retry-After",
            ResponseHeaderType::Integer,
        )];
        registry.register_operation(&spec);

        let doc = registry.build_openapi(&test_info()).unwrap();
        let json = serde_json::to_value(doc).unwrap();
        let response = &json["paths"]["/jobs"]["get"]["responses"]["200"];
        assert!(response.get("content").is_none());
        assert_eq!(
            response["headers"]["Retry-After"]["schema"]["type"],
            "integer"
        );
        assert!(
            response["headers"]["Retry-After"]
                .get("description")
                .is_none()
        );
    }

    #[test]
    fn test_build_empty_openapi() {
        let registry = OpenApiRegistryImpl::new();
        let info = OpenApiInfo {
            title: "Test API".to_owned(),
            version: "1.0.0".to_owned(),
            description: Some("Test API Description".to_owned()),
            servers: Vec::new(),
        };
        let doc = registry.build_openapi(&info).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        // Verify it's valid OpenAPI document structure
        assert!(json.get("openapi").is_some());
        assert!(json.get("info").is_some());
        assert!(json.get("paths").is_some());

        // Verify info section
        let openapi_info = json.get("info").unwrap();
        assert_eq!(openapi_info.get("title").unwrap(), "Test API");
        assert_eq!(openapi_info.get("version").unwrap(), "1.0.0");
        assert_eq!(
            openapi_info.get("description").unwrap(),
            "Test API Description"
        );
    }

    #[test]
    fn test_build_openapi_with_operation() {
        let registry = OpenApiRegistryImpl::new();
        let spec = OperationSpec {
            method: Method::GET,
            path: "/users/{id}".to_owned(),
            operation_id: Some("get_user".to_owned()),
            summary: Some("Get user by ID".to_owned()),
            description: Some("Retrieves a user by their ID".to_owned()),
            tags: vec!["users".to_owned()],
            params: vec![ParamSpec::path("id").description("User ID")],
            request_body: None,
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "User found".to_owned(),
                schema: None,
                headers: vec![],
            }],
            handler_id: "get_users_id".to_owned(),
            authenticated: false,
            exposed: false,
            throttling: None,
            allowed_request_content_types: None,
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        };

        registry.register_operation(&spec);
        let info = OpenApiInfo::default();
        let doc = registry.build_openapi(&info).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        // Verify path exists
        let paths = json.get("paths").unwrap();
        assert!(paths.get("/users/{id}").is_some());

        // Verify operation details
        let get_op = paths.get("/users/{id}").unwrap().get("get").unwrap();
        assert_eq!(get_op.get("operationId").unwrap(), "get_user");
        assert_eq!(get_op.get("summary").unwrap(), "Get user by ID");
    }

    #[test]
    fn test_ensure_schema_raw() {
        let registry = OpenApiRegistryImpl::new();
        let schema = Schema::Object(ObjectBuilder::new().build());
        let schemas = vec![("TestSchema".to_owned(), RefOr::T(schema))];

        let name = registry.ensure_schema_raw("TestSchema", schemas);
        assert_eq!(name, "TestSchema");
        assert_eq!(registry.components_registry.load().len(), 1);
    }

    #[test]
    fn test_build_openapi_with_binary_request() {
        use crate::api::operation_builder::RequestBodySchema;

        let registry = OpenApiRegistryImpl::new();
        let spec = OperationSpec {
            method: Method::POST,
            path: "/files/v1/upload".to_owned(),
            operation_id: Some("upload_file".to_owned()),
            summary: Some("Upload a file".to_owned()),
            description: Some("Upload raw binary file".to_owned()),
            tags: vec!["upload".to_owned()],
            params: vec![],
            request_body: Some(crate::api::operation_builder::RequestBodySpec {
                content_type: "application/octet-stream",
                description: Some("Raw file bytes".to_owned()),
                schema: RequestBodySchema::Binary,
                required: true,
            }),
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "Upload successful".to_owned(),
                schema: None,
                headers: vec![],
            }],
            handler_id: "post_upload".to_owned(),
            authenticated: false,
            exposed: false,
            throttling: None,
            allowed_request_content_types: Some(vec!["application/octet-stream"]),
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        };

        registry.register_operation(&spec);
        let info = OpenApiInfo::default();
        let doc = registry.build_openapi(&info).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        // Verify path exists
        let paths = json.get("paths").unwrap();
        assert!(paths.get("/files/v1/upload").is_some());

        // Verify request body has application/octet-stream with binary schema
        let post_op = paths.get("/files/v1/upload").unwrap().get("post").unwrap();
        let request_body = post_op.get("requestBody").unwrap();
        let content = request_body.get("content").unwrap();
        let octet_stream = content
            .get("application/octet-stream")
            .expect("application/octet-stream content type should exist");

        // Verify schema is type: string, format: binary
        let schema = octet_stream.get("schema").unwrap();
        assert_eq!(schema.get("type").unwrap(), "string");
        assert_eq!(schema.get("format").unwrap(), "binary");

        // Verify required flag
        assert_eq!(request_body.get("required").unwrap(), true);
    }

    #[test]
    fn test_build_openapi_with_pagination() {
        let registry = OpenApiRegistryImpl::new();

        let mut filter: operation_builder::ODataPagination<
            std::collections::BTreeMap<String, Vec<String>>,
        > = operation_builder::ODataPagination::default();
        filter.allowed_fields.insert(
            "name".to_owned(),
            vec!["eq", "ne", "contains", "startswith", "endswith", "in"]
                .into_iter()
                .map(String::from)
                .collect(),
        );
        filter.allowed_fields.insert(
            "age".to_owned(),
            vec!["eq", "ne", "gt", "ge", "lt", "le", "in"]
                .into_iter()
                .map(String::from)
                .collect(),
        );

        let mut order_by: operation_builder::ODataPagination<Vec<String>> =
            operation_builder::ODataPagination::default();
        order_by.allowed_fields.push("name asc".to_owned());
        order_by.allowed_fields.push("name desc".to_owned());
        order_by.allowed_fields.push("age asc".to_owned());
        order_by.allowed_fields.push("age desc".to_owned());

        let mut spec = OperationSpec {
            method: Method::GET,
            path: "/test".to_owned(),
            operation_id: Some("test_op".to_owned()),
            summary: Some("Test".to_owned()),
            description: None,
            tags: vec![],
            params: vec![],
            request_body: None,
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "OK".to_owned(),
                schema: None,
                headers: vec![],
            }],
            handler_id: "get_test".to_owned(),
            authenticated: false,
            exposed: false,
            throttling: None,
            allowed_request_content_types: None,
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        };
        spec.vendor_extensions.x_odata_filter = Some(filter);
        spec.vendor_extensions.x_odata_orderby = Some(order_by);

        registry.register_operation(&spec);
        let info = OpenApiInfo::default();
        let doc = registry.build_openapi(&info).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        let paths = json.get("paths").unwrap();
        let op = paths.get("/test").unwrap().get("get").unwrap();

        let filter_ext = op
            .get("x-odata-filter")
            .expect("x-odata-filter should be present");

        let allowed_fields = filter_ext.get("allowedFields").unwrap();
        assert!(allowed_fields.get("name").is_some());
        assert!(allowed_fields.get("age").is_some());

        let order_ext = op
            .get("x-odata-orderby")
            .expect("x-odata-orderby should be present");

        let allowed_order = order_ext.get("allowedFields").unwrap().as_array().unwrap();
        assert!(allowed_order.iter().any(|v| v.as_str() == Some("name asc")));
        assert!(allowed_order.iter().any(|v| v.as_str() == Some("age desc")));
    }

    #[test]
    fn test_public_operation_emits_visibility_extension() {
        let registry = OpenApiRegistryImpl::new();
        let public = OperationSpec {
            method: Method::GET,
            path: "/calc/v1/ping".to_owned(),
            operation_id: Some("ping".to_owned()),
            summary: Some("Ping".to_owned()),
            description: None,
            tags: vec![],
            params: vec![],
            request_body: None,
            responses: vec![ResponseSpec {
                status: 200,
                content_type: "application/json",
                description: "OK".to_owned(),
                schema: None,
                headers: vec![],
            }],
            handler_id: "get_ping".to_owned(),
            authenticated: false,
            exposed: true,
            throttling: None,
            allowed_request_content_types: None,
            vendor_extensions: VendorExtensions::default(),
            license_requirement: None,
        };
        // A second, internal operation must NOT carry the extension.
        let mut internal = public.clone();
        internal.path = "/calc/v1/internal".to_owned();
        internal.handler_id = "get_internal".to_owned();
        internal.operation_id = Some("internal".to_owned());
        internal.exposed = false;

        registry.register_operation(&public);
        registry.register_operation(&internal);
        let doc = registry.build_openapi(&OpenApiInfo::default()).unwrap();
        let json = serde_json::to_value(&doc).unwrap();
        let paths = json.get("paths").unwrap();

        let public_op = paths.get("/calc/v1/ping").unwrap().get("get").unwrap();
        assert_eq!(
            public_op
                .get("x-toolkit-visibility")
                .and_then(|v| v.as_str()),
            Some("exposed"),
            "public operation must advertise the gateway visibility extension"
        );

        let internal_op = paths.get("/calc/v1/internal").unwrap().get("get").unwrap();
        assert!(
            internal_op.get("x-toolkit-visibility").is_none(),
            "non-public operation must not carry the visibility extension"
        );
    }

    /// Helper: build a minimal `OpenAPI` doc with the given component schemas.
    fn build_test_openapi(schemas: BTreeMap<String, RefOr<Schema>>) -> OpenApi {
        let mut components = ComponentsBuilder::new();
        for (name, schema) in schemas {
            components = components.schema(name, schema);
        }
        OpenApiBuilder::new()
            .components(Some(components.build()))
            .build()
    }

    #[test]
    fn test_dangling_refs_detects_missing_in_components() {
        let mut schemas: BTreeMap<String, RefOr<Schema>> = BTreeMap::new();
        // Register "Foo" with a $ref to "Bar" which is NOT registered
        let foo_schema = serde_json::from_value::<Schema>(serde_json::json!({
            "type": "object",
            "properties": {
                "bar": { "$ref": "#/components/schemas/Bar" }
            }
        }))
        .unwrap();
        schemas.insert("Foo".to_owned(), RefOr::T(foo_schema));

        let openapi = build_test_openapi(schemas);
        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
        assert_eq!(dangling, vec!["Bar".to_owned()]);
    }

    #[test]
    fn test_dangling_refs_no_false_positives() {
        let mut schemas: BTreeMap<String, RefOr<Schema>> = BTreeMap::new();
        // Register "Bar"
        let bar_schema = Schema::Object(ObjectBuilder::new().build());
        schemas.insert("Bar".to_owned(), RefOr::T(bar_schema));

        // Register "Foo" referencing "Bar"
        let foo_schema = serde_json::from_value::<Schema>(serde_json::json!({
            "type": "object",
            "properties": {
                "bar": { "$ref": "#/components/schemas/Bar" }
            }
        }))
        .unwrap();
        schemas.insert("Foo".to_owned(), RefOr::T(foo_schema));

        let openapi = build_test_openapi(schemas);
        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
        assert!(
            dangling.is_empty(),
            "Expected no dangling refs but got: {dangling:?}"
        );
    }

    #[test]
    fn test_dangling_refs_detects_missing_in_operations() {
        // Build an OpenAPI doc with a response $ref to "MissingDto" but no
        // matching component schema — simulates the scenario CodeRabbit flagged.
        let openapi_json = serde_json::json!({
            "openapi": "3.1.0",
            "info": { "title": "test", "version": "0.1.0" },
            "paths": {
                "/items": {
                    "get": {
                        "responses": {
                            "200": {
                                "description": "OK",
                                "content": {
                                    "application/json": {
                                        "schema": { "$ref": "#/components/schemas/MissingDto" }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "components": {
                "schemas": {}
            }
        });
        let openapi: OpenApi = serde_json::from_value(openapi_json).unwrap();
        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
        assert_eq!(dangling, vec!["MissingDto".to_owned()]);
    }

    // --- array responses -------------------------------------------------
    //
    // A top-level array must be emitted inline, referencing the item type,
    // and must NOT create a component of its own. utoipa names every `Vec<T>`
    // `Vec`, so a named array component makes all list endpoints collide.

    #[test]
    fn array_response_emits_inline_array_referencing_item() {
        let registry = OpenApiRegistryImpl::new();
        registry.register_operation(&spec_with_response(
            "/gears",
            "list_gears",
            Some(ResponseSchema::Array {
                items_schema_name: "GearDto".to_owned(),
            }),
        ));

        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
        let schema = response_schema_json(&doc, "/gears");

        assert_eq!(schema["type"], "array");
        assert_eq!(schema["items"]["$ref"], "#/components/schemas/GearDto");
        // The array itself is not a component.
        assert!(schema.get("$ref").is_none());
        assert!(doc["components"]["schemas"].get("Vec").is_none());
    }

    #[test]
    fn ref_response_still_emits_plain_ref() {
        let registry = OpenApiRegistryImpl::new();
        registry.register_operation(&spec_with_response(
            "/gear",
            "get_gear",
            Some(ResponseSchema::Ref {
                schema_name: "GearDto".to_owned(),
            }),
        ));

        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
        let schema = response_schema_json(&doc, "/gear");

        assert_eq!(schema["$ref"], "#/components/schemas/GearDto");
        assert!(schema.get("type").is_none());
    }

    /// `OperationBuilder::multipart_json` declares the *item* schema under the
    /// bare `multipart/mixed` media-type key: no `boundary=` parameter (that is
    /// generated per response at runtime, so it is not a property of the
    /// operation), and a `$ref` rather than the opaque string blob a
    /// non-json-like media type would render as.
    #[test]
    fn multipart_mixed_response_emits_the_item_ref_under_a_bare_media_type() {
        let registry = OpenApiRegistryImpl::new();
        let mut spec = spec_with_response(
            "/events",
            "stream_events",
            Some(ResponseSchema::Ref {
                schema_name: "FrameDto".to_owned(),
            }),
        );
        spec.responses[0].content_type = "multipart/mixed";
        registry.register_operation(&spec);

        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
        let content = &doc["paths"]["/events"]["get"]["responses"]["200"]["content"];

        assert_eq!(
            content["multipart/mixed"]["schema"]["$ref"],
            "#/components/schemas/FrameDto"
        );
        // The runtime boundary must not leak into the spec's media-type key.
        assert_eq!(
            content.as_object().map(|o| o.keys().collect::<Vec<_>>()),
            Some(vec![&"multipart/mixed".to_owned()])
        );
        // Not rendered as a string with a custom format — that is what a
        // non-json-like media type would produce, and it would lose the item
        // schema entirely.
        assert!(content["multipart/mixed"]["schema"].get("format").is_none());
    }

    #[test]
    fn schemaless_json_response_still_emits_free_form_object() {
        let registry = OpenApiRegistryImpl::new();
        registry.register_operation(&spec_with_response("/any", "any_op", None));

        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
        let schema = response_schema_json(&doc, "/any");

        assert!(schema.get("$ref").is_none());
        assert_ne!(schema["type"], "array");
    }

    /// The regression this whole change exists for: two list endpoints
    /// returning different item types used to both register a component named
    /// `Vec`, silently clobbering each other (and, after M-14, panicking).
    #[test]
    fn two_distinct_array_responses_do_not_collide() {
        #[derive(utoipa::ToSchema)]
        #[allow(dead_code)]
        struct AlphaDto {
            alpha: String,
        }
        #[derive(utoipa::ToSchema)]
        #[allow(dead_code)]
        struct BetaDto {
            beta: i32,
        }

        let registry = OpenApiRegistryImpl::new();
        // Registering the ITEM types is what the array builder method does.
        let a = ensure_schema::<AlphaDto>(&registry);
        let b = ensure_schema::<BetaDto>(&registry);
        assert_eq!((a.as_str(), b.as_str()), ("AlphaDto", "BetaDto"));

        registry.register_operation(&spec_with_response(
            "/alphas",
            "list_alphas",
            Some(ResponseSchema::Array {
                items_schema_name: a,
            }),
        ));
        registry.register_operation(&spec_with_response(
            "/betas",
            "list_betas",
            Some(ResponseSchema::Array {
                items_schema_name: b,
            }),
        ));

        let openapi = registry.build_openapi(&test_info()).unwrap();
        assert!(
            collect_all_dangling_refs_in_openapi(&openapi).is_empty(),
            "array item refs must point at registered components"
        );

        let doc = serde_json::to_value(&openapi).unwrap();
        let schemas = &doc["components"]["schemas"];
        assert!(schemas.get("AlphaDto").is_some());
        assert!(schemas.get("BetaDto").is_some());
        assert!(schemas.get("Vec").is_none());
        assert_eq!(
            response_schema_json(&doc, "/alphas")["items"]["$ref"],
            "#/components/schemas/AlphaDto"
        );
        assert_eq!(
            response_schema_json(&doc, "/betas")["items"]["$ref"],
            "#/components/schemas/BetaDto"
        );
    }

    #[test]
    #[should_panic(expected = "would register the component name `Vec`")]
    fn ensure_schema_rejects_vec_directly() {
        #[derive(utoipa::ToSchema)]
        #[allow(dead_code)]
        struct ItemDto {
            x: u8,
        }
        let registry = OpenApiRegistryImpl::new();
        let _ = ensure_schema::<Vec<ItemDto>>(&registry);
    }

    #[test]
    #[should_panic(expected = "OpenAPI schema name collision")]
    fn ensure_schema_raw_panics_on_conflicting_definition() {
        let registry = OpenApiRegistryImpl::new();
        registry.ensure_schema_raw(
            "Dup",
            vec![("Dup".to_owned(), RefOr::Ref(Ref::from_schema_name("First")))],
        );
        registry.ensure_schema_raw(
            "Dup",
            vec![(
                "Dup".to_owned(),
                RefOr::Ref(Ref::from_schema_name("Second")),
            )],
        );
    }

    #[test]
    fn ensure_schema_raw_allows_identical_reregistration() {
        let registry = OpenApiRegistryImpl::new();
        let entry = || {
            vec![(
                "Same".to_owned(),
                RefOr::Ref(Ref::from_schema_name("Target")),
            )]
        };
        registry.ensure_schema_raw("Same", entry());
        registry.ensure_schema_raw("Same", entry());
        assert_eq!(registry.components_registry.load().len(), 1);
    }
}