cachekit-rs 0.11.0

Caching for Rust (beta). Supports cachekit.io SaaS, Redis, Memcached, local File, and Cloudflare Workers.
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
use std::collections::HashMap;
use std::sync::OnceLock;
use std::time::Duration;

use async_trait::async_trait;
use bytes::Bytes;
use reqwest::header::{HeaderName, HeaderValue, InvalidHeaderValue};
use zeroize::Zeroizing;

use crate::backend::{
    delete_succeeded, encode_key, ttl_header, Backend, Freshness, HealthStatus, LockableBackend,
};
use crate::error::{BackendError, BackendErrorKind};
use crate::metrics::{metrics_headers_named, MetricsProvider, METRICS_HEADER_NAMES};
use crate::session::session_headers;
use crate::url_validator::cachekitio_base_url;

// ── CachekitIO ────────────────────────────────────────────────────────────────

/// HTTP backend that talks to the cachekit.io SaaS API.
pub struct CachekitIO {
    client: reqwest::Client,
    api_key: Zeroizing<String>,
    api_url: String,
    /// `Authorization` and the session headers, built once so no request
    /// re-formats or re-parses them. The bearer value is marked sensitive, so
    /// a request's `Debug` output redacts it, and its buffer is wiped when the
    /// last clone drops.
    static_headers: [(HeaderName, HeaderValue); 3],
    /// The telemetry header names, parsed once, in [`METRICS_HEADER_NAMES`] order.
    metrics_header_names: [HeaderName; 5],
    /// Source of the `X-CacheKit-*` telemetry headers. Set once: by the
    /// builder when the user supplies one, otherwise by the client at build
    /// time via [`Backend::attach_metrics`] (first writer wins).
    metrics_provider: OnceLock<MetricsProvider>,
}

/// Redact `api_key` from debug output.
impl std::fmt::Debug for CachekitIO {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachekitIO")
            .field("api_url", &self.api_url)
            .field("api_key", &"<redacted>")
            .finish()
    }
}

impl CachekitIO {
    /// Start building a [`CachekitIO`] instance.
    pub fn builder() -> CachekitIOBuilder {
        CachekitIOBuilder::default()
    }

    /// Return the configured API URL (useful in tests / introspection).
    pub fn api_url(&self) -> &str {
        &self.api_url
    }

    /// Return a reference to the underlying HTTP client.
    pub(crate) fn client(&self) -> &reqwest::Client {
        &self.client
    }

    /// Return the API key as a string slice (for error sanitizing in sibling modules).
    pub(crate) fn api_key_str(&self) -> &str {
        self.api_key.as_str()
    }

    /// Build the full URL for a cache key path segment.
    ///
    /// Keys are percent-encoded via [`encode_key`](crate::backend::encode_key) so
    /// slashes or special characters do not break the URL structure. Fallible: it
    /// rejects exactly the keys `encode_key` rejects (CWE-22, spec rule 2).
    fn url(&self, key: &str) -> Result<String, BackendError> {
        Ok(format!("{}/v1/cache/{}", self.api_url, encode_key(key)?))
    }

    /// Build the TTL URL for a cache key (`…/ttl`). Composes on [`Self::url`], so
    /// it inherits the same [`encode_key`](crate::backend::encode_key) guard and
    /// the `/v1/cache/` prefix lives in one place (matching the wasm `workers`
    /// backend). `pub(crate)` so the [`TtlInspectable`](super::TtlInspectable)
    /// impl in the sibling `cachekitio_ttl` module builds its path through it.
    pub(crate) fn ttl_url(&self, key: &str) -> Result<String, BackendError> {
        Ok(format!("{}/ttl", self.url(key)?))
    }

    /// Build the lock URL for a cache key (`…/lock`). Composes on [`Self::url`]
    /// (same guard, same single prefix). `pub(crate)` so the
    /// [`LockableBackend`](super::LockableBackend) impl in the sibling
    /// `cachekitio_lock` module builds its path through it.
    pub(crate) fn lock_url(&self, key: &str) -> Result<String, BackendError> {
        Ok(format!("{}/lock", self.url(key)?))
    }

    /// Build the health-check URL.
    fn health_url(&self) -> String {
        format!("{}/v1/cache/health", self.api_url)
    }

    /// Apply the bearer token, session and metrics headers to a request builder.
    pub(crate) fn with_standard_headers(
        &self,
        mut req: reqwest::RequestBuilder,
    ) -> reqwest::RequestBuilder {
        for (name, value) in &self.static_headers {
            req = req.header(name.clone(), value.clone());
        }
        for (name, value) in
            metrics_headers_named(self.metrics_provider.get(), &self.metrics_header_names)
        {
            req = req.header(name, value);
        }
        req
    }

    /// Build the `PUT` for [`Backend::set`] without sending it, so tests can
    /// pin its headers.
    fn put_request(
        &self,
        key: &str,
        value: Vec<u8>,
        ttl: Option<Duration>,
    ) -> Result<reqwest::RequestBuilder, BackendError> {
        let mut req = self
            .client
            .put(self.url(key)?)
            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
            .body(value);

        if let Some(ttl) = ttl {
            let (name, value) = ttl_header(ttl);
            req = req.header(name, value);
        }

        Ok(self.with_standard_headers(req))
    }

    /// Read error body from response and build a sanitized BackendError.
    pub(crate) async fn error_from_response(&self, resp: reqwest::Response) -> BackendError {
        let status = resp.status().as_u16();
        let quota_denied = status == 429 && resp.headers().contains_key(DENY_REASON_HEADER);
        let body = resp.bytes().await.unwrap_or_default();
        let err = from_http_status_sanitized(status, &body, self.api_key.as_str());
        if quota_denied {
            err.with_quota_denied()
        } else {
            err
        }
    }
}

// ── Error helpers ────────────────────────────────────────────────────────────

/// Convert a reqwest error into a BackendError, sanitizing the API key from the message.
pub(crate) fn reqwest_err_sanitized(e: reqwest::Error, api_key: &str) -> BackendError {
    let kind = if e.is_timeout() {
        BackendErrorKind::Timeout
    } else {
        BackendErrorKind::Transient
    };
    BackendError {
        kind,
        message: BackendError::sanitize_message(&e.to_string(), api_key),
        source: Some(Box::new(e)),
    }
}

/// Build a [`BackendError`] from an HTTP status + body, sanitizing the API key from output.
pub(crate) fn from_http_status_sanitized(status: u16, body: &[u8], api_key: &str) -> BackendError {
    let sanitized =
        BackendError::sanitize_message(std::str::from_utf8(body).unwrap_or(""), api_key);
    BackendError::from_http_status(status, sanitized.as_bytes())
}

// ── Freshness headers ────────────────────────────────────────────────────────

/// Read a `GET 200`'s [`Freshness`] from its headers (`spec/saas-api.md`
/// § Stale-While-Revalidate, § Remaining Freshness).
///
/// An absent `X-CacheKit-Freshness` means fresh (a pre-SWR server). Any value
/// other than exactly `fresh` means stale, because revalidating is the safe
/// reading of a token the client does not know; every copy of a repeated
/// header must say `fresh`. An absent `X-CacheKit-Fresh-For` means no server
/// bound. A repeated one has no single bound, so it counts as `0`.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn freshness_from_headers(headers: &reqwest::header::HeaderMap) -> Freshness {
    let is_stale = headers
        .get_all("x-cachekit-freshness")
        .iter()
        .any(|value| value != "fresh");
    let mut fresh_for = headers.get_all("x-cachekit-fresh-for").iter();
    let fresh_for = match (fresh_for.next(), fresh_for.next()) {
        (None, _) => None,
        (Some(value), None) => Some(parse_fresh_for(value.as_bytes())),
        (Some(_), Some(_)) => Some(Duration::ZERO),
    };
    Freshness {
        is_stale,
        fresh_for,
    }
}

/// `X-CacheKit-Fresh-For` must be 1–7 ASCII digits and at most 2,592,000 (the
/// 30-day TTL cap); anything else counts as `0`. The length check runs first,
/// so the range check never sees a value that a fixed-width parse could wrap
/// back into range (`4297559296` as a `u32` is `2592000`).
#[cfg(not(target_arch = "wasm32"))]
fn parse_fresh_for(value: &[u8]) -> Duration {
    const MAX_FRESH_FOR_SECS: u64 = 2_592_000;
    if !(1..=7).contains(&value.len()) || !value.iter().all(u8::is_ascii_digit) {
        return Duration::ZERO;
    }
    match std::str::from_utf8(value).map(str::parse::<u64>) {
        Ok(Ok(secs)) if secs <= MAX_FRESH_FOR_SECS => Duration::from_secs(secs),
        _ => Duration::ZERO,
    }
}

// ── Backend impl ──────────────────────────────────────────────────────────────

#[cfg(not(target_arch = "wasm32"))]
#[cfg_attr(not(feature = "unsync"), async_trait)]
#[cfg_attr(feature = "unsync", async_trait(?Send))]
impl Backend for CachekitIO {
    fn attach_metrics(&self, provider: MetricsProvider) {
        // A provider supplied on the builder is already set and wins.
        self.metrics_provider.get_or_init(|| provider);
    }

    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, BackendError> {
        Ok(self.get_with_freshness(key).await?.map(|(bytes, _)| bytes))
    }

    async fn get_with_freshness(
        &self,
        key: &str,
    ) -> Result<Option<(Vec<u8>, Freshness)>, BackendError> {
        let req = self.with_standard_headers(self.client.get(self.url(key)?));

        let resp = req
            .send()
            .await
            .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;

        match resp.status().as_u16() {
            200 => {
                let freshness = freshness_from_headers(resp.headers());
                let bytes = resp
                    .bytes()
                    .await
                    .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;
                Ok(Some((Vec::from(bytes), freshness)))
            }
            404 => Ok(None),
            _ => Err(self.error_from_response(resp).await),
        }
    }

    async fn set(
        &self,
        key: &str,
        value: Vec<u8>,
        ttl: Option<Duration>,
    ) -> Result<(), BackendError> {
        let resp = self
            .put_request(key, value, ttl)?
            .timeout(WRITE_TIMEOUT)
            .send()
            .await
            .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;

        let status = resp.status().as_u16();
        if (200..300).contains(&status) {
            Ok(())
        } else {
            Err(self.error_from_response(resp).await)
        }
    }

    /// `true` on every successful delete, whether or not the key existed: the
    /// server does not report existence on `DELETE`.
    async fn delete(&self, key: &str) -> Result<bool, BackendError> {
        let req = self.with_standard_headers(self.client.delete(self.url(key)?));

        let resp = req
            .timeout(WRITE_TIMEOUT)
            .send()
            .await
            .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;

        if delete_succeeded(resp.status().as_u16()) {
            Ok(true)
        } else {
            Err(self.error_from_response(resp).await)
        }
    }

    async fn exists(&self, key: &str) -> Result<bool, BackendError> {
        let req = self.with_standard_headers(self.client.head(self.url(key)?));

        let resp = req
            .send()
            .await
            .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;

        match resp.status().as_u16() {
            200 => Ok(true),
            404 => Ok(false),
            // Through the header-aware path, so a quota-deny `429` is marked.
            _ => Err(self.error_from_response(resp).await),
        }
    }

    async fn health(&self) -> Result<HealthStatus, BackendError> {
        let start = std::time::Instant::now();

        let req = self.with_standard_headers(self.client.get(self.health_url()));

        let resp = req
            .send()
            .await
            .map_err(|e| reqwest_err_sanitized(e, self.api_key.as_str()))?;

        let latency = start.elapsed();
        let status = resp.status().as_u16();

        if (200..300).contains(&status) {
            let mut details = HashMap::new();
            details.insert("http_status".to_string(), status.to_string());
            Ok(HealthStatus {
                is_healthy: true,
                latency_ms: latency.as_secs_f64() * 1000.0,
                backend_type: "cachekitio".to_string(),
                details,
            })
        } else {
            Err(self.error_from_response(resp).await)
        }
    }

    fn as_lockable(&self) -> Option<&dyn LockableBackend> {
        Some(self)
    }
}

// ── Prebuilt headers ──────────────────────────────────────────────────────────

/// Build the per-client constant headers: `Authorization: Bearer <key>`,
/// marked sensitive as `bearer_auth` would, and the process's session headers.
/// The bearer outlives every request and each request clones it, so its buffer
/// is a zeroising owner those clones share: the last drop wipes the key.
///
/// # Errors
///
/// [`CachekitError::Config`](crate::error::CachekitError::Config) when the key
/// holds bytes an HTTP header cannot carry. The message never echoes the key.
fn static_headers(
    api_key: &str,
) -> Result<[(HeaderName, HeaderValue); 3], crate::error::CachekitError> {
    use crate::error::CachekitError;

    let mut bearer = Zeroizing::new(Vec::with_capacity("Bearer ".len() + api_key.len()));
    bearer.extend_from_slice(b"Bearer ");
    bearer.extend_from_slice(api_key.as_bytes());
    let mut auth = header_over(bearer).map_err(|_| {
        CachekitError::Config("api_key holds characters an HTTP header cannot carry".to_string())
    })?;
    auth.set_sensitive(true);

    let [(id_name, id), (start_name, start)] = session_headers();
    let header = |name: &str, value: &str| {
        Ok::<_, CachekitError>((
            HeaderName::from_bytes(name.as_bytes())
                .map_err(|e| CachekitError::Config(format!("header name {name}: {e}")))?,
            HeaderValue::from_str(value)
                .map_err(|e| CachekitError::Config(format!("header {name}: {e}")))?,
        ))
    };
    Ok([
        (reqwest::header::AUTHORIZATION, auth),
        header(id_name, id)?,
        header(start_name, start)?,
    ])
}

/// A header value over `owner`'s buffer, not a copy of it: clones share the
/// buffer, and `owner` drops with the last of them.
fn header_over<T: AsRef<[u8]> + Send + 'static>(
    owner: T,
) -> Result<HeaderValue, InvalidHeaderValue> {
    HeaderValue::from_maybe_shared(Bytes::from_owner(owner))
}

/// Parse [`METRICS_HEADER_NAMES`] once per client.
fn metrics_header_names() -> Result<[HeaderName; 5], crate::error::CachekitError> {
    let [a, b, c, d, e] = METRICS_HEADER_NAMES.map(|name| {
        HeaderName::from_bytes(name.as_bytes())
            .map_err(|e| crate::error::CachekitError::Config(format!("header name {name}: {e}")))
    });
    Ok([a?, b?, c?, d?, e?])
}

// ── Builder ───────────────────────────────────────────────────────────────────

/// `User-Agent` on every native CachekitIO request, so the service and its edge
/// can tell this SDK and version apart from other HTTP clients.
#[cfg(not(target_arch = "wasm32"))]
const USER_AGENT: &str = concat!("cachekit-rs/", env!("CARGO_PKG_VERSION"));

/// How long an idle pooled connection is kept for reuse. Cloudflare closes an
/// idle client HTTP/1.1 connection after 400 s, not configurable; reqwest's
/// 90 s default dropped connections the edge would still serve, so a request
/// after a 90-390 s gap paid DNS, TCP and TLS again. 390 s leaves a 10 s
/// margin, and reqwest's 15 s TCP keepalive keeps NAT mappings alive meanwhile.
/// Per-attempt budget for every request but a write, connect and TLS
/// included: the protocol's `CACHEKIT_TIMEOUT` default (`spec/saas-api.md`),
/// as in cachekit-py and cachekit-ts. It was 30 s, so under the retrying
/// presets a request the service accepted and never answered held a call for
/// ~90 s before it failed open.
#[cfg(not(target_arch = "wasm32"))]
const READ_TIMEOUT: Duration = Duration::from_secs(5);

/// Per-attempt budget for a write (`PUT`, `DELETE`): twice the read budget,
/// because a write carries the payload and the service commits it before it
/// answers, so a slow but healthy write must not time out and be re-sent.
#[cfg(not(target_arch = "wasm32"))]
const WRITE_TIMEOUT: Duration = Duration::from_secs(10);

/// Header on a `429` that denies a spent quota or balance rather than a rate
/// limit; such an error is never retried within the call (see
/// [`crate::error::QuotaDenied`]).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // wasm32 uses the Workers backend
const DENY_REASON_HEADER: &str = "x-cachekit-deny-reason";

#[cfg(not(target_arch = "wasm32"))]
const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(390);

/// The settings behind every native [`CachekitIO`] client, unbuilt so tests can
/// add `.no_proxy()` and reach a loopback stub whatever the proxy env says.
#[cfg(not(target_arch = "wasm32"))]
fn http_client_builder() -> reqwest::ClientBuilder {
    reqwest::Client::builder()
        .use_rustls_tls()
        .user_agent(USER_AGENT)
        .redirect(reqwest::redirect::Policy::none())
        .timeout(READ_TIMEOUT)
        .connect_timeout(READ_TIMEOUT)
        .pool_idle_timeout(POOL_IDLE_TIMEOUT)
}

/// The HTTP client every native [`CachekitIO`] uses.
#[cfg(not(target_arch = "wasm32"))]
fn http_client() -> reqwest::Result<reqwest::Client> {
    http_client_builder().build()
}

/// wasm32: the platform's `fetch` owns pooling and timeouts; no User-Agent is set.
/// It also cannot refuse redirects (reqwest's wasm32 client sets no redirect
/// mode), so `CachekitIO` must not gain a wasm32 `Backend` impl; `WorkersCachekitIO`
/// is the wasm32 backend.
#[cfg(target_arch = "wasm32")]
fn http_client() -> reqwest::Result<reqwest::Client> {
    reqwest::Client::builder().build()
}

/// Builder for [`CachekitIO`].
#[derive(Default)]
#[must_use]
pub struct CachekitIOBuilder {
    api_key: Option<Zeroizing<String>>,
    api_url: Option<String>,
    allow_custom_host: bool,
    metrics_provider: Option<MetricsProvider>,
}

impl CachekitIOBuilder {
    /// Set the API key (required).
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(Zeroizing::new(key.into()));
        self
    }

    /// Override the API base URL (default: `https://api.cachekit.io`).
    pub fn api_url(mut self, url: impl Into<String>) -> Self {
        self.api_url = Some(url.into());
        self
    }

    /// Allow non-standard hostnames (e.g. custom proxies). Private IPs are still blocked.
    pub fn allow_custom_host(mut self, allow: bool) -> Self {
        self.allow_custom_host = allow;
        self
    }

    /// Override the source of the `X-CacheKit-*` telemetry headers.
    ///
    /// Not needed for normal use: `CacheKitBuilder::build` attaches the
    /// client's own live counters to any backend without one. Set this only
    /// to report numbers from somewhere else; it takes precedence.
    pub fn metrics_provider(mut self, provider: MetricsProvider) -> Self {
        self.metrics_provider = Some(provider);
        self
    }

    /// Consume the builder and construct a [`CachekitIO`].
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `api_key` was not set, or holds bytes an HTTP header cannot carry
    ///   (a control character such as a newline).
    /// - the resolved URL scheme is not `https`, or the URL carries a query or
    ///   a fragment.
    /// - the URL carries credentials, or its hostname is not permitted (see
    ///   [`validate_cachekitio_url`](crate::url_validator::validate_cachekitio_url)).
    pub fn build(self) -> Result<CachekitIO, crate::error::CachekitError> {
        use crate::error::CachekitError;

        let api_key = self
            .api_key
            .filter(|k| !k.is_empty())
            .ok_or_else(|| CachekitError::Config("api_key is required".to_string()))?;

        let api_url = self
            .api_url
            .unwrap_or_else(|| "https://api.cachekit.io".to_string());

        let api_url = cachekitio_base_url(&api_url, self.allow_custom_host)?;

        let client = http_client()
            .map_err(|e| CachekitError::Config(format!("failed to build HTTP client: {e}")))?;

        let static_headers = static_headers(&api_key)?;
        let metrics_header_names = metrics_header_names()?;

        Ok(CachekitIO {
            client,
            api_key,
            api_url,
            static_headers,
            metrics_header_names,
            metrics_provider: self
                .metrics_provider
                .map_or_else(OnceLock::new, OnceLock::from),
        })
    }
}

// ── Freshness-header parsing tests ───────────────────────────────────────────

#[cfg(all(test, not(target_arch = "wasm32")))]
#[allow(clippy::expect_used)] // test-only: a malformed fixture header should panic loudly
mod freshness_header_tests {
    use std::time::Duration;

    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};

    use super::freshness_from_headers;

    /// Build a header map with the wire's mixed-case names; `append` keeps
    /// repeats, as a proxy that duplicates a header would.
    fn headers(pairs: &[(&str, &[u8])]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.append(
                HeaderName::from_bytes(name.as_bytes()).expect("valid header name"),
                HeaderValue::from_bytes(value).expect("valid header value"),
            );
        }
        map
    }

    fn label(values: &[&[u8]]) -> bool {
        let pairs: Vec<_> = values
            .iter()
            .map(|v| ("X-CacheKit-Freshness", *v))
            .collect();
        freshness_from_headers(&headers(&pairs)).is_stale
    }

    fn fresh_for(values: &[&[u8]]) -> Option<Duration> {
        let pairs: Vec<_> = values
            .iter()
            .map(|v| ("X-CacheKit-Fresh-For", *v))
            .collect();
        freshness_from_headers(&headers(&pairs)).fresh_for
    }

    // ── Protocol vectors ─────────────────────────────────────────────────────
    //
    // `tests/vectors/freshness-headers.json`, vendored verbatim from
    // cachekit-io/protocol `test-vectors/freshness-headers.json` 1.0.0 (merge
    // commit `f35635445a6a7461f93061aa51332e4f0d25c614`). Do not edit the JSON
    // here; change it upstream and re-vendor, then update `FIXTURE_SHA256`.

    const FIXTURE: &str = include_str!("../../tests/vectors/freshness-headers.json");

    /// sha256 of the vendored file, pinned so a local edit cannot drift from the
    /// protocol copy unnoticed.
    const FIXTURE_SHA256: &str = "74beb975b6855f52d9dd453279873faf8048a9c3c79a8167cfda099beec5fcd3"; // pragma: allowlist secret

    /// One fixture row. `deny_unknown_fields` makes a new row field upstream
    /// fail loudly here rather than be silently ignored.
    #[derive(serde::Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Row<T> {
        name: String,
        value: Option<String>,
        #[serde(alias = "stale", alias = "fresh_for")]
        expected: T,
        #[serde(rename = "note")]
        _note: String,
    }

    #[derive(serde::Deserialize)]
    struct Fixture {
        freshness_vectors: Vec<Row<bool>>,
        fresh_for_vectors: Vec<Row<Option<u64>>>,
    }

    /// The headers a `GET 200` carries for one row: none when `value` is null,
    /// otherwise one field line whose bytes are the value's characters, each
    /// U+0000..=U+00FF standing for one byte (the fixture's contract).
    fn row_headers(name: &str, value: Option<&str>) -> HeaderMap {
        let Some(value) = value else {
            return HeaderMap::new();
        };
        let bytes: Vec<u8> = value
            .chars()
            .map(|c| u8::try_from(u32::from(c)).expect("fixture value char above U+00FF"))
            .collect();
        headers(&[(name, &bytes)])
    }

    fn fixture() -> Fixture {
        serde_json::from_str(FIXTURE)
            .expect("vendored freshness-headers.json must match the fixture schema")
    }

    #[test]
    fn vendored_fixture_matches_the_pinned_sha256() {
        use sha2::{Digest, Sha256};
        assert_eq!(
            hex::encode(Sha256::digest(FIXTURE.as_bytes())),
            FIXTURE_SHA256,
            "tests/vectors/freshness-headers.json differs from the pinned protocol copy: \
             re-vendor it from protocol and update FIXTURE_SHA256"
        );
    }

    #[test]
    fn fixture_freshness_rows_classify_as_specified() {
        let rows = fixture().freshness_vectors;
        assert!(!rows.is_empty(), "fixture has no freshness rows");
        for row in &rows {
            let map = row_headers("X-CacheKit-Freshness", row.value.as_deref());
            assert_eq!(
                freshness_from_headers(&map).is_stale,
                row.expected,
                "row {}",
                row.name
            );
        }
    }

    #[test]
    fn fixture_fresh_for_rows_read_as_specified() {
        let rows = fixture().fresh_for_vectors;
        assert!(!rows.is_empty(), "fixture has no fresh_for rows");
        for row in &rows {
            let map = row_headers("X-CacheKit-Fresh-For", row.value.as_deref());
            assert_eq!(
                freshness_from_headers(&map).fresh_for,
                row.expected.map(Duration::from_secs),
                "row {}",
                row.name
            );
        }
    }

    // ── rs-local cases the fixture cannot carry ──────────────────────────────
    //
    // The fixture's rows are one field line each, and none starts or ends with
    // white space (stacks differ on it). reqwest keeps both repeated lines and
    // edge white space, so rs pins its own reading of them here.

    #[test]
    fn repeated_lines_are_fresh_only_when_every_copy_is_fresh() {
        assert!(!label(&[b"fresh", b"fresh"]));
        assert!(label(&[b"fresh", b"stale"]));
        assert_eq!(
            fresh_for(&[b"10", b"10"]),
            Some(Duration::ZERO),
            "a repeated bound counts as 0"
        );
    }

    #[test]
    fn edge_white_space_is_not_stripped() {
        assert!(label(&[b"fresh "]), "`fresh ` must read as stale");
        assert_eq!(
            fresh_for(&[b" 5"]),
            Some(Duration::ZERO),
            "` 5` must count as 0"
        );
    }
}

// ── Telemetry-header wiring tests ─────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::expect_used)] // test-only: a builder failure on a fixture should panic loudly
mod metrics_wiring_tests {
    use std::sync::Arc;

    use super::CachekitIO;
    use crate::backend::Backend;
    use crate::metrics::{metrics_headers, L1Stats, MetricsProvider};

    fn provider(l1_hits: u64) -> MetricsProvider {
        Arc::new(move || {
            Some(L1Stats {
                l1_hits,
                l2_hits: 0,
                misses: 0,
                l1_enabled: true,
            })
        })
    }

    fn l1_hits_header(backend: &CachekitIO) -> Option<String> {
        metrics_headers(backend.metrics_provider.get())
            .into_iter()
            .find(|h| h.0 == "X-CacheKit-L1-Hits")
            .map(|h| h.1)
    }

    #[test]
    fn attach_fills_an_unset_provider() {
        let backend = CachekitIO::builder()
            .api_key("ck_test_key")
            .build()
            .expect("builder succeeds");
        assert_eq!(l1_hits_header(&backend), None, "nothing attached yet");

        backend.attach_metrics(provider(7));
        assert_eq!(l1_hits_header(&backend).as_deref(), Some("7"));
    }

    #[test]
    fn builder_provider_is_retained_over_attach() {
        let backend = CachekitIO::builder()
            .api_key("ck_test_key")
            .metrics_provider(provider(1))
            .build()
            .expect("builder succeeds");

        backend.attach_metrics(provider(99));
        assert_eq!(
            l1_hits_header(&backend).as_deref(),
            Some("1"),
            "user-supplied provider wins"
        );
    }
}

// ── Cache-key path encoding tests (CWE-22) ────────────────────────────────────

#[cfg(test)]
#[allow(clippy::expect_used)] // test-only: a builder/parse failure on a fixture should panic loudly
mod path_encoding_tests {
    use super::CachekitIO;
    use crate::backend::path_encoding_vectors::{reject_keys, transmittable, RS_NEAR_MISSES};
    use url::Url;

    const API: &str = "https://api.cachekit.io";

    fn backend() -> CachekitIO {
        CachekitIO::builder()
            .api_url(API)
            .api_key("ck_test_key")
            .build()
            .expect("builder should succeed for the canonical host")
    }

    /// Repro. Before any guard, a raw-encoded `.`/`..` key collapses in
    /// rust-url (the parser `reqwest` uses) *before* the request leaves the
    /// process: the segment is stripped and the path escapes `/v1/cache/`.
    /// `%2E%2E` collapses identically, which is why the fix rejects rather than
    /// re-encodes (WHATWG treats `%2e%2e` as a dot-segment too).
    #[test]
    fn repro_raw_dot_key_escapes_the_cache_prefix() {
        let cases = [
            ("..", "", "/v1/"),
            ("..", "/ttl", "/v1/ttl"),
            ("..", "/lock", "/v1/lock"),
            (".", "", "/v1/cache/"),
        ];
        for (key, suffix, escaped) in cases {
            let raw = format!("{API}/v1/cache/{}{suffix}", urlencoding::encode(key));
            let parsed = Url::parse(&raw).expect("parses");
            assert_eq!(
                parsed.path(),
                escaped,
                "raw {key:?}{suffix} should collapse to {escaped}"
            );
            // The %2E form the Python SDK emits collapses just the same in rust-url.
            let pct = key.replace('.', "%2E");
            let enc = format!("{API}/v1/cache/{pct}{suffix}");
            assert_eq!(
                Url::parse(&enc).expect("parses").path(),
                escaped,
                "%2E-encoded {key:?}{suffix} also collapses — encoding cannot fix this in rust-url"
            );
        }
    }

    /// Spec rule 2 — every fixture reject row (the empty key, `.`, `..`,
    /// `health`, `ttl`, `lock`) is rejected by every builder (base, ttl, lock):
    /// no URL is produced, so no rewritten or mis-routed request can be sent.
    #[test]
    fn reserved_segments_rejected_by_every_builder() {
        let b = backend();
        let keys = reject_keys();
        assert!(!keys.is_empty(), "fixture has no reject rows");
        for key in &keys {
            assert!(b.url(key).is_err(), "url({key:?}) must be rejected");
            assert!(b.ttl_url(key).is_err(), "ttl_url({key:?}) must be rejected");
            assert!(
                b.lock_url(key).is_err(),
                "lock_url({key:?}) must be rejected"
            );
        }
    }

    /// Every transmittable fixture row, plus the rs near-misses, builds a URL
    /// whose *parsed* path (the real wire path, post-normalisation) stays inside
    /// `/v1/cache/`. Asserting on the unparsed `format!` output would pass while
    /// still shipping a traversal, so we parse with the same `url` crate
    /// `reqwest` uses.
    #[test]
    fn safe_keys_never_escape_the_cache_prefix() {
        let b = backend();
        let fixture_keys: Vec<String> = transmittable().into_iter().map(|v| v.key).collect();
        let vectors = fixture_keys
            .iter()
            .map(String::as_str)
            .chain(RS_NEAR_MISSES.iter().copied());
        for key in vectors {
            let base = Url::parse(&b.url(key).expect("url")).expect("parse base");
            let ttl = Url::parse(&b.ttl_url(key).expect("ttl_url")).expect("parse ttl");
            let lock = Url::parse(&b.lock_url(key).expect("lock_url")).expect("parse lock");

            assert!(
                base.path().starts_with("/v1/cache/") && base.path().len() > "/v1/cache/".len(),
                "base path {} escaped prefix for {key:?}",
                base.path()
            );
            assert_eq!(
                base.path(),
                format!("/v1/cache/{}", urlencoding::encode(key)),
                "base wire path mismatch for {key:?}"
            );
            assert!(
                ttl.path().starts_with("/v1/cache/") && ttl.path().ends_with("/ttl"),
                "ttl path {} escaped prefix for {key:?}",
                ttl.path()
            );
            assert!(
                lock.path().starts_with("/v1/cache/") && lock.path().ends_with("/lock"),
                "lock path {} escaped prefix for {key:?}",
                lock.path()
            );
        }
    }
}

// ── PUT TTL header tests ──────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::expect_used)] // test-only: a builder failure on a fixture should panic loudly
mod put_ttl_header_tests {
    use std::time::Duration;

    use super::CachekitIO;

    fn put(ttl: Option<Duration>) -> reqwest::Request {
        CachekitIO::builder()
            .api_key("ck_test_key")
            .build()
            .expect("builder succeeds")
            .put_request("k", b"v".to_vec(), ttl)
            .expect("key encodes")
            .build()
            .expect("request builds")
    }

    #[test]
    fn put_sends_x_cachekit_ttl_and_no_legacy_x_ttl() {
        let req = put(Some(Duration::from_secs(300)));
        assert_eq!(
            req.headers()
                .get("X-CacheKit-TTL")
                .and_then(|v| v.to_str().ok()),
            Some("300")
        );
        assert!(req.headers().get("X-TTL").is_none(), "legacy header sent");
    }

    #[test]
    fn put_without_ttl_sends_no_ttl_header() {
        let req = put(None);
        assert!(req.headers().get("X-CacheKit-TTL").is_none());
        assert!(req.headers().get("X-TTL").is_none());
    }
}

// ── Prebuilt header tests ─────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::expect_used)] // test-only: a builder failure on a fixture should panic loudly
mod prebuilt_header_tests {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    use super::{header_over, CachekitIO};
    use crate::metrics::{metrics_headers, L1Stats, MetricsProvider};
    use crate::session::session_headers;

    const KEY: &str = "ck_live_prebuilt_secret";

    fn put(provider: Option<MetricsProvider>) -> reqwest::Request {
        let mut builder = CachekitIO::builder().api_key(KEY);
        if let Some(provider) = provider {
            builder = builder.metrics_provider(provider);
        }
        builder
            .build()
            .expect("builder succeeds")
            .put_request("k", b"v".to_vec(), None)
            .expect("key encodes")
            .build()
            .expect("request builds")
    }

    #[test]
    fn bearer_is_sent_and_redacted_from_debug() {
        let req = put(None);
        let auth = req
            .headers()
            .get(reqwest::header::AUTHORIZATION)
            .expect("authorization header");
        assert_eq!(auth.as_bytes(), format!("Bearer {KEY}").as_bytes());
        assert!(auth.is_sensitive(), "prebuilt bearer must be sensitive");
        let debug = format!("{req:?}");
        assert!(!debug.contains(KEY), "api key leaked into Debug: {debug}");
    }

    /// The bearer's zeroising owner is the header's buffer, not a copy of it:
    /// clones share it, and it drops (wiping the key) only with the last one.
    #[test]
    fn header_clones_share_the_owner_until_the_last_drops() {
        struct Owner(Vec<u8>, Arc<AtomicBool>);
        impl AsRef<[u8]> for Owner {
            fn as_ref(&self) -> &[u8] {
                &self.0
            }
        }
        impl Drop for Owner {
            fn drop(&mut self) {
                self.1.store(true, Ordering::SeqCst);
            }
        }

        let dropped = Arc::new(AtomicBool::new(false));
        let header = header_over(Owner(b"Bearer k".to_vec(), Arc::clone(&dropped))).expect("valid");
        let clone = header.clone();
        drop(header);
        assert!(
            !dropped.load(Ordering::SeqCst),
            "owner dropped while a clone lives"
        );
        assert_eq!(clone.as_bytes(), b"Bearer k");
        drop(clone);
        assert!(
            dropped.load(Ordering::SeqCst),
            "owner outlived its last clone"
        );
    }

    #[test]
    fn a_key_no_header_can_carry_fails_build_without_echoing_it() {
        let err = CachekitIO::builder()
            .api_key("ck_bad\nkey")
            .build()
            .expect_err("newline in key");
        assert!(!err.to_string().contains("ck_bad"), "{err}");
    }

    #[test]
    fn requests_go_to_the_validated_url_as_serialized() {
        let backend = CachekitIO::builder()
            .api_key("ck_test_key")
            .api_url("https://api.cachekit.io\\@evil.example")
            .build()
            .expect("allowlisted host");
        assert_eq!(backend.api_url(), "https://api.cachekit.io/@evil.example");
    }

    /// The prebuilt headers carry the same names and values the string
    /// builders produce (header names compare case-insensitively).
    #[test]
    fn session_and_metrics_headers_match_their_string_builders() {
        let provider: MetricsProvider = Arc::new(|| {
            Some(L1Stats {
                l1_hits: 3,
                l2_hits: 2,
                misses: 5,
                l1_enabled: true,
            })
        });
        let req = put(Some(provider.clone()));
        let expected = session_headers()
            .into_iter()
            .map(|(n, v)| (n, v.to_string()))
            .chain(metrics_headers(Some(&provider)));
        let mut count = 0;
        for (name, value) in expected {
            let got = req.headers().get_all(name).iter().collect::<Vec<_>>();
            assert_eq!(got.len(), 1, "{name} sent {} times", got.len());
            assert_eq!(got[0].as_bytes(), value.as_bytes(), "{name}");
            count += 1;
        }
        assert_eq!(count, 7);
    }

    #[test]
    fn disabled_metrics_send_only_the_status_header() {
        let req = put(None);
        assert_eq!(
            req.headers()
                .get("X-CacheKit-L1-Status")
                .map(|v| v.as_bytes()),
            Some(&b"disabled"[..])
        );
        assert!(req.headers().get("X-CacheKit-L1-Hits").is_none());
    }
}

// ── HTTP client settings tests ────────────────────────────────────────────────

#[cfg(all(test, not(target_arch = "wasm32")))]
#[allow(clippy::expect_used)] // test-only: a stub-server failure should panic loudly
mod http_client_tests {
    use std::io::{BufRead, BufReader, Read, Write};
    use std::net::TcpListener;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    use super::{http_client_builder, CachekitIO, READ_TIMEOUT, WRITE_TIMEOUT};
    use crate::backend::Backend;
    use crate::error::BackendErrorKind;

    /// The production client minus the system proxy: an `HTTP_PROXY` or
    /// `ALL_PROXY` that does not exempt loopback would otherwise take the
    /// stub's requests.
    fn client() -> reqwest::Client {
        http_client_builder()
            .no_proxy()
            .build()
            .expect("client builds")
    }

    /// A keep-alive HTTP/1.1 stub on loopback: answers every request `200`,
    /// records each request's header lines and body, and counts accepted
    /// connections.
    struct Stub {
        url: String,
        connections: Arc<Mutex<usize>>,
        requests: Arc<Mutex<Vec<Vec<String>>>>,
        bodies: Arc<Mutex<Vec<Vec<u8>>>>,
    }

    const OK: &[u8] = b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n";

    fn stub() -> Stub {
        stub_with(|_| Some(OK))
    }

    /// [`stub`], but `answer(n)` gives the reply to the stub's `n`th request
    /// (from 0); `None` reads the request and never answers it.
    fn stub_with(answer: fn(usize) -> Option<&'static [u8]>) -> Stub {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind stub");
        let url = format!("http://{}/", listener.local_addr().expect("addr"));
        let connections = Arc::new(Mutex::new(0));
        let requests = Arc::new(Mutex::new(Vec::new()));
        let bodies = Arc::new(Mutex::new(Vec::new()));
        let (conns, reqs, bods) = (connections.clone(), requests.clone(), bodies.clone());
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { return };
                *conns.lock().expect("lock") += 1;
                let (reqs, bods) = (reqs.clone(), bods.clone());
                std::thread::spawn(move || {
                    let mut reader = BufReader::new(stream.try_clone().expect("clone"));
                    loop {
                        let mut head = Vec::new();
                        loop {
                            let mut line = String::new();
                            if reader.read_line(&mut line).unwrap_or(0) == 0 {
                                return;
                            }
                            if line == "\r\n" {
                                break;
                            }
                            head.push(line.trim_end().to_owned());
                        }
                        let len = head
                            .iter()
                            .find_map(|h| {
                                let (name, value) = h.split_once(':')?;
                                name.eq_ignore_ascii_case("content-length")
                                    .then(|| value.trim().parse::<usize>().ok())?
                            })
                            .unwrap_or(0);
                        let mut body = vec![0; len];
                        if reader.read_exact(&mut body).is_err() {
                            return;
                        }
                        bods.lock().expect("lock").push(body);
                        let n = {
                            let mut reqs = reqs.lock().expect("lock");
                            reqs.push(head);
                            reqs.len() - 1
                        };
                        let Some(reply) = answer(n) else {
                            // Hold the connection open, unanswered, for good.
                            loop {
                                std::thread::park();
                            }
                        };
                        if stream.write_all(reply).is_err() {
                            return;
                        }
                    }
                });
            }
        });
        Stub {
            url,
            connections,
            requests,
            bodies,
        }
    }

    /// Connections the stub accepted for two GETs `idle` apart, on the
    /// tokio clock reqwest's pool reads.
    async fn connections_after_idle(idle: Duration) -> usize {
        let stub = stub();
        let client = client();
        client.get(&stub.url).send().await.expect("first GET");
        tokio::time::pause();
        tokio::time::advance(idle).await;
        tokio::time::resume();
        client.get(&stub.url).send().await.expect("second GET");
        let n = *stub.connections.lock().expect("lock");
        n
    }

    #[tokio::test]
    async fn refresh_ttl_sends_a_sub_second_ttl_as_one() {
        use crate::backend::TtlInspectable;
        let stub = stub();
        let backend = backend_at(&stub);

        let refreshed = backend
            .refresh_ttl("k", Duration::from_millis(500))
            .await
            .expect("a sub-second TTL is sent, not rejected");

        assert!(refreshed);
        let requests = stub.requests.lock().expect("lock");
        let head = &requests[0];
        assert!(head[0].starts_with("PATCH /v1/cache/k/ttl "), "{head:?}");
        assert_eq!(stub.bodies.lock().expect("lock")[0], br#"{"ttl":1}"#);
    }

    #[tokio::test]
    async fn refresh_ttl_rejects_zero_before_sending() {
        use crate::backend::TtlInspectable;
        let stub = stub();
        let backend = backend_at(&stub);

        let err = backend
            .refresh_ttl("k", Duration::ZERO)
            .await
            .expect_err("TTL 0 is an error");

        assert_eq!(err.kind, BackendErrorKind::Permanent);
        assert!(stub.requests.lock().expect("lock").is_empty());
    }

    #[tokio::test]
    async fn sends_cachekit_rs_user_agent() {
        let stub = stub();
        client().get(&stub.url).send().await.expect("GET");
        let want = format!("user-agent: cachekit-rs/{}", env!("CARGO_PKG_VERSION"));
        let requests = stub.requests.lock().expect("lock");
        assert!(
            requests[0].iter().any(|h| h.eq_ignore_ascii_case(&want)),
            "no `{want}` in {:?}",
            requests[0]
        );
    }

    #[tokio::test]
    async fn reuses_a_connection_idle_389_s() {
        assert_eq!(connections_after_idle(Duration::from_secs(389)).await, 1);
    }

    #[tokio::test]
    async fn redials_a_connection_idle_past_390_s() {
        assert_eq!(connections_after_idle(Duration::from_secs(391)).await, 2);
    }

    /// A production [`CachekitIO`] aimed at `stub` over plain HTTP: the
    /// builder only accepts `https`, so the test swaps the client and URL.
    fn backend_at(stub: &Stub) -> CachekitIO {
        let mut backend = CachekitIO::builder()
            .api_key("ck_test_key")
            .build()
            .expect("builder succeeds for the default host");
        backend.client = client();
        backend.api_url = stub.url.trim_end_matches('/').to_owned();
        backend
    }

    /// How long `op` takes on the tokio clock, paused once the stub's first
    /// request has opened the pooled connection: an unanswered request then
    /// advances virtual time straight to whichever timer fires first.
    async fn paused_elapsed<T>(op: impl std::future::Future<Output = T>) -> (T, Duration) {
        tokio::time::pause();
        let start = tokio::time::Instant::now();
        let out = op.await;
        let elapsed = start.elapsed();
        tokio::time::resume();
        (out, elapsed)
    }

    /// `elapsed` is `budget`, give or take the tokio timer's 1 ms resolution.
    fn assert_budget(elapsed: Duration, budget: Duration) {
        assert!(
            elapsed >= budget && elapsed <= budget + Duration::from_millis(2),
            "took {elapsed:?}, budget {budget:?}"
        );
    }

    /// The stub's request count once it reaches `at_least`, or after 2 s.
    ///
    /// The stub records a request on its own thread; a stalled request may
    /// time out on the paused clock before that thread has read it.
    #[cfg(feature = "reliability")]
    fn recorded(stub: &Stub, at_least: usize) -> usize {
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        loop {
            let n = stub.requests.lock().expect("lock").len();
            if n >= at_least || std::time::Instant::now() >= deadline {
                return n;
            }
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    /// Answers the first request (to pool a connection), stalls every later one.
    fn first_only(n: usize) -> Option<&'static [u8]> {
        (n == 0).then_some(OK)
    }

    #[tokio::test]
    async fn an_unanswered_read_times_out_after_5_s() {
        let stub = stub_with(first_only);
        let backend = backend_at(&stub);
        backend
            .exists("warm")
            .await
            .expect("first request pools a connection");

        let (result, elapsed) = paused_elapsed(backend.get("k")).await;

        let err = result.expect_err("an unanswered GET times out");
        assert_eq!(err.kind, BackendErrorKind::Timeout);
        assert_budget(elapsed, READ_TIMEOUT);
    }

    #[tokio::test]
    async fn an_unanswered_write_times_out_after_10_s() {
        let stub = stub_with(first_only);
        let backend = backend_at(&stub);
        backend
            .exists("warm")
            .await
            .expect("first request pools a connection");

        let (result, elapsed) = paused_elapsed(backend.set("k", b"v".to_vec(), None)).await;

        let err = result.expect_err("an unanswered PUT times out");
        assert_eq!(err.kind, BackendErrorKind::Timeout);
        assert_budget(elapsed, WRITE_TIMEOUT);
    }

    #[cfg(feature = "reliability")]
    mod through_the_reliability_stack {
        use super::*;
        use crate::client::SharedBackend;
        use crate::reliability::{
            wrap_reliable, ReliabilityConfig, RetryConfig, CACHEKITIO_DEADLINES,
        };

        /// The default stack with jitter off, so virtual time is exact.
        fn reliable(backend: CachekitIO) -> SharedBackend {
            reliable_with_breaker(backend).0
        }

        fn reliable_with_breaker(
            backend: CachekitIO,
        ) -> (
            SharedBackend,
            Option<Arc<crate::reliability::CircuitBreaker>>,
        ) {
            #[cfg(not(feature = "unsync"))]
            let shared: SharedBackend = Arc::new(backend);
            #[cfg(feature = "unsync")]
            let shared: SharedBackend = std::rc::Rc::new(backend);
            let config = ReliabilityConfig {
                retry: Some(RetryConfig {
                    jitter: false,
                    ..RetryConfig::default()
                }),
                ..ReliabilityConfig::default()
            };
            wrap_reliable(shared, config, Some(CACHEKITIO_DEADLINES))
        }

        const QUOTA_DENY: &[u8] = b"HTTP/1.1 429 Too Many Requests\r\n\
            x-cachekit-deny-reason: quota\r\ncontent-length: 0\r\n\r\n";
        const RATE_LIMITED: &[u8] = b"HTTP/1.1 429 Too Many Requests\r\n\
            retry-after: 1\r\ncontent-length: 0\r\n\r\n";

        /// Was 3 x 30 s + backoff = 90.3 s and 3 requests.
        #[tokio::test]
        async fn an_unanswered_get_costs_one_attempt_and_5_s() {
            let stub = stub_with(first_only);
            let backend = reliable(backend_at(&stub));
            backend
                .exists("warm")
                .await
                .expect("first request pools a connection");

            let (result, elapsed) = paused_elapsed(backend.get("k")).await;

            assert_eq!(result.expect_err("stalled").kind, BackendErrorKind::Timeout);
            assert_budget(elapsed, Duration::from_secs(5));
            assert_eq!(recorded(&stub, 2), 2, "warm-up + one GET");
        }

        #[tokio::test]
        async fn a_quota_denied_exists_is_sent_once() {
            let stub = stub_with(|_| Some(QUOTA_DENY));
            let backend = reliable(backend_at(&stub));

            let err = backend.exists("k").await.expect_err("denied");

            assert_eq!(err.kind, BackendErrorKind::Transient);
            assert!(err.is_quota_denied());
            assert_eq!(recorded(&stub, 1), 1, "no in-call retry");
        }

        #[tokio::test]
        async fn a_quota_deny_is_sent_once_and_stays_transient() {
            let stub = stub_with(|_| Some(QUOTA_DENY));
            let backend = reliable(backend_at(&stub));

            let err = backend.get("k").await.expect_err("denied");

            assert_eq!(
                err.kind,
                BackendErrorKind::Transient,
                "fails open, counts toward the breaker"
            );
            assert!(err.is_quota_denied());
            assert_eq!(
                stub.requests.lock().expect("lock").len(),
                1,
                "no in-call retry"
            );
        }

        #[tokio::test]
        async fn quota_denies_still_open_the_breaker() {
            let stub = stub_with(|_| Some(QUOTA_DENY));
            let (backend, breaker) = reliable_with_breaker(backend_at(&stub));

            for _ in 0..5 {
                backend.get("k").await.expect_err("denied");
            }

            let breaker = breaker.expect("default stack has a breaker");
            assert_eq!(breaker.state(), crate::reliability::CircuitState::Open);
            assert_eq!(
                stub.requests.lock().expect("lock").len(),
                5,
                "one request per op"
            );
        }

        #[tokio::test]
        async fn a_rate_limit_429_still_retries() {
            let stub = stub_with(|_| Some(RATE_LIMITED));
            let backend = reliable(backend_at(&stub));

            let err = backend.get("k").await.expect_err("rate limited");

            assert_eq!(err.kind, BackendErrorKind::Transient);
            assert!(!err.is_quota_denied());
            assert_eq!(
                stub.requests.lock().expect("lock").len(),
                3,
                "every attempt is sent"
            );
        }
    }
}