pjson-rs 0.7.0

Priority JSON Streaming Protocol - high-performance priority-based JSON streaming (requires nightly Rust)
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
//! Rate limiting system for WebSocket connections to prevent DoS attacks

use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::{
    net::IpAddr,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};
use thiserror::Error;

/// Hard upper bound on the number of distinct client IPs [`WebSocketRateLimiter`]
/// tracks at once, independent of the periodic TTL-based [`WebSocketRateLimiter::cleanup_expired`]
/// sweep. The sweep only runs every few minutes ([`DEFAULT_CLEANUP_INTERVAL`]) and
/// cannot by itself prevent an in-window burst of distinct IPs from growing the
/// map unboundedly between sweeps. Once at capacity, requests from IPs not
/// already tracked are rejected with [`RateLimitError::CapacityExceeded`]
/// rather than growing the map further; already-tracked IPs are unaffected.
///
/// **Reject-new, not evict-to-admit — a deliberate choice.** At capacity, a
/// not-yet-tracked IP is turned away rather than evicting an arbitrary
/// existing entry to make room. Evict-to-admit would let an attacker forge
/// fresh IPs to repeatedly evict *established* clients' rate-limit state,
/// letting them bypass their own accumulated request count — the opposite of
/// what this limiter exists to prevent. Reject-new instead trades that for:
/// under a sustained attack that fills the table faster than
/// [`WebSocketRateLimiter::cleanup_expired`] can free idle entries, new
/// clients are turned away (a `503`, see `RateLimitService::call` in
/// `infrastructure::http::middleware`) until capacity frees up. This is
/// considered the safer default — it protects already-established traffic at
/// the cost of new-client admission under capacity pressure, rather than the
/// reverse.
pub const MAX_TRACKED_CLIENTS: usize = 100_000;

/// Default interval between periodic [`WebSocketRateLimiter::cleanup_expired`]
/// sweeps spawned by [`WebSocketRateLimiter::spawn_cleanup_task`].
pub const DEFAULT_CLEANUP_INTERVAL: Duration = Duration::from_secs(300);

/// Rate limiting errors
#[derive(Error, Debug, Clone)]
pub enum RateLimitError {
    /// Request count exceeded the per-window limit.
    #[error("Rate limit exceeded: {limit} requests per {window:?}")]
    LimitExceeded {
        /// Configured per-window request limit.
        limit: u32,
        /// Configured window duration.
        window: Duration,
    },

    /// Per-IP concurrent connection cap was reached.
    #[error("Connection limit exceeded: {current}/{max} connections")]
    ConnectionLimitExceeded {
        /// Current connection count for the IP.
        current: usize,
        /// Configured maximum number of connections per IP.
        max: usize,
    },

    /// Frame larger than the configured maximum was rejected.
    #[error("Frame size limit exceeded: {size} bytes > {max} bytes")]
    FrameSizeExceeded {
        /// Observed frame size in bytes.
        size: usize,
        /// Configured maximum frame size in bytes.
        max: usize,
    },

    /// The limiter is already tracking [`MAX_TRACKED_CLIENTS`] distinct
    /// clients; requests from not-yet-tracked clients are rejected until the
    /// next cleanup sweep frees capacity.
    #[error("Rate limiter at capacity: {max} tracked clients")]
    CapacityExceeded {
        /// Configured maximum number of tracked clients.
        max: usize,
    },
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Maximum requests per time window
    pub max_requests_per_window: u32,
    /// Time window for rate limiting
    pub window_duration: Duration,
    /// Maximum concurrent connections per IP
    pub max_connections_per_ip: usize,
    /// Maximum WebSocket frame size
    pub max_frame_size: usize,
    /// Maximum message rate (messages per second)
    pub max_messages_per_second: u32,
    /// Burst allowance (extra messages above rate)
    pub burst_allowance: u32,
    /// Deadline for a single outbound WebSocket sink write before the
    /// connection is treated as stalled and closed.
    ///
    /// Guards against a peer that stops reading wedging the connection's
    /// task indefinitely. Bounds a single write, not overall throughput —
    /// see `infrastructure::websocket::WRITE_TIMEOUT`'s doc for the
    /// tradeoff this implies for large frames sent to slow clients, and
    /// raise this value if that tradeoff doesn't fit a deployment's
    /// expected client bandwidth. Defaults to the same 10s value as
    /// `infrastructure::websocket::WRITE_TIMEOUT`; the two constants are
    /// independent (different feature gates), so an intentional change to
    /// one should be mirrored in the other unless a divergence is
    /// deliberate. [`Self::low_resource`] tightens this to 3s. This value
    /// governs the server side only — `PjsWebSocketClient` has its own
    /// independent write-timeout knob (see
    /// `infrastructure::websocket::PjsWebSocketClient::with_write_timeout`),
    /// also defaulting to `WRITE_TIMEOUT`.
    pub write_timeout: Duration,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            max_requests_per_window: 100,
            window_duration: Duration::from_secs(60),
            max_connections_per_ip: 10,
            max_frame_size: 1024 * 1024, // 1MB
            max_messages_per_second: 30,
            burst_allowance: 5,
            write_timeout: Duration::from_secs(10),
        }
    }
}

impl RateLimitConfig {
    /// Configuration for high-traffic scenarios
    pub fn high_traffic() -> Self {
        Self {
            max_requests_per_window: 1000,
            max_connections_per_ip: 50,
            max_messages_per_second: 100,
            burst_allowance: 20,
            ..Default::default()
        }
    }

    /// Configuration for low-resource environments
    pub fn low_resource() -> Self {
        Self {
            max_requests_per_window: 20,
            max_connections_per_ip: 2,
            max_frame_size: 256 * 1024, // 256KB
            max_messages_per_second: 5,
            burst_allowance: 2,
            // 3s (30% of the 10s default) — within this preset's range of
            // reductions applied to its other fields (16.7%-40% of
            // `Default`, though above their ~20-25% median). Freeing a
            // wedged connection task matters more under resource
            // constraints than absorbing ordinary network jitter.
            //
            // Note: this does not shrink what a single outbound write must
            // flush in time. `max_frame_size` above bounds inbound frames
            // only; outbound frame size is governed elsewhere and is
            // unaffected by this preset. A slow-but-honest client now
            // needs roughly 3.3x the downlink bandwidth it needed under
            // the 10s default to avoid being disconnected as "stalled"
            // (see `infrastructure::websocket::WRITE_TIMEOUT`'s doc for
            // the full bandwidth-vs-deadline tradeoff) — raise this value
            // if a low-resource deployment still expects to serve large
            // frames to bandwidth-constrained clients.
            write_timeout: Duration::from_secs(3),
            ..Default::default()
        }
    }
}

/// Rate limit tracking for a specific client
#[derive(Debug)]
struct ClientRateLimit {
    /// Request timestamps within current window
    requests: Vec<Instant>,
    /// Current connection count
    connection_count: usize,
    /// Token bucket for message rate limiting
    tokens: f64,
    /// Last token refill time
    last_refill: Instant,
}

impl ClientRateLimit {
    fn new(burst_allowance: u32) -> Self {
        let now = Instant::now();
        Self {
            requests: Vec::new(),
            connection_count: 0,
            tokens: burst_allowance as f64, // Start with burst allowance tokens
            last_refill: now,
        }
    }

    /// Refill tokens based on time passed
    fn refill_tokens(&mut self, config: &RateLimitConfig) {
        let now = Instant::now();
        let time_passed = now.duration_since(self.last_refill).as_secs_f64();

        // Add tokens at configured rate
        let tokens_to_add = time_passed * config.max_messages_per_second as f64;
        let max_tokens = (config.max_messages_per_second + config.burst_allowance) as f64;

        self.tokens = (self.tokens + tokens_to_add).min(max_tokens);
        self.last_refill = now;
    }

    /// Check if message rate is within limits
    fn check_message_rate(&mut self, config: &RateLimitConfig) -> Result<(), RateLimitError> {
        self.refill_tokens(config);

        if self.tokens >= 1.0 {
            self.tokens -= 1.0;
            Ok(())
        } else {
            Err(RateLimitError::LimitExceeded {
                limit: config.max_messages_per_second,
                window: Duration::from_secs(1),
            })
        }
    }
}

/// Rate limiter for WebSocket connections
#[derive(Debug)]
pub struct WebSocketRateLimiter {
    config: RateLimitConfig,
    clients: Arc<DashMap<IpAddr, ClientRateLimit>>,
    /// Guards [`WebSocketRateLimiter::spawn_cleanup_task`] so it spawns at
    /// most one background task per limiter even if called repeatedly (e.g.
    /// by several `RateLimitMiddleware`s sharing the same `Arc`).
    ///
    /// An `AtomicBool` rather than `std::sync::Once`: `Once` permanently
    /// consumes its "run" on the first call regardless of what that call
    /// does, so a first call outside a Tokio runtime would consume it and
    /// silently prevent every later, in-runtime call from ever spawning.
    /// This flag is only set `true` once a spawn actually succeeds; a failed
    /// attempt (no runtime) rolls it back to `false` so a later call can
    /// retry.
    cleanup_spawned: AtomicBool,
}

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

impl WebSocketRateLimiter {
    /// Create new rate limiter with configuration
    pub fn new(config: RateLimitConfig) -> Self {
        Self {
            config,
            clients: Arc::new(DashMap::new()),
            cleanup_spawned: AtomicBool::new(false),
        }
    }

    /// Returns the rate-limit configuration this limiter was constructed with.
    pub fn config(&self) -> &RateLimitConfig {
        &self.config
    }

    /// Returns the number of requests still permitted for `ip` within the
    /// current window: `max_requests_per_window` minus the number of request
    /// timestamps currently recorded for that client that still fall inside
    /// `window_duration`.
    ///
    /// An IP with no tracked state (never seen, or evicted by
    /// [`Self::cleanup_expired`]) has its full quota remaining. Read-only —
    /// unlike [`Self::check_request`], this never prunes `client.requests`
    /// itself; it counts a window-filtered view without mutating state, using
    /// the same `checked_sub`/fail-closed guard `check_request` uses (skip
    /// filtering, i.e. count every tracked timestamp, rather than panicking
    /// or under-counting on a host whose uptime is shorter than
    /// `window_duration`). This reflects only the request-count window
    /// backing `check_request`/`X-RateLimit-*` response headers — it says
    /// nothing about the independent connection-count
    /// ([`Self::check_connection`]) or message-rate ([`Self::check_message`])
    /// limits.
    pub fn remaining_for(&self, ip: IpAddr) -> u32 {
        let Some(client) = self.clients.get(&ip) else {
            return self.config.max_requests_per_window;
        };

        let now = Instant::now();
        let window_start = now.checked_sub(self.config.window_duration);
        let used = client
            .requests
            .iter()
            .filter(|&&t| window_start.is_none_or(|start| t > start))
            .count();

        self.config
            .max_requests_per_window
            .saturating_sub(used as u32)
    }

    /// Returns the duration until `ip`'s rate-limit window next admits at
    /// least one more request — i.e. until its oldest currently-counted
    /// request timestamp ages out of `window_duration`. `Duration::ZERO` if
    /// `ip` is untracked or has no request currently counted against it
    /// (quota is already fully available, so there is nothing to wait for).
    ///
    /// `client.requests` is push-ordered ascending and `retain` (used by
    /// [`Self::check_request`]) preserves that order, so the earliest entry
    /// still inside the window is the next to expire and determines this
    /// value — this is the real sliding-window reset instant, not an
    /// approximation. Backs both the `X-RateLimit-Reset` response header and
    /// the `Retry-After` hint on a `429` rejection.
    ///
    /// Fails closed like [`Self::remaining_for`]: on a host whose uptime is
    /// shorter than `window_duration` (`now.checked_sub` underflows), this
    /// returns the full `window_duration` rather than treating every
    /// untrimmed timestamp as already-expired — the latter would report
    /// `Duration::ZERO` (quota already fully available) for a client that
    /// is, in reality, still within its window.
    pub fn reset_after(&self, ip: IpAddr) -> Duration {
        let Some(client) = self.clients.get(&ip) else {
            return Duration::ZERO;
        };

        let now = Instant::now();
        let Some(window_start) = now.checked_sub(self.config.window_duration) else {
            return self.config.window_duration;
        };
        let earliest_active = client.requests.iter().find(|&&t| t > window_start);

        match earliest_active {
            Some(&earliest) => self
                .config
                .window_duration
                .saturating_sub(now.saturating_duration_since(earliest)),
            None => Duration::ZERO,
        }
    }

    /// Spawn a background task that periodically calls [`Self::cleanup_expired`].
    ///
    /// Idempotent: calling this more than once on the same limiter (e.g. when
    /// several `RateLimitMiddleware`s wrap the same shared `Arc`) spawns only
    /// one task. Requires a Tokio runtime; if none is available, logs a
    /// warning and returns without spawning rather than panicking, since
    /// bare construction of this limiter (and its wrappers) must remain
    /// usable from non-async contexts — a later call to this method (e.g.
    /// once code has entered an async runtime) can still succeed.
    ///
    /// The task holds only a `Weak` reference to `self` and exits on its
    /// own once every strong reference to the limiter is dropped, so it never
    /// keeps the limiter (or its client map) alive past its last owner.
    pub fn spawn_cleanup_task(self: &Arc<Self>, period: Duration) {
        // Claim the right to spawn. If another call already claimed it
        // (whether it succeeded or is in flight), this call is a no-op.
        //
        // Narrow window, not airtight: a concurrent in-runtime caller whose
        // `swap` lands between a no-runtime caller's `swap(true)` above and
        // its rollback `store(false)` below observes the claim as already
        // taken and returns without spawning, even though it could have
        // succeeded. No current call site constructs a limiter and races
        // `spawn_cleanup_task` from both a runtime and a non-runtime thread
        // concurrently, so this is intentionally left as a plain `swap`
        // rather than a CAS retry loop; revisit if that changes.
        if self.cleanup_spawned.swap(true, Ordering::AcqRel) {
            return;
        }

        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            // Release the claim: no runtime was available, so nothing was
            // actually spawned. A later call must be able to retry rather
            // than finding cleanup permanently disabled.
            self.cleanup_spawned.store(false, Ordering::Release);
            tracing::warn!(
                "WebSocketRateLimiter::spawn_cleanup_task: no Tokio runtime available; \
                 periodic cleanup not started"
            );
            return;
        };

        let weak = Arc::downgrade(self);
        handle.spawn(async move {
            let mut interval = tokio::time::interval(period);
            loop {
                interval.tick().await;
                let Some(limiter) = weak.upgrade() else {
                    break;
                };
                limiter.cleanup_expired();
                tracing::debug!("WebSocketRateLimiter: cleanup pass completed");
            }
        });
    }

    /// Whether a cleanup task spawn has been successfully claimed (test-only).
    ///
    /// Lets tests assert that a call site (e.g. `RateLimitMiddleware::new`/
    /// `from_limiter`) actually wired up `spawn_cleanup_task` without waiting
    /// for a real cleanup pass on the production [`DEFAULT_CLEANUP_INTERVAL`].
    #[cfg(test)]
    pub(crate) fn is_cleanup_task_spawned(&self) -> bool {
        self.cleanup_spawned.load(Ordering::Acquire)
    }

    /// Check if request is allowed (HTTP upgrade to WebSocket)
    pub fn check_request(&self, ip: IpAddr) -> Result<(), RateLimitError> {
        if !self.clients.contains_key(&ip) && self.clients.len() >= MAX_TRACKED_CLIENTS {
            return Err(RateLimitError::CapacityExceeded {
                max: MAX_TRACKED_CLIENTS,
            });
        }

        let now = Instant::now();
        let burst = self.config.burst_allowance;
        let mut client = self
            .clients
            .entry(ip)
            .or_insert_with(|| ClientRateLimit::new(burst));

        // `checked_sub` rather than a bare subtraction: on a host whose
        // uptime is shorter than `window_duration` (observed to matter on
        // Windows' QPC-backed `Instant`, which is in the CI matrix), the
        // naive subtraction underflows and panics on the request hot path.
        //
        // On underflow, skip trimming this call rather than either
        // panicking or wiping the client's history: wiping (falling back to
        // an empty window) would fail *open* for exactly the client this
        // control exists to stop — one already at or over its limit could
        // bypass it entirely just by making one more request during this
        // narrow condition (a freshly booted host, or a deliberately
        // crashed-and-restarted service). Denying every request outright
        // instead would fail closed correctly, but for *every* client,
        // including ones that have never made a request before — no
        // different from a hard outage for up to `window_duration` after
        // every process start, on a host that happens to hit this edge
        // case. Keeping the untrimmed history is the fail-closed choice
        // that costs neither: an already-over-limit client's stale entries
        // still count against it (a superset of the correctly windowed
        // history is at least as likely to already be at/over the limit),
        // while a client with no prior history is unaffected either way.
        // The history transiently over-retains stale entries only for the
        // (self-limiting) duration this condition holds; once real uptime
        // exceeds `window_duration`, `checked_sub` succeeds again and
        // trimming resumes, catching up on the backlog in one pass.
        if let Some(window_start) = now.checked_sub(self.config.window_duration) {
            client.requests.retain(|&time| time > window_start);
        }

        // Check request rate limit
        if client.requests.len() >= self.config.max_requests_per_window as usize {
            return Err(RateLimitError::LimitExceeded {
                limit: self.config.max_requests_per_window,
                window: self.config.window_duration,
            });
        }

        // Add current request
        client.requests.push(now);
        Ok(())
    }

    /// Check if new connection is allowed
    pub fn check_connection(&self, ip: IpAddr) -> Result<(), RateLimitError> {
        if !self.clients.contains_key(&ip) && self.clients.len() >= MAX_TRACKED_CLIENTS {
            return Err(RateLimitError::CapacityExceeded {
                max: MAX_TRACKED_CLIENTS,
            });
        }

        let burst = self.config.burst_allowance;
        let mut client = self
            .clients
            .entry(ip)
            .or_insert_with(|| ClientRateLimit::new(burst));

        if client.connection_count >= self.config.max_connections_per_ip {
            return Err(RateLimitError::ConnectionLimitExceeded {
                current: client.connection_count,
                max: self.config.max_connections_per_ip,
            });
        }

        client.connection_count += 1;
        Ok(())
    }

    /// Register connection close
    pub fn close_connection(&self, ip: IpAddr) {
        if let Some(mut client) = self.clients.get_mut(&ip) {
            client.connection_count = client.connection_count.saturating_sub(1);
        }
    }

    /// Check if WebSocket message is allowed
    pub fn check_message(&self, ip: IpAddr, frame_size: usize) -> Result<(), RateLimitError> {
        // Check frame size
        if frame_size > self.config.max_frame_size {
            return Err(RateLimitError::FrameSizeExceeded {
                size: frame_size,
                max: self.config.max_frame_size,
            });
        }

        // Check message rate
        if let Some(mut client) = self.clients.get_mut(&ip) {
            client.check_message_rate(&self.config)?;
        }

        Ok(())
    }

    /// Get current statistics for monitoring
    pub fn stats(&self) -> RateLimitStats {
        let mut stats = RateLimitStats::default();

        for entry in self.clients.iter() {
            stats.total_clients += 1;
            stats.total_connections += entry.value().connection_count;

            if entry.value().connection_count > 0 {
                stats.active_clients += 1;
            }
        }

        stats
    }

    /// Clean up expired entries (call periodically)
    pub fn cleanup_expired(&self) {
        let now = Instant::now();
        // `checked_sub` rather than a bare subtraction: on a host whose
        // uptime is shorter than `window_duration * 2` (fresh container, or
        // a large configured window), the naive subtraction underflows
        // `Instant` and panics, permanently killing whichever loop calls
        // this. Skip this pass instead — the next sweep, once enough
        // wall-clock time has elapsed, will succeed.
        let Some(cutoff) = now.checked_sub(self.config.window_duration * 2) else {
            return;
        };

        self.clients.retain(|_, client| {
            // Remove clients with no recent activity and no connections
            !(client.connection_count == 0
                && client.requests.last().is_none_or(|&time| time < cutoff))
        });
    }
}

/// Rate limiting statistics
#[derive(Debug, Default, Clone)]
pub struct RateLimitStats {
    /// Total distinct clients tracked.
    pub total_clients: usize,
    /// Clients that have shown activity within the recent window.
    pub active_clients: usize,
    /// Sum of currently held connections across all clients.
    pub total_connections: usize,
}

/// Rate limiting middleware for tracking client IPs
///
/// Deliberately not `Clone`: [`Drop`] decrements a connection counter, so a
/// clone would silently over-decrement it. Existing callers that need to
/// share ownership wrap this in `Arc` instead (see
/// `infrastructure::websocket::server`).
#[derive(Debug)]
pub struct RateLimitGuard {
    rate_limiter: Arc<WebSocketRateLimiter>,
    client_ip: IpAddr,
}

impl RateLimitGuard {
    /// Create new guard for a client connection
    pub fn new(
        rate_limiter: Arc<WebSocketRateLimiter>,
        client_ip: IpAddr,
    ) -> Result<Self, RateLimitError> {
        rate_limiter.check_connection(client_ip)?;

        Ok(Self {
            rate_limiter,
            client_ip,
        })
    }

    /// Check if message is allowed
    pub fn check_message(&self, frame_size: usize) -> Result<(), RateLimitError> {
        self.rate_limiter.check_message(self.client_ip, frame_size)
    }
}

impl Drop for RateLimitGuard {
    fn drop(&mut self) {
        self.rate_limiter.close_connection(self.client_ip);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn test_rate_limit_requests() {
        let config = RateLimitConfig {
            max_requests_per_window: 2,
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // First two requests should succeed
        assert!(limiter.check_request(ip).is_ok());
        assert!(limiter.check_request(ip).is_ok());

        // Third request should be rate limited
        assert!(limiter.check_request(ip).is_err());

        // Wait for window to reset
        thread::sleep(Duration::from_millis(110));

        // Should work again
        assert!(limiter.check_request(ip).is_ok());
    }

    #[test]
    fn test_connection_limits() {
        let config = RateLimitConfig {
            max_connections_per_ip: 2,
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Two connections should succeed
        assert!(limiter.check_connection(ip).is_ok());
        assert!(limiter.check_connection(ip).is_ok());

        // Third connection should fail
        assert!(limiter.check_connection(ip).is_err());

        // Close one connection
        limiter.close_connection(ip);

        // Should work again
        assert!(limiter.check_connection(ip).is_ok());
    }

    #[test]
    fn test_message_rate_limiting() {
        let config = RateLimitConfig {
            max_messages_per_second: 2,
            burst_allowance: 2, // Allow 2 burst messages
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config.clone());
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // First connection should create the client entry
        let client = limiter
            .clients
            .entry(ip)
            .or_insert_with(|| ClientRateLimit::new(config.burst_allowance));
        // Tokens are already initialized with burst_allowance
        drop(client);

        // Should allow burst messages
        assert!(limiter.check_message(ip, 1024).is_ok());
        assert!(limiter.check_message(ip, 1024).is_ok());

        // Should be rate limited now (no more tokens)
        assert!(limiter.check_message(ip, 1024).is_err());
    }

    #[test]
    fn test_frame_size_limits() {
        let config = RateLimitConfig {
            max_frame_size: 1024,
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Small frame should succeed
        assert!(limiter.check_message(ip, 512).is_ok());

        // Large frame should fail
        assert!(limiter.check_message(ip, 2048).is_err());
    }

    #[test]
    fn test_rate_limit_guard() {
        let config = RateLimitConfig {
            max_connections_per_ip: 1,
            ..Default::default()
        };

        let limiter = Arc::new(WebSocketRateLimiter::new(config));
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Create guard
        let guard = RateLimitGuard::new(limiter.clone(), ip).unwrap();

        // Second connection should fail
        assert!(RateLimitGuard::new(limiter.clone(), ip).is_err());

        // Drop guard
        drop(guard);

        // Should work again
        assert!(RateLimitGuard::new(limiter, ip).is_ok());
    }

    #[test]
    fn test_token_refill_over_time() {
        let config = RateLimitConfig {
            max_messages_per_second: 1,
            burst_allowance: 0,
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config.clone());
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Pre-fill tokens to test refill
        {
            let mut client = limiter
                .clients
                .entry(ip)
                .or_insert_with(|| ClientRateLimit::new(config.burst_allowance));
            client.tokens = 0.5; // Start with partial token
        }

        // Should fail with insufficient tokens
        assert!(limiter.check_message(ip, 512).is_err());

        // Wait for token refill (1 second = max_messages_per_second tokens)
        thread::sleep(Duration::from_millis(1100));

        // Should work again after tokens refill (refilled tokens + remaining time)
        let result = limiter.check_message(ip, 512);
        // After 1.1 seconds, should have refilled enough tokens to pass
        assert!(result.is_ok(), "Expected refilled tokens to allow message");
    }

    #[test]
    fn test_cleanup_expired_entries() {
        let config = RateLimitConfig {
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));

        // Add some client entries
        assert!(limiter.check_connection(ip1).is_ok());
        assert!(limiter.check_connection(ip2).is_ok());

        // Should have 2 clients
        assert_eq!(limiter.stats().total_clients, 2);

        // Close connection for ip1
        limiter.close_connection(ip1);

        // Wait beyond the cleanup window
        thread::sleep(Duration::from_millis(250));

        // Cleanup should remove idle clients
        limiter.cleanup_expired();

        // After cleanup, ip1 should be removed but ip2 might remain if it has recent activity
        let stats = limiter.stats();
        // At minimum, ip1 should be cleaned up if no connections
        assert!(stats.total_clients <= 2);
    }

    #[test]
    fn test_multiple_ips_isolation() {
        let config = RateLimitConfig {
            max_requests_per_window: 1,
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));

        // ip1 should be rate limited after 1 request
        assert!(limiter.check_request(ip1).is_ok());
        assert!(limiter.check_request(ip1).is_err());

        // ip2 should NOT be affected by ip1's limit
        assert!(limiter.check_request(ip2).is_ok());
        assert!(limiter.check_request(ip2).is_err());
    }

    #[test]
    fn test_burst_allowance_boundary() {
        let config = RateLimitConfig {
            max_messages_per_second: 1,
            burst_allowance: 0,
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config.clone());
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // With 0 burst, even the first message might be throttled
        // depending on token distribution
        let mut client = limiter
            .clients
            .entry(ip)
            .or_insert_with(|| ClientRateLimit::new(config.burst_allowance));
        client.tokens = 0.0;
        drop(client);

        // Should fail with no tokens
        assert!(limiter.check_message(ip, 512).is_err());
    }

    #[test]
    fn test_rate_limit_config_high_traffic() {
        let config = RateLimitConfig::high_traffic();

        assert_eq!(config.max_requests_per_window, 1000);
        assert_eq!(config.max_connections_per_ip, 50);
        assert_eq!(config.max_messages_per_second, 100);
        assert_eq!(config.burst_allowance, 20);
        assert!(config.max_frame_size >= 1024 * 1024);
    }

    #[test]
    fn test_rate_limit_config_low_resource() {
        let config = RateLimitConfig::low_resource();

        assert_eq!(config.max_requests_per_window, 20);
        assert_eq!(config.max_connections_per_ip, 2);
        assert_eq!(config.max_messages_per_second, 5);
        assert_eq!(config.burst_allowance, 2);
        assert_eq!(config.max_frame_size, 256 * 1024);
        assert_eq!(config.write_timeout, Duration::from_secs(3));
        assert!(config.write_timeout < RateLimitConfig::default().write_timeout);
    }

    #[test]
    fn test_frame_size_boundary_exact() {
        let config = RateLimitConfig {
            max_frame_size: 1024,
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Exactly at limit should succeed
        assert!(limiter.check_message(ip, 1024).is_ok());

        // Just over limit should fail
        assert!(limiter.check_message(ip, 1025).is_err());

        // Zero-size frame should succeed (though uncommon)
        assert!(limiter.check_message(ip, 0).is_ok());
    }

    #[test]
    fn test_stats_accuracy() {
        let config = RateLimitConfig {
            max_connections_per_ip: 5,
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));

        // Add connections
        assert!(limiter.check_connection(ip1).is_ok());
        assert!(limiter.check_connection(ip1).is_ok());
        assert!(limiter.check_connection(ip2).is_ok());

        let stats = limiter.stats();
        assert_eq!(stats.total_clients, 2);
        assert_eq!(stats.total_connections, 3);
        assert_eq!(stats.active_clients, 2);

        // Close a connection
        limiter.close_connection(ip1);

        let stats = limiter.stats();
        assert_eq!(stats.total_connections, 2);
    }

    #[test]
    fn test_window_duration_respected() {
        let config = RateLimitConfig {
            max_requests_per_window: 1,
            window_duration: Duration::from_millis(50),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // First request succeeds
        assert!(limiter.check_request(ip).is_ok());

        // Second request within window fails
        assert!(limiter.check_request(ip).is_err());

        // Wait for window to pass
        thread::sleep(Duration::from_millis(60));

        // Request after window passes succeeds
        assert!(limiter.check_request(ip).is_ok());
    }

    #[test]
    fn test_default_limiter() {
        // Test Default implementation for WebSocketRateLimiter
        let limiter = WebSocketRateLimiter::default();
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Default limiter should allow requests
        assert!(limiter.check_request(ip).is_ok());
        assert!(limiter.check_connection(ip).is_ok());

        // Verify default config values are applied
        let stats = limiter.stats();
        assert_eq!(stats.total_clients, 1);
        assert_eq!(stats.total_connections, 1);
    }

    #[test]
    fn test_cleanup_expired_removes_inactive_clients() {
        let config = RateLimitConfig {
            window_duration: Duration::from_millis(50),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));
        let ip3 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 3));

        // Add requests for multiple IPs
        assert!(limiter.check_request(ip1).is_ok());
        assert!(limiter.check_request(ip2).is_ok());
        assert!(limiter.check_connection(ip3).is_ok());

        let initial_stats = limiter.stats();
        assert_eq!(initial_stats.total_clients, 3);

        // Wait for cleanup window
        thread::sleep(Duration::from_millis(150));

        // ip3 has no requests, so it should be removed
        limiter.cleanup_expired();

        let after_cleanup = limiter.stats();
        // ip3 should be removed (no requests, no connections after cleanup)
        assert!(after_cleanup.total_clients <= initial_stats.total_clients);
    }

    #[test]
    fn test_client_with_zero_connections_and_no_recent_requests_cleaned() {
        let config = RateLimitConfig {
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));

        // Make a request
        assert!(limiter.check_request(ip).is_ok());

        // Verify client exists
        let initial_stats = limiter.stats();
        assert_eq!(initial_stats.total_clients, 1);

        // Wait beyond cleanup window (2x window_duration)
        thread::sleep(Duration::from_millis(250));

        // Cleanup should remove the client (no connections and stale requests)
        limiter.cleanup_expired();

        let final_stats = limiter.stats();
        // The client should be removed if no active connections
        assert_eq!(final_stats.total_clients, 0);
    }

    #[test]
    fn test_cleanup_preserves_active_clients() {
        let config = RateLimitConfig {
            window_duration: Duration::from_millis(100),
            ..Default::default()
        };

        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2));

        // ip1: has active connection
        assert!(limiter.check_connection(ip1).is_ok());

        // ip2: has recent request but no connection
        assert!(limiter.check_request(ip2).is_ok());

        let initial_stats = limiter.stats();
        assert_eq!(initial_stats.total_clients, 2);

        // Wait some time (but not beyond full cleanup window)
        thread::sleep(Duration::from_millis(80));

        // Make another request to ip2 to keep it fresh
        let _ = limiter.check_request(ip2);

        // Cleanup should preserve both clients
        limiter.cleanup_expired();

        let final_stats = limiter.stats();
        // ip1 should be preserved (active connection)
        assert!(final_stats.total_clients >= 1);
    }

    #[test]
    fn test_close_connection_on_nonexistent_ip() {
        let limiter = WebSocketRateLimiter::default();
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 99));

        // Closing connection on non-existent IP should not panic
        limiter.close_connection(ip);

        // Stats should be empty
        let stats = limiter.stats();
        assert_eq!(stats.total_clients, 0);
    }

    #[test]
    fn test_check_message_on_nonexistent_client() {
        let limiter = WebSocketRateLimiter::default();
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 88));

        // Checking message on non-existent IP should be OK for frame size
        // but not create the client entry if it doesn't exist in clients map
        assert!(limiter.check_message(ip, 512).is_ok());
    }

    #[test]
    fn test_rate_limit_guard_check_message() {
        let config = RateLimitConfig {
            max_connections_per_ip: 5,
            max_frame_size: 1024,
            max_messages_per_second: 10,
            burst_allowance: 5,
            ..Default::default()
        };

        let limiter = Arc::new(WebSocketRateLimiter::new(config));
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        let guard = RateLimitGuard::new(limiter.clone(), ip).unwrap();

        assert!(guard.check_message(512).is_ok());
        assert!(guard.check_message(512).is_ok());
        assert!(guard.check_message(2048).is_err());
    }

    #[test]
    fn test_rate_limit_guard_check_message_rate_limit() {
        let config = RateLimitConfig {
            max_connections_per_ip: 5,
            max_frame_size: 10_000,
            max_messages_per_second: 2,
            burst_allowance: 2,
            ..Default::default()
        };

        let limiter = Arc::new(WebSocketRateLimiter::new(config));
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));

        let guard = RateLimitGuard::new(limiter.clone(), ip).unwrap();

        assert!(guard.check_message(512).is_ok());
        assert!(guard.check_message(512).is_ok());
        assert!(guard.check_message(512).is_err());
    }

    #[test]
    fn test_capacity_cap_rejects_new_clients_when_full() {
        let limiter = WebSocketRateLimiter::default();

        for i in 0..MAX_TRACKED_CLIENTS as u32 {
            let ip = IpAddr::V4(Ipv4Addr::from(i));
            limiter.check_request(ip).unwrap();
        }
        assert_eq!(limiter.stats().total_clients, MAX_TRACKED_CLIENTS);

        // A new, not-yet-tracked IP is rejected once at capacity — this is
        // what bounds the map's size *within* a single cleanup sweep window,
        // not just across sweeps.
        let overflow_ip = IpAddr::V4(Ipv4Addr::from(MAX_TRACKED_CLIENTS as u32));
        let result = limiter.check_request(overflow_ip);
        assert!(matches!(
            result,
            Err(RateLimitError::CapacityExceeded { max }) if max == MAX_TRACKED_CLIENTS
        ));
        assert_eq!(limiter.stats().total_clients, MAX_TRACKED_CLIENTS);

        // An already-tracked IP is unaffected by the cap.
        let existing_ip = IpAddr::V4(Ipv4Addr::from(0u32));
        assert!(limiter.check_request(existing_ip).is_ok());
    }

    #[test]
    fn test_cleanup_expired_never_panics_regardless_of_window_duration() {
        // `Instant` intentionally exposes no public constructor for an
        // arbitrary point in time, so whether `Instant::now().checked_sub(..)`
        // actually underflows for a given `window_duration` depends on the
        // OS's monotonic clock epoch, which is unspecified and cannot be
        // forced deterministically from a portable unit test (observed to
        // matter in practice on Windows' QPC-backed `Instant` near process
        // or host start — exercised naturally by the Windows CI legs, not by
        // this test). What this test pins down instead is the invariant that
        // actually matters regardless of which branch runs on a given host:
        // `cleanup_expired` must never panic for any configured
        // `window_duration`, including ones designed to underflow, and must
        // never evict a client with a request timestamped just now.
        for window_secs in [1, 60, 3600, u64::MAX / 8] {
            let config = RateLimitConfig {
                window_duration: Duration::from_secs(window_secs),
                ..Default::default()
            };
            let limiter = WebSocketRateLimiter::new(config);
            let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
            limiter.check_request(ip).unwrap();

            limiter.cleanup_expired(); // Must not panic for any window_secs above.

            assert_eq!(
                limiter.stats().total_clients,
                1,
                "a client with a just-now request must survive cleanup regardless \
                 of window_secs={window_secs}"
            );
        }
    }

    #[test]
    fn test_check_request_never_panics_regardless_of_window_duration() {
        // Same rationale as the `cleanup_expired` test above, but for the
        // `checked_sub` guard on the request hot path in `check_request`,
        // and its two read-only siblings `remaining_for`/`reset_after`
        // (which share the same guard). Whether `checked_sub` actually
        // underflows for a given window_secs is platform-dependent (see
        // `test_cleanup_expired_never_panics_...` above) — this test only
        // pins down that none of the three ever panics regardless of which
        // branch runs, including with a `window_duration` near `u64::MAX`
        // seconds (reachable, since `RateLimitConfig` is `Deserialize` with
        // an all-`pub` `window_duration: Duration` field).
        for window_secs in [1, 60, 3600, u64::MAX / 8] {
            let config = RateLimitConfig {
                window_duration: Duration::from_secs(window_secs),
                ..Default::default()
            };
            let limiter = WebSocketRateLimiter::new(config);
            let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

            let _ = limiter.check_request(ip); // Must not panic for any window_secs above.
            let _ = limiter.remaining_for(ip);
            let _ = limiter.reset_after(ip);
        }
    }

    #[test]
    fn test_remaining_for_fresh_ip_returns_full_quota() {
        let config = RateLimitConfig {
            max_requests_per_window: 10,
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Never-seen IP has its full quota remaining.
        assert_eq!(limiter.remaining_for(ip), 10);
    }

    #[test]
    fn test_remaining_for_decreases_with_consumed_requests() {
        let config = RateLimitConfig {
            max_requests_per_window: 5,
            window_duration: Duration::from_secs(60),
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        assert_eq!(limiter.remaining_for(ip), 5);

        limiter.check_request(ip).unwrap();
        assert_eq!(limiter.remaining_for(ip), 4);

        limiter.check_request(ip).unwrap();
        limiter.check_request(ip).unwrap();
        assert_eq!(limiter.remaining_for(ip), 2);
    }

    #[test]
    fn test_remaining_for_saturates_at_zero_when_quota_exhausted() {
        let config = RateLimitConfig {
            max_requests_per_window: 2,
            window_duration: Duration::from_secs(60),
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Exhaust the quota; the second call succeeds, the third is rejected
        // and must not record an extra timestamp.
        assert!(limiter.check_request(ip).is_ok());
        assert!(limiter.check_request(ip).is_ok());
        assert!(limiter.check_request(ip).is_err());

        // `saturating_sub` must not underflow even if usage ever exceeded
        // the configured limit.
        assert_eq!(limiter.remaining_for(ip), 0);
    }

    #[test]
    fn test_remaining_for_isolated_per_ip() {
        let config = RateLimitConfig {
            max_requests_per_window: 3,
            window_duration: Duration::from_secs(60),
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));

        limiter.check_request(ip1).unwrap();
        limiter.check_request(ip1).unwrap();

        assert_eq!(limiter.remaining_for(ip1), 1);
        assert_eq!(limiter.remaining_for(ip2), 3);
    }

    #[test]
    fn test_remaining_for_prunes_expired_requests_like_check_request() {
        // Deterministic counterexample for the gap `remaining_for` used to
        // have: without window pruning, 5 requests at t=0 under a 500ms
        // window would still read as 0 remaining at t=1000ms, even though
        // `check_request` would freely admit all 5 again by then. Timing
        // margins are kept generous (5x an earlier, tighter version) to stay
        // well clear of OS timer granularity / nextest parallelism jitter.
        let config = RateLimitConfig {
            max_requests_per_window: 5,
            window_duration: Duration::from_millis(500),
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        for _ in 0..5 {
            limiter.check_request(ip).unwrap();
        }
        assert_eq!(limiter.remaining_for(ip), 0);

        thread::sleep(Duration::from_millis(1000));

        assert_eq!(limiter.remaining_for(ip), 5);
        assert!(limiter.check_request(ip).is_ok());
    }

    #[test]
    fn test_reset_after_untracked_ip_is_zero() {
        let limiter = WebSocketRateLimiter::default();
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        assert_eq!(limiter.reset_after(ip), Duration::ZERO);
    }

    #[test]
    fn test_reset_after_reflects_oldest_active_request() {
        // Timing margins scaled up (5x an earlier, tighter version) to stay
        // well clear of OS timer granularity / nextest parallelism jitter.
        let config = RateLimitConfig {
            max_requests_per_window: 5,
            window_duration: Duration::from_millis(1000),
            ..Default::default()
        };
        let limiter = WebSocketRateLimiter::new(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        limiter.check_request(ip).unwrap();
        let just_after = limiter.reset_after(ip);
        // Just after the request, almost the entire window remains.
        assert!(just_after > Duration::from_millis(750));
        assert!(just_after <= Duration::from_millis(1000));

        thread::sleep(Duration::from_millis(600));
        let later = limiter.reset_after(ip);
        // The wait has shrunk by roughly the elapsed sleep.
        assert!(later < just_after);
        assert!(later <= Duration::from_millis(400));

        thread::sleep(Duration::from_millis(1000));
        // The oldest (only) request has now aged out of the window.
        assert_eq!(limiter.reset_after(ip), Duration::ZERO);
    }

    #[tokio::test]
    async fn test_spawn_cleanup_task_is_idempotent() {
        let limiter = Arc::new(WebSocketRateLimiter::new(RateLimitConfig {
            window_duration: Duration::from_millis(1),
            ..Default::default()
        }));

        // Calling this more than once must not spawn a second task (and must
        // not panic); the loop below only passes if exactly the expected
        // single cleanup pass took effect.
        limiter.spawn_cleanup_task(Duration::from_millis(10));
        limiter.spawn_cleanup_task(Duration::from_millis(10));

        let ip = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
        limiter.check_request(ip).unwrap();

        tokio::time::sleep(Duration::from_millis(100)).await;

        assert_eq!(limiter.stats().total_clients, 0);
    }
}