rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
//! Network utilities for the proxy server.
//!
//! This module provides network-related functionality including
//! creating TCP listeners with SO_REUSEPORT for multi-worker setups and
//! applying per-connection socket tuning (TCP_NODELAY) to accepted streams.

use socket2::{Domain, Protocol, Socket, Type};
use std::net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6};
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
use tracing::warn;

/// Default listen backlog; overridable via `RIFT_TCP_BACKLOG`.
const DEFAULT_BACKLOG: i32 = 1024;

/// Default `hyper`/`hyper-util` connection buffer cap; overridable via `RIFT_HTTP_MAX_BUF`.
/// Hyper's own default is ~400KB, sized for arbitrary internet traffic; mock/proxy requests are
/// small and numerous, so a 64KB ceiling bounds per-connection memory without touching normal
/// traffic.
pub const DEFAULT_HTTP_MAX_BUF: usize = 64 * 1024;

/// Default HTTP/1 header-read timeout (slowloris hygiene); overridable via
/// `RIFT_HTTP_HEADER_TIMEOUT` (seconds).
const DEFAULT_HTTP_HEADER_TIMEOUT: Duration = Duration::from_secs(30);

/// `hyper`'s h1 buffer floor (`proto::h1::MINIMUM_MAX_BUFFER_SIZE`, currently 8KB). It isn't part
/// of hyper's public API, so it's mirrored here as a guard: `http1::Builder::max_buf_size` (and
/// the `auto::Builder` equivalent) panics if handed anything smaller. Enforced only in `parse` so
/// a bogus/too-small env value degrades to the default instead of crashing the server.
const HYPER_H1_MIN_MAX_BUF: usize = 8192;

/// HTTP connection-builder tuning knobs (issue #716): the hyper/hyper-util `serve_connection`
/// builders otherwise run on hyper's own defaults (a ~400KB buffer, no header-read timeout, and
/// no cap on concurrent connections).
///
/// Populated from the environment ([`HttpTuning::from_env`]) once per listener setup, mirroring
/// [`SocketTuning`] — not read per accepted connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HttpTuning {
    /// Cap on the connection's internal read/write buffer (`Builder::max_buf_size`).
    pub max_buf_size: usize,
    /// How long to wait for a client to finish sending request headers before closing the
    /// connection (`Builder::header_read_timeout`) — mitigates slowloris-style stalls.
    pub header_read_timeout: Duration,
    /// Cap on concurrently accepted connections. `None` (the default) preserves today's
    /// behavior: unlimited, accept-as-fast-as-the-kernel-hands-them-over.
    pub max_connections: Option<usize>,
}

/// Why a tuning value that was *present* could not be used (issue #1009).
///
/// An enum rather than a string so each case is asserted exactly in tests, and so the rendered
/// wording lives in one place — the operator reading the log needs the bound, not "unparsable".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FallbackReason {
    /// Not a number at all — a suffix (`1MB`), a typo, or an empty value.
    NotANumber,
    /// A number, but under the floor hyper requires.
    BelowMinimum,
    /// A number, but zero or negative where the knob needs a positive one.
    NotPositive,
    /// Not one of the accepted boolean spellings.
    UnrecognizedBoolean,
}

impl std::fmt::Display for FallbackReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotANumber => f.write_str("not a number"),
            Self::BelowMinimum => write!(
                f,
                "below the {HYPER_H1_MIN_MAX_BUF}-byte minimum hyper requires"
            ),
            Self::NotPositive => f.write_str("must be greater than zero"),
            Self::UnrecognizedBoolean => {
                f.write_str("not a recognized boolean (true/1/on or false/0/off)")
            }
        }
    }
}

/// One environment value that was set but had to be ignored.
///
/// Returned from the pure parsers rather than logged by them: `parse` stays env-free and
/// side-effect-free (its existing design goal), and the tests can assert on what *would* be
/// warned without capturing a tracing subscriber.
#[derive(Debug, Clone, PartialEq, Eq)]
struct TuningFallback {
    var: &'static str,
    value: String,
    reason: FallbackReason,
}

impl TuningFallback {
    fn new(var: &'static str, value: &str, reason: FallbackReason) -> Self {
        Self {
            var,
            value: value.to_string(),
            reason,
        }
    }
}

/// Emit one `warn` per ignored value.
///
/// Deliberately not gated by a `Once`: this fires only when a value is actually unusable, and a
/// line per listener start sits next to that listener's own startup output where an operator will
/// connect it to the right process.
fn warn_fallbacks(fallbacks: &[TuningFallback]) {
    for f in fallbacks {
        warn!(
            var = f.var,
            value = %f.value,
            reason = %f.reason,
            "ignoring unusable tuning value; using the default instead"
        );
    }
}

/// Parse a number, recording *why* it was unusable rather than collapsing every failure into a
/// silent default. An unset value is the domain-optional case and reports nothing.
fn parse_number<T>(
    var: &'static str,
    raw: Option<&str>,
    accept: impl Fn(&T) -> bool,
    rejected: FallbackReason,
    out: &mut Vec<TuningFallback>,
) -> Option<T>
where
    T: std::str::FromStr,
{
    let trimmed = raw?.trim();
    match trimmed.parse::<T>() {
        Ok(v) if accept(&v) => Some(v),
        Ok(_) => {
            out.push(TuningFallback::new(var, trimmed, rejected));
            None
        }
        Err(_) => {
            out.push(TuningFallback::new(
                var,
                trimmed,
                FallbackReason::NotANumber,
            ));
            None
        }
    }
}

impl Default for HttpTuning {
    fn default() -> Self {
        Self {
            max_buf_size: DEFAULT_HTTP_MAX_BUF,
            header_read_timeout: DEFAULT_HTTP_HEADER_TIMEOUT,
            max_connections: None,
        }
    }
}

impl HttpTuning {
    /// Read tuning from the environment: `RIFT_HTTP_MAX_BUF` (bytes), `RIFT_HTTP_HEADER_TIMEOUT`
    /// (seconds), and `RIFT_MAX_CONNECTIONS` (connection count, opt-in).
    ///
    /// An **unset** variable falls back to [`HttpTuning::default`] silently — expressing no
    /// preference is not a mistake. A variable that is **set but unusable** also falls back, but
    /// warns first (issue #1009): the operator wrote something they expected to take effect, and
    /// the old silence meant the only symptom was behaviour that did not match the config.
    #[must_use]
    pub fn from_env() -> Self {
        let (tuning, fallbacks) = Self::parse(
            std::env::var("RIFT_HTTP_MAX_BUF").ok().as_deref(),
            std::env::var("RIFT_HTTP_HEADER_TIMEOUT").ok().as_deref(),
            std::env::var("RIFT_MAX_CONNECTIONS").ok().as_deref(),
        );
        warn_fallbacks(&fallbacks);
        tuning
    }

    /// Pure parser behind [`HttpTuning::from_env`] — kept env-free so it is testable without
    /// mutating process-global state, and returning its warnings rather than logging them so a
    /// test can assert on them without a tracing subscriber.
    ///
    /// The resulting values are exactly what this function produced before #1009; only the second
    /// element of the tuple is new.
    fn parse(
        max_buf: Option<&str>,
        header_timeout_secs: Option<&str>,
        max_conns: Option<&str>,
    ) -> (Self, Vec<TuningFallback>) {
        let defaults = Self::default();
        let mut fallbacks = Vec::new();

        let max_buf_size = parse_number(
            "RIFT_HTTP_MAX_BUF",
            max_buf,
            |&v: &usize| v >= HYPER_H1_MIN_MAX_BUF,
            FallbackReason::BelowMinimum,
            &mut fallbacks,
        )
        .unwrap_or(defaults.max_buf_size);

        let header_read_timeout = parse_number(
            "RIFT_HTTP_HEADER_TIMEOUT",
            header_timeout_secs,
            |&secs: &u64| secs > 0,
            FallbackReason::NotPositive,
            &mut fallbacks,
        )
        .map(Duration::from_secs)
        .unwrap_or(defaults.header_read_timeout);

        // Opt-in, and the one knob where `0` is an answer rather than a mistake: it reads as "no
        // cap", which is exactly what it gets, so it stays silent. Garbage still warns — that is
        // an operator who wanted a cap and has not got one.
        let max_connections = match max_conns.map(str::trim) {
            None => None,
            Some(raw) => match raw.parse::<usize>() {
                Ok(0) => None,
                Ok(n) => Some(n),
                Err(_) => {
                    fallbacks.push(TuningFallback::new(
                        "RIFT_MAX_CONNECTIONS",
                        raw,
                        FallbackReason::NotANumber,
                    ));
                    None
                }
            },
        };

        (
            Self {
                max_buf_size,
                header_read_timeout,
                max_connections,
            },
            fallbacks,
        )
    }
}

/// Accept-loop / socket tuning knobs.
///
/// Populated from the environment ([`SocketTuning::from_env`]) at listener
/// setup so the values are read once, not per accepted connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SocketTuning {
    /// `listen(2)` backlog for the accept queue.
    pub backlog: i32,
    /// Whether to set `TCP_NODELAY` on accepted streams (disable Nagle).
    pub nodelay: bool,
}

impl Default for SocketTuning {
    fn default() -> Self {
        Self {
            backlog: DEFAULT_BACKLOG,
            nodelay: true,
        }
    }
}

impl SocketTuning {
    /// Read tuning from the environment: `RIFT_TCP_BACKLOG` (positive integer) and
    /// `RIFT_TCP_NODELAY` (`true`/`1`/`on` enables, `false`/`0`/`off` disables).
    ///
    /// Unset falls back to [`SocketTuning::default`] silently; set-but-unusable falls back with a
    /// warning (issue #1009). `RIFT_TCP_NODELAY` is the reason that distinction matters here: any
    /// unrecognised spelling still keeps the default of *enabled*, so the typo `flase` used to
    /// leave Nagle disabled — the opposite of what was written — with nothing logged.
    #[must_use]
    pub fn from_env() -> Self {
        let (tuning, fallbacks) = Self::parse(
            std::env::var("RIFT_TCP_BACKLOG").ok().as_deref(),
            std::env::var("RIFT_TCP_NODELAY").ok().as_deref(),
        );
        warn_fallbacks(&fallbacks);
        tuning
    }

    /// Pure parser behind [`SocketTuning::from_env`] — kept env-free so it is
    /// testable without mutating process-global state.
    fn parse(backlog: Option<&str>, nodelay: Option<&str>) -> (Self, Vec<TuningFallback>) {
        let defaults = Self::default();
        let mut fallbacks = Vec::new();

        let backlog = parse_number(
            "RIFT_TCP_BACKLOG",
            backlog,
            |&b: &i32| b > 0,
            FallbackReason::NotPositive,
            &mut fallbacks,
        )
        .unwrap_or(defaults.backlog);

        // Acceptance is unchanged: the falsey set still disables, everything else still leaves the
        // default in place. What is new is that "everything else" no longer passes for an opinion.
        let nodelay = match nodelay.map(str::trim) {
            None => defaults.nodelay,
            Some(s)
                if s.eq_ignore_ascii_case("false") || s == "0" || s.eq_ignore_ascii_case("off") =>
            {
                false
            }
            Some(s)
                if s.eq_ignore_ascii_case("true") || s == "1" || s.eq_ignore_ascii_case("on") =>
            {
                true
            }
            Some(s) => {
                fallbacks.push(TuningFallback::new(
                    "RIFT_TCP_NODELAY",
                    s,
                    FallbackReason::UnrecognizedBoolean,
                ));
                defaults.nodelay
            }
        };

        (Self { backlog, nodelay }, fallbacks)
    }
}

/// A bind host as an operator writes it, on `port`, as the literal address to bind.
///
/// Accepts an IPv4 literal (`127.0.0.1`), a bare IPv6 literal (`::1` — Mountebank's spelling and the
/// one `MB_HOST` carries) and a bracketed IPv6 literal (`[::1]` — the URL-authority spelling). An
/// IPv6 literal may carry a numeric scope id (`fe80::1%2`, `[fe80::1%2]`), which link-local binds
/// need. `None` for anything else: a DNS name, or brackets around something that is not IPv6
/// (`[1.2.3.4]`). An option rather than an error so each door keeps its own refusal wording and its
/// own policy on names — the admin plane refuses them, an imposter resolves them (issue #1137).
///
/// Built from the parsed address, never by parsing `"{host}:{port}"`: that string is ambiguous for a
/// bare IPv6 host, whose port reads as one more hextet.
#[must_use]
pub fn bind_addr(host: &str, port: u16) -> Option<SocketAddr> {
    match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
        Some(inner) => ipv6_scoped(inner, port),
        None => match host.parse::<IpAddr>() {
            Ok(ip) => Some(SocketAddr::new(ip, port)),
            Err(_) => ipv6_scoped(host, port),
        },
    }
}

/// The host spelling that [`bind_addr`] reads back to `addr`'s IP **and scope** — the inverse of
/// [`bind_addr`], for the doors that carry a host as a string rather than a [`SocketAddr`]
/// (issue #1150).
///
/// `IpAddr`'s own `Display` cannot do this: the scope id lives on `SocketAddrV6`, so
/// `addr.ip().to_string()` silently yields an unscoped spelling that rebinds the wrong interface.
/// An unscoped address is spelled without a zone — never `%0` — because this string is handed to
/// callers and shows up in API responses.
///
/// Flowinfo is **not** carried: a host string has nowhere to put it. That is lossless for every
/// address [`bind_addr`] produces, since it always builds flowinfo 0 — but an address taken from a
/// bound socket's `local_addr()` can carry one, and it will not survive this round trip.
#[must_use]
pub fn bind_host(addr: &SocketAddr) -> String {
    match addr {
        SocketAddr::V6(v6) if v6.scope_id() != 0 => format!("{}%{}", v6.ip(), v6.scope_id()),
        _ => addr.ip().to_string(),
    }
}

/// `ip` or `ip%scope` (numeric scope) as an IPv6 socket address.
fn ipv6_scoped(host: &str, port: u16) -> Option<SocketAddr> {
    let (ip, scope_id) = match host.split_once('%') {
        Some((ip, scope)) => (ip, scope.parse::<u32>().ok()?),
        None => (host, 0),
    };
    let ip = ip.parse::<Ipv6Addr>().ok()?;
    Some(SocketAddr::V6(SocketAddrV6::new(ip, port, 0, scope_id)))
}

/// Create a TCP listener with SO_REUSEPORT enabled for multi-worker setup,
/// using tuning read from the environment.
///
/// This allows multiple workers to bind to the same port, enabling
/// load distribution across multiple processes.
pub fn create_reusable_listener(addr: SocketAddr) -> std::io::Result<TcpListener> {
    create_reusable_listener_tuned(addr, &SocketTuning::from_env())
}

/// Node's `listen(port)` with no host (#1514): `[::]:port`, dual-stack, else `0.0.0.0:port`. Node
/// falls back on any error from the IPv6 bind; "address in use" never reaches it, because libuv
/// defers `EADDRINUSE` to `listen()`, so here it is the caller's conflict and is returned rather
/// than retried on IPv4, which would hand `localhost` clients to the holder.
///
/// `bind` is the socket builder to use, so imposters ([`create_reusable_listener`]) and the server
/// listeners ([`bind_server_listener`], issue #1528) share the one fallback rule.
pub fn bind_unspecified<T>(
    port: u16,
    mut bind: impl FnMut(SocketAddr) -> std::io::Result<T>,
) -> std::io::Result<T> {
    match bind(SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, port))) {
        Err(e) if e.kind() != std::io::ErrorKind::AddrInUse => {
            tracing::debug!("no dual-stack [::]:{port} ({e}); binding 0.0.0.0:{port}");
            bind(SocketAddr::from((std::net::Ipv4Addr::UNSPECIFIED, port)))
        }
        bound => bound,
    }
}

/// Whether an IPv6-only listener holds `port` on the IPv6 wildcard (issue #1501): a plain
/// `IPV6_V6ONLY` bind of `[::]:port` is refused with `AddrInUse`. Any other failure (no IPv6 on
/// the host, an address the stack does not offer) is not a holder, so the answer is `false`.
pub(crate) fn ipv6_only_listener_holds(port: u16) -> bool {
    let probe = || -> std::io::Result<()> {
        let socket = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))?;
        socket.set_only_v6(true)?;
        let addr = SocketAddr::new(std::net::Ipv6Addr::UNSPECIFIED.into(), port);
        socket.bind(&addr.into())
    };
    matches!(probe(), Err(e) if e.kind() == std::io::ErrorKind::AddrInUse)
}

/// Whether another socket listens on `127.0.0.1:port` beside our reusable wildcard listener (issue
/// #1501). On macOS and the BSDs a wildcard bind with `SO_REUSEADDR` succeeds next to a loopback
/// listener, which then keeps every `127.0.0.1` connection, and the kernel's port-0 search does not
/// look past the wildcard either. A loopback bind with `SO_REUSEADDR` alone succeeds next to our own
/// wildcard listener and is refused with `AddrInUse` by a loopback holder. Any other failure is not
/// a holder. Linux refuses the wildcard bind itself, and this probe would collide with our own
/// listener there, so it is only compiled for the BSD family.
#[cfg(any(
    target_os = "macos",
    target_os = "ios",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
))]
pub(crate) fn loopback_listener_holds(port: u16) -> bool {
    let probe = || -> std::io::Result<()> {
        let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?;
        socket.set_reuse_address(true)?;
        let addr = SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
        socket.bind(&addr.into())
    };
    matches!(probe(), Err(e) if e.kind() == std::io::ErrorKind::AddrInUse)
}

/// Create a TCP listener with an explicit [`SocketTuning`] (backlog).
pub fn create_reusable_listener_tuned(
    addr: SocketAddr,
    tuning: &SocketTuning,
) -> std::io::Result<TcpListener> {
    TcpListener::from_std(create_listener(addr, tuning, true)?)
}

/// A server-level listener (admin API, `/metrics`, front door, intercept; issue #1528): dual-stack
/// on every IPv6 address, like an imposter, but without `SO_REUSEPORT`, so no second process can
/// share the admin port. Returned nonblocking, ready for `tokio::net::TcpListener::from_std`.
pub fn bind_server_listener(addr: SocketAddr) -> std::io::Result<std::net::TcpListener> {
    create_listener(addr, &SocketTuning::default(), false)
}

/// The one socket builder behind [`create_reusable_listener_tuned`] and [`bind_server_listener`].
fn create_listener(
    addr: SocketAddr,
    tuning: &SocketTuning,
    reuse_port: bool,
) -> std::io::Result<std::net::TcpListener> {
    let domain = if addr.is_ipv4() {
        Domain::IPV4
    } else {
        Domain::IPV6
    };

    let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
    // Dual-stack on every IPv6 bind, as libuv sets it for Node (#1514): `[::]` then takes IPv4
    // clients too, on Windows and under `net.ipv6.bindv6only=1` as well. A specific IPv6 address
    // such as `::1` is unaffected.
    if domain == Domain::IPV6 {
        socket.set_only_v6(false)?;
    }

    // A server listener keeps what `tokio::net::TcpListener::bind` did before #1528: `SO_REUSEADDR`
    // on Unix only, since on Windows it lets another socket take the port over.
    if reuse_port || cfg!(not(windows)) {
        socket.set_reuse_address(true)?;
    }

    // Set SO_REUSEPORT on Unix (macOS, Linux, BSD)
    // On macOS, SO_REUSEPORT is available but through setsockopt
    #[cfg(target_os = "linux")]
    if reuse_port {
        use std::os::fd::AsRawFd;
        unsafe {
            let optval: libc::c_int = 1;
            let ret = libc::setsockopt(
                socket.as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_REUSEPORT,
                &optval as *const _ as *const libc::c_void,
                std::mem::size_of_val(&optval) as libc::socklen_t,
            );
            if ret != 0 {
                return Err(std::io::Error::last_os_error());
            }
        }
    }

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    if reuse_port {
        use std::os::fd::AsRawFd;
        unsafe {
            let optval: libc::c_int = 1;
            let ret = libc::setsockopt(
                socket.as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_REUSEPORT,
                &optval as *const _ as *const libc::c_void,
                std::mem::size_of_val(&optval) as libc::socklen_t,
            );
            if ret != 0 {
                return Err(std::io::Error::last_os_error());
            }
        }
    }
    socket.set_nonblocking(true)?;

    socket.bind(&addr.into())?;
    socket.listen(tuning.backlog)?;
    Ok(socket.into())
}

/// Apply per-connection tuning to a freshly accepted stream.
///
/// A failure to set `TCP_NODELAY` is logged, not fatal: the connection is still
/// fully functional (just potentially higher-latency for small writes), so
/// serving the request is preferable to dropping the connection.
pub fn apply_stream_tuning(stream: &TcpStream, tuning: &SocketTuning) {
    if !tuning.nodelay {
        return;
    }
    if let Err(e) = stream.set_nodelay(true) {
        tracing::warn!("failed to set TCP_NODELAY on accepted stream: {e}");
    }
}

// ── Accept-error handling (issue #750) ───────────────────────────────────────────────────────
//
// A bare `accept(2)` error arm that logs and immediately retries has two coupled defects, both
// amplified ×N under the per-core listener fan-out (#745): it spins hot on a *systemic* error
// (fd exhaustion cannot be cured by retrying), and it logs per failed accept — the exact
// per-event-rate logging trap the journal-cap fix (#741) removed. The pieces below fix both with
// no cost on the happy path.

/// Whether an `accept(2)` error means the listener itself is unusable, as opposed to a transient
/// or resource-pressure condition that retrying can clear.
///
/// `EBADF` / `ENOTSOCK` / `EINVAL` say the descriptor is not a working listening socket; no amount
/// of backoff fixes that, so a loop whose owner can observe its death should terminate and surface
/// the error rather than retry forever (issues #826, #834). Everything else — including unknown
/// errnos — is left to the two-way [`classify_accept_error`], which retries.
///
/// Not every loop wants this: the imposter serve loops deliberately never terminate, because a
/// dying imposter loop is independently recoverable through the still-live admin API. Loops whose
/// failure is the *only* signal an owner gets (the admin plane, the metrics plane)
/// consult this first.
///
/// Unix-only by construction: these are POSIX errnos. On other platforms nothing is treated as
/// fatal, matching the conservative "retry rather than die" default.
#[cfg(unix)]
pub fn is_fatal_listener_error(e: &std::io::Error) -> bool {
    matches!(
        e.raw_os_error(),
        Some(libc::EBADF) | Some(libc::ENOTSOCK) | Some(libc::EINVAL)
    )
}

#[cfg(not(unix))]
pub fn is_fatal_listener_error(_e: &std::io::Error) -> bool {
    false
}

/// Which clients an imposter-serving listener admits (issue #1523): every imposter port and the
/// front door check it once per accepted connection, before any byte is read or TLS is attempted.
///
/// `LoopbackOnly` is Mountebank's `--localOnly` (`util/ip.js:5-52`), which admits only the loopback
/// interface's addresses and refuses everyone else. Two deliberate edges, both host-local: Rift
/// admits all of `127.0.0.0/8` where Linux Mountebank lists only `127.0.0.1`, and refuses macOS's
/// `fe80::1%lo0`, which Mountebank lists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PeerPolicy {
    /// Every peer (the default; no `--local-only`).
    #[default]
    Any,
    /// Loopback peers only: `127.0.0.0/8`, `::1`, and their IPv4-mapped forms.
    LoopbackOnly,
}

impl PeerPolicy {
    /// Whether a client at `peer` may be served.
    ///
    /// The address is canonicalised first: a dual-stack (`[::]`) listener reports an IPv4 client
    /// as `::ffff:a.b.c.d`, for which `Ipv6Addr::is_loopback` is false.
    #[must_use]
    pub fn admits(self, peer: IpAddr) -> bool {
        match self {
            Self::Any => true,
            Self::LoopbackOnly => peer.to_canonical().is_loopback(),
        }
    }
}

/// How an `accept(2)` error should be handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceptErrorClass {
    /// Expected under load; the next accept is likely fine — retry immediately, log at `debug`.
    Transient,
    /// Resource exhaustion (or an unknown error): retrying now cannot succeed until something
    /// frees, so back off. Unknown errors land here deliberately — spinning on an unrecognized
    /// failure is the worse outcome.
    Systemic,
}

/// Classify via [`std::io::ErrorKind`] so no `libc` dependency is needed: only the transient
/// classes are named (`ECONNABORTED`/`EINTR`/`ECONNRESET`); everything else — resource exhaustion
/// like `EMFILE`/`ENFILE`/`ENOBUFS` (`Uncategorized`) or `ENOMEM` (`OutOfMemory`), and any truly
/// unknown error — falls through `_` to systemic.
pub fn classify_accept_error(e: &std::io::Error) -> AcceptErrorClass {
    use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, Interrupted};
    match e.kind() {
        ConnectionAborted | Interrupted | ConnectionReset => AcceptErrorClass::Transient,
        _ => AcceptErrorClass::Systemic,
    }
}

/// Exponential backoff for the systemic accept-error path: 1ms doubling to a 1s cap, reset on the
/// first successful accept. Pure and clock-free so the schedule is unit-testable without sockets.
#[derive(Debug)]
pub struct AcceptBackoff {
    current: Duration,
}

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

impl AcceptBackoff {
    const INITIAL: Duration = Duration::from_millis(1);
    const MAX: Duration = Duration::from_secs(1);

    pub fn new() -> Self {
        Self {
            current: Self::INITIAL,
        }
    }

    /// The delay to wait now; advances the schedule (double, capped) for the next call.
    pub fn next_delay(&mut self) -> Duration {
        let delay = self.current;
        self.current = (self.current * 2).min(Self::MAX);
        delay
    }

    pub fn reset(&mut self) {
        self.current = Self::INITIAL;
    }
}

/// What a systemic accept error should produce in the log (issue #838).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceptErrorEvent {
    /// The transition *into* the error state — emit the onset `error!`.
    Onset,
    /// Still failing after another [`AcceptErrorLog::REEMIT_EVERY`] suppressed errors — emit a
    /// reminder carrying the running suppressed count.
    StillDown { suppressed: u64 },
}

/// Rate-limited logging for the systemic accept-error path, mirroring the journal-cap warn fix
/// (#741): one `error!` on entering the error state, near-silence while in it (counting suppressed
/// errors), one `info!` carrying the suppressed count on recovery.
///
/// "Near-silence" rather than silence because a *sustained* outage would otherwise leave a single
/// log line as its only evidence — possibly emitted weeks before anyone looked. Since the retry
/// policy keeps the listener bound while it cannot serve, a wedged listener no longer refuses
/// connections, so that one line may be the only local signal there is (issue #838). Every
/// [`Self::REEMIT_EVERY`] suppressed errors the outage re-announces itself.
#[derive(Debug, Default)]
pub struct AcceptErrorLog {
    in_error: bool,
    suppressed: u64,
}

impl AcceptErrorLog {
    /// How many suppressed errors pass between reminder log lines while an outage persists.
    ///
    /// Deliberately a **count**, not a duration: this type is pure and clock-free so its schedule
    /// is unit-testable without sockets or a timer. The count maps onto time closely enough —
    /// a sustained outage sits at [`AcceptBackoff::MAX`] (1 s), so ≈1 error/s puts a reminder
    /// roughly every 10 minutes. Early in an outage the 1 ms→1 s ramp delivers errors faster and
    /// the first reminder arrives sooner, which is the right bias.
    pub const REEMIT_EVERY: u64 = 600;

    /// Record a systemic error. Returns `Some(Onset)` on the transition *into* the error state,
    /// `Some(StillDown { .. })` on every `REEMIT_EVERY`-th error while it persists, and `None`
    /// otherwise (the error is counted, not logged).
    ///
    /// A reminder does **not** reset the suppressed count: it stays the running total for the
    /// outage, so [`Self::on_success`] still reports the whole outage on recovery.
    pub fn on_error(&mut self) -> Option<AcceptErrorEvent> {
        if self.in_error {
            self.suppressed += 1;
            if self.suppressed.is_multiple_of(Self::REEMIT_EVERY) {
                Some(AcceptErrorEvent::StillDown {
                    suppressed: self.suppressed,
                })
            } else {
                None
            }
        } else {
            self.in_error = true;
            self.suppressed = 0;
            Some(AcceptErrorEvent::Onset)
        }
    }

    /// Record a successful accept. Returns `Some(suppressed)` **only** on the transition *out* of
    /// the error state (emit the single recovery `info!`); `None` in steady state, so a healthy
    /// accept path pays just one branch.
    pub fn on_success(&mut self) -> Option<u64> {
        if self.in_error {
            self.in_error = false;
            Some(std::mem::take(&mut self.suppressed))
        } else {
            None
        }
    }
}

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

    // ---- issue #1514: Node's default listen ----------------------------------------------

    #[test]
    fn bind_unspecified_takes_ipv6_first() {
        let mut calls = Vec::new();
        let bound = bind_unspecified(7, |addr| {
            calls.push(addr);
            Ok(addr)
        });
        assert_eq!(bound.expect("bound"), "[::]:7".parse().expect("addr"));
        assert_eq!(calls.len(), 1, "no IPv4 call after a v6 success");
    }

    #[test]
    fn bind_unspecified_falls_back_to_ipv4_on_any_other_error() {
        for kind in [
            std::io::ErrorKind::Unsupported,
            std::io::ErrorKind::AddrNotAvailable,
        ] {
            let mut calls = Vec::new();
            let bound = bind_unspecified(7, |addr: SocketAddr| {
                calls.push(addr);
                if addr.is_ipv6() {
                    Err(std::io::Error::from(kind))
                } else {
                    Ok(addr)
                }
            });
            assert_eq!(
                bound.expect("v4"),
                "0.0.0.0:7".parse().expect("addr"),
                "{kind:?}"
            );
            assert_eq!(calls.len(), 2);
        }
    }

    #[test]
    fn bind_unspecified_returns_address_in_use_without_falling_back() {
        let mut calls = 0;
        let bound = bind_unspecified(7, |_addr: SocketAddr| -> std::io::Result<SocketAddr> {
            calls += 1;
            Err(std::io::Error::from(std::io::ErrorKind::AddrInUse))
        });
        assert_eq!(
            bound.expect_err("in use").kind(),
            std::io::ErrorKind::AddrInUse
        );
        assert_eq!(calls, 1, "Node never retries an in-use port on IPv4");
    }

    #[test]
    fn an_ipv6_wildcard_listener_is_dual_stack() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .build()
            .expect("runtime");
        let _guard = rt.enter();
        let Ok(listener) = create_reusable_listener("[::]:0".parse().expect("addr")) else {
            return; // no IPv6 on this host
        };
        assert!(
            !socket2::SockRef::from(&listener)
                .only_v6()
                .expect("IPV6_V6ONLY")
        );
    }

    // ---- issue #1528: server-level listeners ---------------------------------------------

    #[test]
    fn a_server_listener_is_dual_stack_on_the_ipv6_wildcard() {
        let Ok(listener) = bind_server_listener("[::]:0".parse().expect("addr")) else {
            return; // no IPv6 on this host
        };
        assert!(
            !socket2::SockRef::from(&listener)
                .only_v6()
                .expect("IPV6_V6ONLY")
        );
    }

    #[test]
    fn a_server_listener_does_not_share_its_port() {
        let first = bind_server_listener("127.0.0.1:0".parse().expect("addr")).expect("bind");
        let addr = first.local_addr().expect("addr");
        let second = bind_server_listener(addr).expect_err("no SO_REUSEPORT on a server listener");
        assert_eq!(second.kind(), std::io::ErrorKind::AddrInUse);
    }

    // ---- issue #1501: the holder checks behind auto-assign ------------------------------

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    ))]
    #[test]
    fn a_loopback_holder_is_seen_beside_our_own_wildcard_listener() {
        let _rt = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .build()
            .expect("runtime");
        let _guard = _rt.enter();
        let ours = create_reusable_listener(SocketAddr::from(([0, 0, 0, 0], 0))).expect("ours");
        let port = ours.local_addr().expect("local addr").port();
        assert!(
            !loopback_listener_holds(port),
            "our own wildcard listener is not a loopback holder"
        );

        let holder = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).expect("socket");
        holder.set_reuse_address(true).expect("SO_REUSEADDR");
        holder
            .bind(&SocketAddr::from(([127, 0, 0, 1], port)).into())
            .expect("a loopback listener binds beside the wildcard");
        holder.listen(4).expect("listen");
        assert!(loopback_listener_holds(port));
    }

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    ))]
    #[test]
    fn a_loopback_holder_is_seen_beside_our_own_dual_stack_listener() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .build()
            .expect("runtime");
        let _guard = rt.enter();
        let Ok(ours) = create_reusable_listener("[::]:0".parse().expect("addr")) else {
            return; // no IPv6 on this host
        };
        let port = ours.local_addr().expect("local addr").port();
        assert!(
            !loopback_listener_holds(port),
            "our own dual-stack listener is not a loopback holder"
        );

        let holder = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).expect("socket");
        holder.set_reuse_address(true).expect("SO_REUSEADDR");
        holder
            .bind(&SocketAddr::from(([127, 0, 0, 1], port)).into())
            .expect("a loopback listener binds beside the dual-stack wildcard");
        holder.listen(4).expect("listen");
        assert!(loopback_listener_holds(port));
    }

    #[test]
    fn an_ipv6_only_holder_is_seen_and_a_free_port_is_not() {
        let Ok(socket) = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP)) else {
            return; // no IPv6 on this host
        };
        socket.set_only_v6(true).expect("IPV6_V6ONLY");
        let any: SocketAddr = SocketAddr::new(std::net::Ipv6Addr::UNSPECIFIED.into(), 0);
        if socket.bind(&any.into()).is_err() {
            return;
        }
        socket.listen(4).expect("listen");
        let port = socket
            .local_addr()
            .expect("local addr")
            .as_socket()
            .expect("inet")
            .port();
        assert!(ipv6_only_listener_holds(port));
        drop(socket);
        assert!(!ipv6_only_listener_holds(port), "released ports are free");
    }

    // ---- issue #716: HTTP connection-builder tuning knobs -------------------------------

    #[test]
    fn http_tuning_defaults() {
        let t = HttpTuning::default();
        assert_eq!(t.max_buf_size, DEFAULT_HTTP_MAX_BUF);
        assert_eq!(t.header_read_timeout, std::time::Duration::from_secs(30));
        assert_eq!(
            t.max_connections, None,
            "unlimited by default (today's behavior)"
        );
    }

    /// Existing value-assertions go through these so they stay about the parsed values; the
    /// fallback list has its own tests below.
    fn http(a: Option<&str>, b: Option<&str>, c: Option<&str>) -> HttpTuning {
        HttpTuning::parse(a, b, c).0
    }
    fn sock(a: Option<&str>, b: Option<&str>) -> SocketTuning {
        SocketTuning::parse(a, b).0
    }
    /// The fallbacks a parse reported, as `(var, value, reason)` — compared against literals.
    fn http_warns(
        a: Option<&str>,
        b: Option<&str>,
        c: Option<&str>,
    ) -> Vec<(&'static str, String, FallbackReason)> {
        HttpTuning::parse(a, b, c)
            .1
            .into_iter()
            .map(|f| (f.var, f.value, f.reason))
            .collect()
    }
    fn sock_warns(a: Option<&str>, b: Option<&str>) -> Vec<(&'static str, String, FallbackReason)> {
        SocketTuning::parse(a, b)
            .1
            .into_iter()
            .map(|f| (f.var, f.value, f.reason))
            .collect()
    }

    #[test]
    fn http_tuning_parse_falls_back_to_defaults_when_unset() {
        assert_eq!(http(None, None, None), HttpTuning::default());
    }

    #[test]
    fn http_tuning_parse_reads_max_buf() {
        assert_eq!(http(Some(" 32768 "), None, None).max_buf_size, 32768);
    }

    #[test]
    fn http_tuning_parse_rejects_garbage_or_zero_max_buf() {
        for v in ["0", "-5", "nope", ""] {
            assert_eq!(
                http(Some(v), None, None).max_buf_size,
                DEFAULT_HTTP_MAX_BUF,
                "value {v} must fall back to the default"
            );
        }
    }

    #[test]
    fn http_tuning_parse_reads_header_timeout_seconds() {
        assert_eq!(
            http(None, Some("10"), None).header_read_timeout,
            std::time::Duration::from_secs(10)
        );
    }

    #[test]
    fn http_tuning_parse_rejects_garbage_header_timeout() {
        for v in ["nope", "-1", ""] {
            assert_eq!(
                http(None, Some(v), None).header_read_timeout,
                std::time::Duration::from_secs(30),
                "value {v} must fall back to the default"
            );
        }
    }

    #[test]
    fn http_tuning_parse_max_connections_opt_in() {
        // Unset or non-positive => unlimited (None); a positive value => a cap.
        assert_eq!(http(None, None, None).max_connections, None);
        assert_eq!(http(None, None, Some("0")).max_connections, None);
        assert_eq!(http(None, None, Some("nope")).max_connections, None);
        assert_eq!(http(None, None, Some(" 500 ")).max_connections, Some(500));
    }

    #[test]
    fn default_tuning_enables_nodelay_and_uses_default_backlog() {
        let t = SocketTuning::default();
        assert_eq!(t.backlog, DEFAULT_BACKLOG);
        assert!(t.nodelay);
    }

    #[test]
    fn parse_falls_back_to_defaults_when_unset() {
        assert_eq!(sock(None, None), SocketTuning::default());
    }

    #[test]
    fn parse_reads_a_positive_backlog() {
        assert_eq!(sock(Some(" 2048 "), None).backlog, 2048);
    }

    #[test]
    fn parse_rejects_non_positive_or_garbage_backlog() {
        assert_eq!(sock(Some("0"), None).backlog, DEFAULT_BACKLOG);
        assert_eq!(sock(Some("-5"), None).backlog, DEFAULT_BACKLOG);
        assert_eq!(sock(Some("nope"), None).backlog, DEFAULT_BACKLOG);
    }

    #[test]
    fn parse_disables_nodelay_on_falsey_values() {
        for v in ["false", "FALSE", "0", "off", "Off"] {
            assert!(!sock(None, Some(v)).nodelay, "value {v}");
        }
    }

    #[test]
    fn parse_keeps_nodelay_enabled_otherwise() {
        for v in ["true", "1", "on", "yes", ""] {
            assert!(sock(None, Some(v)).nodelay, "value {v}");
        }
    }

    // ─── Issue #1009: a present-but-unusable value must not vanish ────────────────

    /// Unset is the domain-optional case: the operator expressed no intent, so there is nothing
    /// to report. This is the half that must stay silent — a warning on every default start would
    /// train operators to ignore the log line that matters.
    #[test]
    fn an_unset_or_valid_environment_reports_nothing() {
        assert_eq!(http_warns(None, None, None), vec![]);
        assert_eq!(sock_warns(None, None), vec![]);
        assert_eq!(
            http_warns(Some("32768"), Some("10"), Some("500")),
            vec![],
            "values that were honoured must not warn"
        );
        assert_eq!(sock_warns(Some("2048"), Some("false")), vec![]);
    }

    /// Two failure shapes, deliberately distinguished: `nope` never was a number, whereas `0` is a
    /// number the knob cannot accept. An operator debugging the second needs the bound, not
    /// "unparsable".
    #[test]
    fn max_buf_says_whether_it_was_unparsable_or_out_of_range() {
        assert_eq!(
            http_warns(Some("nope"), None, None),
            vec![(
                "RIFT_HTTP_MAX_BUF",
                "nope".to_string(),
                FallbackReason::NotANumber
            )]
        );
        assert_eq!(
            http_warns(Some("0"), None, None),
            vec![(
                "RIFT_HTTP_MAX_BUF",
                "0".to_string(),
                FallbackReason::BelowMinimum
            )]
        );
        // `1MB` is the plausible hand-edit this exists for: a suffix hyper never accepted.
        assert_eq!(
            http_warns(Some("1MB"), None, None),
            vec![(
                "RIFT_HTTP_MAX_BUF",
                "1MB".to_string(),
                FallbackReason::NotANumber
            )]
        );
    }

    #[test]
    fn a_zero_header_timeout_is_reported_as_non_positive() {
        // Zero does not mean "no timeout" here — it is rejected — so silently treating it as a
        // request for one would leave slowloris mitigation off with nothing said.
        assert_eq!(
            http_warns(None, Some("0"), None),
            vec![(
                "RIFT_HTTP_HEADER_TIMEOUT",
                "0".to_string(),
                FallbackReason::NotPositive
            )]
        );
        assert_eq!(
            http_warns(None, Some("nope"), None),
            vec![(
                "RIFT_HTTP_HEADER_TIMEOUT",
                "nope".to_string(),
                FallbackReason::NotANumber
            )]
        );
    }

    /// The one number that must stay quiet at zero. `RIFT_MAX_CONNECTIONS=0` reads as "no cap",
    /// and no cap is exactly what it gets — the operator's intent was honoured, so there is
    /// nothing to warn about. Garbage in the same slot still warns.
    #[test]
    fn max_connections_zero_is_honoured_silently_but_garbage_is_not() {
        assert_eq!(http_warns(None, None, Some("0")), vec![]);
        assert_eq!(http_warns(None, None, Some("nope")).len(), 1);
        assert_eq!(
            http_warns(None, None, Some("nope"))[0].2,
            FallbackReason::NotANumber
        );
    }

    #[test]
    fn backlog_says_whether_it_was_unparsable_or_non_positive() {
        for v in ["0", "-5"] {
            assert_eq!(
                sock_warns(Some(v), None),
                vec![(
                    "RIFT_TCP_BACKLOG",
                    v.to_string(),
                    FallbackReason::NotPositive
                )],
                "value {v}"
            );
        }
        assert_eq!(
            sock_warns(Some("nope"), None),
            vec![(
                "RIFT_TCP_BACKLOG",
                "nope".to_string(),
                FallbackReason::NotANumber
            )]
        );
    }

    /// The nastiest case in this issue, and the reason it is not only about *unparsable* values:
    /// every unrecognised spelling counted as "enabled", so the typo `flase` silently kept Nagle
    /// disabled — the exact opposite of what was written, with nothing logged. Behaviour is
    /// deliberately unchanged (still the default); only the silence is.
    #[test]
    fn an_unrecognised_nodelay_spelling_warns_and_keeps_the_default() {
        for v in ["flase", "yes", "", "disabled"] {
            assert_eq!(
                sock_warns(None, Some(v)),
                vec![(
                    "RIFT_TCP_NODELAY",
                    v.to_string(),
                    FallbackReason::UnrecognizedBoolean
                )],
                "value {v}"
            );
            assert!(
                sock(None, Some(v)).nodelay,
                "behaviour must be unchanged for {v}"
            );
        }
    }

    #[test]
    fn every_recognised_nodelay_spelling_is_silent() {
        for v in [
            "true", "TRUE", "1", "on", "On", "false", "FALSE", "0", "off",
        ] {
            assert_eq!(sock_warns(None, Some(v)), vec![], "value {v}");
        }
    }

    /// Several bad values at once each get their own line, so a fleet-wide bad push names every
    /// knob it broke rather than only the first.
    #[test]
    fn each_unusable_value_is_reported_separately() {
        let warns = http_warns(Some("nope"), Some("0"), Some("bad"));
        assert_eq!(warns.len(), 3, "got: {warns:?}");
        let vars: Vec<&str> = warns.iter().map(|w| w.0).collect();
        assert_eq!(
            vars,
            vec![
                "RIFT_HTTP_MAX_BUF",
                "RIFT_HTTP_HEADER_TIMEOUT",
                "RIFT_MAX_CONNECTIONS"
            ]
        );
    }

    #[tokio::test]
    async fn accepted_stream_gets_nodelay() {
        let addr: SocketAddr = "127.0.0.1:0".parse().expect("addr");
        let listener =
            create_reusable_listener_tuned(addr, &SocketTuning::default()).expect("listener");
        let local = listener.local_addr().expect("local_addr");

        let client = tokio::spawn(async move { TcpStream::connect(local).await });

        let (server_stream, _) = listener.accept().await.expect("accept");
        apply_stream_tuning(&server_stream, &SocketTuning::default());
        assert!(server_stream.nodelay().expect("nodelay query"));

        let _ = client.await.expect("join").expect("connect");
    }

    #[tokio::test]
    async fn nodelay_left_untouched_when_disabled() {
        let addr: SocketAddr = "127.0.0.1:0".parse().expect("addr");
        let tuning = SocketTuning {
            backlog: 128,
            nodelay: false,
        };
        let listener = create_reusable_listener_tuned(addr, &tuning).expect("listener");
        let local = listener.local_addr().expect("local_addr");

        let client = tokio::spawn(async move { TcpStream::connect(local).await });

        let (server_stream, _) = listener.accept().await.expect("accept");
        // With nodelay disabled we must not force it on; the OS default is off.
        apply_stream_tuning(&server_stream, &tuning);
        assert!(!server_stream.nodelay().expect("nodelay query"));

        let _ = client.await.expect("join").expect("connect");
    }
}

#[cfg(test)]
mod accept_error {
    use super::*;
    use std::io::{Error, ErrorKind};

    // The fatal class (#826, shared by every owner-observable loop since #834): a broken listener fd
    // must still end the loop so its owner can report the death instead of retrying forever.
    #[cfg(unix)]
    #[test]
    fn broken_listener_errnos_are_fatal_but_pressure_is_not() {
        for raw in [libc::EBADF, libc::ENOTSOCK, libc::EINVAL] {
            assert!(
                is_fatal_listener_error(&Error::from_raw_os_error(raw)),
                "errno {raw} means the listener is unusable; retrying forever would hide a dead listener from its owner"
            );
        }
        // Recoverable pressure and transient blips must never be treated as fatal.
        for raw in [libc::EMFILE, libc::ENFILE, libc::ECONNABORTED, libc::EINTR] {
            assert!(
                !is_fatal_listener_error(&Error::from_raw_os_error(raw)),
                "errno {raw} is recoverable and must be retried, not fatal"
            );
        }
    }

    #[test]
    fn classify_transient_vs_systemic() {
        for kind in [
            ErrorKind::ConnectionAborted,
            ErrorKind::Interrupted,
            ErrorKind::ConnectionReset,
        ] {
            assert_eq!(
                classify_accept_error(&Error::from(kind)),
                AcceptErrorClass::Transient,
                "{kind:?} must be transient (retry immediately)"
            );
        }
        // EMFILE (24) / ENFILE (23) map to Uncategorized -> systemic; and a named non-transient
        // kind is systemic too. Unknown must never be treated as transient.
        for e in [
            Error::from_raw_os_error(24), // EMFILE
            Error::from_raw_os_error(23), // ENFILE
            Error::from(ErrorKind::OutOfMemory),
            Error::from(ErrorKind::Other),
        ] {
            assert_eq!(
                classify_accept_error(&e),
                AcceptErrorClass::Systemic,
                "{e:?} must back off, not spin"
            );
        }
    }

    #[test]
    fn backoff_doubles_from_1ms_caps_at_1s_and_resets() {
        let mut b = AcceptBackoff::new();
        assert_eq!(
            b.next_delay(),
            Duration::from_millis(1),
            "first delay is 1ms, not 0"
        );
        assert_eq!(b.next_delay(), Duration::from_millis(2));
        assert_eq!(b.next_delay(), Duration::from_millis(4));
        assert_eq!(b.next_delay(), Duration::from_millis(8));
        // Fast-forward well past the cap.
        for _ in 0..20 {
            b.next_delay();
        }
        assert_eq!(b.next_delay(), Duration::from_secs(1), "capped at 1s");
        b.reset();
        assert_eq!(
            b.next_delay(),
            Duration::from_millis(1),
            "reset returns to 1ms"
        );
    }

    // The log state machine backs the "one error! on onset, one info! with the suppressed count
    // on recovery" AC without sockets: on_error transitions once, steady state stays silent.
    #[test]
    fn log_emits_once_per_transition_with_suppressed_count() {
        let mut log = AcceptErrorLog::default();
        assert_eq!(
            log.on_error(),
            Some(AcceptErrorEvent::Onset),
            "first systemic error -> emit the one error!"
        );
        assert_eq!(log.on_error(), None, "second is suppressed");
        assert_eq!(log.on_error(), None, "third is suppressed");
        assert_eq!(
            log.on_success(),
            Some(2),
            "recovery emits one info! carrying the 2 suppressed errors"
        );
        assert_eq!(log.on_success(), None, "steady state is silent");
        assert_eq!(log.on_success(), None);

        // A fresh outage re-arms: one error!, count restarts from 0.
        assert_eq!(log.on_error(), Some(AcceptErrorEvent::Onset));
        assert_eq!(
            log.on_success(),
            Some(0),
            "immediate recovery suppressed nothing"
        );
    }

    // Issue #838: a sustained outage must re-announce itself, or its only evidence is one log line
    // emitted whenever it started. Reminders are count-based so this stays clock-free.
    #[test]
    fn sustained_outage_reemits_every_n_and_keeps_the_running_total() {
        let mut log = AcceptErrorLog::default();
        assert_eq!(log.on_error(), Some(AcceptErrorEvent::Onset));

        // Everything strictly between onset and the Nth suppressed error is silent.
        for i in 1..AcceptErrorLog::REEMIT_EVERY {
            assert_eq!(log.on_error(), None, "suppressed error {i} must not log");
        }
        assert_eq!(
            log.on_error(),
            Some(AcceptErrorEvent::StillDown {
                suppressed: AcceptErrorLog::REEMIT_EVERY
            }),
            "the REEMIT_EVERY-th suppressed error re-announces the outage"
        );

        // The reminder does NOT reset the count — the next one carries 2N, and recovery still
        // reports the whole outage.
        for _ in 1..AcceptErrorLog::REEMIT_EVERY {
            assert_eq!(log.on_error(), None);
        }
        assert_eq!(
            log.on_error(),
            Some(AcceptErrorEvent::StillDown {
                suppressed: AcceptErrorLog::REEMIT_EVERY * 2
            }),
            "reminders carry the running total, not a per-window count"
        );
        assert_eq!(
            log.on_success(),
            Some(AcceptErrorLog::REEMIT_EVERY * 2),
            "recovery reports every error suppressed during the outage"
        );

        // And a fresh outage re-arms the reminder schedule from zero.
        assert_eq!(log.on_error(), Some(AcceptErrorEvent::Onset));
        assert_eq!(log.on_error(), None, "the new outage counts from 0 again");
    }
}

#[cfg(test)]
mod bind_host_spellings {
    use super::*;
    use std::net::Ipv4Addr;

    fn v6(ip: Ipv6Addr, port: u16, scope_id: u32) -> SocketAddr {
        SocketAddr::V6(SocketAddrV6::new(ip, port, 0, scope_id))
    }

    // Issue #1137: both IPv6 spellings an operator writes denote the same address.
    #[test]
    fn ip_literals_in_every_spelling_resolve() {
        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
        let cases: [(&str, SocketAddr); 9] = [
            ("::1", v6(Ipv6Addr::LOCALHOST, 80, 0)),
            ("[::1]", v6(Ipv6Addr::LOCALHOST, 80, 0)),
            ("::", v6(Ipv6Addr::UNSPECIFIED, 80, 0)),
            ("[::]", v6(Ipv6Addr::UNSPECIFIED, 80, 0)),
            (
                "::ffff:127.0.0.1",
                v6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 1), 80, 0),
            ),
            // A numeric scope id survives: `[fe80::1%2]` bound before #1137 and must still.
            ("[fe80::1%2]", v6(link_local, 80, 2)),
            ("fe80::1%2", v6(link_local, 80, 2)),
            ("0.0.0.0", SocketAddr::from((Ipv4Addr::UNSPECIFIED, 80))),
            ("127.0.0.1", SocketAddr::from((Ipv4Addr::LOCALHOST, 80))),
        ];
        for (host, want) in cases {
            assert_eq!(bind_addr(host, 80), Some(want), "host {host:?}");
        }
    }

    // A name is not a literal, and brackets mean IPv6 — `[1.2.3.4]` is not an address.
    #[test]
    fn names_and_malformed_literals_are_not_addresses() {
        for host in [
            "localhost",
            "[localhost]",
            "[1.2.3.4]",
            "1.2.3.4%2",
            "[",
            "[]",
            "[::1",
            "::1]",
            "[fe80::1%eth0]",
            "fe80::1%",
            "",
        ] {
            assert_eq!(bind_addr(host, 80), None, "host {host:?}");
        }
    }

    // The bug was a string round trip: `::1` + `:7654` read as one more hextet. The port must land
    // in the port, never in the address.
    #[test]
    fn the_port_lands_in_the_port() {
        assert_eq!(
            bind_addr("::1", 7654),
            Some(v6(Ipv6Addr::LOCALHOST, 7654, 0))
        );
        assert_eq!(bind_addr("[::1]", 0), Some(v6(Ipv6Addr::LOCALHOST, 0, 0)));
        assert_eq!(
            bind_addr("0.0.0.0", 2525),
            Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 2525)))
        );
    }

    // Issue #1150: `bind_host` is `bind_addr`'s inverse, and the scope id is the whole reason it
    // exists — `IpAddr::to_string` cannot spell one, so anything that rebuilds a host string from
    // `.ip()` silently drops it.
    #[test]
    fn bind_host_spells_the_scope_id() {
        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
        assert_eq!(bind_host(&v6(link_local, 80, 2)), "fe80::1%2");
        assert_eq!(bind_host(&v6(link_local, 80, 42)), "fe80::1%42");
        assert_eq!(bind_host(&v6(link_local, 80, 1)), "fe80::1%1");
    }

    // An unscoped address must not grow a `%0`. `bind_addr` would read it back correctly, but the
    // string is handed to `InterceptStartOptions.host` and shows up in API responses.
    #[test]
    fn bind_host_of_an_unscoped_address_has_no_zone() {
        assert_eq!(bind_host(&v6(Ipv6Addr::LOCALHOST, 80, 0)), "::1");
        assert_eq!(bind_host(&v6(Ipv6Addr::UNSPECIFIED, 80, 0)), "::");
        assert_eq!(
            bind_host(&SocketAddr::from((Ipv4Addr::LOCALHOST, 80))),
            "127.0.0.1"
        );
        assert_eq!(
            bind_host(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, 80))),
            "0.0.0.0"
        );
    }

    // The round trip, over exactly the addresses `bind_addr` can produce (it always builds
    // flowinfo 0, so an address with flowinfo set is out of the property's domain).
    #[test]
    fn bind_host_round_trips_through_bind_addr() {
        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
        for addr in [
            SocketAddr::from((Ipv4Addr::LOCALHOST, 2525)),
            SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)),
            v6(Ipv6Addr::LOCALHOST, 2525, 0),
            v6(Ipv6Addr::UNSPECIFIED, 80, 0),
            v6(link_local, 2525, 2),
            v6(link_local, 0, 1),
        ] {
            assert_eq!(
                bind_addr(&bind_host(&addr), addr.port()),
                Some(addr),
                "round trip for {addr}"
            );
        }
    }
}

#[cfg(test)]
mod peer_policy {
    use super::PeerPolicy;
    use std::net::IpAddr;

    fn ip(s: &str) -> IpAddr {
        s.parse().expect("IP literal")
    }

    const LOOPBACK: [&str; 4] = ["127.0.0.1", "127.0.0.2", "::1", "::ffff:127.0.0.1"];
    const REMOTE: [&str; 5] = [
        "192.168.1.5",
        "::ffff:192.168.1.5",
        "10.0.0.1",
        "fe80::1",
        "2001:db8::1",
    ];

    // A dual-stack listener reports an IPv4 client as `::ffff:a.b.c.d`, which
    // `Ipv6Addr::is_loopback` alone calls non-loopback: the mapped form must be admitted.
    #[test]
    fn loopback_only_admits_every_loopback_spelling() {
        for peer in LOOPBACK {
            assert!(
                PeerPolicy::LoopbackOnly.admits(ip(peer)),
                "{peer} is loopback"
            );
        }
    }

    // `fe80::1` is macOS's lo0 link-local, which Mountebank admits; refusing it is the safe side.
    #[test]
    fn loopback_only_refuses_everything_else() {
        for peer in REMOTE {
            assert!(
                !PeerPolicy::LoopbackOnly.admits(ip(peer)),
                "{peer} is not loopback"
            );
        }
    }

    #[test]
    fn any_admits_every_peer() {
        for peer in LOOPBACK.iter().chain(REMOTE.iter()) {
            assert!(PeerPolicy::Any.admits(ip(peer)), "{peer}");
        }
        assert_eq!(PeerPolicy::default(), PeerPolicy::Any);
    }
}