Skip to main content

irtt_server/
config.rs

1use std::time::Duration;
2
3/// Default bound on the number of simultaneously live sessions.
4///
5/// This is `irtt-rs` resource policy, not an interoperability requirement. The
6/// protocol has no rejection response, so a server refuses by staying silent
7/// and the client sees an open timeout it already has to tolerate. Upstream was
8/// observed to impose no session bound at all; the server specification
9/// explicitly records that as an upstream policy choice which a compatible
10/// server is not expected to reproduce.
11pub const DEFAULT_MAX_SESSIONS: usize = 1024;
12
13/// Default bound on the executable echo datagram size of one session, in bytes.
14///
15/// This is `irtt-rs` resource policy, not an interoperability requirement and
16/// not a protocol constant. The server specification records upstream defaulting
17/// to *unlimited*, which leaves a remotely negotiated allocation unbounded; that
18/// is explicitly not a compatibility target.
19///
20/// 65,507 is the largest payload an IPv4 UDP datagram can carry, so it is the
21/// conservative ceiling above which no negotiated length could be emitted as one
22/// datagram on any address family. It bounds a session's echo buffer to roughly
23/// 64 KiB, and it is already the maximum a normal `irtt-rs` client will ask for,
24/// so ordinary traffic never meets it.
25///
26/// It is **not** an MTU and promises nothing about what a path will carry. Path
27/// and interface policy is a separate, later concern; this value exists to keep
28/// allocation bounded, not to predict fragmentation.
29pub const DEFAULT_MAX_PACKET_LENGTH: usize = 65_507;
30
31/// Default floor on the send interval a session may negotiate, and the cadence
32/// its reply allowance replenishes at.
33///
34/// This matches the reference server's default policy. It is policy on both
35/// sides: the server specification lists the minimum send interval among the
36/// reference server's freely changeable defaults, not among the values the wire
37/// format fixes.
38pub const DEFAULT_MIN_SEND_INTERVAL: Duration = Duration::from_millis(10);
39
40/// Default number of echo requests a session may have answered before its
41/// allowance has to replenish.
42///
43/// This matches the reference server's default policy, and like it, the
44/// allowance is per session: one session's burst is not another's.
45pub const DEFAULT_BURST_ALLOWANCE: u32 = 5;
46
47/// Default idle lifetime of a session.
48///
49/// A session that goes this long without an echo request is released. This
50/// matches the reference server's default of one minute, but the deadline it
51/// measures is deliberately not upstream's: `irtt-rs` expires immediately at the
52/// deadline, applies it to sessions that have never carried an echo request, and
53/// emits no final reply. See [`ServerConfig::with_idle_timeout`].
54pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
55
56/// How many timestamps a server is willing to provide.
57///
58/// This is **server policy**, deliberately a separate type from the wire
59/// [`StampAt`](irtt_proto::StampAt) a session requests and negotiates: one
60/// describes what a client asked for, the other what this server will hand out.
61/// Negotiation reduces the requested `StampAt` accordingly, and only it — the
62/// requested [`Clock`](irtt_proto::Clock) is never rewritten, because the clean
63/// evidence records a timestamp allowance restricting timestamp *placement*, not
64/// the clock domains it is read from.
65///
66/// See [`ServerConfig::with_timestamp_allowance`] for the mapping.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
68pub enum TimestampAllowance {
69    /// No timestamps at all: every request is negotiated to
70    /// [`StampAt::None`](irtt_proto::StampAt::None).
71    None,
72    /// At most one timestamp *instant*. A request for both receive and send
73    /// becomes [`StampAt::Midpoint`](irtt_proto::StampAt::Midpoint); every
74    /// placement that already names a single instant is left alone.
75    ///
76    /// This restricts placement, not field count: the reply still carries one
77    /// field per negotiated clock domain, so a session on
78    /// [`Clock::Both`](irtt_proto::Clock::Both) receives both a wall and a
79    /// monotonic midpoint field.
80    Single,
81    /// Every requested placement is honored. This is the default, and the
82    /// behavior of a server that configures nothing.
83    #[default]
84    Dual,
85}
86
87/// Configuration for a [`ServerCore`](crate::ServerCore).
88///
89/// Fields are private and set through consuming builder methods, so later
90/// slices can add configuration without breaking construction.
91///
92/// **Server fill is deliberately not configurable.** The policy is fixed and
93/// safe: every valid descriptor is honored, one that cannot be parsed falls back
94/// to `pattern:69727474`, and a client expressing no preference is served that
95/// same default. There is no allow-list to configure, because refusing a valid
96/// mode would prevent nothing — the payload carries no protocol meaning, a
97/// descriptor is bounded to 32 wire bytes, a random fill is bounded by
98/// [`max_packet_length`](Self::max_packet_length) like every other reply, and
99/// `none` is zero-filled here rather than left as residue. An operator
100/// restriction can be added if a real use case turns up.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct ServerConfig {
103    hmac_key: Option<Vec<u8>>,
104    max_sessions: usize,
105    max_packet_length: usize,
106    min_send_interval: Duration,
107    burst_allowance: u32,
108    idle_timeout: Duration,
109    max_test_duration: Option<Duration>,
110    timestamp_allowance: TimestampAllowance,
111    dscp_allowed: bool,
112}
113
114impl ServerConfig {
115    /// Sets the HMAC key, enabling authentication for this server.
116    ///
117    /// Authentication is global: with a key configured, every request must
118    /// carry `FLAG_HMAC` and a valid MAC, and every reply is authenticated.
119    /// Without one, any request carrying `FLAG_HMAC` is dropped.
120    #[must_use]
121    pub fn with_hmac_key(mut self, key: impl Into<Vec<u8>>) -> Self {
122        self.hmac_key = Some(key.into());
123        self
124    }
125
126    /// Sets the maximum number of simultaneously live sessions.
127    ///
128    /// Once the table holds this many sessions, a session-creating open is
129    /// silently dropped; nothing is evicted. Zero refuses every
130    /// session-creating open while still answering no-test opens, which create
131    /// no state. There is deliberately no unbounded setting.
132    #[must_use]
133    pub fn with_max_sessions(mut self, max_sessions: usize) -> Self {
134        self.max_sessions = max_sessions;
135        self
136    }
137
138    /// Sets the maximum echo datagram size a session may negotiate, in bytes.
139    ///
140    /// This governs the *executable* echo datagram of a session, not the size of
141    /// the open exchange: a requested positive Length above this value is
142    /// reduced to it during negotiation, and an open whose mandatory echo field
143    /// block would not fit is silently refused, since the server could not emit
144    /// a compliant reply for it. Authentication counts toward that field block.
145    /// The same limit additionally admits inbound echo request datagrams by
146    /// their received length, before any receive state moves.
147    ///
148    /// The value is trusted local configuration, like
149    /// [`with_max_sessions`](Self::with_max_sessions): an operator may
150    /// deliberately raise it far past what any path carries, and that is their
151    /// resource choice to make. What must stay bounded is the *default*, which
152    /// is why there is deliberately no unlimited setting.
153    ///
154    /// Zero is accepted and is not a synonym for unlimited. No session can
155    /// describe an echo packet smaller than its mandatory field block, so a zero
156    /// maximum silently refuses every session-creating open — and every no-test
157    /// open too, since both are validated against the same effective session.
158    #[must_use]
159    pub fn with_max_packet_length(mut self, max_packet_length: usize) -> Self {
160        self.max_packet_length = max_packet_length;
161        self
162    }
163
164    /// Sets the floor on the send interval a session may negotiate, which is
165    /// also the cadence its reply allowance replenishes at.
166    ///
167    /// A requested interval below this is raised to it during negotiation, and
168    /// an absent Interval — which means the wire default of zero, not an
169    /// explicit zero, which is refused — is answered with it. The negotiated
170    /// value may still end up *below* this floor, because the idle-timeout cap
171    /// of [`with_idle_timeout`](Self::with_idle_timeout) is applied afterwards;
172    /// where that happens, the session's allowance replenishes at the shorter
173    /// negotiated interval instead, so this server never enforces a cadence
174    /// slower than the one it handed the client.
175    ///
176    /// [`Duration::ZERO`] disables both: no interval is raised, and an
177    /// otherwise admissible echo never waits for allowance. It does **not**
178    /// disable the burst allowance, which refuses everything when it is zero.
179    #[must_use]
180    pub fn with_min_send_interval(mut self, min_send_interval: Duration) -> Self {
181        self.min_send_interval = min_send_interval;
182        self
183    }
184
185    /// Sets how many echo requests a session may have answered before its
186    /// allowance has to replenish.
187    ///
188    /// The allowance is per session, starts full, is spent one unit per served
189    /// echo and refills at one unit per
190    /// [`min_send_interval`](Self::min_send_interval), never above this value.
191    /// An echo arriving with no allowance is dropped without a reply and
192    /// without advancing any reception statistic.
193    ///
194    /// Zero is accepted and means no allowance at all: every echo is
195    /// rate-limited, whatever the interval is set to. It is deliberately not a
196    /// synonym for unlimited.
197    #[must_use]
198    pub fn with_burst_allowance(mut self, burst_allowance: u32) -> Self {
199        self.burst_allowance = burst_allowance;
200        self
201    }
202
203    /// Sets how long a session may go without a served or rate-limited echo
204    /// request before it is released.
205    ///
206    /// The deadline runs from the open, not from the first echo, so a session
207    /// that never carries one still ages out. Release is silent — the protocol
208    /// defines no expiry notification — and immediate at the deadline.
209    ///
210    /// This additionally caps the negotiated send interval at a quarter of the
211    /// timeout, so a client sending at the interval it was given cannot idle
212    /// itself out.
213    ///
214    /// [`Duration::ZERO`] is accepted and is not a synonym for "never expire":
215    /// it releases a session the next time expiry is evaluated. There is
216    /// deliberately no unbounded setting.
217    #[must_use]
218    pub fn with_idle_timeout(mut self, idle_timeout: Duration) -> Self {
219        self.idle_timeout = idle_timeout;
220        self
221    }
222
223    /// Sets the maximum test duration a session may negotiate.
224    ///
225    /// A requested Duration above this is reduced to it, and a *continuous*
226    /// request — an absent Duration, meaning the wire default of zero — is
227    /// answered with it too, since restricting continuous mode to a finite test
228    /// is the whole point of configuring a maximum. An explicit zero Duration
229    /// is refused before negotiation and never reaches this.
230    ///
231    /// [`Duration::ZERO`] means *no maximum*, exactly as
232    /// [`without_max_test_duration`](Self::without_max_test_duration) does. A
233    /// finite maximum of zero could only be honored by negotiating a Duration of
234    /// zero, which on the wire means continuous — the opposite of a limit — so
235    /// rewriting a client's finite request into a continuous one is refused
236    /// rather than encoded.
237    #[must_use]
238    pub fn with_max_test_duration(mut self, max_test_duration: Duration) -> Self {
239        self.max_test_duration = (!max_test_duration.is_zero()).then_some(max_test_duration);
240        self
241    }
242
243    /// Removes any configured maximum test duration, which is the default.
244    ///
245    /// A session then negotiates the duration it asked for, including
246    /// continuous, and no server-initiated close is ever triggered by duration.
247    /// The session table bound and the idle timeout still apply, so this is not
248    /// an unbounded setting.
249    #[must_use]
250    pub fn without_max_test_duration(mut self) -> Self {
251        self.max_test_duration = None;
252        self
253    }
254
255    /// Sets how many timestamps this server is willing to provide.
256    ///
257    /// A requested placement above the allowance is reduced during negotiation,
258    /// so the open reply is honest about what the session's echo replies will
259    /// carry:
260    ///
261    /// | Requested | [`Dual`] | [`Single`] | [`None`] |
262    /// |-----------|----------|------------|----------|
263    /// | `None` | `None` | `None` | `None` |
264    /// | `Send` | `Send` | `Send` | `None` |
265    /// | `Receive` | `Receive` | `Receive` | `None` |
266    /// | `Both` | `Both` | **`Midpoint`** | `None` |
267    /// | `Midpoint` | `Midpoint` | `Midpoint` | `None` |
268    ///
269    /// The one substitution is the observed one: under a single-timestamp
270    /// allowance a request for both instants is answered with the *midpoint*,
271    /// not with whichever of the two the server felt like keeping.
272    ///
273    /// The requested [`Clock`](irtt_proto::Clock) is left exactly as it was in
274    /// every case. The allowance restricts which *instants* are reported, and
275    /// each reported instant still carries one field per negotiated clock domain
276    /// — [`Single`] on [`Clock::Both`](irtt_proto::Clock::Both) reports a wall
277    /// and a monotonic midpoint. Only [`None`] removes timestamp fields
278    /// outright, and it does so because the echo layout carries none once the
279    /// placement is [`StampAt::None`](irtt_proto::StampAt::None).
280    ///
281    /// Restriction runs *before* the effective-session check, which is what
282    /// makes a [`None`] allowance accept a request that selected timestamps
283    /// without sending a Clock: such a session is refused as requested, because
284    /// timestamps from no clock cannot be produced, but under this policy its
285    /// effective placement is none and the absent clock no longer matters.
286    ///
287    /// [`Dual`]: TimestampAllowance::Dual
288    /// [`Single`]: TimestampAllowance::Single
289    /// [`None`]: TimestampAllowance::None
290    #[must_use]
291    pub fn with_timestamp_allowance(mut self, timestamp_allowance: TimestampAllowance) -> Self {
292        self.timestamp_allowance = timestamp_allowance;
293        self
294    }
295
296    /// Sets whether this server provides the traffic-class marking a session
297    /// requests.
298    ///
299    /// `true`, the default, negotiates the requested DSCP parameter unchanged —
300    /// including a raw value outside `0..=255`, which stays in the negotiated
301    /// parameters and is transported unmarked.
302    ///
303    /// `false` negotiates it to **zero**, whatever was requested, so the reply
304    /// tells the client its replies will be unmarked and the session's stored
305    /// parameters say the same. The open is never refused over DSCP, and nothing
306    /// is clamped or wrapped: this is an operator policy about providing
307    /// traffic-class marking at all, not a judgement about a particular value.
308    ///
309    /// It is also not socket capability detection. What a given host can apply
310    /// to a socket is a transport concern, settled per send by the runtime.
311    #[must_use]
312    pub fn with_dscp_allowed(mut self, dscp_allowed: bool) -> Self {
313        self.dscp_allowed = dscp_allowed;
314        self
315    }
316
317    /// The configured HMAC key, if this server authenticates.
318    #[must_use]
319    pub fn hmac_key(&self) -> Option<&[u8]> {
320        self.hmac_key.as_deref()
321    }
322
323    /// The maximum number of simultaneously live sessions.
324    #[must_use]
325    pub fn max_sessions(&self) -> usize {
326        self.max_sessions
327    }
328
329    /// The maximum echo datagram size a session may negotiate, in bytes.
330    #[must_use]
331    pub fn max_packet_length(&self) -> usize {
332        self.max_packet_length
333    }
334
335    /// The floor on a negotiated send interval, and the allowance refill
336    /// cadence.
337    #[must_use]
338    pub fn min_send_interval(&self) -> Duration {
339        self.min_send_interval
340    }
341
342    /// How many echo requests a session may have answered before its allowance
343    /// has to replenish.
344    #[must_use]
345    pub fn burst_allowance(&self) -> u32 {
346        self.burst_allowance
347    }
348
349    /// How long a session may go without an echo request before it is released.
350    #[must_use]
351    pub fn idle_timeout(&self) -> Duration {
352        self.idle_timeout
353    }
354
355    /// The maximum test duration a session may negotiate, if one is configured.
356    ///
357    /// Never `Some(Duration::ZERO)`: a zero maximum is stored as `None`, since
358    /// a negotiated Duration of zero means continuous rather than instant.
359    #[must_use]
360    pub fn max_test_duration(&self) -> Option<Duration> {
361        self.max_test_duration
362    }
363
364    /// How many timestamps this server is willing to provide.
365    #[must_use]
366    pub fn timestamp_allowance(&self) -> TimestampAllowance {
367        self.timestamp_allowance
368    }
369
370    /// Whether a requested DSCP value is negotiated as asked, rather than to
371    /// zero.
372    #[must_use]
373    pub fn dscp_allowed(&self) -> bool {
374        self.dscp_allowed
375    }
376}
377
378impl Default for ServerConfig {
379    /// An unauthenticated server bounded to [`DEFAULT_MAX_SESSIONS`] sessions,
380    /// each negotiating at most [`DEFAULT_MAX_PACKET_LENGTH`] bytes per echo,
381    /// no faster than [`DEFAULT_MIN_SEND_INTERVAL`] with a burst of
382    /// [`DEFAULT_BURST_ALLOWANCE`], and released after
383    /// [`DEFAULT_IDLE_TIMEOUT`] without an echo request.
384    ///
385    /// No maximum test duration is configured, matching the reference server's
386    /// ordinary policy. A session is still bounded, by the table size and the
387    /// idle timeout.
388    ///
389    /// Both capability restrictions are off: every requested timestamp placement
390    /// is honored ([`TimestampAllowance::Dual`]) and a requested DSCP value is
391    /// negotiated as asked. They are opt-in, so an existing configuration
392    /// negotiates exactly what it did before they existed.
393    fn default() -> Self {
394        Self {
395            hmac_key: None,
396            max_sessions: DEFAULT_MAX_SESSIONS,
397            max_packet_length: DEFAULT_MAX_PACKET_LENGTH,
398            min_send_interval: DEFAULT_MIN_SEND_INTERVAL,
399            burst_allowance: DEFAULT_BURST_ALLOWANCE,
400            idle_timeout: DEFAULT_IDLE_TIMEOUT,
401            max_test_duration: None,
402            timestamp_allowance: TimestampAllowance::Dual,
403            dscp_allowed: true,
404        }
405    }
406}