Skip to main content

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 ends the session. Drafts 07-22 close it
309    /// as a `PROTOCOL_VIOLATION`; draft-23 Section 6.3: "If the control stream
310    /// is closed, the peer MUST close the session with CLOSED_CONTROL_STREAM."
311    /// The documented escalation is [`Self::CloseSession`].
312    ///
313    /// Codes above the QUIC varint ceiling (2^62 - 1) are refused with
314    /// [`Refusal::ErrorCodeOutOfRange`](crate::capability::Refusal::ErrorCodeOutOfRange)
315    /// before anything is sent, rather than silently becoming a FIN.
316    ResetStream {
317        /// The application error code to send.
318        code: u64,
319    },
320    /// Close both legs of the session with this code and reason.
321    ///
322    /// `code` is a *session termination* code, a different namespace from
323    /// a stream reset code: `0x0` NO_ERROR, `0x1` INTERNAL_ERROR, `0x2`
324    /// UNAUTHORIZED, `0x3` PROTOCOL_VIOLATION. Note that session
325    /// INTERNAL_ERROR is `0x1` while stream-reset INTERNAL_ERROR is `0x0`.
326    ///
327    /// Honoured at **every** site that returns an [`Action`], including
328    /// [`Site::StreamEnd`](crate::capability::Site::StreamEnd) on a data
329    /// stream *and* on the control stream. A close is session-scoped, so
330    /// no site can be the wrong one for it: unlike
331    /// [`Self::ResetStream`], there is no per-stream object it needs and
332    /// nothing left to forward that honouring it could corrupt. It is the
333    /// documented escalation for the two sites where a stream reset is a
334    /// protocol violation.
335    ///
336    /// The first close request wins; later ones are refused with
337    /// [`Refusal::SessionAlreadyClosing`](crate::capability::Refusal::SessionAlreadyClosing).
338    CloseSession {
339        /// The session termination code.
340        code: u32,
341        /// The reason phrase.
342        reason: Bytes,
343    },
344}
345
346impl Action {
347    /// Wrap this action in a [`Action::Delay`].
348    pub fn delayed(self, by: Duration) -> Self {
349        Action::Delay { by, then: Box::new(self) }
350    }
351    /// Wrap this action in a [`Action::Hold`].
352    pub fn held(self, gate: Gate) -> Self {
353        Action::Hold { gate, then: Box::new(self) }
354    }
355}
356
357/// How [`Action::Drop`] removes an object.
358///
359/// `MarkMissing` — a zero-length object carrying status
360/// `ObjectDoesNotExist`, the obvious default to reach for — is **not in
361/// this enum**. That status was removed from the registry in
362/// draft-17, and drafts 15-19 do not validate the status on write, so a
363/// naive implementation emits a code point those drafts do not define, on a
364/// stream that round-trips green against itself. Dropping an object
365/// therefore always removes its bytes; nothing here can leave a tombstone
366/// behind.
367///
368/// The absence is a compile-time fact, not a promise:
369///
370/// ```compile_fail
371/// use moqtap_proxy::action::DropMode;
372/// // drop_mark_missing_is_not_constructible: no such variant.
373/// let _mode = DropMode::MarkMissing;
374/// ```
375///
376/// The companion example below is what makes that `compile_fail` block
377/// mean something: if the path or the import were wrong, the block would
378/// still "pass" for the wrong reason, and this one would go red.
379///
380/// ```
381/// use moqtap_proxy::action::{Action, DropMode};
382/// let mode = DropMode::Elide;
383/// assert!(matches!(mode, DropMode::Elide));
384/// let _action = Action::Drop(mode);
385/// ```
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387#[non_exhaustive]
388pub enum DropMode {
389    /// Remove the object's bytes from the wire, preserving every survivor's
390    /// **absolute** object ID.
391    ///
392    /// Drafts 07-13, and fetch streams on drafts 07-14, encode absolute
393    /// IDs, so this is pure byte deletion: every survivor is forwarded
394    /// verbatim, including any non-minimally-encoded varint it arrived
395    /// with. Drafts 14-23 delta-encode, so the *one* object following an
396    /// elided run has its leading ID varint rewritten and nothing else;
397    /// every later object is again forwarded verbatim, because the wire
398    /// cursor re-converges after that one fix-up.
399    ///
400    /// Eliding `2` from `0,1,2,3,4` yields a stream decoding to `0,1,3,4` —
401    /// not `0,1,2,3`.
402    ///
403    /// Refused when the object is index 0 of a stream whose subgroup ID is
404    /// defined as the first object's ID
405    /// ([`ObjectMeta::subgroup_id`](crate::framer::ObjectMeta::subgroup_id)
406    /// is `None`), because removing it silently redefines the subgroup ID
407    /// for the receiver. Also refused when the object carries a status,
408    /// which is conservatively treated as a boundary marker.
409    Elide,
410}
411
412/// What to do with a unidirectional stream.
413///
414/// Returned from both
415/// [`ProxyHook::on_stream_open`](crate::hook::ProxyHook::on_stream_open)
416/// and
417/// [`ProxyHook::on_stream_header`](crate::hook::ProxyHook::on_stream_header).
418/// The observable effect of `Reject` differs between the two, and both are
419/// honest:
420///
421/// * At open, no peer stream is created at all.
422/// * At header, the peer stream already exists — it is opened before any
423///   byte of the source is read, whether that is in the accept loop or, for
424///   a stream whose open was deferred by [`Self::OpenAfter`], in the
425///   stream's own task once the delay has elapsed — so it is reset with
426///   `code` having carried zero payload bytes, and the source is stopped
427///   with `code`.
428///
429/// The same asymmetry decides where [`Self::OpenAfter`] is legal: it is a
430/// decision about *when the peer stream comes into existence*, so only the
431/// open site can take it. [`Self::SerializeAfter`] is a decision about when
432/// the first **byte** is written, which both sites can still take.
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum StreamAction {
436    /// Forward the stream normally.
437    Open,
438    /// Do not forward this stream. The source is stopped with `code`.
439    Reject {
440        /// The application error code.
441        code: u64,
442    },
443    /// Forward the stream, but do not open the peer stream until `after`
444    /// has elapsed.
445    ///
446    /// **Valid at
447    /// [`ProxyHook::on_stream_open`](crate::hook::ProxyHook::on_stream_open)
448    /// only.** By
449    /// [`ProxyHook::on_stream_header`](crate::hook::ProxyHook::on_stream_header)
450    /// the peer stream already exists — it is opened before the first
451    /// source byte is read, which is what makes a header arrive at all — so
452    /// there is nothing left to defer and the header site refuses it with
453    /// [`Refusal::WrongSite`](crate::capability::Refusal::WrongSite),
454    /// reported as `ProxyEvent::ActionRefused`. It is refused rather than
455    /// quietly ignored: a hook that asks for a deferral this crate cannot
456    /// perform is told so, and the stream is forwarded unchanged.
457    /// Delaying a stream's *opening* on something only its header reveals
458    /// — its track alias, say — would want the header site, and is
459    /// therefore not expressible in this release: the open decision has to
460    /// be taken before a byte is read.
461    ///
462    /// This models a relay that is slow to accept a subscription rather
463    /// than one that is slow to send: the subscriber observes no stream at
464    /// all for `after`, not an open-but-idle one. For the latter, see
465    /// [`Self::SerializeAfter`], which *is* valid at both sites.
466    ///
467    /// The deferral is a wire-visible one, not a bookkeeping note: the peer
468    /// stream is not opened and the source is not read until `after` has
469    /// elapsed, so a stream opened later and not deferred reaches the peer
470    /// first.
471    OpenAfter(Duration),
472    /// Open the peer stream now, but write nothing on it until the stream
473    /// named by the key has ended.
474    ///
475    /// Head-of-line simulation: two streams that a relay would have
476    /// interleaved are forced into sequence, so a caller can reproduce a
477    /// subscriber that stalls behind an unrelated group.
478    ///
479    /// Valid at **both** stream sites — it defers the first write, not the
480    /// stream's existence.
481    ///
482    /// One stream is exempt, and it is worth knowing before writing a
483    /// hook against it: on the drafts whose control plane is a pair of
484    /// unidirectional streams, a stream that turns out to *be* one of them
485    /// is not held. Holding a control stream's first write would hold
486    /// SETUP, and the session with it. The open site cannot tell in
487    /// advance — which stream it is is decided by the first varint on it,
488    /// read after the decision has been taken — so the decision is
489    /// admitted and then does not apply to that one stream.
490    ///
491    /// The key comes from
492    /// [`StreamCtx::key`](crate::hook::StreamCtx::key) on a stream the hook
493    /// was shown earlier. A key naming a stream that has already ended, or
494    /// that never existed in this session, **proceeds immediately** and
495    /// reports `Impairment { SerializeTargetUnknown }` once — a caller
496    /// cannot deadlock a stream by naming the wrong one, and the mistake is
497    /// reported rather than silently waited out.
498    SerializeAfter(StreamKey),
499}
500
501/// How a stream ended.
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503#[non_exhaustive]
504pub enum StreamEnd {
505    /// The source finished the stream cleanly.
506    Fin,
507    /// The source peer sent `RESET_STREAM`.
508    Reset {
509        /// The peer's application error code.
510        code: u64,
511    },
512    /// The destination peer sent `STOP_SENDING`.
513    Stopped {
514        /// The peer's application error code.
515        code: u64,
516    },
517    /// The session was cancelled while the stream was open.
518    Cancelled,
519}
520
521/// Engine-side knobs for action execution. Carried on the session config.
522#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523#[non_exhaustive]
524pub struct EgressConfig {
525    /// Bytes a per-stream pending queue may hold before the read side is
526    /// stalled. Past this point `Delay` and `Hold` are backpressure rather
527    /// than latency, and the transition is reported once per stream.
528    /// Default 1 MiB.
529    pub max_pending_bytes: usize,
530    /// Ceiling on any single [`Action::Hold`] and on any single
531    /// [`Action::Delay`]. A clamped delay is reported. Default 30 s.
532    ///
533    /// The ceiling is an `Instant` deadline, and `Instant` does not
534    /// behave the same way across a machine suspend on every platform: a
535    /// 30 s hold armed before a laptop sleeps may fire immediately on
536    /// resume (Windows `QueryPerformanceCounter`) or 30 s after resume
537    /// (Linux `CLOCK_MONOTONIC`). Irrelevant on CI; surprising when
538    /// debugging a run on a laptop.
539    pub max_hold: Duration,
540    /// How long a requested close gives this session's egress queues to
541    /// flush before both legs are closed anyway. Default 100 ms.
542    ///
543    /// Only [`ProxyControl::close_session`](crate::control::ProxyControl::close_session)
544    /// reads this. Every other way a session ends — a peer going away, a
545    /// hook's [`Action::CloseSession`], the proxy being cancelled — tears
546    /// down at once and has always done so. A requested close is different
547    /// because somebody is waiting for it to mean something: closing the
548    /// instant the request lands discards whatever a `Delay` or a `Hold`
549    /// was still holding, and the caller cannot tell that from a session
550    /// that had nothing queued.
551    ///
552    /// The bound is the point. An unbounded drain turns a close into a call
553    /// that may never finish: a stream whose destination peer has stopped
554    /// reading never empties its queue, and a shaped class whose bucket is
555    /// dry empties it only at the configured rate. Whatever is still queued
556    /// when this elapses is discarded and reported as
557    /// [`ImpairmentKind::QueuedBytesAtTeardown`](crate::event::ImpairmentKind::QueuedBytesAtTeardown),
558    /// so bytes that did not make it are named rather than lost quietly,
559    /// and the close still carries the code that was asked for.
560    ///
561    /// # The default is a guess, and here is the measurement that replaces it
562    ///
563    /// 100 ms was chosen because it is long enough for a loopback flush and
564    /// short enough that a caller closing sessions in a loop does not
565    /// notice, not because anything was measured. To replace it: pin one
566    /// queue state — a fixed object size, a fixed unit count, a fixed
567    /// destination window, written down beside the figure — sweep this
568    /// timeout across that state, and take the knee at which the **stranded
569    /// byte count reaches zero**. Quote the queue state with the number; a
570    /// knee measured against 4 KiB objects says nothing about 256 KiB ones.
571    ///
572    /// Measure stranded *bytes*, never elapsed time. Timing the drain
573    /// measures the fixture that filled the queue — how fast the source
574    /// wrote, how the destination's flow-control window happened to open —
575    /// and a timeout tuned against it is tuned against the harness. The
576    /// byte count is the thing that is either zero or not.
577    pub drain_timeout: Duration,
578}
579
580impl Default for EgressConfig {
581    fn default() -> Self {
582        Self {
583            max_pending_bytes: 1024 * 1024,
584            max_hold: Duration::from_secs(30),
585            drain_timeout: Duration::from_millis(100),
586        }
587    }
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    #[test]
595    fn streams_contains_objects_structurally() {
596        assert!(Interest::STREAMS.contains(Interest::OBJECTS));
597        assert!(!Interest::STREAMS.contains(Interest::CONTROL));
598        assert!(!Interest::STREAMS.contains(Interest::DATAGRAMS));
599    }
600
601    #[test]
602    fn none_is_the_default_and_contains_nothing() {
603        assert_eq!(Interest::default(), Interest::NONE);
604        assert!(Interest::NONE.is_none());
605        assert!(!Interest::OBJECTS.is_none());
606        assert!(Interest::NONE.contains(Interest::NONE));
607        assert!(!Interest::NONE.contains(Interest::OBJECTS));
608    }
609
610    #[test]
611    fn union_and_bitor_agree() {
612        let a = Interest::CONTROL | Interest::DATAGRAMS;
613        assert_eq!(a, Interest::CONTROL.union(Interest::DATAGRAMS));
614        assert!(a.contains(Interest::CONTROL));
615        assert!(a.contains(Interest::DATAGRAMS));
616        assert!(!a.contains(Interest::OBJECTS));
617    }
618
619    #[test]
620    fn a_gate_is_level_triggered() {
621        let g = Gate::new();
622        assert!(!g.is_released());
623        let clone = g.clone();
624        g.release();
625        assert!(g.is_released());
626        assert!(clone.is_released(), "clones share one release");
627        g.release();
628        assert!(g.is_released(), "release is idempotent");
629    }
630
631    #[tokio::test]
632    async fn waiting_on_an_already_released_gate_returns_immediately() {
633        let g = Gate::new();
634        g.release();
635        g.wait().await;
636    }
637
638    #[test]
639    fn modifiers_wrap_the_action_they_are_given() {
640        let a = Action::Pass.delayed(Duration::from_millis(5));
641        match a {
642            Action::Delay { by, then } => {
643                assert_eq!(by, Duration::from_millis(5));
644                assert!(matches!(*then, Action::Pass));
645            }
646            other => panic!("expected Delay, got {other:?}"),
647        }
648        let h = Action::Drop(DropMode::Elide).held(Gate::new());
649        match h {
650            Action::Hold { gate, then } => {
651                assert!(!gate.is_released());
652                assert!(matches!(*then, Action::Drop(DropMode::Elide)));
653            }
654            other => panic!("expected Hold, got {other:?}"),
655        }
656    }
657
658    #[test]
659    fn truncate_carries_its_own_reset_code() {
660        let t = Action::Truncate { bytes: 7, code: 0x2 };
661        match t {
662            Action::Truncate { bytes, code } => {
663                assert_eq!(bytes, 7);
664                assert_eq!(code, 0x2);
665            }
666            other => panic!("expected Truncate, got {other:?}"),
667        }
668    }
669
670    #[test]
671    fn egress_defaults_are_one_mib_and_thirty_seconds() {
672        let c = EgressConfig::default();
673        assert_eq!(c.max_pending_bytes, 1024 * 1024);
674        assert_eq!(c.max_hold, Duration::from_secs(30));
675    }
676}