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
//! Global connection and memory-pressure limits.
//!
//! Two coarse back-pressure controls that the accept loops consult before
//! taking on a new connection: a process-wide concurrent-connection cap
//! (Invariant 64) tracked by an atomic counter, and a memory-pressure check
//! (Invariant 66) that reads `/proc/meminfo` on Linux. Together they let the
//! server shed load instead of falling over when overwhelmed.
//!
//! The connection counter is acquired with
//! [`acquire_connection`](crate::security::limits::acquire_connection) and
//! released with
//! [`release_connection`](crate::security::limits::release_connection); in the
//! server these are paired by an RAII guard so a dropped connection always
//! decrements the count.
use ;
/// Global connection counter (Invariant 64: Bounded request queues)
static ACTIVE_CONNECTIONS: AtomicUsize = new;
const MAX_CONNECTIONS: usize = 10000;
/// Memory pressure threshold (Invariant 66) — accept loops reject new
/// connections when less than this fraction of system memory is available.
pub const MEMORY_PRESSURE_THRESHOLD: f64 = 0.05; // 5% free
/// Whether the active-connection count has reached the global cap.
/// Try to reserve a connection slot.
///
/// Returns `true` if a slot was taken (the caller must later call
/// [`release_connection`]), or `false` if the cap was already reached — in
/// which case nothing is reserved and the connection should be rejected.
/// Release a slot previously reserved by [`acquire_connection`].
/// Whether available system memory has dropped below `threshold` (a fraction in
/// `0.0..=1.0`, e.g. [`MEMORY_PRESSURE_THRESHOLD`]).
///
/// Reads `/proc/meminfo` on Linux. On other platforms, or if the file cannot
/// be read, returns `false` (fail open — never block traffic on a missing
/// metric).
/// Current number of active connections (for metrics and tests).