reddb-io-server 1.45.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
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
//! S3-Compatible Storage Backend
//!
//! Works with: AWS S3, Cloudflare R2, DigitalOcean Spaces, Google Cloud Storage (S3 mode).
//!
//! # Configuration
//!
//! | Provider | Endpoint | Region |
//! |----------|----------|--------|
//! | AWS S3 | `https://s3.{region}.amazonaws.com` | us-east-1, etc. |
//! | Cloudflare R2 | `https://{account_id}.r2.cloudflarestorage.com` | auto |
//! | DigitalOcean Spaces | `https://{region}.digitaloceanspaces.com` | nyc3, sfo3, etc. |
//! | Google Cloud Storage | `https://storage.googleapis.com` | us, eu, etc. |
//!
//! # Transport
//!
//! Uses `curl` via `std::process::Command` for HTTP transport. This avoids pulling in a
//! TLS library while remaining universally available on all target platforms.
//!
//! Cross-platform note: the null device path differs per OS (`/dev/null` on
//! Unix, `NUL` on Windows). `null_device()` below picks the right one so
//! `curl -o` discards response bodies correctly on every platform.
//!
//! # Example
//! ```ignore
//! use reddb::storage::backend::s3::{S3Backend, S3Config};
//!
//! let backend = S3Backend::new(S3Config::aws(
//!     "my-bucket", "us-east-1", "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG..."
//! ));
//! ```

use super::{
    AtomicRemoteBackend, BackendError, BackendObjectVersion, ConditionalDelete, ConditionalPut,
    RemoteBackend,
};
use crate::crypto;
use std::collections::BTreeMap;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for an S3-compatible object storage endpoint.

/// Largest object a single S3 `PUT` accepts.
const SINGLE_PUT_MAX_BYTES: u64 = 5 * 1024 * 1024 * 1024;
const CURL_CONNECT_TIMEOUT_SECS: u64 = 10;
const CURL_STALL_TIMEOUT_SECS: u64 = 60;

#[derive(Debug, Clone)]
pub struct S3Config {
    /// S3-compatible endpoint URL (e.g., `"https://s3.us-east-1.amazonaws.com"`).
    /// Must include scheme (`https://`). No trailing slash.
    pub endpoint: String,
    /// Bucket name.
    pub bucket: String,
    /// Key prefix prepended to every `remote_key` (e.g., `"databases/"`).
    pub key_prefix: String,
    /// Access key ID.
    pub access_key: String,
    /// Secret access key.
    pub secret_key: String,
    /// AWS region (e.g., `"us-east-1"`, `"auto"` for R2).
    pub region: String,
    /// Use path-style addressing (`{endpoint}/{bucket}/{key}`) instead
    /// of virtual-host-style (`{scheme}://{bucket}.{endpoint_host}/{key}`).
    /// Required for MinIO, Ceph RGW, Garage, SeaweedFS, and any
    /// self-hosted S3-compatible store. AWS S3 / R2 / DO Spaces /
    /// GCS interop accept either style — true is the safe default
    /// for cloud-agnostic deployments. Override via env
    /// `RED_S3_PATH_STYLE=false` for providers that hard-require
    /// virtual-host (rare).
    pub path_style: bool,
}

impl S3Config {
    /// Create a config targeting **AWS S3**.
    pub fn aws(bucket: &str, region: &str, access_key: &str, secret_key: &str) -> Self {
        Self {
            endpoint: format!("https://s3.{region}.amazonaws.com"),
            bucket: bucket.into(),
            key_prefix: String::new(),
            access_key: access_key.into(),
            secret_key: secret_key.into(),
            region: region.into(),
            path_style: true,
        }
    }

    /// Create a config targeting **Cloudflare R2**.
    pub fn r2(account_id: &str, bucket: &str, access_key: &str, secret_key: &str) -> Self {
        Self {
            endpoint: format!("https://{account_id}.r2.cloudflarestorage.com"),
            bucket: bucket.into(),
            key_prefix: String::new(),
            access_key: access_key.into(),
            secret_key: secret_key.into(),
            region: "auto".into(),
            path_style: true,
        }
    }

    /// Create a config targeting **DigitalOcean Spaces**.
    pub fn digitalocean(region: &str, bucket: &str, access_key: &str, secret_key: &str) -> Self {
        Self {
            endpoint: format!("https://{region}.digitaloceanspaces.com"),
            bucket: bucket.into(),
            key_prefix: String::new(),
            access_key: access_key.into(),
            secret_key: secret_key.into(),
            region: region.into(),
            path_style: true,
        }
    }

    /// Create a config targeting **Google Cloud Storage** (S3-compatible mode).
    pub fn gcs(bucket: &str, access_key: &str, secret_key: &str) -> Self {
        Self {
            endpoint: "https://storage.googleapis.com".into(),
            bucket: bucket.into(),
            key_prefix: String::new(),
            access_key: access_key.into(),
            secret_key: secret_key.into(),
            region: "us".into(),
            path_style: true,
        }
    }

    /// Create a config targeting a generic S3-compatible endpoint
    /// (MinIO, Ceph, Garage, SeaweedFS, B2 S3-compat, IDrive,
    /// Storj, Wasabi, etc.). The operator passes the full endpoint
    /// URL; region defaults to `us-east-1` because most self-hosted
    /// stores ignore it.
    pub fn generic(endpoint: &str, bucket: &str, access_key: &str, secret_key: &str) -> Self {
        Self {
            endpoint: endpoint.trim_end_matches('/').into(),
            bucket: bucket.into(),
            key_prefix: String::new(),
            access_key: access_key.into(),
            secret_key: secret_key.into(),
            region: "us-east-1".into(),
            path_style: true,
        }
    }

    /// Set a key prefix (e.g., `"databases/prod/"`).
    pub fn with_prefix(mut self, prefix: &str) -> Self {
        self.key_prefix = prefix.into();
        self
    }

    /// Override the addressing style (path-style vs virtual-host).
    pub fn with_path_style(mut self, path_style: bool) -> Self {
        self.path_style = path_style;
        self
    }

    /// Override the AWS region.
    pub fn with_region(mut self, region: &str) -> Self {
        self.region = region.into();
        self
    }
}

// ---------------------------------------------------------------------------
// Backend
// ---------------------------------------------------------------------------

/// S3-compatible storage backend.
///
/// Implements AWS Signature Version 4 for request authentication and
/// delegates HTTP transport to `curl(1)`.
pub struct S3Backend {
    config: S3Config,
    credentials_file: Option<PathBuf>,
}

struct TemporaryCredentials {
    schema_version: u64,
    bucket: String,
    prefix: String,
    access_key_id: String,
    secret_access_key: String,
    session_token: String,
    expires_at_unix_seconds: u64,
}

impl crate::serde_json::JsonDecode for TemporaryCredentials {
    fn from_json_value(value: crate::serde_json::Value) -> Result<Self, String> {
        let invalid = || "invalid temporary credential schema".to_string();
        let fields = value.as_object().ok_or_else(invalid)?;
        if fields.len() != 7 {
            return Err(invalid());
        }
        let text = |name: &str| {
            fields
                .get(name)
                .and_then(|v| v.as_str())
                .map(str::to_owned)
                .ok_or_else(invalid)
        };
        let integer = |name: &str| match fields.get(name) {
            Some(crate::serde_json::Value::Integer(n)) if *n >= 0 => Ok(*n as u64),
            Some(crate::serde_json::Value::Number(n))
                if n.is_finite()
                    && *n >= 0.0
                    && n.fract() == 0.0
                    && *n <= 9_007_199_254_740_991.0 =>
            {
                Ok(*n as u64)
            }
            Some(crate::serde_json::Value::Decimal(n)) => n.parse::<u64>().map_err(|_| invalid()),
            _ => Err(invalid()),
        };
        Ok(Self {
            schema_version: integer("schema_version")?,
            bucket: text("bucket")?,
            prefix: text("prefix")?,
            access_key_id: text("access_key_id")?,
            secret_access_key: text("secret_access_key")?,
            session_token: text("session_token")?,
            expires_at_unix_seconds: integer("expires_at_unix_seconds")?,
        })
    }
}

impl S3Backend {
    /// Create a new S3 backend with the given configuration.
    pub fn new(config: S3Config) -> Self {
        Self {
            config,
            credentials_file: None,
        }
    }

    /// Reopen one atomically rotated JSON credential file for every request.
    /// Missing, expired or differently scoped credentials never fall back to
    /// the static keys in the configuration. Projected Kubernetes Secrets must
    /// mount the directory rather than a non-rotating `subPath` file.
    pub fn with_credentials_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.credentials_file = Some(path.into());
        self
    }

    fn temporary_credentials(
        &self,
        now: u64,
    ) -> Result<Option<TemporaryCredentials>, BackendError> {
        let Some(path) = &self.credentials_file else {
            return Ok(None);
        };
        let invalid = || {
            BackendError::Internal(
                "temporary S3 credentials unavailable, expired or outside configured scope".into(),
            )
        };
        if !path.is_absolute() || !self.config.endpoint.starts_with("https://") {
            return Err(invalid());
        }
        const MAX_BYTES: u64 = 32 * 1024;
        let mut bytes = Vec::new();
        fs::File::open(path)
            .map_err(|_| invalid())?
            .take(MAX_BYTES + 1)
            .read_to_end(&mut bytes)
            .map_err(|_| invalid())?;
        if bytes.len() as u64 > MAX_BYTES {
            return Err(invalid());
        }
        let credentials: TemporaryCredentials =
            crate::serde_json::from_slice(&bytes).map_err(|_| invalid())?;
        if credentials.schema_version != 1
            || credentials.bucket != self.config.bucket
            || credentials.prefix != self.config.key_prefix
            || credentials.prefix.is_empty()
            || !credentials.prefix.ends_with('/')
            || credentials.expires_at_unix_seconds <= now.saturating_add(30)
            || [
                &credentials.access_key_id,
                &credentials.secret_access_key,
                &credentials.session_token,
            ]
            .iter()
            .any(|v| v.is_empty() || !v.bytes().all(|b| (33..=126).contains(&b)))
        {
            return Err(invalid());
        }
        Ok(Some(credentials))
    }

    // -----------------------------------------------------------------------
    // Request signing (AWS Signature Version 4)
    // -----------------------------------------------------------------------

    /// Build a fully-signed set of HTTP headers for an S3 request.
    ///
    /// Returns a `BTreeMap` of header name -> value that must be sent with the
    /// HTTP request. The map includes `Host`, `x-amz-date`,
    /// `x-amz-content-sha256`, and `Authorization`.
    fn build_signed_request(
        &self,
        method: &str,
        object_key: &str,
        body: &[u8],
    ) -> Result<BTreeMap<String, String>, BackendError> {
        self.build_signed_request_with_query(method, object_key, "", body)
    }

    fn build_signed_request_with_query(
        &self,
        method: &str,
        object_key: &str,
        canonical_querystring: &str,
        body: &[u8],
    ) -> Result<BTreeMap<String, String>, BackendError> {
        self.build_signed_request_with_query_and_headers(
            method,
            object_key,
            canonical_querystring,
            body,
            &[],
        )
    }

    fn build_signed_request_with_query_and_headers(
        &self,
        method: &str,
        object_key: &str,
        canonical_querystring: &str,
        body: &[u8],
        extra_headers: &[(&str, &str)],
    ) -> Result<BTreeMap<String, String>, BackendError> {
        self.build_signed_request_with_body_hash(
            method,
            object_key,
            canonical_querystring,
            &sha256_hex(body),
            extra_headers,
        )
    }

    /// Sign a request whose payload digest was computed elsewhere (a file
    /// hashed as a stream, so uploads never hold the whole body in memory).
    fn build_signed_request_with_body_hash(
        &self,
        method: &str,
        object_key: &str,
        canonical_querystring: &str,
        body_hash: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<BTreeMap<String, String>, BackendError> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| BackendError::Internal(format!("clock error: {e}")))?;

        let secs = now.as_secs();
        let credentials = self.temporary_credentials(secs)?;
        let (timestamp, datestamp) = format_iso8601(secs);
        let body_hash = body_hash.to_string();

        // Extract host from endpoint (strip scheme).
        let host = self
            .config
            .endpoint
            .trim_start_matches("https://")
            .trim_start_matches("http://");

        let mut headers = BTreeMap::new();
        headers.insert("host".into(), host.into());
        headers.insert("x-amz-content-sha256".into(), body_hash.clone());
        headers.insert("x-amz-date".into(), timestamp.clone());

        // For PUT requests, set content-type so S3 doesn't reject.
        if method == "PUT" {
            headers.insert("content-type".into(), "application/octet-stream".into());
        }
        for (name, value) in extra_headers {
            headers.insert(name.to_ascii_lowercase(), value.trim().to_string());
        }

        let mut request_config = self.config.clone();
        if let Some(credentials) = credentials {
            request_config.access_key = credentials.access_key_id;
            request_config.secret_key = credentials.secret_access_key;
            headers.insert("x-amz-security-token".into(), credentials.session_token);
        }
        let auth = sign_s3v4(
            method,
            object_key,
            canonical_querystring,
            &headers,
            &body_hash,
            &request_config,
            &timestamp,
            &datestamp,
        );

        headers.insert("Authorization".into(), auth);

        Ok(headers)
    }

    fn split_status(stdout: &[u8]) -> (u16, Vec<u8>) {
        // Search the raw bytes: an index into a lossily decoded copy does not
        // line up with `stdout` once a non-UTF-8 byte was replaced.
        const MARKER: &[u8] = b"HTTPSTATUS:";
        match stdout
            .windows(MARKER.len())
            .rposition(|window| window == MARKER)
        {
            Some(idx) => {
                let code = std::str::from_utf8(&stdout[idx + MARKER.len()..])
                    .ok()
                    .and_then(|raw| raw.trim().parse().ok())
                    .unwrap_or(0);
                (code, stdout[..idx].to_vec())
            }
            None => (0, stdout.to_vec()),
        }
    }

    fn header_value(headers: &[u8], name: &str) -> Option<String> {
        let needle = format!("{}:", name.to_ascii_lowercase());
        String::from_utf8_lossy(headers)
            .lines()
            .filter_map(|line| {
                let trimmed = line.trim();
                let lower = trimmed.to_ascii_lowercase();
                lower
                    .starts_with(&needle)
                    .then(|| trimmed[needle.len()..].trim().to_string())
            })
            .last()
            .filter(|value| !value.is_empty())
    }

    /// Build the full URL for the given object key, honoring the
    /// configured addressing style.
    ///
    /// Path-style: `https://endpoint/bucket/key` — what MinIO, Ceph,
    /// Garage, SeaweedFS, and self-hosted S3-compatible stores
    /// require.
    ///
    /// Virtual-host style: `https://bucket.endpoint-host/key` — the
    /// modern AWS default. Switching is a one-line config change in
    /// case a provider rejects path-style.
    fn object_url(&self, object_key: &str) -> String {
        if self.config.path_style {
            return format!(
                "{}/{}/{}",
                self.config.endpoint, self.config.bucket, object_key
            );
        }
        // Virtual-host style: prepend bucket as a subdomain of the
        // endpoint host. Splits scheme + host carefully so an
        // endpoint with a non-default port (`https://host:9000`)
        // still produces a valid URL.
        let trimmed = self.config.endpoint.trim_end_matches('/');
        if let Some(rest) = trimmed.strip_prefix("https://") {
            return format!("https://{}.{}/{}", self.config.bucket, rest, object_key);
        }
        if let Some(rest) = trimmed.strip_prefix("http://") {
            return format!("http://{}.{}/{}", self.config.bucket, rest, object_key);
        }
        // Endpoint missing a scheme — fall back to path-style; safer
        // than producing a malformed URL the operator can't debug.
        format!("{}/{}/{}", trimmed, self.config.bucket, object_key)
    }

    /// Build the full object key by prepending the configured prefix.
    fn full_key(&self, remote_key: &str) -> String {
        format!("{}{}", self.config.key_prefix, remote_key)
    }

    /// Execute a curl command and return its output.
    fn exec_curl(cmd: &mut std::process::Command) -> Result<std::process::Output, BackendError> {
        // A request must never hang forever: bound the connect, and abort a
        // transfer that stalls below 1 KiB/s for a minute. Large objects
        // still stream for as long as they keep moving.
        cmd.arg("--connect-timeout")
            .arg(CURL_CONNECT_TIMEOUT_SECS.to_string())
            .arg("--speed-limit")
            .arg("1024")
            .arg("--speed-time")
            .arg(CURL_STALL_TIMEOUT_SECS.to_string());
        cmd.output()
            .map_err(|e| BackendError::Transport(format!("curl not available: {e}")))
    }

    /// Streamed SHA-256 of an upload body plus a size check against the
    /// single-PUT limit (multipart is not implemented yet).
    fn upload_body_hash(local_path: &Path) -> Result<String, BackendError> {
        let size = fs::metadata(local_path)
            .map_err(|e| BackendError::Transport(format!("stat local file: {e}")))?
            .len();
        if size > SINGLE_PUT_MAX_BYTES {
            return Err(BackendError::Config(format!(
                "{} is {size} bytes; a single S3 PUT is limited to {SINGLE_PUT_MAX_BYTES} bytes \
                 and multipart upload is not supported yet",
                local_path.display()
            )));
        }
        reddb_file::sha256_file_hex(local_path)
            .map_err(|e| BackendError::Transport(format!("hash local file: {e}")))
    }

    /// Sibling temporary path for a download, so the target is replaced
    /// atomically and only after a complete 2xx response.
    fn download_temp_path(local_path: &Path) -> PathBuf {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let name = local_path
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_else(|| "download".into());
        local_path.with_file_name(format!(
            ".{name}.download-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ))
    }

    /// Platform-specific "null device" for `curl -o`. On Unix it's
    /// `/dev/null`; on Windows it's `NUL`. Callers that pass this to
    /// the `-o` flag get discarded response bodies on every platform.
    #[inline]
    fn null_device() -> &'static str {
        #[cfg(windows)]
        {
            "NUL"
        }
        #[cfg(not(windows))]
        {
            "/dev/null"
        }
    }
}

// ---------------------------------------------------------------------------
// RemoteBackend implementation
// ---------------------------------------------------------------------------

impl RemoteBackend for S3Backend {
    fn name(&self) -> &str {
        "s3"
    }

    fn download(&self, remote_key: &str, local_path: &Path) -> Result<bool, BackendError> {
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);

        let headers = self.build_signed_request("GET", &object_key, &[])?;

        // Callers download over live files (`/admin/restore` targets the
        // data file). Write a sibling temporary file and rename it into
        // place only after a complete 2xx; on any other outcome the target
        // is left untouched.
        let temp = Self::download_temp_path(local_path);
        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sS")
            .arg("-o")
            .arg(temp.as_os_str())
            .arg("-w")
            .arg("HTTPSTATUS:%{http_code}");
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let result = (|| {
            let output = Self::exec_curl(&mut cmd)?;
            if !output.status.success() {
                return Err(BackendError::Transport(format!(
                    "download failed (exit {}): {}",
                    output.status.code().unwrap_or(-1),
                    String::from_utf8_lossy(&output.stderr)
                )));
            }
            let (code, _) = Self::split_status(&output.stdout);
            if !Self::read_status("GET", &url, code)? {
                return Ok(false);
            }
            let file = fs::OpenOptions::new()
                .read(true)
                .open(&temp)
                .map_err(|e| BackendError::Transport(format!("open downloaded file: {e}")))?;
            file.sync_all()
                .map_err(|e| BackendError::Transport(format!("sync downloaded file: {e}")))?;
            fs::rename(&temp, local_path)
                .map_err(|e| BackendError::Transport(format!("install downloaded file: {e}")))?;
            Ok(true)
        })();
        let _ = fs::remove_file(&temp);
        result
    }

    fn upload(&self, local_path: &Path, remote_key: &str) -> Result<(), BackendError> {
        let body_hash = Self::upload_body_hash(local_path)?;

        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);

        let headers =
            self.build_signed_request_with_body_hash("PUT", &object_key, "", &body_hash, &[])?;

        // `-T` streams the file from disk; `--data-binary @file` buffers it.
        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sf").arg("-T").arg(local_path.as_os_str());
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;

        if output.status.success() {
            Ok(())
        } else {
            Err(BackendError::Transport(format!(
                "upload failed (exit {}): {}",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stderr)
            )))
        }
    }

    fn exists(&self, remote_key: &str) -> Result<bool, BackendError> {
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);

        let headers = self.build_signed_request("HEAD", &object_key, &[])?;

        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sS")
            .arg("-I") // HEAD request
            .arg("-o")
            .arg(Self::null_device())
            .arg("-w")
            .arg("HTTPSTATUS:%{http_code}");
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;
        if !output.status.success() {
            return Err(BackendError::Transport(format!(
                "exists check failed (exit {}): {}",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stderr)
            )));
        }
        let (code, _) = Self::split_status(&output.stdout);
        Self::read_status("HEAD", &url, code)
    }

    fn delete(&self, remote_key: &str) -> Result<(), BackendError> {
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);

        let headers = self.build_signed_request("DELETE", &object_key, &[])?;

        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sf")
            .arg("-X")
            .arg("DELETE")
            .arg("-o")
            .arg(Self::null_device());
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;

        // S3 returns 204 on successful delete, or 404 if already gone -- both are fine.
        if output.status.success() || output.status.code() == Some(22) {
            Ok(())
        } else {
            Err(BackendError::Transport(format!(
                "delete failed (exit {}): {}",
                output.status.code().unwrap_or(-1),
                String::from_utf8_lossy(&output.stderr)
            )))
        }
    }

    fn list(&self, prefix: &str) -> Result<Vec<String>, BackendError> {
        let object_prefix = self.full_key(prefix);
        let mut keys = Vec::new();
        let mut continuation: Option<String> = None;
        // ListObjectsV2 returns at most 1000 keys per page. Restore treats a
        // missing archived WAL segment as data loss, so every page is read.
        loop {
            // SigV4 canonical query parameters are sorted by name.
            let canonical_querystring = match &continuation {
                Some(token) => format!(
                    "continuation-token={}&list-type=2&prefix={}",
                    uri_encode(token, true),
                    uri_encode(&object_prefix, true)
                ),
                None => format!("list-type=2&prefix={}", uri_encode(&object_prefix, true)),
            };
            let url = format!(
                "{}/{}?{}",
                self.config.endpoint, self.config.bucket, canonical_querystring
            );
            let headers =
                self.build_signed_request_with_query("GET", "", &canonical_querystring, &[])?;

            let mut cmd = std::process::Command::new("curl");
            cmd.arg("-sf");
            for (k, v) in &headers {
                cmd.arg("-H").arg(format!("{k}: {v}"));
            }
            cmd.arg(&url);

            let output = Self::exec_curl(&mut cmd)?;
            if !output.status.success() {
                return Err(BackendError::Transport(format!(
                    "list failed (exit {}): {}",
                    output.status.code().unwrap_or(-1),
                    String::from_utf8_lossy(&output.stderr)
                )));
            }

            let xml = String::from_utf8(output.stdout).map_err(|err| {
                BackendError::Transport(format!("list response was not utf-8: {err}"))
            })?;
            keys.extend(parse_list_objects_keys(&xml).into_iter().filter_map(|key| {
                key.strip_prefix(&self.config.key_prefix)
                    .map(|k| k.to_string())
            }));
            match parse_list_continuation(&xml)? {
                Some(token) if continuation.as_deref() == Some(token.as_str()) => {
                    return Err(BackendError::Transport(
                        "list returned the same continuation token twice".into(),
                    ));
                }
                Some(token) => continuation = Some(token),
                None => break,
            }
        }
        Ok(keys)
    }
}

impl AtomicRemoteBackend for S3Backend {
    fn object_version(
        &self,
        remote_key: &str,
    ) -> Result<Option<BackendObjectVersion>, BackendError> {
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);
        let headers = self.build_signed_request("HEAD", &object_key, &[])?;

        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sS")
            .arg("-D")
            .arg("-")
            .arg("-o")
            .arg(Self::null_device())
            .arg("-w")
            .arg("HTTPSTATUS:%{http_code}")
            // `-I`, not `-X HEAD`: with `-X HEAD` curl still waits for the
            // `Content-Length` body a HEAD response never sends, and blocks
            // until the server drops the connection (minutes on R2).
            .arg("-I");
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;
        if !output.status.success() {
            return Err(BackendError::Transport(format!(
                "s3 HEAD {url}: curl failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }
        let (code, body) = Self::split_status(&output.stdout);
        match code {
            200..=299 => Self::header_value(&body, "etag")
                .map(BackendObjectVersion::new)
                .map(Some)
                .ok_or_else(|| BackendError::Internal(format!("s3 HEAD {url} missing ETag"))),
            404 => Ok(None),
            401 | 403 => Err(BackendError::Auth(format!(
                "s3 HEAD {url} returned status {code}"
            ))),
            other => Err(BackendError::Transport(format!(
                "s3 HEAD {url} returned status {other}"
            ))),
        }
    }

    fn upload_conditional(
        &self,
        local_path: &Path,
        remote_key: &str,
        condition: ConditionalPut,
    ) -> Result<BackendObjectVersion, BackendError> {
        let body_hash = Self::upload_body_hash(local_path)?;
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);
        let condition_header = match &condition {
            ConditionalPut::IfAbsent => ("if-none-match", "*"),
            ConditionalPut::IfVersion(version) => ("if-match", version.token.as_str()),
        };
        let headers = self.build_signed_request_with_body_hash(
            "PUT",
            &object_key,
            "",
            &body_hash,
            &[condition_header],
        )?;

        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sS")
            .arg("-D")
            .arg("-")
            .arg("-o")
            .arg(Self::null_device())
            .arg("-w")
            .arg("HTTPSTATUS:%{http_code}")
            .arg("-T")
            .arg(local_path.as_os_str());
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;
        if !output.status.success() {
            return Err(BackendError::Transport(format!(
                "s3 conditional PUT {url}: curl failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }
        let (code, response_headers) = Self::split_status(&output.stdout);
        Self::conditional_put_version(&url, code, &response_headers)
    }

    fn delete_conditional(
        &self,
        remote_key: &str,
        condition: ConditionalDelete,
    ) -> Result<(), BackendError> {
        let object_key = self.full_key(remote_key);
        let url = self.object_url(&object_key);
        let ConditionalDelete::IfVersion(version) = condition;
        let headers = self.build_signed_request_with_query_and_headers(
            "DELETE",
            &object_key,
            "",
            &[],
            &[("if-match", version.token.as_str())],
        )?;

        let mut cmd = std::process::Command::new("curl");
        cmd.arg("-sS")
            .arg("-o")
            .arg(Self::null_device())
            .arg("-w")
            .arg("HTTPSTATUS:%{http_code}")
            .arg("-X")
            .arg("DELETE");
        for (k, v) in &headers {
            cmd.arg("-H").arg(format!("{k}: {v}"));
        }
        cmd.arg(&url);

        let output = Self::exec_curl(&mut cmd)?;
        if !output.status.success() {
            return Err(BackendError::Transport(format!(
                "s3 conditional DELETE {url}: curl failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }
        let (code, _) = Self::split_status(&output.stdout);
        match code {
            200..=299 => Ok(()),
            404 | 409 | 412 => Err(BackendError::PreconditionFailed(format!(
                "s3 conditional DELETE {url} returned status {code}"
            ))),
            401 | 403 => Err(BackendError::Auth(format!(
                "s3 conditional DELETE {url} returned status {code}"
            ))),
            other => Err(BackendError::Transport(format!(
                "s3 conditional DELETE {url} returned status {other}"
            ))),
        }
    }
}

impl S3Backend {
    /// Map a GET/HEAD status to "present", "absent", or an error. Only 404
    /// means absent: a 401/403 is an authorization failure, and reporting it
    /// as a missing object would let a misconfigured boot start from empty
    /// state or a restore skip data.
    fn read_status(method: &str, url: &str, code: u16) -> Result<bool, BackendError> {
        match code {
            200..=299 => Ok(true),
            404 => Ok(false),
            401 | 403 => Err(BackendError::Auth(format!(
                "s3 {method} {url} returned status {code}"
            ))),
            other => Err(BackendError::Transport(format!(
                "s3 {method} {url} returned status {other}"
            ))),
        }
    }

    /// Map a conditional PUT response to the version it installed.
    ///
    /// The version must come from this PUT's own response. A follow-up HEAD
    /// races a successor: if this writer stalls after its PUT commits and a
    /// successor CASes the object, the HEAD returns the successor's ETag, and
    /// this writer's next `If-Match` would overwrite the successor. A 2xx
    /// without an ETag therefore fails closed instead of falling back to HEAD.
    fn conditional_put_version(
        url: &str,
        code: u16,
        response_headers: &[u8],
    ) -> Result<BackendObjectVersion, BackendError> {
        match code {
            200..=299 => Self::header_value(response_headers, "etag")
                .map(BackendObjectVersion::new)
                .ok_or_else(|| {
                    BackendError::Internal(format!(
                        "s3 conditional PUT {url} response missing ETag"
                    ))
                }),
            404 | 409 | 412 => Err(BackendError::PreconditionFailed(format!(
                "s3 conditional PUT {url} returned status {code}"
            ))),
            401 | 403 => Err(BackendError::Auth(format!(
                "s3 conditional PUT {url} returned status {code}"
            ))),
            other => Err(BackendError::Transport(format!(
                "s3 conditional PUT {url} returned status {other}"
            ))),
        }
    }
}

// ---------------------------------------------------------------------------
// AWS Signature Version 4 implementation
// ---------------------------------------------------------------------------

/// Compute the `Authorization` header value for AWS Signature Version 4.
fn sign_s3v4(
    method: &str,
    object_key: &str,
    canonical_querystring: &str,
    headers: &BTreeMap<String, String>,
    body_hash: &str,
    config: &S3Config,
    timestamp: &str,
    datestamp: &str,
) -> String {
    let service = "s3";

    // -- Step 1: Canonical request ----------------------------------------

    // Canonical URI: /{bucket}/{key} — URI-encode each path component.
    let canonical_uri = format!(
        "/{}{}",
        uri_encode(&config.bucket, false),
        if object_key.is_empty() {
            String::new()
        } else {
            format!("/{}", uri_encode_path(object_key))
        }
    );

    // Canonical headers (sorted, lower-cased keys, trimmed values).
    let mut canonical_headers = String::new();
    let mut signed_header_names: Vec<&str> = Vec::new();
    for (k, v) in headers {
        canonical_headers.push_str(&format!("{}:{}\n", k.to_lowercase(), v.trim()));
        signed_header_names.push(k.as_str());
    }
    let signed_headers = signed_header_names
        .iter()
        .map(|s| s.to_lowercase())
        .collect::<Vec<_>>()
        .join(";");

    let canonical_request = format!(
        "{}\n{}\n{}\n{}\n{}\n{}",
        method, canonical_uri, canonical_querystring, canonical_headers, signed_headers, body_hash
    );

    // -- Step 2: String to sign -------------------------------------------

    let credential_scope = format!("{datestamp}/{}/{service}/aws4_request", config.region);

    let string_to_sign = format!(
        "AWS4-HMAC-SHA256\n{}\n{}\n{}",
        timestamp,
        credential_scope,
        sha256_hex(canonical_request.as_bytes()),
    );

    // -- Step 3: Signing key derivation -----------------------------------
    //
    // HMAC-SHA256 chain:
    //   kDate    = HMAC("AWS4" + secret_key, datestamp)
    //   kRegion  = HMAC(kDate, region)
    //   kService = HMAC(kRegion, service)
    //   kSigning = HMAC(kService, "aws4_request")

    let k_date = hmac_sha256(
        format!("AWS4{}", config.secret_key).as_bytes(),
        datestamp.as_bytes(),
    );
    let k_region = hmac_sha256(&k_date, config.region.as_bytes());
    let k_service = hmac_sha256(&k_region, service.as_bytes());
    let k_signing = hmac_sha256(&k_service, b"aws4_request");

    // -- Step 4: Signature ------------------------------------------------

    let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));

    format!(
        "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}",
        config.access_key, credential_scope, signed_headers, signature
    )
}

/// `Some(token)` when a ListObjectsV2 page is truncated. A truncated page
/// without a token is an error rather than a silently short listing.
fn parse_list_continuation(xml: &str) -> Result<Option<String>, BackendError> {
    let truncated = xml_element(xml, "IsTruncated").is_some_and(|value| value.trim() == "true");
    if !truncated {
        return Ok(None);
    }
    xml_element(xml, "NextContinuationToken")
        .map(|token| Some(xml_unescape(token.trim())))
        .ok_or_else(|| {
            BackendError::Transport("truncated list response has no continuation token".into())
        })
}

fn xml_element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
    let open = format!("<{name}>");
    let close = format!("</{name}>");
    let start = xml.find(&open)? + open.len();
    let end = xml[start..].find(&close)? + start;
    Some(&xml[start..end])
}

fn xml_unescape(value: &str) -> String {
    value
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

fn parse_list_objects_keys(xml: &str) -> Vec<String> {
    let mut keys = Vec::new();
    let mut rest = xml;
    let open = "<Key>";
    let close = "</Key>";
    while let Some(start) = rest.find(open) {
        let after_start = &rest[start + open.len()..];
        let Some(end) = after_start.find(close) else {
            break;
        };
        keys.push(after_start[..end].to_string());
        rest = &after_start[end + close.len()..];
    }
    keys
}

// ---------------------------------------------------------------------------
// Crypto helpers (delegate to crate::crypto)
// ---------------------------------------------------------------------------

/// HMAC-SHA256 returning raw bytes.
fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
    crypto::hmac::hmac_sha256(key, data).to_vec()
}

/// SHA-256 returning lower-case hex string.
fn sha256_hex(data: &[u8]) -> String {
    hex::encode(crypto::sha256::sha256(data))
}

// ---------------------------------------------------------------------------
// URI encoding helpers (per AWS Sig v4 spec)
// ---------------------------------------------------------------------------

/// URI-encode a string per RFC 3986, plus AWS quirks:
///   - Unreserved characters (A-Z a-z 0-9 - _ . ~) are NOT encoded.
///   - Everything else is percent-encoded.
///   - If `encode_slash` is false, '/' is kept literal (for path components).
fn uri_encode(input: &str, encode_slash: bool) -> String {
    let mut encoded = String::with_capacity(input.len() * 2);
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                encoded.push(byte as char);
            }
            b'/' if !encode_slash => {
                encoded.push('/');
            }
            _ => {
                encoded.push_str(&format!("%{:02X}", byte));
            }
        }
    }
    encoded
}

/// URI-encode a full object key path, keeping '/' separators literal.
fn uri_encode_path(path: &str) -> String {
    uri_encode(path, false)
}

// ---------------------------------------------------------------------------
// Time formatting
// ---------------------------------------------------------------------------

/// Produce ISO 8601 timestamp and datestamp from Unix epoch seconds.
///
/// Returns `("20260409T120000Z", "20260409")`.
fn format_iso8601(epoch_secs: u64) -> (String, String) {
    // Manual UTC calendar conversion (no chrono dependency).
    let secs_per_day: u64 = 86400;
    let days = epoch_secs / secs_per_day;
    let day_secs = epoch_secs % secs_per_day;

    let hours = day_secs / 3600;
    let minutes = (day_secs % 3600) / 60;
    let seconds = day_secs % 60;

    // Days since Unix epoch (1970-01-01) to (year, month, day).
    let (year, month, day) = civil_from_days(days as i64);

    let timestamp = format!(
        "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
        year, month, day, hours, minutes, seconds
    );
    let datestamp = format!("{:04}{:02}{:02}", year, month, day);

    (timestamp, datestamp)
}

/// Convert a day count from the Unix epoch to a (year, month, day) triple.
///
/// Adapted from Howard Hinnant's `civil_from_days` algorithm.
fn civil_from_days(mut days: i64) -> (i32, u32, u32) {
    days += 719_468; // shift epoch from 1970-01-01 to 0000-03-01
    let era = if days >= 0 {
        days / 146_097
    } else {
        (days - 146_096) / 146_097
    };
    let doe = (days - era * 146_097) as u32; // day of era [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // year of era [0, 399]
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year [0, 365]
    let mp = (5 * doy + 2) / 153; // month index [0, 11]
    let d = doy - (153 * mp + 2) / 5 + 1; // day [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // month [1, 12]
    let y = if m <= 2 { y + 1 } else { y };
    (y as i32, m, d)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn scoped_credentials() -> serde_json::Value {
        serde_json::json!({"schema_version": 1, "bucket": "synthetic-bucket", "prefix": "org/db/",
            "access_key_id": "temporary-access", "secret_access_key": "temporary-secret",
            "session_token": "temporary-session", "expires_at_unix_seconds":
                SystemTime::now().duration_since(UNIX_EPOCH).expect("clock").as_secs() + 3600})
    }

    #[test]
    fn temporary_file_rotates_all_signing_material_without_restart() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let path = directory.path().join("credentials.json");
        let config = S3Config::generic(
            "https://synthetic.invalid",
            "synthetic-bucket",
            "fallback-access",
            "fallback-secret",
        )
        .with_prefix("org/db/");
        let backend = S3Backend::new(config).with_credentials_file(&path);
        let mut credentials = scoped_credentials();
        fs::write(&path, serde_json::to_vec(&credentials).expect("JSON"))
            .expect("credentials file");
        let first = backend
            .build_signed_request("PUT", "org/db/example", b"data")
            .expect("signed request");
        assert_eq!(first["x-amz-security-token"], "temporary-session");
        assert!(first["Authorization"].contains("Credential=temporary-access/"));
        assert!(first["Authorization"].contains("x-amz-security-token"));
        assert!(!first["Authorization"].contains("fallback-access"));
        credentials["access_key_id"] = "rotated-access".into();
        credentials["secret_access_key"] = "rotated-secret".into();
        credentials["session_token"] = "rotated-session".into();
        let replacement = directory.path().join("replacement.json");
        fs::write(
            &replacement,
            serde_json::to_vec(&credentials).expect("JSON"),
        )
        .expect("replacement file");
        fs::rename(&replacement, &path).expect("atomic rotation");
        let second = backend
            .build_signed_request("PUT", "org/db/example", b"data")
            .expect("rotated request");
        assert_eq!(second["x-amz-security-token"], "rotated-session");
        assert!(second["Authorization"].contains("Credential=rotated-access/"));
        assert_ne!(first["Authorization"], second["Authorization"]);
        fs::remove_file(&path).expect("remove credentials");
        assert!(backend
            .build_signed_request("GET", "org/db/example", b"")
            .is_err());
    }

    #[test]
    fn invalid_temporary_file_never_falls_back_or_exposes_material() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let path = directory.path().join("credentials.json");
        let backend = S3Backend::new(
            S3Config::generic(
                "https://synthetic.invalid",
                "synthetic-bucket",
                "fallback",
                "fallback",
            )
            .with_prefix("org/db/"),
        )
        .with_credentials_file(&path);
        for (field, value) in [
            ("schema_version", serde_json::json!(2)),
            ("schema_version", serde_json::json!(1.5)),
            ("bucket", serde_json::json!("other-bucket")),
            ("prefix", serde_json::json!("org/other/")),
            ("access_key_id", serde_json::json!("")),
            ("secret_access_key", serde_json::json!("secret\r\ninjected")),
            ("session_token", serde_json::json!("secret\ninjected")),
            ("expires_at_unix_seconds", serde_json::json!(0)),
            (
                "expires_at_unix_seconds",
                serde_json::json!(9_000_000_000.5),
            ),
            ("unknown", serde_json::json!("secret-unknown")),
        ] {
            let mut value_object = scoped_credentials();
            value_object[field] = value;
            fs::write(&path, serde_json::to_vec(&value_object).expect("JSON")).expect("file");
            let error = backend
                .build_signed_request("GET", "org/db/example", b"")
                .expect_err("reject invalid credentials");
            let message = error.to_string();
            assert!(!message.contains("secret") && !message.contains(path.to_str().expect("path")));
        }
        for bytes in [b"malformed-secret-json".to_vec(), vec![b'x'; 32 * 1024 + 1]] {
            fs::write(&path, bytes).expect("file");
            assert!(backend
                .build_signed_request("GET", "org/db/example", b"")
                .is_err());
        }
        fs::write(
            &path,
            serde_json::to_vec(&scoped_credentials()).expect("JSON"),
        )
        .expect("file");
        let insecure = S3Backend::new(
            S3Config::generic(
                "http://synthetic.invalid",
                "synthetic-bucket",
                "fallback",
                "fallback",
            )
            .with_prefix("org/db/"),
        )
        .with_credentials_file(path);
        assert!(insecure
            .build_signed_request("GET", "org/db/example", b"")
            .is_err());
    }

    #[test]
    fn test_sha256_hex_empty() {
        // SHA-256 of empty input is the well-known constant.
        let hash = sha256_hex(b"");
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn test_hmac_sha256_rfc4231_case1() {
        // RFC 4231 Test Case 1
        let key = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap();
        let data = b"Hi There";
        let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
        assert_eq!(hex::encode(hmac_sha256(&key, data)), expected);
    }

    #[test]
    fn test_format_iso8601() {
        // 2023-01-15 12:30:45 UTC = 1673785845
        let (ts, ds) = format_iso8601(1_673_785_845);
        assert_eq!(ts, "20230115T123045Z");
        assert_eq!(ds, "20230115");
    }

    #[test]
    fn test_format_iso8601_epoch() {
        let (ts, ds) = format_iso8601(0);
        assert_eq!(ts, "19700101T000000Z");
        assert_eq!(ds, "19700101");
    }

    #[test]
    fn test_uri_encode_simple() {
        assert_eq!(uri_encode("hello world", true), "hello%20world");
        assert_eq!(uri_encode("foo/bar", true), "foo%2Fbar");
        assert_eq!(uri_encode("foo/bar", false), "foo/bar");
    }

    #[test]
    fn test_uri_encode_unreserved() {
        // Unreserved characters should pass through.
        let unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
        assert_eq!(uri_encode(unreserved, true), unreserved);
    }

    #[test]
    fn test_civil_from_days() {
        // 1970-01-01 = day 0
        assert_eq!(civil_from_days(0), (1970, 1, 1));
        // 2000-01-01 = day 10957
        assert_eq!(civil_from_days(10957), (2000, 1, 1));
        // 2024-02-29 (leap year) = day 19782
        assert_eq!(civil_from_days(19782), (2024, 2, 29));
    }

    #[test]
    fn test_s3v4_signature_known_vector() {
        // Verify signature against a known AWS test vector.
        // This uses the AWS example values from the Sig V4 documentation.
        let config = S3Config {
            endpoint: "https://s3.us-east-1.amazonaws.com".into(),
            bucket: "examplebucket".into(),
            key_prefix: String::new(),
            access_key: "AKIAIOSFODNN7EXAMPLE".into(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(),
            region: "us-east-1".into(),
            path_style: true,
        };

        let mut headers = BTreeMap::new();
        headers.insert("host".into(), "s3.us-east-1.amazonaws.com".into());
        headers.insert(
            "x-amz-content-sha256".into(),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into(),
        );
        headers.insert("x-amz-date".into(), "20130524T000000Z".into());

        let auth = sign_s3v4(
            "GET",
            "test.txt",
            "",
            &headers,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            &config,
            "20130524T000000Z",
            "20130524",
        );

        // Verify structure of the Authorization header.
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/"));
        assert!(auth.contains("20130524/us-east-1/s3/aws4_request"));
        assert!(auth.contains("SignedHeaders=host;x-amz-content-sha256;x-amz-date"));
        assert!(auth.contains("Signature="));

        // Ensure the signature is 64 hex chars.
        let sig = auth.split("Signature=").nth(1).unwrap();
        assert_eq!(sig.len(), 64);
        assert!(sig.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_config_constructors() {
        let aws = S3Config::aws("mybucket", "eu-west-1", "AK", "SK");
        assert_eq!(aws.endpoint, "https://s3.eu-west-1.amazonaws.com");
        assert_eq!(aws.region, "eu-west-1");
        assert_eq!(aws.bucket, "mybucket");
        assert!(aws.key_prefix.is_empty());

        let r2 = S3Config::r2("abc123", "mybucket", "AK", "SK");
        assert_eq!(r2.endpoint, "https://abc123.r2.cloudflarestorage.com");
        assert_eq!(r2.region, "auto");

        let do_spaces = S3Config::digitalocean("nyc3", "mybucket", "AK", "SK");
        assert_eq!(do_spaces.endpoint, "https://nyc3.digitaloceanspaces.com");
        assert_eq!(do_spaces.region, "nyc3");

        let gcs = S3Config::gcs("mybucket", "AK", "SK");
        assert_eq!(gcs.endpoint, "https://storage.googleapis.com");
        assert_eq!(gcs.region, "us");
    }

    #[test]
    fn test_config_with_prefix() {
        let config = S3Config::aws("b", "us-east-1", "AK", "SK").with_prefix("databases/prod/");
        assert_eq!(config.key_prefix, "databases/prod/");
    }

    #[test]
    fn test_build_signed_request_structure() {
        let backend = S3Backend::new(S3Config::aws("mybucket", "us-east-1", "AK", "SK"));
        let headers = backend
            .build_signed_request("GET", "test.rdb", &[])
            .unwrap();

        assert!(headers.contains_key("host"));
        assert!(headers.contains_key("x-amz-date"));
        assert!(headers.contains_key("x-amz-content-sha256"));
        assert!(headers.contains_key("Authorization"));

        let auth = &headers["Authorization"];
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AK/"));
        assert!(auth.contains("/us-east-1/s3/aws4_request"));
    }

    #[test]
    fn test_build_signed_request_put_has_content_type() {
        let backend = S3Backend::new(S3Config::aws("mybucket", "us-east-1", "AK", "SK"));
        let headers = backend
            .build_signed_request("PUT", "test.rdb", b"hello")
            .unwrap();

        assert_eq!(
            headers.get("content-type").unwrap(),
            "application/octet-stream"
        );
    }

    #[test]
    fn test_full_key() {
        let backend =
            S3Backend::new(S3Config::aws("b", "us-east-1", "AK", "SK").with_prefix("db/"));
        assert_eq!(backend.full_key("mydb.rdb"), "db/mydb.rdb");
    }

    #[test]
    fn test_object_url() {
        let backend = S3Backend::new(S3Config::aws("mybucket", "us-east-1", "AK", "SK"));
        assert_eq!(
            backend.object_url("data/test.rdb"),
            "https://s3.us-east-1.amazonaws.com/mybucket/data/test.rdb"
        );
    }

    #[test]
    fn test_object_url_virtual_host_style() {
        let backend = S3Backend::new(
            S3Config::aws("mybucket", "us-east-1", "AK", "SK").with_path_style(false),
        );
        assert_eq!(
            backend.object_url("data/test.rdb"),
            "https://mybucket.s3.us-east-1.amazonaws.com/data/test.rdb"
        );
    }

    #[test]
    fn test_object_url_path_style_minio() {
        // MinIO/Ceph self-hosted endpoint with port. Path-style is
        // the only supported addressing — verify it works for an
        // endpoint that includes a non-default port.
        let backend = S3Backend::new(S3Config::generic(
            "http://minio:9000",
            "bench",
            "minio",
            "minio123",
        ));
        assert_eq!(
            backend.object_url("snapshots/1.snap"),
            "http://minio:9000/bench/snapshots/1.snap"
        );
    }

    /// Serve one canned HTTP response per connection, in order.
    fn canned_server(responses: Vec<(u16, &'static [u8])>) -> String {
        use std::io::{BufRead, BufReader, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let endpoint = format!("http://{}", listener.local_addr().expect("addr"));
        std::thread::spawn(move || {
            for (status, body) in responses {
                let Ok((stream, _)) = listener.accept() else {
                    return;
                };
                let mut reader = BufReader::new(stream.try_clone().expect("clone"));
                loop {
                    let mut line = String::new();
                    if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
                        break;
                    }
                }
                let mut stream = stream;
                let _ = write!(
                    stream,
                    "HTTP/1.1 {status} X\r\nConnection: close\r\nContent-Length: {}\r\n\r\n",
                    body.len()
                );
                let _ = stream.write_all(body);
            }
        });
        endpoint
    }

    #[test]
    fn failed_download_never_touches_the_existing_target() {
        let dir = tempfile::tempdir().expect("dir");
        let target = dir.path().join("data.rdb");
        std::fs::write(&target, b"live database").expect("seed target");
        let endpoint = canned_server(vec![
            (503, b"<Error>SlowDown</Error>"),
            (403, b"<Error>AccessDenied</Error>"),
            (404, b"<Error>NoSuchKey</Error>"),
            (200, b"restored bytes"),
        ]);
        let backend = S3Backend::new(S3Config::generic(&endpoint, "b", "k", "s"));
        assert!(matches!(
            backend.download("data.rdb", &target),
            Err(BackendError::Transport(_))
        ));
        assert!(matches!(
            backend.download("data.rdb", &target),
            Err(BackendError::Auth(_))
        ));
        assert!(matches!(backend.download("data.rdb", &target), Ok(false)));
        assert_eq!(std::fs::read(&target).expect("target"), b"live database");
        assert!(matches!(backend.download("data.rdb", &target), Ok(true)));
        assert_eq!(std::fs::read(&target).expect("target"), b"restored bytes");

        // Connection refused (nothing listens any more): target intact.
        let unreachable = S3Backend::new(S3Config::generic("http://127.0.0.1:9", "b", "k", "s"));
        assert!(unreachable.download("data.rdb", &target).is_err());
        assert_eq!(std::fs::read(&target).expect("target"), b"restored bytes");
        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
            .expect("list")
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().contains(".download-"))
            .collect();
        assert!(leftovers.is_empty(), "temporary downloads are removed");
    }

    #[test]
    fn split_status_finds_the_marker_in_raw_bytes() {
        let mut stdout = vec![0xff, 0xfe, b'x'];
        stdout.extend_from_slice(b"HTTPSTATUS:412");
        let (code, body) = S3Backend::split_status(&stdout);
        assert_eq!(code, 412);
        assert_eq!(body, vec![0xff, 0xfe, b'x']);
        assert_eq!(S3Backend::split_status(b"no marker").0, 0);
    }

    #[test]
    fn read_status_reports_denied_access_instead_of_absence() {
        assert!(matches!(S3Backend::read_status("GET", "u", 200), Ok(true)));
        assert!(matches!(S3Backend::read_status("GET", "u", 404), Ok(false)));
        for code in [401, 403] {
            assert!(matches!(
                S3Backend::read_status("HEAD", "u", code),
                Err(BackendError::Auth(_))
            ));
        }
        assert!(matches!(
            S3Backend::read_status("GET", "u", 500),
            Err(BackendError::Transport(_))
        ));
    }

    #[test]
    fn conditional_put_version_comes_from_the_put_response() {
        let headers = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n\
            ETag: \"put-etag\"\r\nContent-Length: 0\r\n\r\n";
        let version = S3Backend::conditional_put_version("https://s3/b/k", 200, headers)
            .expect("2xx with ETag");
        assert_eq!(version.token, "\"put-etag\"");
    }

    #[test]
    fn conditional_put_without_response_etag_fails_closed() {
        let missing =
            S3Backend::conditional_put_version("https://s3/b/k", 200, b"HTTP/1.1 200 OK\r\n");
        assert!(matches!(missing, Err(BackendError::Internal(_))));
        for code in [404, 409, 412] {
            let result = S3Backend::conditional_put_version("https://s3/b/k", code, b"");
            assert!(matches!(result, Err(BackendError::PreconditionFailed(_))));
        }
        let denied = S3Backend::conditional_put_version("https://s3/b/k", 403, b"");
        assert!(matches!(denied, Err(BackendError::Auth(_))));
    }
}