Skip to main content

weida_core/
limits.rs

1//! Resource limits.
2//!
3//! Master doc §50: no internal queue may be unbounded, and every allocation
4//! that a remote peer can influence must have a defensive ceiling. Each field
5//! below names the remote-controlled quantity it bounds.
6//!
7//! **`Limits` is a per-connection profile.** Every field applies to one
8//! connection — which is what a runtime holding one profile per connection
9//! tier will need
10//! (`docs/decisions/0002-control-and-bulk-separation.md` §6.4). Numbers that
11//! belong to a runtime rather than to a connection — how many connections a
12//! binding accepts, how many one peer may hold, how deep an endpoint's queue
13//! is, how many resolved addresses a dial tries — live on `RuntimeConfig`
14//! instead, so that no profile can carry a value nothing reads.
15
16use std::time::Duration;
17
18/// Resource limits applied to one connection.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct Limits {
21    /// Largest frame header this side will accept, in bytes. Checked against
22    /// the preamble length *before* any allocation.
23    pub max_header_bytes: u64,
24    /// QUIC concurrent inbound unidirectional streams. Bounds the number of
25    /// live per-stream parse tasks for one-way transfers.
26    pub max_concurrent_uni_streams: u32,
27    /// QUIC concurrent inbound bidirectional streams; bounds live request
28    /// exchanges per connection and, with `max_header_bytes`, worst-case
29    /// header memory.
30    pub max_concurrent_bidi_streams: u32,
31    /// QUIC per-stream receive window in bytes. Bounds buffered payload for one
32    /// transfer and provides backpressure to the sender.
33    pub stream_receive_window: u64,
34    /// QUIC per-connection receive window in bytes.
35    pub connection_receive_window: u64,
36    /// QUIC keep-alive interval. Sent by the dialling side only, so a binding's
37    /// value is not used.
38    pub keep_alive: Duration,
39    /// QUIC idle timeout, applied in both directions.
40    pub idle_timeout: Duration,
41    /// How long to wait for the peer HELLO before closing the connection with
42    /// `NEGOTIATION_FAILED`, in milliseconds.
43    pub hello_timeout_ms: u64,
44    /// Subscription filters one peer connection may hold at once, summed over
45    /// every path. Exceeding it closes the connection with `LIMIT_EXCEEDED`:
46    /// SUBSCRIBE has no stream to answer with an ERROR frame.
47    pub max_subscriptions: usize,
48    /// Payload bytes a publisher may hold queued for one subscriber. A message
49    /// that does not fit is dropped for that subscriber and counted; the
50    /// publisher never blocks on a slow consumer.
51    pub subscriber_buffer_bytes: usize,
52    /// Producer scopes — paths and topics — a receiver tracks per connection
53    /// for gap detection or reassembly, when `PerProducer` ordering is
54    /// negotiated. The peer chooses the scope names, so the table needs a
55    /// ceiling; at the cap a new scope is simply not tracked, no gap is
56    /// reported for it and nothing is held back for it.
57    pub max_sequence_scopes: usize,
58    /// Transfers a receiver may hold back at once, summed over scopes, when
59    /// `PerProducer(reassemble)` ordering is negotiated. A held transfer is
60    /// an unread stream, so the bytes it pins are quinn's — up to
61    /// `stream_receive_window` for it and `connection_receive_window` for the
62    /// hold as a whole. At the cap the oldest held transfer is released out
63    /// of order with its gap reported, never held in a growing buffer.
64    pub max_reorder_hold: usize,
65    /// Live transfers on one **local** connection, where the OS connection
66    /// *is* the stream and there is no multiplexing
67    /// ([decisions/0010](../../../docs/decisions/0010-local-transport.md)
68    /// §4.2). Windows caps named-pipe instances at 1-255, which is the
69    /// tightest platform limit and therefore the one the default respects;
70    /// an `open` at the cap waits for a live transfer to end, exactly as a
71    /// QUIC `open` waits on the peer's stream budget, rather than refusing.
72    /// A peer configured with zero can therefore open nothing and waits
73    /// until its caller's deadline, exactly as one granted no QUIC streams.
74    ///
75    /// **Each local stream is a file descriptor** on `AF_UNIX` (a handle on
76    /// a named pipe), on each side, besides the connection's own. QUIC is not
77    /// affected: all its streams share one UDP socket. macOS starts a
78    /// process with a soft limit of 256 descriptors, which the default alone
79    /// nearly fills, and a process that holds both ends overruns it with
80    /// `EMFILE`; such a process raises `RLIMIT_NOFILE` or lowers this limit.
81    pub max_local_streams: usize,
82    /// Connections a subscriber parks toward a peer it dialled, so that peer
83    /// can open a stream back
84    /// ([decisions/0012](../../../docs/decisions/0012-local-connection-grouping.md)
85    /// §4.4). An accepted socket cannot be dialled, so fan-out over a local
86    /// socket transport rides connections the subscriber opened and left
87    /// waiting; each is a file descriptor held for a copy that may never
88    /// come, and each counts against `max_local_streams` on both sides. A
89    /// publisher that finds none parked drops that copy and counts it, the
90    /// same answer fan-out already gives an exhausted subscriber budget. Zero
91    /// disables the pool, which makes a subscription over such a transport an
92    /// error at subscribe time rather than a silence.
93    pub max_parked_reverse: usize,
94
95    /// Identities a receiver remembers per connection for `Bounded`
96    /// deduplication. The window bounds how long an identity is kept, not
97    /// how many arrive within it, so the count needs its own ceiling; at the
98    /// cap the oldest entry is evicted, which costs suppression rather than
99    /// memory.
100    pub max_dedup_entries: usize,
101
102    /// Bytes of a peer's QUIC datagrams buffered unread per connection,
103    /// oldest dropped first. **Zero turns flows off**: the connection then
104    /// advertises neither capability code `1` nor `max_datagram_frame_size`,
105    /// buffers nothing and runs no datagram reader
106    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §4.5).
107    /// [`DEFAULT_DATAGRAM_RECEIVE_BYTES`] is the documented value for turning
108    /// them on.
109    pub datagram_receive_bytes: usize,
110    /// Bytes of datagrams queued for sending per connection on QUIC, and per
111    /// flow on a local transport; beyond it the oldest queued one is
112    /// discarded. Bounds what this side holds for a peer that reads slowly.
113    pub datagram_send_bytes: usize,
114    /// Whether this side lists capability code `2` on a QUIC connection, so
115    /// that when the peer lists it too each side sends the other its view of
116    /// the path every 2 s and keeps the peer's latest record, read as
117    /// `ConnectionStats::remote`
118    /// ([decisions/0036](../../../docs/decisions/0036-connection-statistics.md)
119    /// §4.5). Off by default; a local transport never lists it.
120    pub path_report: bool,
121    /// Inbound flows one connection may hold live. Each is a FLOW stream the
122    /// peer opened and a ring this side keeps; a FLOW beyond it is stopped
123    /// with `LIMIT_EXCEEDED`.
124    pub max_flows: usize,
125    /// Unread datagram bytes held per inbound flow; a consumer that falls
126    /// behind loses its oldest datagrams, counted per flow.
127    pub flow_queue_bytes: usize,
128    /// Bytes of datagrams held per connection for flow ids with no live flow
129    /// yet — a datagram can overtake its FLOW header — and the one place a
130    /// peer can make this side hold datagrams it never registered.
131    pub flow_early_bytes: usize,
132    /// How long a datagram waits in that ring for its FLOW header before it
133    /// is dropped and counted.
134    pub flow_early_hold: Duration,
135
136    /// The congestion controller of this profile's QUIC connections. Not a
137    /// bound, but a per-connection choice, which is why it lives here: a
138    /// bulk profile that shares a bottleneck with media may want a different
139    /// controller than a media profile
140    /// ([decisions/0034](../../../docs/decisions/0034-late-is-lost.md) §6).
141    pub congestion: Congestion,
142
143    /// How long one inbound stream may take to deliver its preamble and then
144    /// its header, each read counted from the moment a header slot was free
145    /// for it, in milliseconds. A stream that stalls inside its frame head
146    /// is stopped with `CANCELED` at the deadline and the connection
147    /// survives: the peer opened a stream and then said nothing, which holds
148    /// a unit of its stream credit and a task for as long as it likes
149    /// otherwise, and the QUIC idle timer does not help against a peer that
150    /// keeps the connection alive with its own pings. The wait for the
151    /// peer's HELLO is not counted ([`Limits::hello_timeout_ms`] bounds it).
152    pub header_timeout_ms: u64,
153    /// Inbound streams one connection may have reading their frame head at
154    /// once, and at least one; the rest wait for a free slot without holding
155    /// a buffer. A head is read, decoded and its raw bytes dropped inside one
156    /// slot, so with `max_header_bytes` this is the worst case of header
157    /// memory per connection ([`Limits::worst_case_header_memory`]),
158    /// independent of how many streams the peer's stream budget lets it open
159    /// and of what they do once their head is read.
160    pub max_header_streams: usize,
161}
162
163/// A QUIC congestion controller, as `quinn` implements them.
164#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
165pub enum Congestion {
166    /// CUBIC (RFC 9438), `quinn`'s default: loss-based.
167    #[default]
168    Cubic,
169    /// NewReno (RFC 9002 §7): loss-based, the conservative baseline.
170    NewReno,
171    /// BBR: model-based, reacts to delay rather than waiting for loss.
172    /// `quinn` marks its implementation experimental.
173    Bbr,
174}
175
176/// The documented `Limits::datagram_receive_bytes` for a profile that
177/// enables datagram flows: 64 KiB, about fifty full datagrams.
178pub const DEFAULT_DATAGRAM_RECEIVE_BYTES: usize = 65_536;
179
180impl Limits {
181    /// Inbound streams that may read a frame head at once: the configured
182    /// [`Limits::max_header_streams`], and never fewer than one, because a
183    /// connection that read no head could serve nothing.
184    pub const fn header_slots(&self) -> usize {
185        if self.max_header_streams == 0 {
186            1
187        } else {
188            self.max_header_streams
189        }
190    }
191
192    /// Worst-case memory a single hostile connection can pin in raw frame-head
193    /// bytes, in bytes.
194    ///
195    /// A stream holds a frame head in memory only while it holds one of the
196    /// [`Limits::header_slots`] slots: the bytes are decoded and dropped
197    /// before the slot is given back. So at most that many heads are in
198    /// memory at once, however many streams the peer opens (up to its stream
199    /// budgets, uni *and* bidi) and whatever those streams do after their
200    /// head: wait on a full queue, or live as long as a FLOW or REPORT stream
201    /// does. A buffer grows with the bytes that actually arrive, so the bound
202    /// is the header cap times the smaller of the slots and the stream
203    /// budgets.
204    ///
205    /// What a stream keeps after its head is decoded is not counted here: the
206    /// decoded header, whose text fields have caps of their own (a few KiB at
207    /// most, `docs/PROTOCOL.md` §10), is part of the stream's state, which the
208    /// stream budgets bound.
209    pub const fn worst_case_header_memory(&self) -> u64 {
210        let budget =
211            self.max_concurrent_uni_streams as u64 + self.max_concurrent_bidi_streams as u64;
212        let reading = self.header_slots() as u64;
213        self.max_header_bytes * if reading < budget { reading } else { budget }
214    }
215}
216
217impl Default for Limits {
218    fn default() -> Self {
219        Limits {
220            max_header_bytes: 16 * 1024,
221            max_concurrent_uni_streams: 2048,
222            max_concurrent_bidi_streams: 1024,
223            stream_receive_window: 1024 * 1024,
224            connection_receive_window: 16 * 1024 * 1024,
225            keep_alive: Duration::from_secs(10),
226            idle_timeout: Duration::from_secs(30),
227            hello_timeout_ms: 10_000,
228            max_subscriptions: 256,
229            subscriber_buffer_bytes: 8 * 1024 * 1024,
230            max_sequence_scopes: 1024,
231            max_reorder_hold: 256,
232            max_local_streams: 255,
233            max_parked_reverse: 8,
234
235            max_dedup_entries: 4096,
236            datagram_receive_bytes: 0,
237            datagram_send_bytes: 65_536,
238            path_report: false,
239            max_flows: 64,
240            flow_queue_bytes: 16_384,
241            flow_early_bytes: 4_096,
242            flow_early_hold: Duration::from_secs(1),
243            congestion: Congestion::Cubic,
244            header_timeout_ms: 10_000,
245            max_header_streams: 64,
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn defaults_match_the_protocol_document() {
256        let l = Limits::default();
257        assert_eq!(l.max_header_bytes, 16384);
258        assert_eq!(l.max_concurrent_uni_streams, 2048);
259        assert_eq!(l.max_concurrent_bidi_streams, 1024);
260        assert_eq!(l.stream_receive_window, 1 << 20);
261        assert_eq!(l.connection_receive_window, 16 << 20);
262        assert_eq!(l.keep_alive, Duration::from_secs(10));
263        assert_eq!(l.idle_timeout, Duration::from_secs(30));
264        assert_eq!(l.hello_timeout_ms, 10_000);
265        assert_eq!(l.max_subscriptions, 256);
266        assert_eq!(l.subscriber_buffer_bytes, 8 << 20);
267        assert_eq!(l.max_sequence_scopes, 1024);
268        assert_eq!(l.max_reorder_hold, 256);
269        assert_eq!(l.max_local_streams, 255);
270        assert_eq!(l.max_parked_reverse, 8);
271        assert_eq!(l.max_dedup_entries, 4096);
272        assert_eq!(l.datagram_receive_bytes, 0);
273        assert_eq!(DEFAULT_DATAGRAM_RECEIVE_BYTES, 64 << 10);
274        assert_eq!(l.datagram_send_bytes, 64 << 10);
275        assert_eq!(l.max_flows, 64);
276        assert_eq!(l.flow_queue_bytes, 16 << 10);
277        assert_eq!(l.flow_early_bytes, 4 << 10);
278        assert_eq!(l.flow_early_hold, Duration::from_secs(1));
279        assert_eq!(l.congestion, Congestion::Cubic);
280        assert_eq!(l.header_timeout_ms, 10_000);
281        assert_eq!(l.max_header_streams, 64);
282    }
283
284    #[test]
285    fn worst_case_header_memory_follows_the_header_phase_cap() {
286        // 16 KiB * 64 streams reading their head at once.
287        assert_eq!(Limits::default().worst_case_header_memory(), 1 << 20);
288        // A budget smaller than the cap is the tighter bound.
289        let few = Limits {
290            max_concurrent_uni_streams: 2,
291            max_concurrent_bidi_streams: 1,
292            ..Limits::default()
293        };
294        assert_eq!(few.worst_case_header_memory(), 3 * 16 * 1024);
295    }
296
297    #[test]
298    fn a_connection_always_has_a_header_slot() {
299        let none = Limits {
300            max_header_streams: 0,
301            ..Limits::default()
302        };
303        assert_eq!(none.header_slots(), 1);
304        assert_eq!(none.worst_case_header_memory(), 16 * 1024);
305        assert_eq!(Limits::default().header_slots(), 64);
306    }
307}