rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
//! S3 API Router
//!
//! Defines all S3-compatible endpoints and routes them to handlers.

use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use axum::{
    body::Body,
    extract::{FromRequest, Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Response},
    routing::{delete, get, head, options, post, put},
    Router,
};
use http_body_util::BodyExt;
use serde::Deserialize;
use std::sync::Arc;
use utoipa::OpenApi;

use crate::AppState;

use super::utils::{error_response, malformed_xml_response};
use super::{
    bucket_stubs, cors, graphql, handlers, multipart, observability_handlers, openapi,
    preprocessing_handlers, query_intelligence_handlers, replication_handlers,
    select_cache_handlers, tiering_handlers, training_handlers, websocket,
};

/// Query parameters for object operations (multipart, tagging, acl, attributes, restore, etc.)
#[derive(Debug, Deserialize, Default)]
pub struct ObjectQueryParams {
    #[serde(rename = "uploadId")]
    pub upload_id: Option<String>,
    #[serde(rename = "partNumber")]
    pub part_number: Option<u32>,
    pub uploads: Option<String>,
    /// If present, this is a tagging operation
    pub tagging: Option<String>,
    /// If present, this is an ACL operation
    pub acl: Option<String>,
    /// If present, this is a GetObjectAttributes operation
    pub attributes: Option<String>,
    /// If present, this is a RestoreObject operation
    pub restore: Option<String>,
    /// If present, this is a GetObjectLegalHold/PutObjectLegalHold operation
    #[serde(rename = "legal-hold")]
    pub legal_hold: Option<String>,
    /// If present, this is a GetObjectRetention/PutObjectRetention operation
    pub retention: Option<String>,
    /// If present, this is a SelectObjectContent operation
    pub select: Option<String>,
    #[serde(rename = "select-type")]
    pub select_type: Option<String>,
    /// If present, this is a GetObjectTorrent operation
    pub torrent: Option<String>,
    /// Maximum number of parts to return for ListParts pagination
    #[serde(rename = "max-parts")]
    pub max_parts: Option<u32>,
    /// Part number marker for ListParts pagination (return parts after this number)
    #[serde(rename = "part-number-marker")]
    pub part_number_marker: Option<u32>,
    /// Version ID for Object Lock and versioned object operations
    #[serde(rename = "versionId")]
    pub version_id: Option<String>,
}

/// Query parameters for bucket-level POST operations
#[derive(Debug, Deserialize, Default)]
pub struct BucketPostQueryParams {
    /// If present, this is a DeleteObjects operation
    pub delete: Option<String>,
}

/// Query parameters for bucket-level PUT operations
#[derive(Debug, Deserialize, Default)]
pub struct BucketPutQueryParams {
    /// If present, this is a PutBucketVersioning operation
    pub versioning: Option<String>,
    /// If present, this is a PutBucketAcl operation
    pub acl: Option<String>,
    /// If present, this is a PutBucketTagging operation
    pub tagging: Option<String>,
    /// If present, this is a PutBucketPolicy operation
    pub policy: Option<String>,
    /// If present, this is a PutBucketEncryption operation
    pub encryption: Option<String>,
    /// If present, this is a PutBucketLifecycleConfiguration operation
    pub lifecycle: Option<String>,
    /// If present, this is a PutBucketCors operation
    pub cors: Option<String>,
    /// If present, this is a PutBucketNotificationConfiguration operation
    pub notification: Option<String>,
    /// If present, this is a PutBucketLogging operation
    pub logging: Option<String>,
    /// If present, this is a PutBucketRequestPayment operation
    #[serde(rename = "requestPayment")]
    pub request_payment: Option<String>,
    /// If present, this is a PutBucketWebsite operation
    pub website: Option<String>,
    /// If present, this is a PutBucketReplication operation
    pub replication: Option<String>,
    /// If present, this is a PutBucketAccelerateConfiguration operation
    pub accelerate: Option<String>,
    /// If present, this is a PutBucketOwnershipControls operation
    #[serde(rename = "ownershipControls")]
    pub ownership_controls: Option<String>,
    /// If present, this is a PutPublicAccessBlock operation
    #[serde(rename = "publicAccessBlock")]
    pub public_access_block: Option<String>,
    /// If present, this is a PutBucketIntelligentTieringConfiguration operation
    #[serde(rename = "intelligent-tiering")]
    pub intelligent_tiering: Option<String>,
    /// If present, this is a PutObjectLockConfiguration operation
    #[serde(rename = "object-lock")]
    pub object_lock: Option<String>,
    /// If present, this is a PutBucketMetricsConfiguration operation
    pub metrics: Option<String>,
    /// If present, this is a PutBucketAnalyticsConfiguration operation
    pub analytics: Option<String>,
    /// If present, this is a PutBucketInventoryConfiguration operation
    pub inventory: Option<String>,
    /// Configuration ID for metrics/analytics/inventory PUT operations
    pub id: Option<String>,
}

/// Query parameters for bucket-level DELETE operations
#[derive(Debug, Deserialize, Default)]
pub struct BucketDeleteQueryParams {
    /// If present, this is a DeleteBucketTagging operation
    pub tagging: Option<String>,
    /// If present, this is a DeleteBucketPolicy operation
    pub policy: Option<String>,
    /// If present, this is a DeleteBucketEncryption operation
    pub encryption: Option<String>,
    /// If present, this is a DeleteBucketLifecycleConfiguration operation
    pub lifecycle: Option<String>,
    /// If present, this is a DeleteBucketCors operation
    pub cors: Option<String>,
    /// If present, this is a DeleteBucketWebsite operation
    pub website: Option<String>,
    /// If present, this is a DeleteBucketReplication operation
    pub replication: Option<String>,
    /// If present, this is a DeleteBucketOwnershipControls operation
    #[serde(rename = "ownershipControls")]
    pub ownership_controls: Option<String>,
    /// If present, this is a DeletePublicAccessBlock operation
    #[serde(rename = "publicAccessBlock")]
    pub public_access_block: Option<String>,
    /// If present, this is a DeleteBucketIntelligentTieringConfiguration operation
    #[serde(rename = "intelligent-tiering")]
    pub intelligent_tiering: Option<String>,
    /// Configuration ID for intelligent-tiering, metrics, analytics, or inventory delete operations
    pub id: Option<String>,
    /// If present, this is a DeleteBucketMetricsConfiguration operation
    pub metrics: Option<String>,
    /// If present, this is a DeleteBucketAnalyticsConfiguration operation
    pub analytics: Option<String>,
    /// If present, this is a DeleteBucketInventoryConfiguration operation
    pub inventory: Option<String>,
}

/// Query parameters for bucket-level GET operations
#[derive(Debug, Deserialize, Default)]
pub struct BucketGetQueryParams {
    /// If present, this is a ListMultipartUploads operation
    pub uploads: Option<String>,
    /// If present, this is a GetBucketLocation operation
    pub location: Option<String>,
    /// If present, this is a GetBucketVersioning operation
    pub versioning: Option<String>,
    /// If present, this is a GetBucketAcl operation
    pub acl: Option<String>,
    /// If present, this is a GetBucketTagging operation
    pub tagging: Option<String>,
    /// If present, this is a GetBucketPolicy operation
    pub policy: Option<String>,
    /// If present, this is a ListObjectVersions operation
    pub versions: Option<String>,
    /// If present, this is a GetBucketEncryption operation
    pub encryption: Option<String>,
    /// If present, this is a GetBucketLifecycleConfiguration operation
    pub lifecycle: Option<String>,
    /// If present, this is a GetBucketCors operation
    pub cors: Option<String>,
    /// If present, this is a GetBucketNotificationConfiguration operation
    pub notification: Option<String>,
    /// If present, this is a GetBucketLogging operation
    pub logging: Option<String>,
    /// If present, this is a GetBucketRequestPayment operation
    #[serde(rename = "requestPayment")]
    pub request_payment: Option<String>,
    /// If present, this is a GetBucketWebsite operation
    pub website: Option<String>,
    /// If present, this is a GetBucketReplication operation
    pub replication: Option<String>,
    /// If present, this is a GetBucketAccelerateConfiguration operation
    pub accelerate: Option<String>,
    /// If present, this is a GetBucketOwnershipControls operation
    #[serde(rename = "ownershipControls")]
    pub ownership_controls: Option<String>,
    /// If present, this is a GetPublicAccessBlock operation
    #[serde(rename = "publicAccessBlock")]
    pub public_access_block: Option<String>,
    /// If present, this is a GetBucketIntelligentTieringConfiguration operation
    #[serde(rename = "intelligent-tiering")]
    pub intelligent_tiering: Option<String>,
    /// If present, this is a GetObjectLockConfiguration operation
    #[serde(rename = "object-lock")]
    pub object_lock: Option<String>,
    /// If present, this is a GetBucketMetricsConfiguration or ListBucketMetricsConfigurations operation
    pub metrics: Option<String>,
    /// If present, this is a GetBucketAnalyticsConfiguration or ListBucketAnalyticsConfigurations operation
    pub analytics: Option<String>,
    /// If present, this is a GetBucketInventoryConfiguration or ListBucketInventoryConfigurations operation
    pub inventory: Option<String>,
    /// Configuration ID for metrics/analytics/inventory operations
    pub id: Option<String>,
    // ListObjects params (shared between V1 and V2)
    pub prefix: Option<String>,
    pub delimiter: Option<String>,
    #[serde(rename = "max-keys")]
    pub max_keys: Option<usize>,
    #[serde(rename = "encoding-type")]
    pub encoding_type: Option<String>,
    // ListObjectsV1-specific params
    pub marker: Option<String>,
    // ListObjectsV2-specific params
    #[serde(rename = "continuation-token")]
    pub continuation_token: Option<String>,
    #[serde(rename = "start-after")]
    pub start_after: Option<String>,
    #[serde(rename = "list-type")]
    pub list_type: Option<String>,
    // ListMultipartUploads params
    #[serde(rename = "max-uploads")]
    pub max_uploads: Option<u32>,
    #[serde(rename = "key-marker")]
    pub key_marker: Option<String>,
    #[serde(rename = "version-id-marker")]
    pub version_id_marker: Option<String>,
    #[serde(rename = "upload-id-marker")]
    pub upload_id_marker: Option<String>,
}

/// Dispatcher for bucket-level GET operations
/// Routes to GetBucketLocation, GetBucketVersioning, GetBucketAcl, ListMultipartUploads, ListObjectsV1, or ListObjectsV2
async fn get_bucket_dispatcher(
    State(state): State<AppState>,
    Path(bucket): Path<String>,
    Query(query): Query<BucketGetQueryParams>,
) -> Response {
    // Check for GetBucketLocation (has ?location)
    if query.location.is_some() {
        return handlers::get_bucket_location(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketVersioning (has ?versioning)
    if query.versioning.is_some() {
        return handlers::get_bucket_versioning(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketAcl (has ?acl)
    if query.acl.is_some() {
        return handlers::get_bucket_acl(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketTagging (has ?tagging)
    if query.tagging.is_some() {
        return handlers::get_bucket_tagging(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketPolicy (has ?policy)
    if query.policy.is_some() {
        return handlers::get_bucket_policy(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for ListObjectVersions (has ?versions)
    if query.versions.is_some() {
        return handlers::list_object_versions(
            State(state),
            Path(bucket),
            Query(handlers::ListObjectVersionsQuery {
                prefix: query.prefix,
                delimiter: query.delimiter,
                max_keys: query.max_keys,
                key_marker: query.key_marker,
                version_id_marker: query.version_id_marker,
            }),
        )
        .await
        .into_response();
    }

    // Check for GetBucketEncryption (has ?encryption)
    if query.encryption.is_some() {
        return bucket_stubs::get_bucket_encryption(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketLifecycleConfiguration (has ?lifecycle)
    if query.lifecycle.is_some() {
        return bucket_stubs::get_bucket_lifecycle(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketCors (has ?cors)
    if query.cors.is_some() {
        return bucket_stubs::get_bucket_cors(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketNotificationConfiguration (has ?notification)
    if query.notification.is_some() {
        return bucket_stubs::get_bucket_notification(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketLogging (has ?logging)
    if query.logging.is_some() {
        return bucket_stubs::get_bucket_logging(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketRequestPayment (has ?requestPayment)
    if query.request_payment.is_some() {
        return bucket_stubs::get_bucket_request_payment(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketWebsite (has ?website)
    if query.website.is_some() {
        return bucket_stubs::get_bucket_website(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketReplication (has ?replication)
    if query.replication.is_some() {
        return bucket_stubs::get_bucket_replication(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketAccelerateConfiguration (has ?accelerate)
    if query.accelerate.is_some() {
        return bucket_stubs::get_bucket_accelerate(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketOwnershipControls (has ?ownershipControls)
    if query.ownership_controls.is_some() {
        return bucket_stubs::get_bucket_ownership_controls(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetPublicAccessBlock (has ?publicAccessBlock)
    if query.public_access_block.is_some() {
        return bucket_stubs::get_public_access_block(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketIntelligentTieringConfiguration (has ?intelligent-tiering)
    if query.intelligent_tiering.is_some() {
        return bucket_stubs::get_bucket_intelligent_tiering(
            State(state),
            Path(bucket),
            query.id.unwrap_or_default(),
        )
        .await
        .into_response();
    }

    // Check for GetObjectLockConfiguration (has ?object-lock)
    if query.object_lock.is_some() {
        return bucket_stubs::get_object_lock_configuration(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for GetBucketMetricsConfiguration or ListBucketMetricsConfigurations (has ?metrics)
    if query.metrics.is_some() {
        // If there's an id parameter, it's GetBucketMetricsConfiguration, else List
        if let Some(ref id) = query.id {
            return bucket_stubs::get_bucket_metrics_configuration(
                State(state),
                Path(bucket),
                id.clone(),
            )
            .await
            .into_response();
        } else {
            return bucket_stubs::list_bucket_metrics_configurations(State(state), Path(bucket))
                .await
                .into_response();
        }
    }

    // Check for GetBucketAnalyticsConfiguration or ListBucketAnalyticsConfigurations (has ?analytics)
    if query.analytics.is_some() {
        if let Some(ref id) = query.id {
            return bucket_stubs::get_bucket_analytics_configuration(
                State(state),
                Path(bucket),
                id.clone(),
            )
            .await
            .into_response();
        } else {
            return bucket_stubs::list_bucket_analytics_configurations(State(state), Path(bucket))
                .await
                .into_response();
        }
    }

    // Check for GetBucketInventoryConfiguration or ListBucketInventoryConfigurations (has ?inventory)
    if query.inventory.is_some() {
        if let Some(ref id) = query.id {
            return bucket_stubs::get_bucket_inventory_configuration(
                State(state),
                Path(bucket),
                id.clone(),
            )
            .await
            .into_response();
        } else {
            return bucket_stubs::list_bucket_inventory_configurations(State(state), Path(bucket))
                .await
                .into_response();
        }
    }

    // Check for ListMultipartUploads (has ?uploads)
    if query.uploads.is_some() {
        return handlers::list_multipart_uploads(
            State(state),
            Path(bucket),
            Query(handlers::ListMultipartUploadsQuery {
                prefix: query.prefix,
                delimiter: query.delimiter,
                max_uploads: query.max_uploads,
                key_marker: query.key_marker,
                upload_id_marker: query.upload_id_marker,
            }),
        )
        .await
        .into_response();
    }

    // Check for list-type=2 to determine V1 or V2
    if query.list_type.as_deref() == Some("2") {
        // ListObjectsV2
        return handlers::list_objects_v2(
            State(state),
            Path(bucket),
            Query(handlers::ListObjectsV2Query {
                prefix: query.prefix,
                delimiter: query.delimiter,
                max_keys: query.max_keys,
                continuation_token: query.continuation_token,
                start_after: query.start_after,
                encoding_type: query.encoding_type,
                list_type: query.list_type,
            }),
        )
        .await
        .into_response();
    }

    // Default to ListObjectsV1 (original S3 API)
    handlers::list_objects_v1(
        State(state),
        Path(bucket),
        Query(handlers::ListObjectsV1Query {
            prefix: query.prefix,
            delimiter: query.delimiter,
            max_keys: query.max_keys,
            marker: query.marker,
            encoding_type: query.encoding_type,
        }),
    )
    .await
    .into_response()
}

/// Dispatcher for PUT object operations
/// Routes to CopyObject, UploadPart, PutObjectTagging, or PutObject based on headers/query params
async fn put_object_dispatcher(
    State(state): State<AppState>,
    Path((bucket, key)): Path<(String, String)>,
    Query(query): Query<ObjectQueryParams>,
    headers: HeaderMap,
    body: Body,
) -> Response {
    // Check for PutObjectTagging (has ?tagging)
    if query.tagging.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return handlers::put_object_tagging(State(state), Path((bucket, key)), body_bytes)
            .await
            .into_response();
    }

    // Check for PutObjectAcl (has ?acl)
    if query.acl.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return error_response(
                    StatusCode::BAD_REQUEST,
                    "IncompleteBody",
                    &format!("Failed to read request body: {}", e),
                    &format!("/{}/{}", bucket, key),
                )
                .into_response();
            }
        };
        return handlers::put_object_acl(
            State(state),
            Path((bucket, key)),
            headers.clone(),
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for PutObjectLegalHold (has ?legal-hold)
    if query.legal_hold.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        let bypass = headers
            .get("x-amz-bypass-governance-retention")
            .and_then(|v| v.to_str().ok())
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        return bucket_stubs::put_object_legal_hold(
            State(state),
            Path((bucket, key)),
            query.version_id,
            bypass,
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for PutObjectRetention (has ?retention)
    if query.retention.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        let bypass = headers
            .get("x-amz-bypass-governance-retention")
            .and_then(|v| v.to_str().ok())
            .map(|v| v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        return bucket_stubs::put_object_retention(
            State(state),
            Path((bucket, key)),
            query.version_id,
            bypass,
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for UploadPartCopy (has uploadId, partNumber, and x-amz-copy-source)
    if let (Some(upload_id), Some(part_number)) = (&query.upload_id, query.part_number) {
        if headers.contains_key("x-amz-copy-source") {
            // This is UploadPartCopy
            return multipart::upload_part_copy(
                State(state),
                Path((bucket, key)),
                Query(multipart::MultipartQuery {
                    upload_id: Some(upload_id.clone()),
                    part_number: Some(part_number),
                    uploads: None,
                    max_parts: None,
                    part_number_marker: None,
                }),
                headers,
            )
            .await
            .into_response();
        }

        // Regular UploadPart - collect body to Bytes
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };

        return multipart::upload_part(
            State(state),
            Path((bucket, key)),
            Query(multipart::MultipartQuery {
                upload_id: Some(upload_id.clone()),
                part_number: Some(part_number),
                uploads: None,
                max_parts: None,
                part_number_marker: None,
            }),
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for CopyObject (has x-amz-copy-source header)
    if headers.contains_key("x-amz-copy-source") {
        return handlers::copy_object(State(state), Path((bucket, key)), headers)
            .await
            .into_response();
    }

    // Default to PutObject — pass the raw Body for streaming
    handlers::put_object(State(state), Path((bucket, key)), headers, body)
        .await
        .into_response()
}

/// Dispatcher for POST object operations
/// Routes to CreateMultipartUpload, CompleteMultipartUpload, or RestoreObject based on query params
async fn post_object_dispatcher(
    State(state): State<AppState>,
    Path((bucket, key)): Path<(String, String)>,
    Query(query): Query<ObjectQueryParams>,
    headers: HeaderMap,
    body: Body,
) -> Response {
    // Check for RestoreObject (has ?restore)
    if query.restore.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                tracing::error!("Failed to collect RestoreObject body: {}", e);
                return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response();
            }
        };
        return handlers::restore_object(State(state), Path((bucket, key)), body_bytes)
            .await
            .into_response();
    }

    // Check for SelectObjectContent (has ?select&select-type=2)
    if query.select.is_some() || query.select_type.is_some() {
        // Collect the request body
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                tracing::error!("Failed to collect request body: {}", e);
                return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response();
            }
        };
        return handlers::select_object_content(State(state), Path((bucket, key)), body_bytes)
            .await
            .into_response();
    }

    // Check for CreateMultipartUpload (has ?uploads)
    if query.uploads.is_some() {
        return multipart::create_multipart_upload(State(state), Path((bucket, key)), headers)
            .await
            .into_response();
    }

    // Check for CompleteMultipartUpload (has ?uploadId)
    if let Some(upload_id) = query.upload_id {
        // Collect body to Bytes
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };

        return multipart::complete_multipart_upload(
            State(state),
            Path((bucket, key)),
            Query(multipart::MultipartQuery {
                upload_id: Some(upload_id),
                part_number: None,
                uploads: None,
                max_parts: None,
                part_number_marker: None,
            }),
            body_bytes,
        )
        .await
        .into_response();
    }

    // No valid operation
    (StatusCode::BAD_REQUEST, "Invalid POST operation").into_response()
}

/// Dispatcher for GET object operations
/// Routes to GetObjectTagging, GetObjectAcl, GetObjectAttributes, ListParts, or GetObject based on query params
async fn get_object_dispatcher(
    State(state): State<AppState>,
    Path((bucket, key)): Path<(String, String)>,
    Query(query): Query<ObjectQueryParams>,
    headers: HeaderMap,
) -> Response {
    // Check for GetObjectTagging (has ?tagging)
    if query.tagging.is_some() {
        return handlers::get_object_tagging(State(state), Path((bucket, key)))
            .await
            .into_response();
    }

    // Check for GetObjectAcl (has ?acl)
    if query.acl.is_some() {
        return handlers::get_object_acl(State(state), Path((bucket, key)))
            .await
            .into_response();
    }

    // Check for GetObjectAttributes (has ?attributes)
    if query.attributes.is_some() {
        return handlers::get_object_attributes(State(state), Path((bucket, key)), headers)
            .await
            .into_response();
    }

    // Check for GetObjectLegalHold (has ?legal-hold)
    if query.legal_hold.is_some() {
        return bucket_stubs::get_object_legal_hold(
            State(state),
            Path((bucket, key)),
            query.version_id,
        )
        .await
        .into_response();
    }

    // Check for GetObjectRetention (has ?retention)
    if query.retention.is_some() {
        return bucket_stubs::get_object_retention(
            State(state),
            Path((bucket, key)),
            query.version_id,
        )
        .await
        .into_response();
    }

    // Check for GetObjectTorrent (has ?torrent)
    if query.torrent.is_some() {
        return bucket_stubs::get_object_torrent(State(state), Path((bucket, key)))
            .await
            .into_response();
    }

    // Check for ListParts (has ?uploadId)
    if let Some(upload_id) = query.upload_id {
        return multipart::list_parts(
            State(state),
            Path((bucket, key)),
            Query(multipart::MultipartQuery {
                upload_id: Some(upload_id),
                part_number: None,
                uploads: None,
                max_parts: query.max_parts,
                part_number_marker: query.part_number_marker,
            }),
        )
        .await
        .into_response();
    }

    // Default to GetObject
    handlers::get_object(State(state), Path((bucket, key)), headers)
        .await
        .into_response()
}

/// Dispatcher for DELETE object operations
/// Routes to DeleteObjectTagging, AbortMultipartUpload, or DeleteObject based on query params
async fn delete_object_dispatcher(
    State(state): State<AppState>,
    Path((bucket, key)): Path<(String, String)>,
    Query(query): Query<ObjectQueryParams>,
    headers: HeaderMap,
) -> Response {
    // Check for DeleteObjectTagging (has ?tagging)
    if query.tagging.is_some() {
        return handlers::delete_object_tagging(State(state), Path((bucket, key)))
            .await
            .into_response();
    }

    // Check for AbortMultipartUpload (has ?uploadId)
    if let Some(upload_id) = query.upload_id {
        return multipart::abort_multipart_upload(
            State(state),
            Path((bucket, key)),
            Query(multipart::MultipartQuery {
                upload_id: Some(upload_id),
                part_number: None,
                uploads: None,
                max_parts: None,
                part_number_marker: None,
            }),
        )
        .await
        .into_response();
    }

    // Default to DeleteObject — check Object Lock protection first.
    let version_str = query.version_id.as_deref().unwrap_or("null");
    let bypass = headers
        .get("x-amz-bypass-governance-retention")
        .and_then(|v| v.to_str().ok())
        .map(|v| v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);

    match state
        .storage
        .object_lock_manager
        .is_protected(&bucket, &key, version_str)
        .await
    {
        Ok(true) => {
            // Determine whether legal hold or retention is responsible
            let active_mode = state
                .storage
                .object_lock_manager
                .retention_mode(&bucket, &key, version_str)
                .await
                .ok()
                .flatten();

            let resource = format!("/{}/{}", bucket, key);
            if let Some(mode) = active_mode {
                if mode == "COMPLIANCE" {
                    return super::utils::error_response(
                        StatusCode::FORBIDDEN,
                        "AccessDenied",
                        "Object is protected by a COMPLIANCE retention policy and cannot be deleted.",
                        &resource,
                    );
                }
                // GOVERNANCE — allow with bypass header
                if bypass {
                    return handlers::delete_object(State(state), Path((bucket, key)))
                        .await
                        .into_response();
                }
                return super::utils::error_response(
                    StatusCode::FORBIDDEN,
                    "AccessDenied",
                    "Object is under GOVERNANCE retention; supply x-amz-bypass-governance-retention: true to delete.",
                    &resource,
                );
            }
            // Legal hold is active
            return super::utils::error_response(
                StatusCode::FORBIDDEN,
                "AccessDenied",
                "Object is protected by a Legal Hold and cannot be deleted.",
                &resource,
            );
        }
        Ok(false) => {}
        Err(_) => {} // Do not block deletion on lock-check I/O error
    }

    handlers::delete_object(State(state), Path((bucket, key)))
        .await
        .into_response()
}

/// Dispatcher for bucket-level POST operations
/// Routes to DeleteObjects or PostObject based on query params and content type
async fn post_bucket_dispatcher(
    State(state): State<AppState>,
    Path(bucket): Path<String>,
    Query(query): Query<BucketPostQueryParams>,
    headers: HeaderMap,
    body: Body,
) -> Response {
    // Check for DeleteObjects (has ?delete)
    if query.delete.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return handlers::delete_objects(State(state), Path(bucket), headers.clone(), body_bytes)
            .await
            .into_response();
    }

    // Check for PostObject (multipart/form-data Content-Type)
    if let Some(content_type) = headers.get("content-type") {
        if let Ok(ct) = content_type.to_str() {
            if ct.starts_with("multipart/form-data") {
                // Convert Body to Multipart - need to use axum's Multipart extractor via Request
                let req = match axum::http::Request::builder()
                    .header("content-type", ct)
                    .body(body)
                {
                    Ok(r) => r,
                    Err(e) => {
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to build request: {}", e),
                        )
                            .into_response();
                    }
                };
                let multipart = match axum::extract::Multipart::from_request(req, &state).await {
                    Ok(m) => m,
                    Err(e) => {
                        return (
                            StatusCode::BAD_REQUEST,
                            format!("Failed to parse multipart: {}", e),
                        )
                            .into_response();
                    }
                };
                return handlers::post_object(State(state), Path(bucket), multipart)
                    .await
                    .into_response();
            }
        }
    }

    // No valid operation
    (StatusCode::BAD_REQUEST, "Invalid POST operation on bucket").into_response()
}

/// Dispatcher for bucket-level PUT operations
/// Routes to PutBucketVersioning, PutBucketAcl, or CreateBucket based on query params
async fn put_bucket_dispatcher(
    State(state): State<AppState>,
    Path(bucket): Path<String>,
    Query(query): Query<BucketPutQueryParams>,
    headers: HeaderMap,
    body: Body,
) -> Response {
    // Check for PutBucketVersioning (has ?versioning)
    if query.versioning.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return handlers::put_bucket_versioning(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketAcl (has ?acl)
    if query.acl.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return error_response(
                    StatusCode::BAD_REQUEST,
                    "IncompleteBody",
                    &format!("Failed to read request body: {}", e),
                    &format!("/{}", bucket),
                )
                .into_response();
            }
        };
        return handlers::put_bucket_acl(State(state), Path(bucket), headers, body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketTagging (has ?tagging)
    if query.tagging.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return handlers::put_bucket_tagging(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketPolicy (has ?policy)
    if query.policy.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return handlers::put_bucket_policy(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketEncryption (has ?encryption)
    if query.encryption.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_encryption(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketLifecycleConfiguration (has ?lifecycle)
    if query.lifecycle.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_lifecycle(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketCors (has ?cors)
    if query.cors.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_cors(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketNotificationConfiguration (has ?notification)
    if query.notification.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        return bucket_stubs::put_bucket_notification(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketLogging (has ?logging)
    if query.logging.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_logging(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketRequestPayment (has ?requestPayment)
    if query.request_payment.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_request_payment(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketWebsite (has ?website)
    if query.website.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_website(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketReplication (has ?replication)
    if query.replication.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        return bucket_stubs::put_bucket_replication(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketAccelerateConfiguration (has ?accelerate)
    if query.accelerate.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        return bucket_stubs::put_bucket_accelerate(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketOwnershipControls (has ?ownershipControls)
    if query.ownership_controls.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_bucket_ownership_controls(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutPublicAccessBlock (has ?publicAccessBlock)
    if query.public_access_block.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to read body: {}", e),
                )
                    .into_response();
            }
        };
        return bucket_stubs::put_public_access_block(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketIntelligentTieringConfiguration (has ?intelligent-tiering)
    if query.intelligent_tiering.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        return bucket_stubs::put_bucket_intelligent_tiering(
            State(state),
            Path(bucket),
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for PutObjectLockConfiguration (has ?object-lock)
    if query.object_lock.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        return bucket_stubs::put_object_lock_configuration(State(state), Path(bucket), body_bytes)
            .await
            .into_response();
    }

    // Check for PutBucketMetricsConfiguration (has ?metrics)
    if query.metrics.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        let id = query.id.unwrap_or_default();
        return bucket_stubs::put_bucket_metrics_configuration(
            State(state),
            Path(bucket),
            id,
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for PutBucketAnalyticsConfiguration (has ?analytics)
    if query.analytics.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        let id = query.id.unwrap_or_default();
        return bucket_stubs::put_bucket_analytics_configuration(
            State(state),
            Path(bucket),
            id,
            body_bytes,
        )
        .await
        .into_response();
    }

    // Check for PutBucketInventoryConfiguration (has ?inventory)
    if query.inventory.is_some() {
        let body_bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(_) => return malformed_xml_response("Failed to read request body").into_response(),
        };
        let id = query.id.unwrap_or_default();
        return bucket_stubs::put_bucket_inventory_configuration(
            State(state),
            Path(bucket),
            id,
            body_bytes,
        )
        .await
        .into_response();
    }

    // Default to CreateBucket
    // If a non-empty body is provided, it must be a valid CreateBucketConfiguration XML.
    // Reject clearly malformed XML (non-empty body that lacks an opening XML tag).
    let body_bytes = match body.collect().await {
        Ok(collected) => collected.to_bytes(),
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Failed to read body: {}", e),
            )
                .into_response();
        }
    };
    if !body_bytes.is_empty() {
        let body_str = String::from_utf8_lossy(&body_bytes);
        let trimmed = body_str.trim();
        // A valid XML document must begin with '<'; anything else is malformed
        if !trimmed.starts_with('<') {
            return (
                StatusCode::BAD_REQUEST,
                [("content-type", "application/xml")],
                r#"<?xml version="1.0" encoding="UTF-8"?><Error><Code>MalformedXML</Code><Message>The XML you provided was not well-formed</Message></Error>"#,
            )
                .into_response();
        }
        // Verify basic XML well-formedness: every opened tag should have a closing counterpart.
        // We check by scanning for unclosed '<' sequences: if we find a '<' that is not
        // followed by a matching '>' anywhere in the document, the XML is malformed.
        let mut depth: i32 = 0;
        let chars: Vec<char> = trimmed.chars().collect();
        let mut i = 0;
        let mut malformed = false;
        while i < chars.len() {
            if chars[i] == '<' {
                if i + 1 >= chars.len() {
                    malformed = true;
                    break;
                }
                // Find closing '>'
                if let Some(gt) = chars[i..].iter().position(|&c| c == '>') {
                    let tag: String = chars[i..i + gt + 1].iter().collect();
                    if tag.starts_with("</") {
                        depth -= 1;
                    } else if !tag.ends_with("/>")
                        && !tag.starts_with("<?")
                        && !tag.starts_with("<!")
                    {
                        depth += 1;
                    }
                    i += gt + 1;
                } else {
                    malformed = true;
                    break;
                }
            } else {
                i += 1;
            }
        }
        if malformed || depth != 0 {
            return (
                StatusCode::BAD_REQUEST,
                [("content-type", "application/xml")],
                r#"<?xml version="1.0" encoding="UTF-8"?><Error><Code>MalformedXML</Code><Message>The XML you provided was not well-formed</Message></Error>"#,
            )
                .into_response();
        }
    }
    // Read x-amz-bucket-object-lock-enabled header for CreateBucket
    let object_lock_enabled = headers
        .get("x-amz-bucket-object-lock-enabled")
        .and_then(|v| v.to_str().ok())
        .map(|v| v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    handlers::create_bucket(State(state), Path(bucket), object_lock_enabled)
        .await
        .into_response()
}

/// Dispatcher for bucket-level DELETE operations
/// Routes to DeleteBucketTagging, DeleteBucketPolicy, or DeleteBucket based on query params
async fn delete_bucket_dispatcher(
    State(state): State<AppState>,
    Path(bucket): Path<String>,
    Query(query): Query<BucketDeleteQueryParams>,
) -> Response {
    // Check for DeleteBucketTagging (has ?tagging)
    if query.tagging.is_some() {
        return handlers::delete_bucket_tagging(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketPolicy (has ?policy)
    if query.policy.is_some() {
        return handlers::delete_bucket_policy(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketEncryption (has ?encryption) - no-op (stub)
    if query.encryption.is_some() {
        return bucket_stubs::delete_bucket_encryption(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketLifecycleConfiguration (has ?lifecycle) - no-op (stub)
    if query.lifecycle.is_some() {
        return bucket_stubs::delete_bucket_lifecycle(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketCors (has ?cors) - no-op (stub)
    if query.cors.is_some() {
        return bucket_stubs::delete_bucket_cors(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketWebsite (has ?website) - no-op (stub)
    if query.website.is_some() {
        return bucket_stubs::delete_bucket_website(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketReplication (has ?replication) - no-op (stub)
    if query.replication.is_some() {
        return bucket_stubs::delete_bucket_replication(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketOwnershipControls (has ?ownershipControls) - no-op (stub)
    if query.ownership_controls.is_some() {
        return bucket_stubs::delete_bucket_ownership_controls(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeletePublicAccessBlock (has ?publicAccessBlock) - no-op (stub)
    if query.public_access_block.is_some() {
        return bucket_stubs::delete_public_access_block(State(state), Path(bucket))
            .await
            .into_response();
    }

    // Check for DeleteBucketIntelligentTieringConfiguration (has ?intelligent-tiering)
    if query.intelligent_tiering.is_some() {
        return bucket_stubs::delete_bucket_intelligent_tiering(
            State(state),
            Path(bucket),
            query.id.unwrap_or_default(),
        )
        .await
        .into_response();
    }

    // Check for DeleteBucketMetricsConfiguration (has ?metrics)
    if query.metrics.is_some() {
        let id = query.id.clone().unwrap_or_default();
        return bucket_stubs::delete_bucket_metrics_configuration(State(state), Path(bucket), id)
            .await
            .into_response();
    }

    // Check for DeleteBucketAnalyticsConfiguration (has ?analytics)
    if query.analytics.is_some() {
        let id = query.id.clone().unwrap_or_default();
        return bucket_stubs::delete_bucket_analytics_configuration(State(state), Path(bucket), id)
            .await
            .into_response();
    }

    // Check for DeleteBucketInventoryConfiguration (has ?inventory)
    if query.inventory.is_some() {
        let id = query.id.clone().unwrap_or_default();
        return bucket_stubs::delete_bucket_inventory_configuration(State(state), Path(bucket), id)
            .await
            .into_response();
    }

    // Default to DeleteBucket
    handlers::delete_bucket(State(state), Path(bucket))
        .await
        .into_response()
}

/// Handler for WriteGetObjectResponse (Lambda Object Lambda stub)
async fn write_get_object_response_handler(
    State(state): State<AppState>,
    headers: HeaderMap,
) -> Response {
    bucket_stubs::write_get_object_response(State(state), headers)
        .await
        .into_response()
}

/// GraphQL query handler
async fn graphql_handler(State(state): State<AppState>, req: GraphQLRequest) -> GraphQLResponse {
    let schema = graphql::build_schema(
        state.storage.clone(),
        Arc::new(state.event_broadcaster.clone()),
    );
    schema.execute(req.into_inner()).await.into()
}

/// GraphQL Playground UI handler
async fn graphql_playground_handler() -> impl IntoResponse {
    Html(
        r#"
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>rs3gw GraphQL Playground</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="https://unpkg.com/graphql-playground-react/build/static/css/index.css">
            <link rel="shortcut icon" href="https://unpkg.com/graphql-playground-react/build/favicon.png">
            <script src="https://unpkg.com/graphql-playground-react/build/static/js/middleware.js"></script>
        </head>
        <body>
            <div id="root"></div>
            <script>
                window.addEventListener('load', function (event) {
                    GraphQLPlayground.init(document.getElementById('root'), {
                        endpoint: '/graphql',
                        settings: {
                            'editor.theme': 'dark',
                            'editor.cursorShape': 'line'
                        },
                        tabs: [
                            {
                                endpoint: '/graphql',
                                query: `# Welcome to rs3gw GraphQL API!
#
# Example queries:

# List all buckets
query ListBuckets {
  buckets {
    name
    createdAt
    region
  }
}

# Get bucket details
query GetBucket {
  bucket(name: "my-bucket") {
    name
    objectCount
    totalSize
    tags {
      key
      value
    }
  }
}

# List objects in a bucket
query ListObjects {
  objects(bucket: "my-bucket", limit: 10) {
    key
    size
    lastModified
    contentType
  }
}

# Search objects by pattern
query SearchObjects {
  searchObjects(pattern: "data", limit: 10) {
    key
    bucket
    size
  }
}

# Get storage statistics
query GetStats {
  stats {
    bucketCount
    totalObjects
    totalSizeBytes
  }
}
`
                            }
                        ]
                    })
                })
            </script>
        </body>
        </html>
        "#,
    )
}

/// Creates the S3-compatible API router
pub fn routes() -> Router<AppState> {
    Router::new()
        // Health check endpoint
        .route("/health", get(handlers::health_check))
        // Liveness / readiness probe
        .route("/ready", get(handlers::ready_check))
        // Prometheus metrics endpoint
        .route("/metrics", get(handlers::metrics))
        // Admin: garbage-collect abandoned multipart uploads
        .route("/api/admin/gc/multipart", post(handlers::admin_gc_multipart))
        // Swagger UI endpoint with embedded OpenAPI spec (custom, non-S3 API)
        .merge(utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
            .url("/openapi.json", openapi::ApiDoc::openapi()))
        // GraphQL endpoint (custom, non-S3 API)
        .route("/graphql", get(graphql_playground_handler).post(graphql_handler))
        // WebSocket event streaming endpoint (custom, non-S3 API)
        .route("/events/stream", get(websocket::ws_handler))
        // Advanced replication management endpoints (custom, non-S3 API)
        .route("/api/replication/{bucket}/config",
            get(replication_handlers::get_replication_config)
            .put(replication_handlers::set_replication_config)
            .delete(replication_handlers::delete_replication_config))
        .route("/api/replication/metrics", get(replication_handlers::get_replication_metrics))
        .route("/api/replication/metrics/{destination}", get(replication_handlers::get_destination_metrics))
        .route("/api/replication/flush", post(replication_handlers::flush_replication_batches))
        // Observability API endpoints (v5.0.0 - custom, non-S3 API)
        .route("/api/observability/profiling", get(observability_handlers::get_profiling_data))
        .route("/api/observability/business-metrics", get(observability_handlers::get_business_metrics))
        .route("/api/observability/anomalies", get(observability_handlers::get_anomalies))
        .route("/api/observability/resources", get(observability_handlers::get_resource_stats))
        .route("/api/observability/health", get(observability_handlers::get_comprehensive_health))
        // Predictive Analytics Endpoints
        .route("/api/observability/predictions/storage-growth", get(observability_handlers::get_storage_growth_prediction))
        .route("/api/observability/predictions/access-patterns", get(observability_handlers::get_access_pattern_prediction))
        .route("/api/observability/predictions/costs", get(observability_handlers::get_cost_forecast))
        .route("/api/observability/predictions/capacity", get(observability_handlers::get_capacity_recommendations))
        // Preprocessing API endpoints (v5.0.0 - custom, non-S3 API)
        .route("/api/preprocessing/pipelines", post(preprocessing_handlers::create_pipeline))
        .route("/api/preprocessing/pipelines", get(preprocessing_handlers::list_pipelines))
        .route("/api/preprocessing/pipelines/{id}", get(preprocessing_handlers::get_pipeline))
        .route("/api/preprocessing/pipelines/{id}", delete(preprocessing_handlers::delete_pipeline))
        .route("/api/preprocessing/apply", post(preprocessing_handlers::apply_pipeline))
        .route("/api/preprocessing/validate", post(preprocessing_handlers::validate_pipeline))
        .route("/api/preprocessing/cache/stats", get(preprocessing_handlers::get_cache_stats))
        .route("/api/preprocessing/cache/clear", post(preprocessing_handlers::clear_cache))
        // Intelligent Tiering API endpoints
        .route("/api/tiering/policies/{bucket}", get(tiering_handlers::get_tiering_policy))
        .route("/api/tiering/policies/{bucket}", put(tiering_handlers::set_tiering_policy))
        .route("/api/tiering/policies/{bucket}", delete(tiering_handlers::delete_tiering_policy))
        .route("/api/tiering/analyze/{bucket}", post(tiering_handlers::analyze_tiering))
        .route("/api/tiering/analyze/{bucket}/predictive", post(tiering_handlers::analyze_tiering_predictive))
        .route("/api/tiering/recommendations/{bucket}/capacity", get(tiering_handlers::get_capacity_recommendations))
        .route("/api/tiering/apply/{bucket}", post(tiering_handlers::apply_tiering_recommendations))
        .route("/api/tiering/history", get(tiering_handlers::get_transition_history))
        .route("/api/tiering/history/{bucket}", get(tiering_handlers::get_bucket_transition_history))
        // S3 Select Query Cache API endpoints
        .route("/api/select/cache/stats", get(select_cache_handlers::get_cache_stats))
        .route("/api/select/cache/clear", post(select_cache_handlers::clear_cache))
        .route("/api/select/cache/invalidate/{etag}", delete(select_cache_handlers::invalidate_object_cache))
        // Cache warming endpoints
        .route("/api/select/cache/patterns", get(select_cache_handlers::get_pattern_stats))
        .route("/api/select/cache/patterns/top", get(select_cache_handlers::get_top_queries))
        .route("/api/select/cache/patterns/recent", get(select_cache_handlers::get_recent_queries))
        .route("/api/select/cache/patterns/clear", post(select_cache_handlers::clear_patterns))
        // Cache persistence endpoints
        .route("/api/select/cache/save", post(select_cache_handlers::save_cache))
        .route("/api/select/cache/load", post(select_cache_handlers::load_cache))
        // Query Intelligence API endpoints (AI-powered query optimization)
        .route("/api/query/intelligence/statistics", get(query_intelligence_handlers::get_statistics))
        .route("/api/query/intelligence/summary", get(query_intelligence_handlers::get_summary))
        .route("/api/query/intelligence/predict-cost", post(query_intelligence_handlers::predict_cost))
        .route("/api/query/intelligence/recommend-strategy", post(query_intelligence_handlers::recommend_strategy))
        .route("/api/query/intelligence/find-similar", post(query_intelligence_handlers::find_similar))
        .route("/api/query/intelligence/index-recommendations", get(query_intelligence_handlers::get_index_recommendations))
        .route("/api/query/intelligence/complexity-distribution", get(query_intelligence_handlers::get_complexity_distribution))
        // Distributed Training API endpoints (v5.0.0 - ML/AI training management)
        .route("/api/training/experiments", post(training_handlers::create_experiment))
        .route("/api/training/experiments/{experiment_id}", get(training_handlers::get_experiment))
        .route("/api/training/experiments/{experiment_id}/status", put(training_handlers::update_experiment_status))
        .route("/api/training/experiments/{experiment_id}/checkpoints", post(training_handlers::save_checkpoint))
        .route("/api/training/experiments/{experiment_id}/checkpoints", get(training_handlers::list_checkpoints))
        .route("/api/training/checkpoints/{checkpoint_id}", get(training_handlers::load_checkpoint))
        .route("/api/training/experiments/{experiment_id}/metrics", post(training_handlers::log_metrics))
        .route("/api/training/experiments/{experiment_id}/metrics", get(training_handlers::get_metrics))
        .route("/api/training/searches", post(training_handlers::create_search))
        .route("/api/training/searches/{search_id}", get(training_handlers::get_search))
        .route("/api/training/searches/{search_id}/trials", post(training_handlers::add_trial))
        // Presigned URL generation endpoint (custom, non-S3 API)
        .route("/presign/{bucket}/{*key}", get(handlers::generate_presigned_url))
        // S3: ListBuckets — returns all buckets owned by the authenticated sender
        .route("/", get(handlers::list_buckets))
        // S3: HeadBucket — check bucket existence and permissions (with and without trailing slash for SDK compatibility)
        .route("/{bucket}", head(handlers::head_bucket))
        .route("/{bucket}/", head(handlers::head_bucket))
        // S3: GetBucketLocation / GetBucketVersioning / GetBucketAcl / ListMultipartUploads / ListObjectsV1 / ListObjectsV2
        .route("/{bucket}", get(get_bucket_dispatcher))
        .route("/{bucket}/", get(get_bucket_dispatcher))
        // S3: CreateBucket / PutBucketVersioning / PutBucketAcl / PutBucketTagging / PutBucketPolicy / PutBucketEncryption / etc.
        .route("/{bucket}", put(put_bucket_dispatcher))
        .route("/{bucket}/", put(put_bucket_dispatcher))
        // S3: DeleteBucket / DeleteBucketTagging / DeleteBucketPolicy / DeleteBucketEncryption / etc.
        .route("/{bucket}", delete(delete_bucket_dispatcher))
        .route("/{bucket}/", delete(delete_bucket_dispatcher))
        // S3: DeleteObjects (?delete) / PostObject (multipart/form-data upload)
        .route("/{bucket}", post(post_bucket_dispatcher))
        .route("/{bucket}/", post(post_bucket_dispatcher))
        // S3: HeadObject — returns metadata without the object body
        .route("/{bucket}/{*key}", head(handlers::head_object))
        // S3: GetObject / GetObjectTagging / GetObjectAcl / GetObjectAttributes / ListParts
        .route("/{bucket}/{*key}", get(get_object_dispatcher))
        // S3: PutObject / CopyObject (x-amz-copy-source) / UploadPart (partNumber+uploadId) / UploadPartCopy / PutObjectTagging / PutObjectAcl
        .route("/{bucket}/{*key}", put(put_object_dispatcher))
        // S3: CreateMultipartUpload (?uploads) / CompleteMultipartUpload (?uploadId) / RestoreObject (?restore) / SelectObjectContent (?select)
        .route("/{bucket}/{*key}", post(post_object_dispatcher))
        // S3: DeleteObject / DeleteObjectTagging (?tagging) / AbortMultipartUpload (?uploadId)
        .route("/{bucket}/{*key}", delete(delete_object_dispatcher))
        // S3 Lambda Object Lambda: WriteGetObjectResponse (stub)
        .route("/WriteGetObjectResponse", post(write_get_object_response_handler))
        // CORS preflight (OPTIONS) for bucket and object endpoints
        .route("/{bucket}", options(cors::options_bucket_handler))
        .route("/{bucket}/", options(cors::options_bucket_handler))
        .route("/{bucket}/{*key}", options(cors::options_object_handler))
}