moqtap_proxy/action.rs
1//! What a hook asks the engine to do, and the vocabulary it asks in.
2
3use std::time::Duration;
4
5use bytes::Bytes;
6use tokio_util::sync::CancellationToken;
7
8use crate::shape::StreamKey;
9
10/// What machinery a hook wants armed.
11///
12/// Bitflags-style with no dependency. Read **once per session**, when the
13/// session starts, and cached; a hook that returns a different value later
14/// is not re-consulted. The byte-pump path is chosen *structurally* — which
15/// function `pipe_data` calls — so re-reading per frame would require the
16/// framer to be armed at all times in order to be able to *become*
17/// interested, which is precisely the cost `Interest::NONE` exists to
18/// avoid. Declare the union of everything the hook may ever want here, and
19/// gate at runtime by returning [`Action::Pass`].
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub struct Interest(u8);
22
23impl Interest {
24 /// Pure byte pump: no parsing on any path. Today's fast path,
25 /// bit-for-bit. The default.
26 pub const NONE: Self = Interest(0);
27 /// Parse control messages and honour actions on them. Routes the
28 /// control stream through the slower parse-then-forward pipe, which
29 /// costs per-frame latency.
30 pub const CONTROL: Self = Interest(1 << 0);
31 /// Frame subgroup and fetch objects and honour actions on them. Costs
32 /// whole-object buffering: an object is not forwarded until it is
33 /// buffered whole, or until the framer gives up on it.
34 pub const OBJECTS: Self = Interest(1 << 1);
35 /// Decode and gate datagrams. The hook fires even when the datagram's
36 /// header does not decode.
37 pub const DATAGRAMS: Self = Interest(1 << 2);
38 /// Decide on unidirectional stream open, stream header, and stream end.
39 ///
40 /// **Includes [`Self::OBJECTS`]**, structurally — the bit pattern is
41 /// `(1 << 3) | (1 << 1)`, so `STREAMS.contains(OBJECTS)` is `true` by
42 /// construction rather than by documentation. The header decision only
43 /// exists once the stream is framed, and framing is what `OBJECTS`
44 /// turns on; a `STREAMS`-only hook that did not imply it would take
45 /// `pipe_data_passthrough` and never see a header at all.
46 ///
47 /// A hook that wants stream decisions but no object decisions still
48 /// declares `STREAMS` and simply returns [`Action::Pass`] from
49 /// [`ProxyHook::on_object`](crate::hook::ProxyHook::on_object) — it
50 /// pays for framing either way, because there is no header without it.
51 ///
52 /// ```
53 /// use moqtap_proxy::action::Interest;
54 /// assert!(Interest::STREAMS.contains(Interest::OBJECTS));
55 /// ```
56 pub const STREAMS: Self = Interest((1 << 3) | (1 << 1));
57
58 /// Whether every flag in `other` is set here.
59 pub const fn contains(self, other: Self) -> bool {
60 self.0 & other.0 == other.0
61 }
62 /// The union of two interests.
63 pub const fn union(self, other: Self) -> Self {
64 Interest(self.0 | other.0)
65 }
66 /// Whether no flag is set.
67 pub const fn is_none(self) -> bool {
68 self.0 == 0
69 }
70}
71
72// The implication `STREAMS ⊇ OBJECTS` is what makes `session.rs`'s
73// `objects_enabled` true for a `STREAMS`-only hook. A revision that
74// wrote `STREAMS` as a plain `1 << 3` would send that hook down
75// `pipe_data_passthrough`, where `on_stream_header` can never fire — a
76// silent no-op rather than a refusal. Fail the build instead.
77const _: () = assert!(Interest::STREAMS.contains(Interest::OBJECTS));
78
79impl std::ops::BitOr for Interest {
80 type Output = Self;
81 fn bitor(self, rhs: Self) -> Self {
82 self.union(rhs)
83 }
84}
85
86/// A cheap, clonable release handle the engine awaits.
87///
88/// Level-triggered: releasing before anyone waits is observed by every
89/// later waiter, so there is no lost-wakeup race. All clones share one
90/// release, and the handle is eight bytes.
91///
92/// The engine never awaits a gate on its own — it always races the gate
93/// against session cancellation and [`EgressConfig::max_hold`], so a hook
94/// that never releases cannot make a stream unkillable.
95///
96/// Deliberately a newtype rather than an exposed `CancellationToken`:
97/// handing the engine the session's own cancel token would conflate
98/// teardown with object release.
99#[derive(Debug, Clone, Default)]
100pub struct Gate(CancellationToken);
101
102impl Gate {
103 /// A new, unreleased gate.
104 pub fn new() -> Self {
105 Self::default()
106 }
107 /// Release every holder. Idempotent.
108 pub fn release(&self) {
109 self.0.cancel();
110 }
111 /// Whether [`Self::release`] has been called.
112 pub fn is_released(&self) -> bool {
113 self.0.is_cancelled()
114 }
115 /// Resolve once the gate is released. Engine-internal: callers race it
116 /// against session cancellation and [`EgressConfig::max_hold`].
117 pub(crate) async fn wait(&self) {
118 self.0.cancelled().await;
119 }
120}
121
122/// What the engine should do with the unit of traffic the hook was shown.
123///
124/// [`Self::Delay`] and [`Self::Hold`] are *modifiers*: they carry the
125/// action to perform once the unit is released. Their `then` must be a
126/// content action — [`Self::Pass`], [`Self::Replace`],
127/// [`Self::ReplacePayload`] or [`Self::Drop`]. Any other nesting is refused
128/// with
129/// [`Refusal::WrongComposition`](crate::capability::Refusal::WrongComposition)
130/// rather than silently ignored, so `Delay { then: ResetStream { .. } }`
131/// and `Delay { then: Truncate { .. } }` (terminals — positional by
132/// construction, so the queue already orders them and a delay would only
133/// move the end of the stream), `Delay { then: CloseSession { .. } }` (a
134/// session-scoped decision, with no per-unit release to attach it to) and
135/// `Delay { then: Delay { .. } }` (a nested modifier) are all loud. Those
136/// four, and only those four, are the refused shapes; the three `detail`
137/// strings in `exec.rs` enumerate them.
138///
139/// # `Delay { then: Drop(_) }` is admitted, and is not inert
140///
141/// A deferred drop is not unobservable: it takes an **ordering slot** in
142/// the stream's pending queue for the whole of `by`, and the queue only
143/// ever writes from its front — so nothing the hook decides after it can
144/// reach the wire until it is released. So
145/// `Action::Drop(DropMode::Elide).delayed(d)` deletes this object *and*
146/// head-of-line-blocks everything after it on that stream for `d`: one
147/// decision, two effects, both on the wire. That is a case worth
148/// expressing — a relay that loses an object and stalls while it notices —
149/// and refusing it would take it away. `Hold { then: Drop(_) }` is the
150/// same impairment under a [`Gate`] instead of a clock.
151///
152/// It follows that this composition is **not** a way to write a
153/// deliberately inert guard. `Drop` deletes the unit wherever it is
154/// admitted, wrapped or not; a hook that wants the unit forwarded
155/// untouched returns [`Self::Pass`], which is the only action that
156/// promises that.
157#[derive(Debug, Clone)]
158#[non_exhaustive]
159pub enum Action {
160 /// Forward unchanged.
161 ///
162 /// On the object site this forwards the framer's own `Bytes` slice —
163 /// never a re-encode, on any draft. That is what makes a no-action
164 /// session byte-identical to the byte pump.
165 Pass,
166 /// Replace the whole unit's wire bytes.
167 ///
168 /// Valid at the control and datagram sites, where the unit is
169 /// self-delimiting and the hook owns all of it. Refused at the object
170 /// site with [`Refusal::WrongSite`](crate::capability::Refusal::WrongSite):
171 /// replacing a whole wire object would require the hook to encode the
172 /// draft's object framing, which is the knowledge this crate exists to
173 /// hide. Use [`Self::ReplacePayload`].
174 Replace(Bytes),
175 /// Replace an object's or a datagram's payload, keeping its framing.
176 ///
177 /// **At the object site.** The replacement must be exactly
178 /// [`ObjectMeta::payload_len`](crate::framer::ObjectMeta::payload_len)
179 /// bytes; a different length is refused with
180 /// [`Refusal::LengthChanged`](crate::capability::Refusal::LengthChanged)
181 /// rather than mis-framed. The engine splices at
182 /// `raw.len() - meta.payload_len`, which is the payload offset on every
183 /// draft and both stream kinds.
184 ///
185 /// Refused when the object carries a status
186 /// ([`ObjectMeta::status`](crate::framer::ObjectMeta::status) is
187 /// `Some`), because a status object has no payload slot.
188 ///
189 /// **At the datagram site**, where it is gated on
190 /// [`Precondition::DatagramPayloadDelimited`](crate::capability::Precondition::DatagramPayloadDelimited):
191 /// the engine splices after the decoded header, at
192 /// `data.len() - cursor.len()`. Refused with
193 /// [`Refusal::PayloadNotDelimited`](crate::capability::Refusal::PayloadNotDelimited)
194 /// in the three cases where no such offset exists — on **draft-14**,
195 /// whose `AnyDatagramHeader` decode consumes the payload; on a **status
196 /// datagram**, which has no payload slot; and when the **header did
197 /// not decode**, where the hook still fires but there is nothing to
198 /// splice after. See
199 /// [`ProxyHook::on_datagram`](crate::hook::ProxyHook::on_datagram),
200 /// whose rustdoc says the same thing from the caller's side.
201 ///
202 /// Refused with
203 /// [`Refusal::WrongSite`](crate::capability::Refusal::WrongSite)
204 /// everywhere else — the control site's unit has no payload/framing
205 /// split the proxy may assume, and the stream sites take a
206 /// [`StreamAction`].
207 ReplacePayload(Bytes),
208 /// Release `then` no earlier than `arrived_at + by`.
209 ///
210 /// A **deadline**, not a spacing: two objects that arrive together,
211 /// each with `Delay { by: 100ms }`, are both released about 100 ms
212 /// later — not at +100 ms and +200 ms. Release times are clamped
213 /// monotonically against the queue's tail, so a later unit can never
214 /// overtake an earlier one regardless of its delay.
215 ///
216 /// Reads continue while units wait, so this is a latency shift rather
217 /// than a rate limit — until the stream's pending queue reaches
218 /// [`EgressConfig::max_pending_bytes`], at which point reads stop and
219 /// the delay becomes backpressure. That transition is reported once as
220 /// `ProxyEvent::Impairment { kind: EgressQueueFull }`.
221 ///
222 /// `by` is clamped to [`EgressConfig::max_hold`]. A clamp is reported
223 /// as `ProxyEvent::Impairment { kind: HoldClamped { .. } }`.
224 ///
225 /// # Resolution
226 ///
227 /// Release timing does **not** use `tokio::time::sleep`, which is
228 /// bounded below by the ~15.6 ms Windows system tick — as is every
229 /// other interruptible wait in `std`. Releases are driven by a
230 /// process-wide release wheel on one dedicated OS thread, measured at
231 /// **p50 0.11-0.17 ms, p95 0.52-0.57 ms end-to-end on Windows 11**
232 /// against 11-15 ms for
233 /// `tokio::time::sleep`. The measured lateness of every deferred
234 /// release is reported in
235 /// [`crate::instrument::Counters::release_errors`]; assert on it
236 /// rather than assuming the delay was honoured.
237 ///
238 /// Three consequences worth knowing:
239 ///
240 /// * When `MOQTAP_RELEASE_TIMER` forces the coarse backend, the floor
241 /// returns to ~15.6 ms on Windows, and the session
242 /// says so exactly once with
243 /// `ProxyEvent::Impairment { kind: CoarseReleaseTimer { .. } }`.
244 /// A run that could not honour its own delays is never silent about
245 /// it. See [`crate::instrument::release_timer_backend`].
246 /// * The wheel is on a real clock, not tokio's. A test using
247 /// `#[tokio::test(start_paused = true)]` and expecting a `Delay` to
248 /// complete will **wait out the real deadline**, not advance
249 /// virtual time. Do not pause time around `Delay` or `Hold`.
250 /// * The wheel's thread is created on the first deferred release in
251 /// the process and is never joined (it lives in a `static
252 /// OnceLock`). Leak detectors and thread counters will see one live
253 /// thread and one leaked allocation after any delaying test. A
254 /// session that never delays never creates it —
255 /// [`crate::instrument::release_timer_started`] is the falsifiable
256 /// form of that claim.
257 Delay {
258 /// How long to hold the unit past its arrival.
259 by: Duration,
260 /// What to do once it is released.
261 then: Box<Action>,
262 },
263 /// Release `then` when `gate` is released, at
264 /// [`EgressConfig::max_hold`], or at session teardown — whichever comes
265 /// first.
266 Hold {
267 /// The release handle.
268 gate: Gate,
269 /// What to do once it is released.
270 then: Box<Action>,
271 },
272 /// Remove the unit from the wire. See [`DropMode`].
273 Drop(DropMode),
274 /// Write the first `bytes` bytes of this unit, then reset the stream.
275 ///
276 /// Positional: everything queued ahead of it is written first, then
277 /// the truncated prefix, then `RESET_STREAM` with `code`.
278 /// `code` is stated rather than defaulted, exactly as in
279 /// [`Self::ResetStream`]. A truncation is a *simulated* publisher
280 /// abandonment and the code is the whole of what it is
281 /// simulating: `0x0` INTERNAL_ERROR reads as "the proxy did this", `0x2`
282 /// DELIVERY_TIMEOUT reads as *a relay hit its delivery timeout*, and the
283 /// two make a subscriber take different paths. There is no default that is
284 /// right for both, so the type asks. The same range check as
285 /// [`Self::ResetStream`] applies:
286 /// [`Refusal::ErrorCodeOutOfRange`](crate::capability::Refusal::ErrorCodeOutOfRange)
287 /// above 2^62 - 1, before anything is sent. On drafts 07-10, which define
288 /// no stream-reset code vocabulary at all, the reset still executes and
289 /// `Effect::Truncated` reports `code_defined: false`.
290 /// The peer observes **at most** `bytes` further bytes, and may observe
291 /// none. quinn clears the receive assembler the moment `RESET_STREAM` is
292 /// processed (`quinn-proto/src/connection/streams/recv.rs`: **Nuke buffers
293 /// so that future reads fail immediately**), so only bytes the peer
294 /// application had already read out survive; `reset()` additionally
295 /// discards anything still in the local send buffer. Assert an upper bound
296 /// and a prefix, never an exact count.
297 ///
298 /// Refused on control streams on every draft, and on datagrams.
299 Truncate {
300 /// How many bytes of this unit to write before resetting.
301 bytes: usize,
302 /// The application error code for the reset that follows.
303 code: u64,
304 },
305 /// Reset the destination stream with this application error code.
306 ///
307 /// Refused on control streams on every draft: resetting a control
308 /// stream at the transport layer is a session-level `PROTOCOL_VIOLATION`
309 /// in all of drafts 07-19. The documented escalation is
310 /// [`Self::CloseSession`].
311 ///
312 /// Codes above the QUIC varint ceiling (2^62 - 1) are refused with
313 /// [`Refusal::ErrorCodeOutOfRange`](crate::capability::Refusal::ErrorCodeOutOfRange)
314 /// before anything is sent, rather than silently becoming a FIN.
315 ResetStream {
316 /// The application error code to send.
317 code: u64,
318 },
319 /// Close both legs of the session with this code and reason.
320 ///
321 /// `code` is a *session termination* code, a different namespace from
322 /// a stream reset code: `0x0` NO_ERROR, `0x1` INTERNAL_ERROR, `0x2`
323 /// UNAUTHORIZED, `0x3` PROTOCOL_VIOLATION. Note that session
324 /// INTERNAL_ERROR is `0x1` while stream-reset INTERNAL_ERROR is `0x0`.
325 ///
326 /// Honoured at **every** site that returns an [`Action`], including
327 /// [`Site::StreamEnd`](crate::capability::Site::StreamEnd) on a data
328 /// stream *and* on the control stream. A close is session-scoped, so
329 /// no site can be the wrong one for it: unlike
330 /// [`Self::ResetStream`], there is no per-stream object it needs and
331 /// nothing left to forward that honouring it could corrupt. It is the
332 /// documented escalation for the two sites where a stream reset is a
333 /// protocol violation.
334 ///
335 /// The first close request wins; later ones are refused with
336 /// [`Refusal::SessionAlreadyClosing`](crate::capability::Refusal::SessionAlreadyClosing).
337 CloseSession {
338 /// The session termination code.
339 code: u32,
340 /// The reason phrase.
341 reason: Bytes,
342 },
343}
344
345impl Action {
346 /// Wrap this action in a [`Action::Delay`].
347 pub fn delayed(self, by: Duration) -> Self {
348 Action::Delay { by, then: Box::new(self) }
349 }
350 /// Wrap this action in a [`Action::Hold`].
351 pub fn held(self, gate: Gate) -> Self {
352 Action::Hold { gate, then: Box::new(self) }
353 }
354}
355
356/// How [`Action::Drop`] removes an object.
357///
358/// `MarkMissing` — a zero-length object carrying status
359/// `ObjectDoesNotExist`, the obvious default to reach for — is **not in
360/// this enum**. That status was removed from the registry in
361/// draft-17, and drafts 15-19 do not validate the status on write, so a
362/// naive implementation emits a code point those drafts do not define, on a
363/// stream that round-trips green against itself. Dropping an object
364/// therefore always removes its bytes; nothing here can leave a tombstone
365/// behind.
366///
367/// The absence is a compile-time fact, not a promise:
368///
369/// ```compile_fail
370/// use moqtap_proxy::action::DropMode;
371/// // drop_mark_missing_is_not_constructible: no such variant.
372/// let _mode = DropMode::MarkMissing;
373/// ```
374///
375/// The companion example below is what makes that `compile_fail` block
376/// mean something: if the path or the import were wrong, the block would
377/// still "pass" for the wrong reason, and this one would go red.
378///
379/// ```
380/// use moqtap_proxy::action::{Action, DropMode};
381/// let mode = DropMode::Elide;
382/// assert!(matches!(mode, DropMode::Elide));
383/// let _action = Action::Drop(mode);
384/// ```
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386#[non_exhaustive]
387pub enum DropMode {
388 /// Remove the object's bytes from the wire, preserving every survivor's
389 /// **absolute** object ID.
390 ///
391 /// Drafts 07-13, and fetch streams on drafts 07-14, encode absolute
392 /// IDs, so this is pure byte deletion: every survivor is forwarded
393 /// verbatim, including any non-minimally-encoded varint it arrived
394 /// with. Drafts 14-21 delta-encode, so the *one* object following an
395 /// elided run has its leading ID varint rewritten and nothing else;
396 /// every later object is again forwarded verbatim, because the wire
397 /// cursor re-converges after that one fix-up.
398 ///
399 /// Eliding `2` from `0,1,2,3,4` yields a stream decoding to `0,1,3,4` —
400 /// not `0,1,2,3`.
401 ///
402 /// Refused when the object is index 0 of a stream whose subgroup ID is
403 /// defined as the first object's ID
404 /// ([`ObjectMeta::subgroup_id`](crate::framer::ObjectMeta::subgroup_id)
405 /// is `None`), because removing it silently redefines the subgroup ID
406 /// for the receiver. Also refused when the object carries a status,
407 /// which is conservatively treated as a boundary marker.
408 Elide,
409}
410
411/// What to do with a unidirectional stream.
412///
413/// Returned from both
414/// [`ProxyHook::on_stream_open`](crate::hook::ProxyHook::on_stream_open)
415/// and
416/// [`ProxyHook::on_stream_header`](crate::hook::ProxyHook::on_stream_header).
417/// The observable effect of `Reject` differs between the two, and both are
418/// honest:
419///
420/// * At open, no peer stream is created at all.
421/// * At header, the peer stream already exists — it is opened before any
422/// byte of the source is read, whether that is in the accept loop or, for
423/// a stream whose open was deferred by [`Self::OpenAfter`], in the
424/// stream's own task once the delay has elapsed — so it is reset with
425/// `code` having carried zero payload bytes, and the source is stopped
426/// with `code`.
427///
428/// The same asymmetry decides where [`Self::OpenAfter`] is legal: it is a
429/// decision about *when the peer stream comes into existence*, so only the
430/// open site can take it. [`Self::SerializeAfter`] is a decision about when
431/// the first **byte** is written, which both sites can still take.
432#[derive(Debug, Clone, Copy, PartialEq, Eq)]
433#[non_exhaustive]
434pub enum StreamAction {
435 /// Forward the stream normally.
436 Open,
437 /// Do not forward this stream. The source is stopped with `code`.
438 Reject {
439 /// The application error code.
440 code: u64,
441 },
442 /// Forward the stream, but do not open the peer stream until `after`
443 /// has elapsed.
444 ///
445 /// **Valid at
446 /// [`ProxyHook::on_stream_open`](crate::hook::ProxyHook::on_stream_open)
447 /// only.** By
448 /// [`ProxyHook::on_stream_header`](crate::hook::ProxyHook::on_stream_header)
449 /// the peer stream already exists — it is opened before the first
450 /// source byte is read, which is what makes a header arrive at all — so
451 /// there is nothing left to defer and the header site refuses it with
452 /// [`Refusal::WrongSite`](crate::capability::Refusal::WrongSite),
453 /// reported as `ProxyEvent::ActionRefused`. It is refused rather than
454 /// quietly ignored: a hook that asks for a deferral this crate cannot
455 /// perform is told so, and the stream is forwarded unchanged.
456 /// Delaying a stream's *opening* on something only its header reveals
457 /// — its track alias, say — would want the header site, and is
458 /// therefore not expressible in this release: the open decision has to
459 /// be taken before a byte is read.
460 ///
461 /// This models a relay that is slow to accept a subscription rather
462 /// than one that is slow to send: the subscriber observes no stream at
463 /// all for `after`, not an open-but-idle one. For the latter, see
464 /// [`Self::SerializeAfter`], which *is* valid at both sites.
465 ///
466 /// The deferral is a wire-visible one, not a bookkeeping note: the peer
467 /// stream is not opened and the source is not read until `after` has
468 /// elapsed, so a stream opened later and not deferred reaches the peer
469 /// first.
470 OpenAfter(Duration),
471 /// Open the peer stream now, but write nothing on it until the stream
472 /// named by the key has ended.
473 ///
474 /// Head-of-line simulation: two streams that a relay would have
475 /// interleaved are forced into sequence, so a caller can reproduce a
476 /// subscriber that stalls behind an unrelated group.
477 ///
478 /// Valid at **both** stream sites — it defers the first write, not the
479 /// stream's existence.
480 ///
481 /// One stream is exempt, and it is worth knowing before writing a
482 /// hook against it: on the drafts whose control plane is a pair of
483 /// unidirectional streams, a stream that turns out to *be* one of them
484 /// is not held. Holding a control stream's first write would hold
485 /// SETUP, and the session with it. The open site cannot tell in
486 /// advance — which stream it is is decided by the first varint on it,
487 /// read after the decision has been taken — so the decision is
488 /// admitted and then does not apply to that one stream.
489 ///
490 /// The key comes from
491 /// [`StreamCtx::key`](crate::hook::StreamCtx::key) on a stream the hook
492 /// was shown earlier. A key naming a stream that has already ended, or
493 /// that never existed in this session, **proceeds immediately** and
494 /// reports `Impairment { SerializeTargetUnknown }` once — a caller
495 /// cannot deadlock a stream by naming the wrong one, and the mistake is
496 /// reported rather than silently waited out.
497 SerializeAfter(StreamKey),
498}
499
500/// How a stream ended.
501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
502#[non_exhaustive]
503pub enum StreamEnd {
504 /// The source finished the stream cleanly.
505 Fin,
506 /// The source peer sent `RESET_STREAM`.
507 Reset {
508 /// The peer's application error code.
509 code: u64,
510 },
511 /// The destination peer sent `STOP_SENDING`.
512 Stopped {
513 /// The peer's application error code.
514 code: u64,
515 },
516 /// The session was cancelled while the stream was open.
517 Cancelled,
518}
519
520/// Engine-side knobs for action execution. Carried on the session config.
521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
522#[non_exhaustive]
523pub struct EgressConfig {
524 /// Bytes a per-stream pending queue may hold before the read side is
525 /// stalled. Past this point `Delay` and `Hold` are backpressure rather
526 /// than latency, and the transition is reported once per stream.
527 /// Default 1 MiB.
528 pub max_pending_bytes: usize,
529 /// Ceiling on any single [`Action::Hold`] and on any single
530 /// [`Action::Delay`]. A clamped delay is reported. Default 30 s.
531 ///
532 /// The ceiling is an `Instant` deadline, and `Instant` does not
533 /// behave the same way across a machine suspend on every platform: a
534 /// 30 s hold armed before a laptop sleeps may fire immediately on
535 /// resume (Windows `QueryPerformanceCounter`) or 30 s after resume
536 /// (Linux `CLOCK_MONOTONIC`). Irrelevant on CI; surprising when
537 /// debugging a run on a laptop.
538 pub max_hold: Duration,
539 /// How long a requested close gives this session's egress queues to
540 /// flush before both legs are closed anyway. Default 100 ms.
541 ///
542 /// Only [`ProxyControl::close_session`](crate::control::ProxyControl::close_session)
543 /// reads this. Every other way a session ends — a peer going away, a
544 /// hook's [`Action::CloseSession`], the proxy being cancelled — tears
545 /// down at once and has always done so. A requested close is different
546 /// because somebody is waiting for it to mean something: closing the
547 /// instant the request lands discards whatever a `Delay` or a `Hold`
548 /// was still holding, and the caller cannot tell that from a session
549 /// that had nothing queued.
550 ///
551 /// The bound is the point. An unbounded drain turns a close into a call
552 /// that may never finish: a stream whose destination peer has stopped
553 /// reading never empties its queue, and a shaped class whose bucket is
554 /// dry empties it only at the configured rate. Whatever is still queued
555 /// when this elapses is discarded and reported as
556 /// [`ImpairmentKind::QueuedBytesAtTeardown`](crate::event::ImpairmentKind::QueuedBytesAtTeardown),
557 /// so bytes that did not make it are named rather than lost quietly,
558 /// and the close still carries the code that was asked for.
559 ///
560 /// # The default is a guess, and here is the measurement that replaces it
561 ///
562 /// 100 ms was chosen because it is long enough for a loopback flush and
563 /// short enough that a caller closing sessions in a loop does not
564 /// notice, not because anything was measured. To replace it: pin one
565 /// queue state — a fixed object size, a fixed unit count, a fixed
566 /// destination window, written down beside the figure — sweep this
567 /// timeout across that state, and take the knee at which the **stranded
568 /// byte count reaches zero**. Quote the queue state with the number; a
569 /// knee measured against 4 KiB objects says nothing about 256 KiB ones.
570 ///
571 /// Measure stranded *bytes*, never elapsed time. Timing the drain
572 /// measures the fixture that filled the queue — how fast the source
573 /// wrote, how the destination's flow-control window happened to open —
574 /// and a timeout tuned against it is tuned against the harness. The
575 /// byte count is the thing that is either zero or not.
576 pub drain_timeout: Duration,
577}
578
579impl Default for EgressConfig {
580 fn default() -> Self {
581 Self {
582 max_pending_bytes: 1024 * 1024,
583 max_hold: Duration::from_secs(30),
584 drain_timeout: Duration::from_millis(100),
585 }
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn streams_contains_objects_structurally() {
595 assert!(Interest::STREAMS.contains(Interest::OBJECTS));
596 assert!(!Interest::STREAMS.contains(Interest::CONTROL));
597 assert!(!Interest::STREAMS.contains(Interest::DATAGRAMS));
598 }
599
600 #[test]
601 fn none_is_the_default_and_contains_nothing() {
602 assert_eq!(Interest::default(), Interest::NONE);
603 assert!(Interest::NONE.is_none());
604 assert!(!Interest::OBJECTS.is_none());
605 assert!(Interest::NONE.contains(Interest::NONE));
606 assert!(!Interest::NONE.contains(Interest::OBJECTS));
607 }
608
609 #[test]
610 fn union_and_bitor_agree() {
611 let a = Interest::CONTROL | Interest::DATAGRAMS;
612 assert_eq!(a, Interest::CONTROL.union(Interest::DATAGRAMS));
613 assert!(a.contains(Interest::CONTROL));
614 assert!(a.contains(Interest::DATAGRAMS));
615 assert!(!a.contains(Interest::OBJECTS));
616 }
617
618 #[test]
619 fn a_gate_is_level_triggered() {
620 let g = Gate::new();
621 assert!(!g.is_released());
622 let clone = g.clone();
623 g.release();
624 assert!(g.is_released());
625 assert!(clone.is_released(), "clones share one release");
626 g.release();
627 assert!(g.is_released(), "release is idempotent");
628 }
629
630 #[tokio::test]
631 async fn waiting_on_an_already_released_gate_returns_immediately() {
632 let g = Gate::new();
633 g.release();
634 g.wait().await;
635 }
636
637 #[test]
638 fn modifiers_wrap_the_action_they_are_given() {
639 let a = Action::Pass.delayed(Duration::from_millis(5));
640 match a {
641 Action::Delay { by, then } => {
642 assert_eq!(by, Duration::from_millis(5));
643 assert!(matches!(*then, Action::Pass));
644 }
645 other => panic!("expected Delay, got {other:?}"),
646 }
647 let h = Action::Drop(DropMode::Elide).held(Gate::new());
648 match h {
649 Action::Hold { gate, then } => {
650 assert!(!gate.is_released());
651 assert!(matches!(*then, Action::Drop(DropMode::Elide)));
652 }
653 other => panic!("expected Hold, got {other:?}"),
654 }
655 }
656
657 #[test]
658 fn truncate_carries_its_own_reset_code() {
659 let t = Action::Truncate { bytes: 7, code: 0x2 };
660 match t {
661 Action::Truncate { bytes, code } => {
662 assert_eq!(bytes, 7);
663 assert_eq!(code, 0x2);
664 }
665 other => panic!("expected Truncate, got {other:?}"),
666 }
667 }
668
669 #[test]
670 fn egress_defaults_are_one_mib_and_thirty_seconds() {
671 let c = EgressConfig::default();
672 assert_eq!(c.max_pending_bytes, 1024 * 1024);
673 assert_eq!(c.max_hold, Duration::from_secs(30));
674 }
675}