moqtap_proxy/exec.rs
1//! The one place an [`Action`] becomes bytes on the wire, or a refusal.
2//!
3//! # Why this module exists at all
4//!
5//! Everything the engine can do is already published, by draft and by site,
6//! in [`crate::capability`]. This module's whole job is to *not* re-derive
7//! any of it: every admission decision here goes through
8//! [`crate::capability::classify`], the same function
9//! [`Capabilities::supports`](crate::capability::Capabilities::supports)
10//! publishes, so the table a caller reads before a run and the code
11//! that runs it are literally the same code. A cell that the table calls
12//! `No(WrongSite { .. })` is refused here *with the refusal value classify
13//! returned*, not with one this file rebuilt from the [`Action`] it was
14//! handed.
15//!
16//! That last distinction is load-bearing and easy to lose. At
17//! [`Site::Object`] both [`ActionKind::Replace`] and
18//! [`ActionKind::ReplaceObject`] classify to the **same** value —
19//! `No(WrongSite { site: Object, action: ActionKind::ReplaceObject })` —
20//! because `Action::Replace(b)` is the one action value that attempts both
21//! kinds at once. If this file synthesized `WrongSite { action:
22//! Replace }` from the value it saw, the published `ReplaceObject` cell would
23//! become unassertable by `tests/action_matrix.rs`, which compares
24//! `refusal == r`. The [`ProxyEvent::ActionRefused`] event's separate
25//! `action` field still reports what the value *was* — `Replace` — because
26//! that is what the hook returned; only `refusal` is the table's.
27//!
28//! # Which refusals are this module's to produce
29//!
30//! Three, and they are the three that depend on the action's payload or on
31//! session state rather than on the `(site, kind)` pair:
32//!
33//! * [`Refusal::WrongComposition`] — what a [`Action::Delay`] /
34//! [`Action::Hold`] wrapped;
35//! * [`Refusal::ErrorCodeOutOfRange`] — a stream error code above the QUIC
36//! varint ceiling;
37//! * [`Refusal::SessionAlreadyClosing`] — a second
38//! [`Action::CloseSession`].
39//!
40//! Everything else is propagated from `classify`. The **table-only**
41//! refusal [`Refusal::StreamNotFramed`] is never emitted from here —
42//! `every_refusal_this_module_emits_is_classifys_or_one_of_its_own_three`
43//! below is the falsifiable form of that claim: it sweeps drafts ×
44//! five sites × thirteen action shapes and asserts that neither variant ever
45//! reaches an `ActionRefused`, and that all three executor-owned refusals do.
46//!
47//! # Event cardinality — what this module guarantees
48//!
49//! * Every **refusal** emits exactly one [`ProxyEvent::ActionRefused`] and
50//! bumps `Counters::actions_refused` exactly once. The two happen in one
51//! function ([`Reporter::refused`]) so they cannot drift, and the counter
52//! is bumped even when the observer is detached — a run with no observer
53//! still counts its refusals.
54//! * Every **applied** action emits exactly one [`ProxyEvent::ActionApplied`]
55//! *per phase*.
56//! * Every **transport failure on an admitted action** emits exactly one
57//! [`ProxyEvent::ActionFailed`], through [`Reporter::failed`]. This module
58//! does not own the transport, so the caller makes that call; it is the
59//! only shape of report this module publishes rather than performs.
60//!
61//! ## `Delay { then: Replace }` — two events, and this is the ruling
62//!
63//! Nothing about the action shape forces the choice, so it is written down
64//! here. It is **two** [`ProxyEvent::ActionApplied`] events, distinguishable
65//! by their `action` field:
66//!
67//! 1. at the decision: `{ action: Delay, effect: Queued { release_at } }` —
68//! the modifier was accepted and the unit is in the queue;
69//! 2. at the release: `{ action: Replace, effect: Replaced { bytes } }` —
70//! the wire actually changed.
71//!
72//! One event would force a choice between reporting the deferral and reporting
73//! the effect, and a queued unit lost at teardown would have reported a
74//! `Replaced` that never happened. Two keep **the engine accepted this** and
75//! *"the wire changed"* separately falsifiable, which is exactly what
76//! [`ImpairmentKind::QueuedBytesAtTeardown`] is paired against. Stated as the
77//! rule a test can count: *one `ActionApplied` for a direct action, two for a
78//! `Delay`/`Hold`*.
79//!
80//! The second event is owed by this module and paid by the caller, because
81//! the release happens in `session.rs`'s `select!` arm long after `execute`
82//! returned. [`DeferredEffects`] is the ledger: `execute` pushes exactly one
83//! entry per [`PendingQueue::push`] and the caller pops exactly one per
84//! released unit, then hands it to [`Reporter::applied_deferred`]. Entries
85//! are `Option` because a *direct* action queued merely for ordering (a
86//! `Pass` behind a delayed unit) reports once at the decision and owes
87//! nothing at release.
88//!
89//! **Units a drain could not flush report nothing further** — that absence
90//! is the designed pairing with `QueuedBytesAtTeardown`, not a lost event.
91//! See [`DeferredEffects`] for the three-call discipline.
92
93use std::collections::VecDeque;
94use std::time::{Duration, Instant};
95
96use bytes::Bytes;
97
98use moqtap_codec::version::DraftVersion;
99
100use crate::action::{Action, DropMode, StreamAction};
101use crate::capability::{classify, ActionKind, CapCtx, Precondition, Refusal, Site, Support};
102use crate::egress::{self, Deferral, Pending, PendingQueue, SessionCloser, Terminal};
103use crate::event::{Effect, ImpairmentKind, ProxyEvent, SessionId};
104use crate::instrument::Recorder;
105use crate::observer::ProxyObserver;
106use crate::shape::StreamKey;
107use crate::types::{DataStreamType, ObjectMeta, ProxySide};
108
109/// The QUIC varint ceiling, `2^62 - 1`.
110///
111/// A stream application error code above it cannot be encoded, and quinn
112/// would panic or truncate rather than refuse. Checked here, before
113/// anything is sent, so the stream stays usable
114/// ([`Refusal::ErrorCodeOutOfRange`]).
115pub(crate) const MAX_APPLICATION_ERROR_CODE: u64 = (1u64 << 62) - 1;
116
117// ── What an action is being applied to ──────────────────────────────
118
119/// The unit an [`Action`] was returned for, with every fact
120/// [`crate::capability::classify`] needs to judge it.
121///
122/// An enum rather than a struct of `Option`s so that an under-populated
123/// [`CapCtx`] is not expressible: each variant carries exactly the facts its
124/// site's rules read, and [`Self::cap_ctx`] is the only place they are
125/// assembled. That is what makes `Support::Conditional` unreachable at
126/// execution time for the four *fact* preconditions — see
127/// [`admit_conditional`].
128///
129/// The two [`StreamAction`] sites are deliberately **not** here: they take
130/// [`execute_stream`], so `execute` cannot be called at a site whose hook
131/// method returns the other type, and `Support::NotAttemptable` is
132/// structurally unreachable from both entry points.
133#[derive(Debug)]
134pub(crate) enum Target<'a> {
135 /// A whole control-stream frame, with its wire bytes.
136 Control {
137 /// The frame's complete wire bytes.
138 raw: Bytes,
139 },
140 /// One framed object, with its wire bytes.
141 Object {
142 /// The object's framing, from the framer.
143 meta: &'a ObjectMeta,
144 /// The stream header's two subgroup-ID mode bits, on drafts 15-19.
145 ///
146 /// `None` on 07-14, whose header types carry no such pair. Supplying
147 /// it on 15-19 is what separates [`Refusal::ReservedHeaderMode`] from
148 /// [`Refusal::WouldRedefineSubgroupId`].
149 subgroup_id_mode: Option<u8>,
150 /// The object's complete wire bytes, framing and payload.
151 raw: Bytes,
152 },
153 /// One datagram.
154 Datagram {
155 /// The datagram's complete wire bytes.
156 raw: Bytes,
157 /// `data.len() - cursor.len()` after a **successful**
158 /// `AnyDatagramHeader::decode`, or `None` when the header did not
159 /// decode.
160 ///
161 /// This is the raw offset, not the verdict:
162 /// [`Self::payload_delimited`] applies draft-14's and the status
163 /// datagram's exceptions on top of it.
164 header_len: Option<usize>,
165 /// Whether the datagram carries an Object Status.
166 is_status: bool,
167 },
168 /// A stream ending. Carries no bytes.
169 StreamEnd {
170 /// `true` selects the control-stream rules for this site, `false`
171 /// the data-stream rules; they differ, so the flag is not cosmetic.
172 is_control_stream: bool,
173 },
174}
175
176impl Target<'_> {
177 /// Which published site this unit is at.
178 pub(crate) fn site(&self) -> Site {
179 match self {
180 Target::Control { .. } => Site::Control,
181 Target::Object { .. } => Site::Object,
182 Target::Datagram { .. } => Site::Datagram,
183 Target::StreamEnd { .. } => Site::StreamEnd,
184 }
185 }
186
187 /// The unit's wire bytes, or `None` at a site that has no unit.
188 fn raw(&self) -> Option<Bytes> {
189 match self {
190 Target::Control { raw } | Target::Object { raw, .. } | Target::Datagram { raw, .. } => {
191 Some(raw.clone())
192 }
193 Target::StreamEnd { .. } => None,
194 }
195 }
196
197 /// Whether a payload-preserving splice has a locatable boundary.
198 ///
199 /// At the object site, always: the payload is the trailing field in
200 /// every layout on all the drafts and both stream kinds.
201 ///
202 /// At the datagram site this is where the three exceptions live, and
203 /// they live *here* rather than at the call site because getting one
204 /// wrong is silent. `header_len` is `data.len() - cursor.len()`, which
205 /// is a real boundary only when the decode both succeeded and left the
206 /// payload behind:
207 ///
208 /// * **draft-14** — `AnyDatagramHeader` there is `DatagramObject`, whose
209 /// `decode` ends by reading all remaining bytes, so `header_len`
210 /// is the whole datagram and splicing would emit
211 /// `header ++ old ++ new`;
212 /// * **a status datagram** — no payload slot exists at all;
213 /// * **`header_len: None`** — the hook fires on an undecodable datagram,
214 /// and there is nothing to splice after.
215 fn payload_delimited(&self, draft: DraftVersion) -> Option<bool> {
216 match self {
217 Target::Object { .. } => Some(true),
218 Target::Datagram { header_len, is_status, .. } => {
219 Some(header_len.is_some() && draft != DraftVersion::Draft14 && !*is_status)
220 }
221 Target::Control { .. } | Target::StreamEnd { .. } => None,
222 }
223 }
224
225 /// Where the payload starts, when [`Self::payload_delimited`] is true.
226 fn payload_offset(&self, draft: DraftVersion) -> Option<usize> {
227 if self.payload_delimited(draft) != Some(true) {
228 return None;
229 }
230 match self {
231 Target::Object { meta, raw, .. } => {
232 usize::try_from(meta.payload_len).ok().and_then(|n| raw.len().checked_sub(n))
233 }
234 Target::Datagram { header_len, .. } => *header_len,
235 Target::Control { .. } | Target::StreamEnd { .. } => None,
236 }
237 }
238
239 /// Assemble the facts [`crate::capability::classify`] reads.
240 ///
241 /// `replacement_len` is the only field that comes from the *action*
242 /// rather than from the unit, which is why it is a parameter.
243 fn cap_ctx(&self, draft: DraftVersion, replacement_len: Option<u64>) -> CapCtx {
244 let mut cx = CapCtx { draft: Some(draft), replacement_len, ..CapCtx::default() };
245 match self {
246 Target::Control { .. } => {}
247 Target::Object { meta, subgroup_id_mode, .. } => {
248 cx.stream_kind = Some(meta.stream_kind);
249 cx.index_in_stream = Some(meta.index_in_stream);
250 cx.subgroup_id_resolved = Some(meta.subgroup_id.is_some());
251 cx.is_status_object = Some(meta.status.is_some());
252 cx.payload_len = Some(meta.payload_len);
253 cx.payload_delimited = Some(true);
254 cx.subgroup_id_mode = *subgroup_id_mode;
255 }
256 Target::Datagram { is_status, .. } => {
257 cx.is_status_object = Some(*is_status);
258 cx.payload_delimited = self.payload_delimited(draft);
259 }
260 Target::StreamEnd { is_control_stream } => {
261 cx.is_control_stream = Some(*is_control_stream);
262 }
263 }
264 cx
265 }
266}
267
268/// Which of the two [`StreamAction`] sites a decision was taken at.
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub(crate) enum StreamSite {
271 /// Between `accept_uni()` and `open_uni()`: no peer stream exists yet.
272 Open,
273 /// In the `FramerOut::Header` arm: the peer stream exists and has
274 /// carried no payload byte.
275 Header,
276}
277
278impl StreamSite {
279 /// The published site this maps to.
280 pub(crate) fn site(self) -> Site {
281 match self {
282 StreamSite::Open => Site::StreamOpen,
283 StreamSite::Header => Site::StreamHeader,
284 }
285 }
286}
287
288/// One unit of traffic, at one site, at one instant.
289#[derive(Debug)]
290pub(crate) struct Unit<'a> {
291 /// What the action applies to.
292 pub(crate) target: Target<'a>,
293 /// The draft this session is running as.
294 pub(crate) draft: DraftVersion,
295 /// When the unit arrived. [`Action::Delay`] is a deadline measured from
296 /// here, not from the moment the hook returned.
297 pub(crate) arrived_at: Instant,
298}
299
300// ── The engine state `execute` mutates ──────────────────────────────
301
302/// The per-stream deferral state.
303///
304/// The two halves travel together because [`DeferredEffects`] is only
305/// correct if it is pushed in lockstep with [`PendingQueue`]; making them
306/// one parameter is the cheapest way to keep a future edit from pushing to
307/// one and not the other.
308#[derive(Debug)]
309pub(crate) struct Queue<'a> {
310 /// The stream's pending deque.
311 pub(crate) pending: &'a mut PendingQueue,
312 /// The release-phase events owed against it.
313 pub(crate) deferred: &'a mut DeferredEffects,
314}
315
316/// Everything [`execute`] may mutate.
317#[derive(Debug)]
318pub(crate) struct Engine<'a> {
319 /// The stream's queue, or `None` at the datagram site.
320 ///
321 /// Datagrams are per-connection and unordered by definition, so they
322 /// have no queue — and [`Action::Delay`] / [`Action::Hold`] are
323 /// refused there, so nothing can need one. `None` is not a fallback
324 /// mode; it is the datagram site's shape.
325 pub(crate) queue: Option<Queue<'a>>,
326 /// Where [`Action::CloseSession`] is recorded.
327 pub(crate) closer: &'a SessionCloser,
328}
329
330impl Engine<'_> {
331 /// Whether a unit written now would overtake something already waiting —
332 /// **or** would escape the pacer.
333 ///
334 /// The second term is the whole of the release wiring's reach into this
335 /// module. `Plan::WriteNow` hands bytes straight to the transport, which
336 /// is correct and cheap on an unshaped stream and is exactly the path a
337 /// token bucket cannot see: `PendingQueue::pop_next_due` is the release
338 /// seam, and a unit that never enters the queue never reaches it. So a
339 /// shaped queue is *always* busy, and every unit on a shaped stream is
340 /// released rather than written.
341 ///
342 /// Nothing else in this module knows a class, a bucket or a discipline.
343 /// The queue tags what it is handed from the class the pipe loop last
344 /// resolved, so `push_unit` stays the one place a push and its ledger
345 /// entry happen together.
346 fn queue_is_busy(&self) -> bool {
347 self.queue.as_ref().is_some_and(|q| !q.pending.is_empty() || q.pending.is_shaped())
348 }
349}
350
351// ── The release-phase ledger ────────────────────────────────────────
352
353/// What a released unit owes the observer.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub(crate) struct Deferred {
356 /// The **inner** action's kind — `Replace` for `Delay { then:
357 /// Replace(b) }`, which is what distinguishes this event from the
358 /// `Queued` one emitted at the decision.
359 pub(crate) action: ActionKind,
360 /// What the release did to the wire.
361 pub(crate) effect: Effect,
362}
363
364/// The [`ProxyEvent::ActionApplied`] events owed at release, in queue order.
365///
366/// A sibling FIFO of [`PendingQueue`] rather than a field on `Pending`,
367/// because `Pending` is `egress.rs`'s type and reporting is not its
368/// concern — that module deliberately emits no events at all.
369///
370/// # The three-call discipline
371///
372/// Exactly one entry is pushed by [`execute`] on every
373/// [`PendingQueue::push`], so `self.len() == pending.len()` at every point
374/// the caller can observe. In `session.rs`:
375///
376/// * **release arm** — one [`Self::pop`] per [`PendingQueue::pop_next_due`],
377/// and each `Some` goes to [`Reporter::applied_deferred`];
378/// * **after a `DrainOutcome::Complete`** — [`Self::take_all`], and every
379/// `Some` in it goes to `applied_deferred`: the drain wrote them, in
380/// order, and they are owed;
381/// * **after any other `DrainOutcome`** — [`Self::clear`], and *nothing* is
382/// emitted. Whatever the fallback could not flush is reported once as
383/// [`ImpairmentKind::QueuedBytesAtTeardown`] instead. The missing second
384/// event is the point: a unit lost at teardown must not have reported a
385/// `Replaced` that never reached the wire.
386#[derive(Debug, Default)]
387pub(crate) struct DeferredEffects {
388 q: VecDeque<Option<Deferred>>,
389}
390
391impl DeferredEffects {
392 /// An empty ledger. Allocates nothing until the first push.
393 pub(crate) fn new() -> Self {
394 Self::default()
395 }
396
397 /// How many entries are owed. Equal to `PendingQueue::len()`.
398 ///
399 /// Read only by the tests below, which assert exactly that equality —
400 /// the three-call discipline is what the pipe loops use, and none of
401 /// them needs a count. Kept rather than `#[cfg(test)]`d because the
402 /// equality is the ledger's whole invariant and a reader looking for it
403 /// should find the accessor beside it.
404 #[allow(dead_code)]
405 pub(crate) fn len(&self) -> usize {
406 self.q.len()
407 }
408
409 /// Whether anything is owed. Tests only — see [`Self::len`].
410 #[allow(dead_code)]
411 pub(crate) fn is_empty(&self) -> bool {
412 self.q.is_empty()
413 }
414
415 /// The entry for the unit that was just released.
416 pub(crate) fn pop(&mut self) -> Option<Deferred> {
417 self.q.pop_front().flatten()
418 }
419
420 /// Every entry still owed, in order. For a drain that completed.
421 pub(crate) fn take_all(&mut self) -> Vec<Deferred> {
422 std::mem::take(&mut self.q).into_iter().flatten().collect()
423 }
424
425 /// Forget everything owed. For a drain that did not complete.
426 pub(crate) fn clear(&mut self) {
427 self.q.clear();
428 }
429
430 /// Record one entry against one [`PendingQueue::push`].
431 fn push(&mut self, entry: Option<Deferred>) {
432 self.q.push_back(entry);
433 }
434}
435
436// ── Reporting ───────────────────────────────────────────────────────
437
438/// Where this module's events and counters go.
439///
440/// Holds the session identity so no call site has to restate it, and holds
441/// the [`Recorder`] so that a counter bump and its event are one function
442/// call apart at most. Borrowed rather than owned: it is built per call from
443/// `session.rs`'s `ForwardCtx`, which this module deliberately does not
444/// name.
445#[derive(Clone, Copy)]
446pub(crate) struct Reporter<'a> {
447 observer: &'a dyn ProxyObserver,
448 /// Cached `observer.wants_events()`. Gates **events only** — counters
449 /// are unconditional.
450 enabled: bool,
451 counters: &'a Recorder,
452 session_id: SessionId,
453 side: ProxySide,
454 stream_id: Option<u64>,
455}
456
457impl std::fmt::Debug for Reporter<'_> {
458 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459 f.debug_struct("Reporter")
460 .field("enabled", &self.enabled)
461 .field("session_id", &self.session_id)
462 .field("side", &self.side)
463 .field("stream_id", &self.stream_id)
464 .finish_non_exhaustive()
465 }
466}
467
468impl<'a> Reporter<'a> {
469 /// Build one for a stream direction, or for the datagram path
470 /// (`stream_id: None`).
471 pub(crate) fn new(
472 observer: &'a dyn ProxyObserver,
473 enabled: bool,
474 counters: &'a Recorder,
475 session_id: SessionId,
476 side: ProxySide,
477 stream_id: Option<u64>,
478 ) -> Self {
479 Self { observer, enabled, counters, session_id, side, stream_id }
480 }
481
482 /// One [`ProxyEvent::ActionApplied`], for one phase of one action — and
483 /// the counter, for the two kinds that have one.
484 ///
485 /// The bumps sit **outside** the `enabled` gate, on exactly the terms
486 /// [`Self::refused`] gives for its own: a session with nobody watching
487 /// still counts what it did, and a counter that moved only when someone
488 /// was looking would agree with its event by construction rather than by
489 /// measurement.
490 ///
491 /// **Each kind reaches this method once per unit it was applied to**,
492 /// which is what makes a match on the kind a count and not an
493 /// over-count. `check_composition` refuses `Delay` and `Hold` as an
494 /// inner action and refuses `Truncate` and `ResetStream` as a wrapped
495 /// one, so a composition can hold neither of these two; and
496 /// [`Self::applied_deferred`], which reports the **inner** kind when a
497 /// deferred unit is released, can therefore never name either of them.
498 /// A delayed unit is counted at its decision and reported again at its
499 /// release under whatever it was wrapping, and only the first of those
500 /// two is a `Delay`.
501 pub(crate) fn applied(&self, site: Site, action: ActionKind, effect: Effect) {
502 match action {
503 ActionKind::Delay => self.counters.note_unit_delayed(),
504 ActionKind::Truncate => self.counters.note_object_truncated(),
505 _ => {}
506 }
507 self.emit(ProxyEvent::ActionApplied {
508 session_id: self.session_id,
509 side: self.side,
510 stream_id: self.stream_id,
511 site,
512 action,
513 effect,
514 });
515 }
516
517 /// The release-phase half of a [`Action::Delay`] / [`Action::Hold`].
518 ///
519 /// Always at [`Site::Object`] or [`Site::Control`] — the two sites with
520 /// a queue — and always with the **inner** action's kind, which is what
521 /// tells it apart from the `Queued` event emitted at the decision.
522 pub(crate) fn applied_deferred(&self, site: Site, deferred: Deferred) {
523 self.applied(site, deferred.action, deferred.effect);
524 }
525
526 /// One [`ProxyEvent::ActionRefused`], and one `actions_refused`.
527 ///
528 /// The counter is bumped **outside** the `enabled` gate on purpose: a
529 /// session with no observer attached still counts what it refused, and
530 /// the counter and the event are asserted independently. Bumping it
531 /// inside would make the two agree only when someone was watching.
532 pub(crate) fn refused(&self, site: Site, action: ActionKind, refusal: Refusal) {
533 self.counters.note_action_refused();
534 self.emit(ProxyEvent::ActionRefused {
535 session_id: self.session_id,
536 side: self.side,
537 stream_id: self.stream_id,
538 site,
539 action,
540 refusal,
541 });
542 }
543
544 /// One [`ProxyEvent::ActionFailed`]: the action was admitted and the
545 /// transport rejected it.
546 ///
547 /// Called by `session.rs`, not from here — this module produces the
548 /// bytes and the plan, and the caller hands them to the transport, so
549 /// only the caller can see the rejection.
550 /// It **follows** an `ActionApplied` for the same attempt rather than
551 /// replacing one. [`execute`] emits the admission before it returns, and
552 /// the caller cannot un-emit it once the transport declines; the two
553 /// together say *the engine did it, and it did not arrive*, which is the
554 /// whole truth and neither event carries it alone. What this is exclusive
555 /// of is `ActionRefused`: a refused unit was never the engine's to place,
556 /// so a transport failure on its bytes is
557 /// [`ImpairmentKind::DatagramNotSent`] instead.
558 ///
559 /// Note the event carries no `stream_id`: it is the datagram path's, and
560 /// a datagram has no stream to name.
561 pub(crate) fn failed(&self, site: Site, action: ActionKind, error: String) {
562 self.emit(ProxyEvent::ActionFailed {
563 session_id: self.session_id,
564 side: self.side,
565 site,
566 action,
567 error,
568 });
569 }
570
571 /// One [`ProxyEvent::Impairment`], carrying the connection it is about.
572 ///
573 /// The leg is worked out here, from the kind, rather than being a
574 /// parameter each call site supplies. A site knows one thing — the
575 /// direction it reads from — and most of what this enum reports is a
576 /// failure to *write*, which belongs to the other connection. Asking
577 /// twenty sites to make that turn is asking for the one to get it wrong
578 /// that nothing downstream can catch: the event still arrives, still
579 /// carries a leg, and names the wrong one.
580 ///
581 /// See [`crate::event::impairment_leg`] for the table and for why four
582 /// kinds answer `None`.
583 ///
584 /// # Ordering
585 ///
586 /// Every caller of this is past the thing it is reporting: the reset has
587 /// been handed to the transport, the datagram has come back refused, the
588 /// queue has been abandoned. That is a rule about the call sites rather
589 /// than something this function can enforce, and it is stated on
590 /// [`ProxyEvent::Impairment`] because it is what an observer is entitled
591 /// to rely on.
592 pub(crate) fn impairment(&self, kind: ImpairmentKind) {
593 let leg = crate::event::impairment_leg(&kind, self.side);
594 self.emit(ProxyEvent::Impairment {
595 session_id: self.session_id,
596 side: self.side,
597 leg,
598 kind,
599 });
600 }
601
602 fn emit(&self, event: ProxyEvent) {
603 if self.enabled {
604 self.observer.on_event(&event);
605 }
606 }
607}
608
609// ── What the caller must do next ────────────────────────────────────
610
611/// The wire operation [`execute`] has decided on but not performed.
612///
613/// This module owns *what the bytes are*; `session.rs` owns the transport
614/// handle and the `await`. Keeping the split here is what lets every rule
615/// below be unit-tested with no QUIC, no runtime and no session — the same
616/// argument `egress.rs` makes for its [`egress::EgressSink`].
617#[derive(Debug, Clone, PartialEq, Eq)]
618pub(crate) enum Plan {
619 /// Hand these bytes to the transport now: `send.write_all` on a stream
620 /// site, `send_datagram` at the datagram site.
621 ///
622 /// A failure at the datagram site is a [`Reporter::failed`], not a
623 /// session teardown: one undeliverable datagram must not take the
624 /// session with it.
625 WriteNow(Bytes),
626 /// Nothing goes to the wire on this call. The unit was queued behind
627 /// something already waiting, elided, or the site carries no bytes.
628 Nothing,
629 /// A positional terminal is now at the tail of the queue. Drain
630 /// honouring release times; the drain returns
631 /// `DrainOutcome::Terminated { forwarded, code }` and the stream is
632 /// over — do not `finish()` it.
633 Terminal,
634 /// Do not forward this stream. Stop the source with `code`; at
635 /// [`StreamSite::Header`] also reset the destination, which already
636 /// exists and has carried nothing.
637 RejectStream {
638 /// The application error code.
639 code: u64,
640 },
641 /// Forward this stream, but do not call `dest.open_uni()` until `after`
642 /// has elapsed. Only [`StreamSite::Open`] can produce this — by the
643 /// header site the peer stream exists, and that site refuses
644 /// [`StreamAction::OpenAfter`] with
645 /// [`Refusal::WrongSite`](crate::capability::Refusal::WrongSite) rather
646 /// than accepting a deferral it cannot perform.
647 ///
648 /// `session.rs`'s unidirectional accept loop consumes it, and the
649 /// deferral reaches the wire: the stream is spawned with **no**
650 /// destination handle, and the per-stream task sleeps `after` — racing
651 /// the session's cancellation — before it opens one. Nothing is read
652 /// from the source in the meantime, so the peer sees no stream at all
653 /// for `after` and then a whole one.
654 ///
655 /// The open happens inside the task but still *before* the first source
656 /// byte is read, which is what keeps the two reject sites different on
657 /// this topology too: by the time the header decision is taken the peer
658 /// stream exists, so a rejection there still resets it.
659 OpenStreamAfter {
660 /// How long to wait before opening the peer stream.
661 after: Duration,
662 },
663 /// Forward this stream, but write nothing on it until `target` has
664 /// ended. An unknown or already-ended target proceeds immediately and
665 /// reports `SerializeTargetUnknown` once.
666 ///
667 /// Consumed at both stream sites, because it defers the first *write*
668 /// rather than the stream's existence: from the open site it is carried
669 /// into the pipe, which waits before reading; at the header site the
670 /// wait happens in the `FramerOut::Header` arm, ahead of the header's
671 /// own bytes. Either way the peer stream is already open and silent.
672 ///
673 /// One stream never waits: the unidirectional control stream of a draft
674 /// whose control plane is a pair of them. Holding its first write would
675 /// hold SETUP, and the session with it.
676 SerializeStreamAfter {
677 /// The stream this one waits on.
678 target: StreamKey,
679 },
680 /// A session close was recorded in the [`SessionCloser`], **and the
681 /// session token is already cancelled** — [`execute`] cancels it once
682 /// the close has been reported, so the caller does not have to. Return
683 /// from the forwarding task; `run_with_transport` reads the code and
684 /// reason back out of the closer once the session's tasks have stopped.
685 ///
686 /// The unit itself is **not** forwarded: the hook returned a close
687 /// *instead of* an action on it.
688 CloseSession {
689 /// The session termination code.
690 code: u32,
691 /// The reason phrase.
692 reason: Bytes,
693 },
694}
695
696/// Everything one [`execute`] call decided.
697#[derive(Debug, Clone)]
698pub(crate) struct Outcome {
699 /// What the caller must do with the wire.
700 pub(crate) plan: Plan,
701 /// The effect that was reported, or the refusal that
702 /// was. **Both have already been emitted** — this is returned for the
703 /// caller's own bookkeeping and for tests, not as an instruction to
704 /// report again.
705 pub(crate) result: Result<Effect, Refusal>,
706 /// The caller must call `framer.note_elided(meta)` before polling the
707 /// framer again.
708 ///
709 /// True for an admitted [`DropMode::Elide`] at [`Site::Object`],
710 /// **including a deferred one**: the framer's cursor is positional and
711 /// `note_elided` asserts it names the object most recently emitted, so
712 /// it cannot be moved to the release.
713 pub(crate) note_elided: bool,
714 /// The [`Action::Delay`] arithmetic, on a `Delay` and only on a `Delay`.
715 ///
716 /// `Deferral::was_clamped()` says whether
717 /// [`crate::action::EgressConfig::max_hold`] cut the request short; when
718 /// it did, [`ImpairmentKind::HoldClamped`] has **already been emitted**.
719 /// Returned so a test can assert the arithmetic without reading the
720 /// observer. `None` for every other action, including [`Action::Hold`],
721 /// which carries no requested duration to clamp.
722 /// Read only by the tests below — the impairment it describes has already
723 /// been emitted, so `session.rs` has nothing left to do with it. It stays
724 /// on the returned value rather than being dropped because *the clamp is
725 /// assertable without an observer* is what makes the arithmetic gateable at
726 /// all.
727 #[allow(dead_code)]
728 pub(crate) clamped: Option<Deferral>,
729 /// Set on the push after which the queue stops accepting reads.
730 /// **Already reported** as [`ImpairmentKind::EgressQueueFull`], once per
731 /// stream. Read only by the tests below, for the same reason
732 /// [`Self::clamped`] is.
733 #[allow(dead_code)]
734 pub(crate) entered_backpressure: bool,
735}
736
737impl Outcome {
738 /// Whether the action was admitted.
739 pub(crate) fn is_applied(&self) -> bool {
740 self.result.is_ok()
741 }
742}
743
744// ── Entry points ────────────────────────────────────────────────────
745
746/// Execute one [`Action`] at one site.
747///
748/// Emits exactly one [`ProxyEvent::ActionApplied`] or exactly one
749/// [`ProxyEvent::ActionRefused`], plus any impairment the decision produced,
750/// and returns the wire operation the caller must perform.
751///
752/// **A refused unit is forwarded unchanged**, through the same
753/// queue-or-write-now fork an admitted `Pass` takes — a refusal must not let
754/// a unit overtake one already waiting.
755///
756/// # Order of checks
757///
758/// 1. [`crate::capability::classify`] on the `(site, kind)` pair. The site's own
759/// verdict comes first because it is the one the published table makes,
760/// and the table must win: `Delay { then: ResetStream }` at the datagram
761/// site is the datagram column's `WrongSite`, not a composition
762/// complaint.
763/// 2. Composition, for [`Action::Delay`] / [`Action::Hold`], which is
764/// validated **before the unit is queued** so a bad composition never
765/// reaches the deque and never bumps `egress_items_queued`.
766/// 3. The inner action, classified in its own right — `Delay { then:
767/// ReplacePayload(b) }` with the wrong length is
768/// [`Refusal::LengthChanged`], reported against the *inner* kind, which
769/// is the informative one.
770/// 4. The numeric code range, then the session-closing latch.
771///
772/// # A close is reported before it takes effect
773///
774/// [`Action::CloseSession`] is recorded in [`plan_action`], but the session
775/// is cancelled only here, after its `ActionApplied` — or its
776/// `SessionAlreadyClosing` refusal — has gone out. Cancelling wakes the
777/// session's other tasks on other worker threads, and they report the
778/// teardown they perform: a `Site::StreamEnd` decision on every stream the
779/// close cuts. Cancelled first, those reports could reach the observer
780/// before the close that caused them, and an observer reading in order
781/// would see a stream end for no reason and only then the close.
782pub(crate) fn execute(
783 unit: &Unit<'_>,
784 action: Action,
785 engine: &mut Engine<'_>,
786 report: &Reporter<'_>,
787) -> Outcome {
788 let site = unit.target.site();
789 match plan_action(unit, action, engine, report) {
790 Ok(applied) => {
791 report.applied(site, applied.action, applied.effect.clone());
792 if matches!(applied.plan, Plan::CloseSession { .. }) {
793 engine.closer.cancel();
794 }
795 Outcome {
796 plan: applied.plan,
797 result: Ok(applied.effect),
798 note_elided: applied.note_elided,
799 clamped: applied.clamped,
800 entered_backpressure: applied.entered_backpressure,
801 }
802 }
803 Err(Refused { action, refusal }) => {
804 report.refused(site, action, refusal.clone());
805 // A close that lost to an earlier one still ends the session:
806 // the earlier one may be a control-plane close inside its drain
807 // window, and a hook asking for the session to end is not asking
808 // to wait that window out. Only a close that reached the latch
809 // is refused this way, so no other refusal cancels anything.
810 if refusal == Refusal::SessionAlreadyClosing {
811 engine.closer.cancel();
812 }
813 let (plan, entered_backpressure) = forward_unchanged(unit, engine, report);
814 Outcome {
815 plan,
816 result: Err(refusal),
817 note_elided: false,
818 clamped: None,
819 entered_backpressure,
820 }
821 }
822 }
823}
824
825/// Execute one [`StreamAction`], at [`Site::StreamOpen`] or
826/// [`Site::StreamHeader`].
827///
828/// A separate entry point rather than a variant of [`Target`], so that the
829/// two sites whose hook methods return [`StreamAction`] cannot be handed an
830/// [`Action`] and `Support::NotAttemptable` stays unreachable at runtime —
831/// a claim made falsifiable by observing **zero** events at those 30-odd
832/// site × action cells.
833pub(crate) fn execute_stream(
834 site: StreamSite,
835 draft: DraftVersion,
836 action: StreamAction,
837 report: &Reporter<'_>,
838) -> Outcome {
839 let published = site.site();
840 let cx = CapCtx { draft: Some(draft), ..CapCtx::default() };
841 // Every arm reports `ForwardedVerbatim` except the rejection: the two
842 // deferral decisions — `OpenAfter` and `SerializeAfter` — change *when*
843 // the stream exists or *when* it first writes, never a byte of it. A
844 // separate `Effect` would claim a content change that never happens.
845 let (kind, effect) = match action {
846 StreamAction::Open => (ActionKind::Open, Effect::ForwardedVerbatim),
847 StreamAction::Reject { code } => (ActionKind::Reject, Effect::StreamRejected { code }),
848 StreamAction::OpenAfter(_) => (ActionKind::OpenAfter, Effect::ForwardedVerbatim),
849 StreamAction::SerializeAfter(_) => (ActionKind::SerializeAfter, Effect::ForwardedVerbatim),
850 };
851
852 let refuse = |refusal: Refusal| {
853 report.refused(published, kind, refusal.clone());
854 Outcome {
855 plan: Plan::Nothing,
856 result: Err(refusal),
857 note_elided: false,
858 clamped: None,
859 entered_backpressure: false,
860 }
861 };
862
863 if let Err(refusal) = admit(classify(published, kind, &cx)) {
864 return refuse(refusal);
865 }
866 if let StreamAction::Reject { code } = action {
867 if let Err(refusal) = check_error_code(code) {
868 return refuse(refusal);
869 }
870 }
871
872 report.applied(published, kind, effect.clone());
873 Outcome {
874 plan: match action {
875 StreamAction::Open => Plan::Nothing,
876 StreamAction::Reject { code } => Plan::RejectStream { code },
877 StreamAction::OpenAfter(after) => Plan::OpenStreamAfter { after },
878 StreamAction::SerializeAfter(target) => Plan::SerializeStreamAfter { target },
879 },
880 result: Ok(effect),
881 note_elided: false,
882 clamped: None,
883 entered_backpressure: false,
884 }
885}
886
887/// Run the elide guards for a **shaper's** tail-drop, and say whether the
888/// unit may be discarded.
889///
890/// [`Overflow::DropTail`](crate::shape::Overflow::DropTail) is sound
891/// precisely because it discards the *arriving* unit at admission time,
892/// where `framer.note_elided` is still legal — the framer's positional
893/// cursor has not moved past the object, so the successor's delta fix-up
894/// can still be armed. That is the same place `Action::Drop(DropMode::Elide)`
895/// is judged, so it is judged by the same code: this function asks
896/// [`crate::capability::classify`] exactly what `prepare_content` asks it,
897/// and the three elide guards — `WouldRedefineSubgroupId`,
898/// `WouldDestroyStatusObject`, `ReservedHeaderMode` — apply unchanged.
899///
900/// # What a refusal means, and why it is reported
901///
902/// `false` means an elide guard refused, and the caller must **admit the
903/// unit anyway** — the queue overshoots its depth by one. A shaper may not
904/// corrupt a stream to honour a depth limit: eliding an object the framer
905/// cannot renumber around does not lose one object, it makes every
906/// successor decode with a wrong absolute ID on drafts 14-23.
907///
908/// The refusal is reported as an ordinary
909/// [`ProxyEvent::ActionRefused`] and bumps `Counters::actions_refused`,
910/// through the same [`Reporter::refused`] every other refusal takes. That
911/// is why any test asserting an exact drop count must assert
912/// `actions_refused == 0` in the same body: without it, the
913/// arrivals-minus-drops arithmetic is off by the number of refusals and
914/// "no guard fired" is hoped rather than checked.
915///
916/// # Why this is not `execute(.., Action::Drop(DropMode::Elide), ..)`
917///
918/// Because no hook returned one. Routing a configured drop through
919/// `execute` would emit `ActionApplied { action: DropElide }` per dropped
920/// unit — a per-object event claiming a hook decision that never happened,
921/// on a path whose reporting is capped at once per stream per outcome. What
922/// the shaper owes
923/// the observer is [`ProxyEvent::Shaped`], which the caller emits; what it
924/// owes on a *refusal* is the refusal, which is here.
925pub(crate) fn shape_elide(unit: &Unit<'_>, report: &Reporter<'_>) -> bool {
926 debug_assert!(
927 matches!(unit.target, Target::Object { .. }),
928 "only a framed object can be tail-dropped: the shaper never sees anything else",
929 );
930 match admit_kind(Site::Object, ActionKind::DropElide, unit, None) {
931 Ok(()) => {
932 report.counters.note_object_elided();
933 true
934 }
935 Err(Refused { action, refusal }) => {
936 report.refused(Site::Object, action, refusal);
937 false
938 }
939 }
940}
941
942// ── Planning ────────────────────────────────────────────────────────
943
944/// A refusal, and the kind to name in the event.
945///
946/// The two are separate because they disagree exactly once, and that
947/// disagreement is the point of the module note: `Action::Replace(b)` at
948/// `Site::Object` is refused with `WrongSite { action: ReplaceObject }` —
949/// `classify`'s value, which the published `ReplaceObject` cell is compared
950/// against — while the event says `action: Replace`, which is what the hook
951/// returned.
952#[derive(Debug, Clone)]
953struct Refused {
954 action: ActionKind,
955 refusal: Refusal,
956}
957
958impl Refused {
959 fn new(action: ActionKind, refusal: Refusal) -> Self {
960 Self { action, refusal }
961 }
962}
963
964/// An admitted action, before its event is emitted.
965#[derive(Debug)]
966struct AppliedPlan {
967 action: ActionKind,
968 effect: Effect,
969 plan: Plan,
970 note_elided: bool,
971 clamped: Option<Deferral>,
972 entered_backpressure: bool,
973}
974
975impl AppliedPlan {
976 fn simple(action: ActionKind, effect: Effect, plan: Plan) -> Self {
977 Self {
978 action,
979 effect,
980 plan,
981 note_elided: false,
982 clamped: None,
983 entered_backpressure: false,
984 }
985 }
986}
987
988/// What a *content* action makes of the unit — the four things a
989/// [`Action::Delay`] / [`Action::Hold`] may wrap, and the same four when
990/// they stand alone.
991#[derive(Debug)]
992struct Content {
993 kind: ActionKind,
994 payload: Payload,
995 effect: Effect,
996 note_elided: bool,
997}
998
999/// The bytes a content action produced, or their absence.
1000#[derive(Debug, Clone, PartialEq, Eq)]
1001enum Payload {
1002 /// Write exactly these bytes.
1003 Write(Bytes),
1004 /// Write nothing. Still takes an ordering slot when the queue is busy:
1005 /// the drop was decided at a point in the stream, and letting it out of
1006 /// band would write a later unit before an earlier one.
1007 Elide,
1008 /// There is no unit. [`Site::StreamEnd`] only.
1009 ///
1010 /// Distinct from [`Self::Elide`] because a stream ending has no place in
1011 /// the deque at all — pushing an empty ordering slot behind a delayed
1012 /// object would owe a ledger entry for a unit that does not exist.
1013 Absent,
1014}
1015
1016fn plan_action(
1017 unit: &Unit<'_>,
1018 action: Action,
1019 engine: &mut Engine<'_>,
1020 report: &Reporter<'_>,
1021) -> Result<AppliedPlan, Refused> {
1022 let site = unit.target.site();
1023 match action {
1024 Action::Delay { by, then } => {
1025 admit_kind(site, ActionKind::Delay, unit, None)?;
1026 check_composition(&then)?;
1027 // `prepare_content` first, and the clamp report strictly after
1028 // it. Every refusal a `Delay` can earn is taken above this line,
1029 // so an impairment emitted below it is reporting a hold that the
1030 // engine really did apply — see
1031 // `a_refused_action_reports_its_refusal_and_no_impairment`,
1032 // which is red the moment these two are swapped.
1033 let content = prepare_content(unit, &then, report)?;
1034 let config = queue_config(engine);
1035 let deferral = egress::defer_by(unit.arrived_at, by, &config);
1036 if deferral.was_clamped() {
1037 // `Some`, always: a `Delay` names its own duration, so this is
1038 // the arm of the report that has a figure to quote. The
1039 // absent case belongs to a shaped release whose bucket named
1040 // no refill instant at all.
1041 report.impairment(ImpairmentKind::HoldClamped {
1042 requested: Some(deferral.requested),
1043 applied: deferral.applied,
1044 });
1045 }
1046 let pending = pending_for(&content.payload, deferral.release_at);
1047 let push = push_unit(engine, report, pending, Some(content.deferred()));
1048 Ok(AppliedPlan {
1049 action: ActionKind::Delay,
1050 effect: Effect::Queued { release_at: push.release_at },
1051 plan: Plan::Nothing,
1052 note_elided: content.note_elided,
1053 clamped: Some(deferral),
1054 entered_backpressure: push.entered_backpressure,
1055 })
1056 }
1057 Action::Hold { gate, then } => {
1058 admit_kind(site, ActionKind::Hold, unit, None)?;
1059 check_composition(&then)?;
1060 let content = prepare_content(unit, &then, report)?;
1061 let config = queue_config(engine);
1062 let ceiling = egress::hold_ceiling(unit.arrived_at, &config);
1063 let pending = pending_for(&content.payload, ceiling).with_gate(gate);
1064 let push = push_unit(engine, report, pending, Some(content.deferred()));
1065 Ok(AppliedPlan {
1066 action: ActionKind::Hold,
1067 effect: Effect::Queued { release_at: push.release_at },
1068 plan: Plan::Nothing,
1069 note_elided: content.note_elided,
1070 clamped: None,
1071 entered_backpressure: push.entered_backpressure,
1072 })
1073 }
1074 Action::Truncate { bytes, code } => {
1075 admit_kind(site, ActionKind::Truncate, unit, None)?;
1076 check_error_code(code).map_err(|r| Refused::new(ActionKind::Truncate, r))?;
1077 let raw = unit.target.raw().unwrap_or_default();
1078 let prefix = raw.slice(..bytes.min(raw.len()));
1079 let forwarded = prefix.len();
1080 let push = push_unit(
1081 engine,
1082 report,
1083 Pending::terminal(Terminal::Truncate { prefix, code }),
1084 None,
1085 );
1086 Ok(AppliedPlan {
1087 action: ActionKind::Truncate,
1088 effect: Effect::Truncated {
1089 forwarded,
1090 code,
1091 code_defined: stream_reset_code_defined(unit.draft),
1092 },
1093 plan: Plan::Terminal,
1094 note_elided: false,
1095 clamped: None,
1096 entered_backpressure: push.entered_backpressure,
1097 })
1098 }
1099 Action::ResetStream { code } => {
1100 admit_kind(site, ActionKind::ResetStream, unit, None)?;
1101 check_error_code(code).map_err(|r| Refused::new(ActionKind::ResetStream, r))?;
1102 let push = push_unit(engine, report, Pending::terminal(Terminal::Reset { code }), None);
1103 Ok(AppliedPlan {
1104 action: ActionKind::ResetStream,
1105 effect: Effect::StreamReset {
1106 code,
1107 code_defined: stream_reset_code_defined(unit.draft),
1108 },
1109 plan: Plan::Terminal,
1110 note_elided: false,
1111 clamped: None,
1112 entered_backpressure: push.entered_backpressure,
1113 })
1114 }
1115 Action::CloseSession { code, reason } => {
1116 admit_kind(site, ActionKind::CloseSession, unit, None)?;
1117 if !engine.closer.request(code, reason.clone()) {
1118 return Err(Refused::new(ActionKind::CloseSession, Refusal::SessionAlreadyClosing));
1119 }
1120 Ok(AppliedPlan::simple(
1121 ActionKind::CloseSession,
1122 Effect::SessionClosing { code },
1123 Plan::CloseSession { code, reason },
1124 ))
1125 }
1126 content_action => {
1127 let content = prepare_content(unit, &content_action, report)?;
1128 let (plan, entered_backpressure) = commit_now(&content.payload, engine, report);
1129 Ok(AppliedPlan {
1130 action: content.kind,
1131 effect: content.effect,
1132 plan,
1133 note_elided: content.note_elided,
1134 clamped: None,
1135 entered_backpressure,
1136 })
1137 }
1138 }
1139}
1140
1141impl Content {
1142 /// The event this content owes when its unit is released.
1143 fn deferred(&self) -> Deferred {
1144 Deferred { action: self.kind, effect: self.effect.clone() }
1145 }
1146}
1147
1148/// Classify and realise one content action.
1149///
1150/// The only place [`Action::Pass`], [`Action::Replace`],
1151/// [`Action::ReplacePayload`] and [`Action::Drop`] turn into bytes, reached
1152/// both directly and through a [`Action::Delay`] / [`Action::Hold`].
1153fn prepare_content(
1154 unit: &Unit<'_>,
1155 action: &Action,
1156 report: &Reporter<'_>,
1157) -> Result<Content, Refused> {
1158 let site = unit.target.site();
1159 match action {
1160 Action::Pass => {
1161 admit_kind(site, ActionKind::Pass, unit, None)?;
1162 Ok(Content {
1163 kind: ActionKind::Pass,
1164 payload: match unit.target.raw() {
1165 Some(raw) => Payload::Write(raw),
1166 // `Site::StreamEnd`: passing a stream ending is today's
1167 // behaviour at all four FIN sites, and today's behaviour
1168 // is to do nothing.
1169 None => Payload::Absent,
1170 },
1171 effect: Effect::ForwardedVerbatim,
1172 note_elided: false,
1173 })
1174 }
1175 Action::Replace(replacement) => {
1176 admit_kind(site, ActionKind::Replace, unit, None)?;
1177 Ok(Content {
1178 kind: ActionKind::Replace,
1179 payload: Payload::Write(replacement.clone()),
1180 effect: Effect::Replaced { bytes: replacement.len() },
1181 note_elided: false,
1182 })
1183 }
1184 Action::ReplacePayload(replacement) => {
1185 let replacement_len = u64::try_from(replacement.len()).ok();
1186 admit_kind(site, ActionKind::ReplacePayload, unit, replacement_len)?;
1187 let raw = unit.target.raw().unwrap_or_default();
1188 // `admit_kind` returning `Ok` is what guarantees the offset
1189 // exists: `Precondition::DatagramPayloadDelimited` is the
1190 // datagram half and the object site is unconditionally
1191 // delimited. The `unwrap_or` is a total-function guard,
1192 // not a fallback with meaning.
1193 let offset = unit.target.payload_offset(unit.draft).unwrap_or(raw.len());
1194 let mut spliced = Vec::with_capacity(offset + replacement.len());
1195 spliced.extend_from_slice(&raw[..offset]);
1196 spliced.extend_from_slice(replacement);
1197 let spliced = Bytes::from(spliced);
1198 Ok(Content {
1199 kind: ActionKind::ReplacePayload,
1200 payload: Payload::Write(spliced.clone()),
1201 effect: Effect::Replaced { bytes: spliced.len() },
1202 note_elided: false,
1203 })
1204 }
1205 Action::Drop(DropMode::Elide) => {
1206 admit_kind(site, ActionKind::DropElide, unit, None)?;
1207 let at_object_site = matches!(unit.target, Target::Object { .. });
1208 let effect = if at_object_site {
1209 report.counters.note_object_elided();
1210 Effect::Elided { renumbered_successor: elide_renumbers_successor(unit) }
1211 } else {
1212 // A control frame or a datagram has no object slot to
1213 // renumber, so the mode is ignored rather than refused and
1214 // the honest report is that the unit is gone.
1215 Effect::Dropped
1216 };
1217 Ok(Content {
1218 kind: ActionKind::DropElide,
1219 payload: Payload::Elide,
1220 effect,
1221 note_elided: at_object_site,
1222 })
1223 }
1224 // Reachable only as a `Delay`/`Hold` inner action, and
1225 // `check_composition` rejects every one of these before we get
1226 // here. Kept total rather than panicking: a capability engine that
1227 // can panic is worse than one that repeats itself.
1228 Action::Delay { .. } | Action::Hold { .. } => {
1229 Err(Refused::new(kind_of(action), NESTED_MODIFIER))
1230 }
1231 Action::Truncate { .. } | Action::ResetStream { .. } => {
1232 Err(Refused::new(kind_of(action), WRAPPED_TERMINAL))
1233 }
1234 Action::CloseSession { .. } => Err(Refused::new(kind_of(action), WRAPPED_CLOSE)),
1235 }
1236}
1237
1238// ── Admission ───────────────────────────────────────────────────────
1239
1240/// Ask [`crate::capability::classify`], and turn its verdict into an admission.
1241fn admit_kind(
1242 site: Site,
1243 kind: ActionKind,
1244 unit: &Unit<'_>,
1245 replacement_len: Option<u64>,
1246) -> Result<(), Refused> {
1247 let cx = unit.target.cap_ctx(unit.draft, replacement_len);
1248 admit(classify(site, kind, &cx)).map_err(|refusal| Refused::new(kind, refusal))
1249}
1250
1251/// The five verdicts, as an admission decision.
1252///
1253/// `NotAttemptable` and `Unreachable` are structurally unreachable from both
1254/// entry points — the first because the two `StreamAction` sites take
1255/// [`execute_stream`] and the four constructor-less kinds have no `Action`
1256/// value, the second because the hook is never invoked on a bypassed stream.
1257/// They are handled rather than `unreachable!()`d for the same reason
1258/// `capability.rs` has `filtered_earlier`: a total function beats a
1259/// panicking one on a forwarding task.
1260fn admit(support: Support) -> Result<(), Refusal> {
1261 match support {
1262 Support::Yes => Ok(()),
1263 Support::No(refusal) => Err(refusal),
1264 Support::Conditional(precondition) => admit_conditional(precondition),
1265 Support::NotAttemptable { refusal, .. } | Support::Unreachable { refusal, .. } => {
1266 Err(refusal)
1267 }
1268 }
1269}
1270
1271/// What a surviving [`Support::Conditional`] means *at execution time*.
1272///
1273/// One of the five preconditions is environmental — it cannot be settled
1274/// from the unit, so the table publishes it as conditional forever and the
1275/// engine admits the action:
1276///
1277/// * [`Precondition::WithinMaxDatagramSize`] — no transport in the workspace
1278/// exposes a maximum datagram size, so the verdict arrives as
1279/// `send_datagram` failing, which is a [`Reporter::failed`], not a
1280/// refusal, and the session survives it.
1281///
1282/// The other four are *facts about the unit*, and [`Target`] supplies every
1283/// one of them, so reaching those arms means a `CapCtx` was assembled
1284/// somewhere other than [`Target::cap_ctx`].
1285/// `no_fact_precondition_survives_execution` sweeps every site × every
1286/// action with fully-populated targets and asserts they never arrive, which
1287/// is what makes the `debug_assert` a claim rather than a hope.
1288fn admit_conditional(precondition: Precondition) -> Result<(), Refusal> {
1289 match precondition {
1290 Precondition::WithinMaxDatagramSize => Ok(()),
1291 Precondition::ReplacementLengthEqualsPayload
1292 | Precondition::NotFirstObjectOfImplicitSubgroup
1293 | Precondition::NotAStatusObject
1294 | Precondition::DatagramPayloadDelimited => {
1295 debug_assert!(
1296 false,
1297 "exec supplies every per-unit fact; {precondition:?} means a CapCtx \
1298 was built outside Target::cap_ctx",
1299 );
1300 Ok(())
1301 }
1302 }
1303}
1304
1305/// *Composition*: a modifier accepts only a content action.
1306///
1307/// Checked **before the unit is queued**, so a bad composition never reaches
1308/// the deque and `egress_items_queued` does not move — which is what
1309/// `a_delay_wrapping_a_terminal_is_refused_before_it_is_queued` asserts.
1310///
1311/// The four legal inner actions are [`Action::Pass`],
1312/// [`Action::Replace`], [`Action::ReplacePayload`] and [`Action::Drop`].
1313/// [`Action::Drop`] belongs on it, and the fact that it does is worth one
1314/// sentence here because a deferred drop reads as inert and is not: it
1315/// holds an ordering slot for the whole of its delay and
1316/// [`PendingQueue::pop_next_due`] only ever considers the front. The unit
1317/// is deleted *and* the rest of the stream is head-of-line-blocked, which
1318/// is the impairment the composition exists to express.
1319/// `a_delayed_drop_is_admitted_and_blocks_the_stream_behind_it` is the
1320/// falsifiable form of that claim — it asserts the successor's clamp, not
1321/// merely the admission, so a revision that queued the drop without an
1322/// ordering slot would still fail it.
1323fn check_composition(inner: &Action) -> Result<(), Refused> {
1324 let refusal = match inner {
1325 Action::Pass | Action::Replace(_) | Action::ReplacePayload(_) | Action::Drop(_) => {
1326 return Ok(())
1327 }
1328 Action::Delay { .. } | Action::Hold { .. } => NESTED_MODIFIER,
1329 Action::Truncate { .. } | Action::ResetStream { .. } => WRAPPED_TERMINAL,
1330 Action::CloseSession { .. } => WRAPPED_CLOSE,
1331 };
1332 Err(Refused::new(kind_of(inner), refusal))
1333}
1334
1335/// A stream application error code must fit a QUIC varint.
1336fn check_error_code(code: u64) -> Result<(), Refusal> {
1337 if code > MAX_APPLICATION_ERROR_CODE {
1338 Err(Refusal::ErrorCodeOutOfRange { code })
1339 } else {
1340 Ok(())
1341 }
1342}
1343
1344const NESTED_MODIFIER: Refusal =
1345 Refusal::WrongComposition { detail: "Delay or Hold wrapping another Delay or Hold" };
1346const WRAPPED_TERMINAL: Refusal =
1347 Refusal::WrongComposition { detail: "Delay or Hold wrapping Truncate or ResetStream" };
1348const WRAPPED_CLOSE: Refusal =
1349 Refusal::WrongComposition { detail: "Delay or Hold wrapping CloseSession" };
1350
1351// ── Committing to the wire or to the queue ──────────────────────────
1352
1353/// Write now, or take an ordering slot behind what is already waiting.
1354///
1355/// A unit that is due now on an **empty** queue is not pushed at all —
1356/// it is written inline in the read arm, which is today's code and today's
1357/// cost. On a **non-empty** queue it must be pushed, or it overtakes the
1358/// units ahead of it; the deque is what holds it back, and its own deadline
1359/// stays `now` (see [`PendingQueue::push`]) so that it goes out the instant
1360/// the units ahead of it have.
1361fn commit_now(payload: &Payload, engine: &mut Engine<'_>, report: &Reporter<'_>) -> (Plan, bool) {
1362 if matches!(payload, Payload::Absent) || !engine.queue_is_busy() {
1363 return (
1364 match payload {
1365 Payload::Write(raw) => Plan::WriteNow(raw.clone()),
1366 Payload::Elide | Payload::Absent => Plan::Nothing,
1367 },
1368 false,
1369 );
1370 }
1371 let push = push_unit(engine, report, pending_for(payload, Instant::now()), None);
1372 (Plan::Nothing, push.entered_backpressure)
1373}
1374
1375/// The refusal path's write: the unit goes out unchanged, through the same
1376/// fork an admitted [`Action::Pass`] takes.
1377fn forward_unchanged(
1378 unit: &Unit<'_>,
1379 engine: &mut Engine<'_>,
1380 report: &Reporter<'_>,
1381) -> (Plan, bool) {
1382 match unit.target.raw() {
1383 Some(raw) => commit_now(&Payload::Write(raw), engine, report),
1384 // `Site::StreamEnd` carries no unit: refusing there leaves the FIN
1385 // exactly as it was, which is `Pass`'s behaviour and today's.
1386 None => (Plan::Nothing, false),
1387 }
1388}
1389
1390fn pending_for(payload: &Payload, release_at: Instant) -> Pending {
1391 match payload {
1392 Payload::Write(raw) => Pending::bytes(raw.clone(), release_at),
1393 // `Absent` cannot be deferred: the only site that produces it,
1394 // `Site::StreamEnd`, refuses `Delay` and `Hold` outright, and
1395 // `commit_now` short-circuits it before it reaches here.
1396 Payload::Elide | Payload::Absent => Pending::elided(release_at),
1397 }
1398}
1399
1400/// Push one unit and record exactly one ledger entry against it.
1401///
1402/// The single place both happen, so `DeferredEffects::len() ==
1403/// PendingQueue::len()` holds by construction rather than by review.
1404fn push_unit(
1405 engine: &mut Engine<'_>,
1406 report: &Reporter<'_>,
1407 unit: Pending,
1408 owed: Option<Deferred>,
1409) -> egress::Push {
1410 let Some(queue) = engine.queue.as_mut() else {
1411 debug_assert!(
1412 false,
1413 "the datagram site has no queue, and Delay/Hold/Truncate/ResetStream \
1414 are refused there — nothing may reach a push",
1415 );
1416 return egress::Push { release_at: Instant::now(), entered_backpressure: false };
1417 };
1418 let push = queue.pending.push(unit);
1419 queue.deferred.push(owed);
1420 if push.entered_backpressure {
1421 if let Some(stream_id) = report.stream_id {
1422 report.impairment(ImpairmentKind::EgressQueueFull { stream_id });
1423 }
1424 }
1425 push
1426}
1427
1428/// Queue bytes the hook was never shown, on a **shaped** stream.
1429///
1430/// The counterpart of `session.rs`'s `write_in_order`, which drains and then
1431/// writes inline. That is right on an unshaped stream and wrong on a shaped
1432/// one twice over: it would let a stream header or an oversized object's
1433/// passthrough chunk escape the pacer, and — worse — the drain it runs first
1434/// honours release times, so on a paced queue it would block the read arm
1435/// for as long as the bucket took, inside a `select!` arm body that polls no
1436/// other branch.
1437///
1438/// Lives here rather than in `session.rs` for the reason `write_in_order`'s
1439/// own doc gives: `DeferredEffects`'s push is this module's, so the ledger
1440/// and the deque can only move together. The entry is `None` — these bytes
1441/// were never a hook decision, so nothing is owed at release.
1442///
1443/// The class is not a parameter: the queue carries the one the pipe loop
1444/// most recently resolved (`PendingQueue::tag_unit`), which for a header or
1445/// a passthrough chunk is `Class::Unshapeable`.
1446pub(crate) fn enqueue_unshown(
1447 pending: &mut PendingQueue,
1448 deferred: &mut DeferredEffects,
1449 raw: Bytes,
1450 report: &Reporter<'_>,
1451) {
1452 let push = pending.push(Pending::bytes(raw, Instant::now()));
1453 deferred.push(None);
1454 if push.entered_backpressure {
1455 if let Some(stream_id) = report.stream_id {
1456 report.impairment(ImpairmentKind::EgressQueueFull { stream_id });
1457 }
1458 }
1459}
1460
1461/// The queue's knobs, or the defaults when there is no queue.
1462///
1463/// The `None` arm is the datagram site, where `Delay` and `Hold` are refused
1464/// before they can ask — it exists so this is an expression rather than a
1465/// panic.
1466fn queue_config(engine: &Engine<'_>) -> crate::action::EgressConfig {
1467 const FALLBACK: crate::action::EgressConfig = crate::action::EgressConfig {
1468 max_pending_bytes: 1024 * 1024,
1469 max_hold: std::time::Duration::from_secs(30),
1470 // Never read here: the drain window belongs to a session close and
1471 // this fallback exists for the datagram site, which has no queue.
1472 // Restated rather than elided because `EgressConfig::default()` is
1473 // not a `const fn`, so this literal has to name every field.
1474 drain_timeout: std::time::Duration::from_millis(100),
1475 };
1476 match engine.queue.as_ref() {
1477 Some(queue) => *queue.pending.config(),
1478 None => FALLBACK,
1479 }
1480}
1481
1482// ── Per-draft facts this module needs ───────────────────────────────
1483
1484/// Whether the draft defines a stream-reset error code vocabulary.
1485///
1486/// Drafts 07-10 do not, so the reset still executes with the code the
1487/// action named and [`Effect::StreamReset`] / [`Effect::Truncated`] report
1488/// `code_defined: false` — the code is a choice there, not a claim.
1489///
1490/// Exhaustive rather than `!matches!(..)`. The negated form leans the other
1491/// way from the rest of these predicates — a draft nobody listed would be
1492/// *granted* a vocabulary rather than refused one, and the proxy would then
1493/// publish `code_defined: true` about a draft no one has read. Either default
1494/// is a guess; this one has to be written down.
1495const fn stream_reset_code_defined(draft: DraftVersion) -> bool {
1496 match draft {
1497 DraftVersion::Draft07
1498 | DraftVersion::Draft08
1499 | DraftVersion::Draft09
1500 | DraftVersion::Draft10 => false,
1501 DraftVersion::Draft11
1502 | DraftVersion::Draft12
1503 | DraftVersion::Draft13
1504 | DraftVersion::Draft14
1505 | DraftVersion::Draft15
1506 | DraftVersion::Draft16
1507 | DraftVersion::Draft17
1508 | DraftVersion::Draft18
1509 | DraftVersion::Draft19
1510 | DraftVersion::Draft20
1511 | DraftVersion::Draft21
1512 | DraftVersion::Draft22
1513 | DraftVersion::Draft23 => true,
1514 }
1515}
1516
1517/// Whether eliding this object leaves the framer owing a successor fix-up.
1518///
1519/// Mirrors `ObjectFramer::elide_owes_a_fixup`, which is private to
1520/// `framer.rs`, and the two stream kinds owe it from different drafts. A
1521/// **subgroup** stream delta-encodes object IDs from draft-14, so the one
1522/// object following an elided run has its leading ID varint rewritten. A
1523/// **fetch** stream owes it from draft-15, where a Serialization Flags field
1524/// lets a frame take any of its Group ID, Subgroup ID, Object ID and
1525/// Priority from the frame before it, and the payment is a re-encode of the
1526/// survivor's whole framing rather than a rewrite of one varint. Drafts
1527/// 07-13 subgroup streams and 07-14 fetch streams state every field
1528/// outright and owe nothing.
1529///
1530/// Duplicated rather than borrowed because the value is needed *before*
1531/// `framer.note_elided(meta)` is called — the effect is reported at the
1532/// decision, and `note_elided` is what arms the fix-up.
1533/// `elide_renumbering_names_the_drafts_that_owe_a_fixup` restates the table
1534/// explicitly; see its comment for why it cannot ask the framer directly,
1535/// and what covers the gap.
1536///
1537/// Both arms are exhaustive matches rather than `matches!`. `false` here means
1538/// *eliding this object costs the next one nothing*, which is the answer that
1539/// forwards a stream whose remaining Locations no longer decode — so a draft
1540/// that arrives without an answer must stop the build rather than take that
1541/// one. The two boundaries differ (subgroup from 14, fetch from 15), which is
1542/// exactly why neither can be extrapolated from the other.
1543fn elide_renumbers_successor(unit: &Unit<'_>) -> bool {
1544 let Target::Object { meta, .. } = &unit.target else {
1545 return false;
1546 };
1547 match meta.stream_kind {
1548 DataStreamType::Subgroup => match unit.draft {
1549 DraftVersion::Draft07
1550 | DraftVersion::Draft08
1551 | DraftVersion::Draft09
1552 | DraftVersion::Draft10
1553 | DraftVersion::Draft11
1554 | DraftVersion::Draft12
1555 | DraftVersion::Draft13 => false,
1556 DraftVersion::Draft14
1557 | DraftVersion::Draft15
1558 | DraftVersion::Draft16
1559 | DraftVersion::Draft17
1560 | DraftVersion::Draft18
1561 | DraftVersion::Draft19
1562 | DraftVersion::Draft20
1563 | DraftVersion::Draft21
1564 | DraftVersion::Draft22
1565 | DraftVersion::Draft23 => true,
1566 },
1567 DataStreamType::Fetch => match unit.draft {
1568 DraftVersion::Draft07
1569 | DraftVersion::Draft08
1570 | DraftVersion::Draft09
1571 | DraftVersion::Draft10
1572 | DraftVersion::Draft11
1573 | DraftVersion::Draft12
1574 | DraftVersion::Draft13
1575 | DraftVersion::Draft14 => false,
1576 DraftVersion::Draft15
1577 | DraftVersion::Draft16
1578 | DraftVersion::Draft17
1579 | DraftVersion::Draft18
1580 | DraftVersion::Draft19
1581 | DraftVersion::Draft20
1582 | DraftVersion::Draft21
1583 | DraftVersion::Draft22
1584 | DraftVersion::Draft23 => true,
1585 },
1586 }
1587}
1588
1589/// The [`ActionKind`] an [`Action`] value attempts.
1590///
1591/// `Action::Replace(b)` maps to [`ActionKind::Replace`] here even at
1592/// [`Site::Object`], where it also carries [`ActionKind::ReplaceObject`].
1593/// That is deliberate: this function answers *what the hook returned*, which
1594/// is the `ActionRefused` event's `action` field. The *refusal* comes from
1595/// `classify`, which names `ReplaceObject`, and the two are compared against
1596/// different things: the event field against what the hook returned, the
1597/// refusal against the published table.
1598const fn kind_of(action: &Action) -> ActionKind {
1599 match action {
1600 Action::Pass => ActionKind::Pass,
1601 Action::Replace(_) => ActionKind::Replace,
1602 Action::ReplacePayload(_) => ActionKind::ReplacePayload,
1603 Action::Delay { .. } => ActionKind::Delay,
1604 Action::Hold { .. } => ActionKind::Hold,
1605 Action::Drop(DropMode::Elide) => ActionKind::DropElide,
1606 Action::Truncate { .. } => ActionKind::Truncate,
1607 Action::ResetStream { .. } => ActionKind::ResetStream,
1608 Action::CloseSession { .. } => ActionKind::CloseSession,
1609 }
1610}
1611
1612#[cfg(test)]
1613mod tests {
1614 use std::sync::{Arc, Mutex};
1615 use std::time::Duration;
1616
1617 use super::*;
1618 use crate::action::{EgressConfig, Gate};
1619 use crate::egress::Item;
1620 use crate::types::Leg;
1621 use tokio_util::sync::CancellationToken;
1622
1623 // ── harness ─────────────────────────────────────────────────────
1624
1625 #[derive(Default)]
1626 struct Recording {
1627 events: Mutex<Vec<ProxyEvent>>,
1628 }
1629
1630 impl ProxyObserver for Recording {
1631 fn on_event(&self, event: &ProxyEvent) {
1632 self.events.lock().unwrap().push(event.clone());
1633 }
1634 }
1635
1636 impl Recording {
1637 fn events(&self) -> Vec<ProxyEvent> {
1638 self.events.lock().unwrap().clone()
1639 }
1640 fn applied(&self) -> Vec<(Site, ActionKind, Effect)> {
1641 self.events()
1642 .into_iter()
1643 .filter_map(|e| match e {
1644 ProxyEvent::ActionApplied { site, action, effect, .. } => {
1645 Some((site, action, effect))
1646 }
1647 _ => None,
1648 })
1649 .collect()
1650 }
1651 fn refused(&self) -> Vec<(Site, ActionKind, Refusal)> {
1652 self.events()
1653 .into_iter()
1654 .filter_map(|e| match e {
1655 ProxyEvent::ActionRefused { site, action, refusal, .. } => {
1656 Some((site, action, refusal))
1657 }
1658 _ => None,
1659 })
1660 .collect()
1661 }
1662 fn impairments(&self) -> Vec<ImpairmentKind> {
1663 self.events()
1664 .into_iter()
1665 .filter_map(|e| match e {
1666 ProxyEvent::Impairment { kind, .. } => Some(kind),
1667 _ => None,
1668 })
1669 .collect()
1670 }
1671
1672 /// Every impairment as the pair a reader actually needs — which
1673 /// connection it is about, and what it says — in emission order.
1674 ///
1675 /// A `Vec` rather than a set, and paired rather than two lists,
1676 /// because both halves of the claim are ordering claims: an
1677 /// impairment reports something that has already happened, so the
1678 /// order they arrive in is the order the proxy did things in, and a
1679 /// kind separated from its leg is a number without a label.
1680 fn attributed_impairments(&self) -> Vec<(Option<Leg>, ImpairmentKind)> {
1681 self.events()
1682 .into_iter()
1683 .filter_map(|e| match e {
1684 ProxyEvent::Impairment { leg, kind, .. } => Some((leg, kind)),
1685 _ => None,
1686 })
1687 .collect()
1688 }
1689 }
1690
1691 /// Everything a call needs, owned, so a test is four lines.
1692 struct Harness {
1693 observer: Arc<Recording>,
1694 counters: Arc<Recorder>,
1695 pending: PendingQueue,
1696 deferred: DeferredEffects,
1697 closer: SessionCloser,
1698 cancel: CancellationToken,
1699 /// The side the pipe this harness stands in for reads from.
1700 ///
1701 /// `ClientToProxy` unless a test says otherwise, which is the shape
1702 /// every test here had before the leg attribution existed. It is a
1703 /// field rather than a per-call argument because a real pipe fixes
1704 /// its side once, at the top of the forwarding task, and a test that
1705 /// could vary it per call would be able to build an event sequence
1706 /// no session can produce.
1707 side: ProxySide,
1708 }
1709
1710 impl Harness {
1711 fn new() -> Self {
1712 Self::with_config(EgressConfig::default())
1713 }
1714
1715 fn with_config(config: EgressConfig) -> Self {
1716 let counters = Arc::new(Recorder::new());
1717 let cancel = CancellationToken::new();
1718 Self {
1719 observer: Arc::new(Recording::default()),
1720 pending: PendingQueue::new(config, counters.clone()),
1721 deferred: DeferredEffects::new(),
1722 closer: SessionCloser::new(cancel.clone()),
1723 counters,
1724 cancel,
1725 side: ProxySide::ClientToProxy,
1726 }
1727 }
1728
1729 /// The same harness, standing in for the pipe that reads from the
1730 /// relay instead of the one that reads from the client.
1731 fn reading_from(mut self, side: ProxySide) -> Self {
1732 self.side = side;
1733 self
1734 }
1735
1736 fn report(&self) -> Reporter<'_> {
1737 Reporter::new(
1738 self.observer.as_ref(),
1739 true,
1740 self.counters.as_ref(),
1741 SessionId(1),
1742 self.side,
1743 Some(4),
1744 )
1745 }
1746
1747 /// A reporter with no stream, as the datagram path builds one.
1748 fn datagram_report(&self) -> Reporter<'_> {
1749 Reporter::new(
1750 self.observer.as_ref(),
1751 true,
1752 self.counters.as_ref(),
1753 SessionId(1),
1754 self.side,
1755 None,
1756 )
1757 }
1758
1759 /// The datagram site's shape: no queue at all.
1760 fn datagram_engine(&self) -> Engine<'_> {
1761 Engine { queue: None, closer: &self.closer }
1762 }
1763
1764 /// The same call on a session **nobody attached an observer to**:
1765 /// `wants_events()` answered `false`, so not one event is emitted.
1766 ///
1767 /// The counters are asserted through it, which is the only way to
1768 /// tell a figure that was measured from one that agrees with its own
1769 /// event because the same `if` guarded both.
1770 fn run_unwatched(&mut self, unit: &Unit<'_>, action: Action) -> Outcome {
1771 let report = Reporter::new(
1772 self.observer.as_ref(),
1773 false,
1774 self.counters.as_ref(),
1775 SessionId(1),
1776 self.side,
1777 Some(4),
1778 );
1779 let mut engine = Engine {
1780 queue: Some(Queue { pending: &mut self.pending, deferred: &mut self.deferred }),
1781 closer: &self.closer,
1782 };
1783 execute(unit, action, &mut engine, &report)
1784 }
1785
1786 fn run(&mut self, unit: &Unit<'_>, action: Action) -> Outcome {
1787 let report = Reporter::new(
1788 self.observer.as_ref(),
1789 true,
1790 self.counters.as_ref(),
1791 SessionId(1),
1792 self.side,
1793 Some(4),
1794 );
1795 let mut engine = Engine {
1796 queue: Some(Queue { pending: &mut self.pending, deferred: &mut self.deferred }),
1797 closer: &self.closer,
1798 };
1799 execute(unit, action, &mut engine, &report)
1800 }
1801 }
1802
1803 fn meta(draft: DraftVersion) -> ObjectMeta {
1804 ObjectMeta {
1805 draft,
1806 stream_kind: DataStreamType::Subgroup,
1807 track_alias: Some(7),
1808 group_id: 1,
1809 subgroup_id: Some(0),
1810 object_id: 3,
1811 publisher_priority: Some(128),
1812 index_in_stream: 3,
1813 payload_len: 4,
1814 status: None,
1815 end_of_range: None,
1816 }
1817 }
1818
1819 /// `[0xAA; 6]` framing followed by a four-byte payload.
1820 fn object_bytes() -> Bytes {
1821 Bytes::from_static(&[0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, b'p', b'a', b'y', b'l'])
1822 }
1823
1824 fn object_unit<'a>(m: &'a ObjectMeta, at: Instant) -> Unit<'a> {
1825 Unit {
1826 target: Target::Object { meta: m, subgroup_id_mode: None, raw: object_bytes() },
1827 draft: m.draft,
1828 arrived_at: at,
1829 }
1830 }
1831
1832 fn control_unit<'a>(draft: DraftVersion, at: Instant) -> Unit<'a> {
1833 Unit {
1834 target: Target::Control { raw: Bytes::from_static(b"control-frame") },
1835 draft,
1836 arrived_at: at,
1837 }
1838 }
1839
1840 fn datagram_unit<'a>(draft: DraftVersion, header_len: Option<usize>) -> Unit<'a> {
1841 Unit {
1842 target: Target::Datagram {
1843 raw: Bytes::from_static(&[0x01, 0x02, 0x03, b'p', b'a', b'y', b'l']),
1844 header_len,
1845 is_status: false,
1846 },
1847 draft,
1848 arrived_at: Instant::now(),
1849 }
1850 }
1851
1852 fn stream_end_unit<'a>(draft: DraftVersion, is_control_stream: bool) -> Unit<'a> {
1853 Unit { target: Target::StreamEnd { is_control_stream }, draft, arrived_at: Instant::now() }
1854 }
1855
1856 /// Every draft the vocabulary names, whether or not this build compiled
1857 /// a codec for it.
1858 ///
1859 /// The axis for the assertions that do not need one: the stream-end and
1860 /// datagram sites answer for a [`DraftVersion`] value, not for a
1861 /// decoder, and they answer the same way in every build — so
1862 /// restricting *those* sweeps to the compiled set would drop rows for
1863 /// nothing. Anything that asserts a verdict at the **object** or
1864 /// **control** site sweeps [`COMPILED_DRAFTS`] instead: both are behind
1865 /// a decoder this build may not carry, and on a draft it does not carry
1866 /// the hook is never invoked at either.
1867 ///
1868 /// Some whole-vocabulary sweeps below keep a control cell on this
1869 /// axis anyway. Neither asserts *which* verdict that cell earns — one
1870 /// counts decision events and checks that a refused unit is forwarded
1871 /// unchanged, the other only that no refusal collected is the framer's
1872 /// `StreamNotFramed` — and the `Unreachable` an uncompiled draft earns
1873 /// satisfies both.
1874 const ALL_DRAFTS: [DraftVersion; DraftVersion::ALL.len()] = DraftVersion::ALL;
1875
1876 /// The drafts this build actually compiled, in publication order.
1877 ///
1878 /// Each element carries its own `#[cfg]`, so the axis is the enabled set
1879 /// and not a hardcoded list — the shape `tests/action_matrix.rs` and
1880 /// the test module of `framer.rs` already use. It is the **only** honest
1881 /// axis for the object site: with no decoder for a draft the framer
1882 /// never addresses its data streams, the hook is never invoked on an
1883 /// object there, and `classify` says so — `Support::Unreachable {
1884 /// refusal: StreamNotFramed { reason: DecodeError } }`, see
1885 /// [`crate::capability::draft_is_compiled`]. Sweeping the whole
1886 /// vocabulary through `execute` therefore measures that guard rather
1887 /// than this module's executor: hardcode the axis and a `--features
1888 /// draft07` build turns twenty-seven of the tests below red.
1889 ///
1890 /// Every row that asserts a **control** verdict sweeps it too, for the
1891 /// same reason one decoder along: `AnyControlMessage::decode` has no arm
1892 /// for an uncompiled draft, so `ControlStreamParser::feed` refuses every
1893 /// frame and `ProxyHook::on_control_message` is never offered one.
1894 /// `classify` publishes that as `Support::Unreachable { refusal:
1895 /// ControlFrameNotDecodable }`, so a control cell left on [`ALL_DRAFTS`]
1896 /// measures the build guard on every draft this one skipped — which is
1897 /// why the only control cells still on that axis are the two whose
1898 /// assertions hold whichever refusal comes back.
1899 ///
1900 /// Under the default (all-drafts) build this is every draft and every
1901 /// object test below runs on all of them. Under `--no-default-features`
1902 /// it is empty: that build has no object site at all, so the object
1903 /// sweeps run zero times rather than asserting the framer's verdict is
1904 /// the executor's. The sites that survive there keep their own coverage
1905 /// through [`ALL_DRAFTS`].
1906 const COMPILED_DRAFTS: &[DraftVersion] = &[
1907 #[cfg(feature = "draft07")]
1908 DraftVersion::Draft07,
1909 #[cfg(feature = "draft08")]
1910 DraftVersion::Draft08,
1911 #[cfg(feature = "draft09")]
1912 DraftVersion::Draft09,
1913 #[cfg(feature = "draft10")]
1914 DraftVersion::Draft10,
1915 #[cfg(feature = "draft11")]
1916 DraftVersion::Draft11,
1917 #[cfg(feature = "draft12")]
1918 DraftVersion::Draft12,
1919 #[cfg(feature = "draft13")]
1920 DraftVersion::Draft13,
1921 #[cfg(feature = "draft14")]
1922 DraftVersion::Draft14,
1923 #[cfg(feature = "draft15")]
1924 DraftVersion::Draft15,
1925 #[cfg(feature = "draft16")]
1926 DraftVersion::Draft16,
1927 #[cfg(feature = "draft17")]
1928 DraftVersion::Draft17,
1929 #[cfg(feature = "draft18")]
1930 DraftVersion::Draft18,
1931 #[cfg(feature = "draft19")]
1932 DraftVersion::Draft19,
1933 #[cfg(feature = "draft20")]
1934 DraftVersion::Draft20,
1935 #[cfg(feature = "draft21")]
1936 DraftVersion::Draft21,
1937 #[cfg(feature = "draft22")]
1938 DraftVersion::Draft22,
1939 #[cfg(feature = "draft23")]
1940 DraftVersion::Draft23,
1941 ];
1942
1943 // ── how many events one action produces ─────────────────────────
1944
1945 #[test]
1946 fn an_applied_action_emits_exactly_one_event() {
1947 for &draft in COMPILED_DRAFTS {
1948 let mut h = Harness::new();
1949 let m = meta(draft);
1950 let out = h.run(&object_unit(&m, Instant::now()), Action::Pass);
1951 assert_eq!(out.plan, Plan::WriteNow(object_bytes()), "draft {draft:?}");
1952 assert_eq!(out.result, Ok(Effect::ForwardedVerbatim), "draft {draft:?}");
1953 assert_eq!(h.observer.events().len(), 1, "draft {draft:?}");
1954 assert_eq!(
1955 h.observer.applied(),
1956 vec![(Site::Object, ActionKind::Pass, Effect::ForwardedVerbatim)],
1957 "draft {draft:?}",
1958 );
1959 assert_eq!(h.counters.snapshot().actions_refused, 0, "draft {draft:?}");
1960 }
1961 }
1962
1963 #[test]
1964 fn a_refusal_emits_exactly_one_event_and_bumps_exactly_one_counter() {
1965 for &draft in COMPILED_DRAFTS {
1966 let mut h = Harness::new();
1967 let m = meta(draft);
1968 let out = h.run(
1969 &object_unit(&m, Instant::now()),
1970 Action::Replace(Bytes::from_static(b"nope")),
1971 );
1972 assert_eq!(h.observer.events().len(), 1, "draft {draft:?}");
1973 assert_eq!(h.counters.snapshot().actions_refused, 1, "draft {draft:?}");
1974 // The unit is forwarded unchanged.
1975 assert_eq!(out.plan, Plan::WriteNow(object_bytes()), "draft {draft:?}");
1976 }
1977 }
1978
1979 #[test]
1980 fn the_counter_moves_even_with_no_observer_attached() {
1981 for &draft in COMPILED_DRAFTS {
1982 let counters = Arc::new(Recorder::new());
1983 let observer = Recording::default();
1984 let cancel = CancellationToken::new();
1985 let closer = SessionCloser::new(cancel);
1986 let mut pending = PendingQueue::new(EgressConfig::default(), counters.clone());
1987 let mut deferred = DeferredEffects::new();
1988 let report = Reporter::new(
1989 &observer,
1990 false, // observer.wants_events() == false
1991 counters.as_ref(),
1992 SessionId(1),
1993 ProxySide::ClientToProxy,
1994 Some(1),
1995 );
1996 let mut engine = Engine {
1997 queue: Some(Queue { pending: &mut pending, deferred: &mut deferred }),
1998 closer: &closer,
1999 };
2000 let m = meta(draft);
2001 let out = execute(
2002 &object_unit(&m, Instant::now()),
2003 Action::Replace(Bytes::from_static(b"x")),
2004 &mut engine,
2005 &report,
2006 );
2007 // `Replace` at the object site is `WrongSite { .. ReplaceObject }`
2008 // on every draft — the executor's refusal, not the framer's.
2009 assert_eq!(
2010 out.result,
2011 Err(Refusal::WrongSite { site: Site::Object, action: ActionKind::ReplaceObject }),
2012 "draft {draft:?}",
2013 );
2014 assert!(observer.events().is_empty(), "events are gated");
2015 assert_eq!(counters.snapshot().actions_refused, 1, "counters are not");
2016 }
2017 }
2018
2019 /// The module note's cardinality contract, swept rather than argued:
2020 /// **exactly one** of `ActionApplied` / `ActionRefused` per `execute`,
2021 /// never both and never neither, and a refused unit's plan is its own
2022 /// bytes, unchanged.
2023 ///
2024 /// `every_refusal_this_module_emits_is_classifys_or_one_of_its_own_three`
2025 /// sweeps *which* refusals may appear; this sweeps *how many events*
2026 /// they arrive with, which is the half a partially-applied action would
2027 /// break. Impairments are excluded on purpose — a clamp or a
2028 /// backpressure transition is not a decision.
2029 #[test]
2030 fn exactly_one_decision_event_per_unit_and_refusals_forward_the_original() {
2031 let mut refused_cells = 0usize;
2032 let mut applied_cells = 0usize;
2033 for draft in ALL_DRAFTS {
2034 let m = meta(draft);
2035 // The stream-end and datagram cells answer for every draft in
2036 // the vocabulary; the object cell only for one this build
2037 // compiled (`COMPILED_DRAFTS`), because on the rest the hook is
2038 // never invoked there at all. The control cell stays on every
2039 // draft even though it is decoder-gated too: on an uncompiled
2040 // one it comes back refused as `ControlFrameNotDecodable`, and
2041 // this test asserts only that there is one decision event and
2042 // that the unit goes out unchanged — true of any refusal.
2043 let object_site_is_reachable = COMPILED_DRAFTS.contains(&draft);
2044 let actions = || {
2045 vec![
2046 Action::Pass,
2047 Action::Replace(Bytes::from_static(b"xxxx")),
2048 Action::ReplacePayload(Bytes::from_static(b"abcd")),
2049 Action::ReplacePayload(Bytes::from_static(b"toolong")),
2050 Action::Drop(DropMode::Elide),
2051 Action::Truncate { bytes: 2, code: 1 },
2052 Action::ResetStream { code: u64::MAX },
2053 Action::CloseSession { code: 1, reason: Bytes::new() },
2054 Action::Pass.delayed(Duration::from_millis(1)),
2055 Action::Pass.held(Gate::new()),
2056 Action::Drop(DropMode::Elide).delayed(Duration::from_millis(1)),
2057 Action::Drop(DropMode::Elide).held(Gate::new()),
2058 Action::ResetStream { code: 1 }.delayed(Duration::from_millis(1)),
2059 Action::CloseSession { code: 1, reason: Bytes::new() }.held(Gate::new()),
2060 ]
2061 };
2062 for action in actions() {
2063 // Each cell gets its own harness, so the queue is empty and
2064 // a refusal's forward is the inline write, not a slot.
2065 let mut cells: Vec<(Unit<'_>, Option<Bytes>)> = vec![
2066 (
2067 control_unit(draft, Instant::now()),
2068 Some(Bytes::from_static(b"control-frame")),
2069 ),
2070 (stream_end_unit(draft, false), None),
2071 (stream_end_unit(draft, true), None),
2072 ];
2073 if object_site_is_reachable {
2074 cells.push((object_unit(&m, Instant::now()), Some(object_bytes())));
2075 }
2076 for (unit, original) in cells {
2077 let mut h = Harness::new();
2078 let out = h.run(&unit, action.clone());
2079 let what = format!("{draft:?} / {:?} / {action:?}", unit.target.site());
2080 let decisions = h
2081 .observer
2082 .events()
2083 .iter()
2084 .filter(|e| {
2085 matches!(
2086 e,
2087 ProxyEvent::ActionApplied { .. } | ProxyEvent::ActionRefused { .. }
2088 )
2089 })
2090 .count();
2091 assert_eq!(decisions, 1, "[{what}] one decision event per unit");
2092 match &out.result {
2093 Ok(_) => {
2094 applied_cells += 1;
2095 assert!(h.observer.refused().is_empty(), "[{what}]");
2096 assert_eq!(h.counters.snapshot().actions_refused, 0, "[{what}]");
2097 }
2098 Err(_) => {
2099 refused_cells += 1;
2100 assert!(
2101 h.observer.applied().is_empty(),
2102 "[{what}] a refused unit reports no ActionApplied",
2103 );
2104 assert_eq!(h.counters.snapshot().actions_refused, 1, "[{what}]");
2105 let want = match &original {
2106 Some(raw) => Plan::WriteNow(raw.clone()),
2107 None => Plan::Nothing,
2108 };
2109 assert_eq!(
2110 out.plan, want,
2111 "[{what}] a refused unit is forwarded unchanged",
2112 );
2113 assert!(!out.note_elided, "[{what}]");
2114 assert!(out.clamped.is_none(), "[{what}]");
2115 assert!(
2116 h.pending.is_empty(),
2117 "[{what}] a refusal on an empty queue writes inline",
2118 );
2119 assert_eq!(h.counters.snapshot().egress_items_queued, 0, "[{what}]");
2120 }
2121 }
2122 }
2123
2124 // The datagram site takes the same entry point with no queue.
2125 let h = Harness::new();
2126 let unit = datagram_unit(draft, Some(3));
2127 let raw = Bytes::from_static(&[0x01, 0x02, 0x03, b'p', b'a', b'y', b'l']);
2128 let report = h.datagram_report();
2129 let mut engine = h.datagram_engine();
2130 let out = execute(&unit, action.clone(), &mut engine, &report);
2131 let what = format!("{draft:?} / Datagram / {action:?}");
2132 let decisions = h
2133 .observer
2134 .events()
2135 .iter()
2136 .filter(|e| {
2137 matches!(
2138 e,
2139 ProxyEvent::ActionApplied { .. } | ProxyEvent::ActionRefused { .. }
2140 )
2141 })
2142 .count();
2143 assert_eq!(decisions, 1, "[{what}] one decision event per unit");
2144 if out.result.is_err() {
2145 refused_cells += 1;
2146 assert!(h.observer.applied().is_empty(), "[{what}]");
2147 assert_eq!(out.plan, Plan::WriteNow(raw), "[{what}] forwarded unchanged");
2148 } else {
2149 applied_cells += 1;
2150 assert!(h.observer.refused().is_empty(), "[{what}]");
2151 }
2152 }
2153 }
2154 assert!(refused_cells > 0 && applied_cells > 0, "the sweep must reach both verdicts");
2155 }
2156
2157 /// A refusal behind a delayed unit takes an ordering slot rather than
2158 /// overtaking it — `execute`'s "through the same queue-or-write-now
2159 /// fork an admitted `Pass` takes" clause, which the empty-queue sweep
2160 /// above cannot reach.
2161 #[test]
2162 fn a_refused_unit_queues_behind_a_delayed_one_rather_than_overtaking_it() {
2163 const DELAY: Duration = Duration::from_millis(60);
2164 for &draft in COMPILED_DRAFTS {
2165 let mut h = Harness::new();
2166 let m = meta(draft);
2167 let at = Instant::now();
2168 h.run(&object_unit(&m, at), Action::Pass.delayed(DELAY));
2169 // `Replace` at the object site is `WrongSite { .. ReplaceObject }`.
2170 let out = h.run(&object_unit(&m, at), Action::Replace(Bytes::from_static(b"no")));
2171 assert!(out.result.is_err(), "draft {draft:?}");
2172 assert_eq!(out.plan, Plan::Nothing, "not written inline: the queue is busy");
2173 assert_eq!(h.pending.len(), 2, "draft {draft:?}");
2174 assert_eq!(h.deferred.len(), 2, "one ledger entry per pushed unit, refusals included");
2175
2176 assert!(
2177 h.pending.pop_next_due(Instant::now()).is_none(),
2178 "the delayed head still blocks the refused unit behind it",
2179 );
2180 let far = Instant::now() + Duration::from_secs(3600);
2181 let head = h.pending.pop_next_due(far).expect("the delayed Pass");
2182 let behind = h.pending.pop_next_due(far).expect("the refused unit, behind it");
2183 assert_eq!(*head.item(), Item::Write(object_bytes()));
2184 assert_eq!(
2185 *behind.item(),
2186 Item::Write(object_bytes()),
2187 "the refused unit's own bytes, not the replacement",
2188 );
2189 assert!(behind.expected_at() >= head.expected_at(), "and not expected ahead of it");
2190 assert_eq!(
2191 h.deferred.take_all(),
2192 vec![Deferred { action: ActionKind::Pass, effect: Effect::ForwardedVerbatim }],
2193 "the refused unit owes no release event",
2194 );
2195 }
2196 }
2197
2198 // ── the ruling: Delay { then: Replace } is two events ────────────
2199
2200 /// The ruling this module was asked to pin, at the one site where
2201 /// `Replace` is a legal inner action — the control site. (`Replace` at
2202 /// the object site is `WrongSite { .. ReplaceObject }` on every draft,
2203 /// so `Delay { then: Replace }` there is a *refusal*, which
2204 /// `a_delay_wrapping_a_refused_inner_action_is_refused` covers.)
2205 #[test]
2206 fn delay_then_replace_reports_queued_now_and_the_inner_effect_at_release() {
2207 let Some(draft) = a_compiled_draft() else { return };
2208 let mut h = Harness::new();
2209 let at = Instant::now();
2210 let out = h.run(
2211 &control_unit(draft, at),
2212 Action::Replace(Bytes::from_static(b"1234")).delayed(Duration::from_millis(50)),
2213 );
2214
2215 // Step 1, at the decision.
2216 assert_eq!(out.plan, Plan::Nothing);
2217 let Ok(Effect::Queued { release_at }) = out.result else {
2218 panic!("expected Queued, got {:?}", out.result)
2219 };
2220 assert!(release_at >= at + Duration::from_millis(50));
2221 assert_eq!(h.observer.applied().len(), 1);
2222 assert_eq!(h.observer.applied()[0].1, ActionKind::Delay);
2223
2224 // Step 2, at the release. One ledger entry, naming the inner kind.
2225 assert_eq!(h.deferred.len(), 1);
2226 assert_eq!(h.pending.len(), 1);
2227 let owed = h.deferred.pop().expect("the delay owes a release event");
2228 assert_eq!(
2229 owed,
2230 Deferred { action: ActionKind::Replace, effect: Effect::Replaced { bytes: 4 } },
2231 );
2232 h.report().applied_deferred(Site::Control, owed);
2233
2234 let applied = h.observer.applied();
2235 assert_eq!(applied.len(), 2, "a deferred action reports twice");
2236 assert_eq!(applied[1].1, ActionKind::Replace);
2237 assert_eq!(applied[1].2, Effect::Replaced { bytes: 4 });
2238 }
2239
2240 #[test]
2241 fn a_delay_wrapping_a_refused_inner_action_is_refused_with_the_inners_reason() {
2242 for &draft in COMPILED_DRAFTS {
2243 let mut h = Harness::new();
2244 let m = meta(draft);
2245 let out = h.run(
2246 &object_unit(&m, Instant::now()),
2247 Action::Replace(Bytes::from_static(b"1234")).delayed(Duration::from_millis(50)),
2248 );
2249 assert_eq!(
2250 out.result,
2251 Err(Refusal::WrongSite { site: Site::Object, action: ActionKind::ReplaceObject }),
2252 "draft {draft:?}",
2253 );
2254 assert_eq!(
2255 h.observer.refused()[0].1,
2256 ActionKind::Replace,
2257 "the event names the inner action, which is the informative one",
2258 );
2259 assert!(h.pending.is_empty(), "the site check happens before the queue");
2260 }
2261 }
2262
2263 #[test]
2264 fn a_direct_action_queued_only_for_ordering_owes_nothing_at_release() {
2265 for &draft in COMPILED_DRAFTS {
2266 let mut h = Harness::new();
2267 let m = meta(draft);
2268 let at = Instant::now();
2269 // Head of the queue: delayed, so the queue is busy.
2270 h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_millis(80)));
2271 // A plain `Pass` behind it must not overtake it — and must report
2272 // once, now, not twice.
2273 let out = h.run(&object_unit(&m, at), Action::Pass);
2274 assert_eq!(out.plan, Plan::Nothing, "a busy queue swallows the write");
2275 assert_eq!(out.result, Ok(Effect::ForwardedVerbatim), "draft {draft:?}");
2276 assert_eq!(h.pending.len(), 2, "draft {draft:?}");
2277 assert_eq!(h.deferred.len(), 2, "one ledger entry per pushed unit");
2278
2279 assert!(h.deferred.pop().is_some(), "the delayed unit owes one");
2280 assert!(h.deferred.pop().is_none(), "the ordering-only unit owes none");
2281 assert_eq!(h.observer.applied().len(), 2, "two decisions, two events");
2282 }
2283 }
2284
2285 #[test]
2286 fn hold_reports_queued_at_the_ceiling_and_owes_the_inner_effect() {
2287 for &draft in COMPILED_DRAFTS {
2288 let mut h = Harness::new();
2289 let m = meta(draft);
2290 let at = Instant::now();
2291 let gate = Gate::new();
2292 let out = h.run(&object_unit(&m, at), Action::Pass.held(gate.clone()));
2293 let Ok(Effect::Queued { release_at }) = out.result else {
2294 panic!("[{draft:?}] expected Queued, got {:?}", out.result)
2295 };
2296 assert!(release_at >= at + Duration::from_secs(30) - Duration::from_millis(1));
2297 assert_eq!(out.clamped, None, "a Hold has no requested duration to clamp");
2298 assert_eq!(
2299 h.deferred.pop(),
2300 Some(Deferred { action: ActionKind::Pass, effect: Effect::ForwardedVerbatim }),
2301 );
2302 assert!(!gate.is_released());
2303 }
2304 }
2305
2306 // ── composition ─────────────────────────────────────────────────
2307
2308 #[test]
2309 fn a_delay_wrapping_a_terminal_is_refused_before_it_is_queued() {
2310 for &draft in COMPILED_DRAFTS {
2311 let mut h = Harness::new();
2312 let m = meta(draft);
2313 let out = h.run(
2314 &object_unit(&m, Instant::now()),
2315 Action::ResetStream { code: 2 }.delayed(Duration::from_millis(10)),
2316 );
2317 assert_eq!(out.result, Err(WRAPPED_TERMINAL), "draft {draft:?}");
2318 assert_eq!(
2319 h.observer.refused(),
2320 vec![(Site::Object, ActionKind::ResetStream, WRAPPED_TERMINAL)],
2321 );
2322 assert!(h.pending.is_empty(), "nothing reached the deque");
2323 assert!(h.deferred.is_empty());
2324 assert_eq!(h.counters.snapshot().egress_items_queued, 0);
2325 // Refused units are still forwarded, unchanged.
2326 assert_eq!(out.plan, Plan::WriteNow(object_bytes()));
2327 }
2328 }
2329
2330 #[test]
2331 fn every_illegal_composition_names_which_one_it_was() {
2332 let cases = [
2333 (Action::Pass.delayed(Duration::from_millis(1)), NESTED_MODIFIER),
2334 (Action::Pass.held(Gate::new()), NESTED_MODIFIER),
2335 (Action::Truncate { bytes: 1, code: 0 }, WRAPPED_TERMINAL),
2336 (Action::ResetStream { code: 0 }, WRAPPED_TERMINAL),
2337 (Action::CloseSession { code: 1, reason: Bytes::new() }, WRAPPED_CLOSE),
2338 ];
2339 for &draft in COMPILED_DRAFTS {
2340 for (inner, expected) in cases.clone() {
2341 let mut h = Harness::new();
2342 let m = meta(draft);
2343 let out = h.run(
2344 &object_unit(&m, Instant::now()),
2345 inner.clone().delayed(Duration::from_millis(1)),
2346 );
2347 assert_eq!(out.result, Err(expected.clone()), "draft {draft:?} / inner {inner:?}");
2348 assert!(h.pending.is_empty());
2349 }
2350 }
2351 }
2352
2353 /// The list of legal inner actions, both directions, against the one
2354 /// function that decides it.
2355 ///
2356 /// A refusal on *other* grounds is not what this asserts — a wrapped
2357 /// `ReplacePayload` at the control site is `WrongSite`, and rightly.
2358 /// What must never happen is `WrongComposition` naming one of the four
2359 /// content actions.
2360 #[test]
2361 fn the_composition_rule_admits_exactly_the_four_content_actions() {
2362 for inner in [
2363 Action::Pass,
2364 Action::Replace(Bytes::from_static(b"xxxx")),
2365 Action::ReplacePayload(Bytes::from_static(b"abcd")),
2366 Action::Drop(DropMode::Elide),
2367 ] {
2368 assert!(
2369 check_composition(&inner).is_ok(),
2370 "{inner:?} is a content action and must be legal inside Delay/Hold",
2371 );
2372 }
2373 for (inner, expected) in [
2374 (Action::Pass.delayed(Duration::ZERO), NESTED_MODIFIER),
2375 (Action::Pass.held(Gate::new()), NESTED_MODIFIER),
2376 (Action::Truncate { bytes: 1, code: 0 }, WRAPPED_TERMINAL),
2377 (Action::ResetStream { code: 0 }, WRAPPED_TERMINAL),
2378 (Action::CloseSession { code: 0, reason: Bytes::new() }, WRAPPED_CLOSE),
2379 ] {
2380 let Err(Refused { action, refusal }) = check_composition(&inner) else {
2381 panic!("{inner:?} is not a content action and must be refused")
2382 };
2383 assert_eq!(refusal, expected, "inner {inner:?}");
2384 assert_eq!(action, kind_of(&inner), "the event names what was wrapped");
2385 }
2386 }
2387
2388 /// The composition ruling for `Delay { then: Drop(_) }`, and the
2389 /// measurement behind it.
2390 ///
2391 /// `Drop` is one of the four legal inner actions, and the `Action`
2392 /// rustdoc says so. It is admitted, and it is not unobservable: the
2393 /// drop takes an ordering slot for the whole of its delay, so the
2394 /// undelayed `Pass` pushed behind it is clamped to the drop's release
2395 /// instead of going out inline. Deleting the unit and stalling the
2396 /// stream behind it is one impairment with two effects, both on the
2397 /// wire.
2398 #[test]
2399 fn a_delayed_drop_is_admitted_and_blocks_the_stream_behind_it() {
2400 const DELAY: Duration = Duration::from_millis(80);
2401 for &draft in COMPILED_DRAFTS {
2402 let mut h = Harness::new();
2403 let m = meta(draft);
2404 let at = Instant::now();
2405 // Whether the elide leaves a successor to renumber is the delta
2406 // drafts' business, not this test's; the table itself is pinned
2407 // by `elide_renumbering_names_the_delta_encoding_drafts`.
2408 let renumbered = elide_renumbers_successor(&object_unit(&m, at));
2409
2410 let out = h.run(&object_unit(&m, at), Action::Drop(DropMode::Elide).delayed(DELAY));
2411 let Ok(Effect::Queued { release_at }) = out.result else {
2412 panic!("[{draft:?}] a delayed Drop is admitted, not refused; got {:?}", out.result)
2413 };
2414 assert!(release_at >= at + DELAY);
2415 assert!(out.note_elided, "the framer's cursor still moves at the decision");
2416 assert_eq!(h.counters.snapshot().actions_refused, 0);
2417 assert!(h.observer.refused().is_empty(), "nothing was refused");
2418 assert_eq!(
2419 h.observer.applied(),
2420 vec![(Site::Object, ActionKind::Delay, Effect::Queued { release_at })],
2421 "step 1 names the modifier",
2422 );
2423
2424 // The observability claim: the next object cannot overtake it.
2425 let behind = h.run(&object_unit(&m, at), Action::Pass);
2426 assert_eq!(behind.plan, Plan::Nothing, "the drop's slot is still holding the queue");
2427 assert_eq!(behind.result, Ok(Effect::ForwardedVerbatim));
2428 assert_eq!(h.deferred.len(), h.pending.len());
2429 assert_eq!(
2430 h.deferred.take_all(),
2431 vec![Deferred {
2432 action: ActionKind::DropElide,
2433 effect: Effect::Elided { renumbered_successor: renumbered },
2434 }],
2435 "step 2 names the inner action; the ordering-only Pass owes nothing",
2436 );
2437
2438 // The `Pass` is due on its own account the instant it is pushed,
2439 // and is still not writable: the elided drop is in front of it
2440 // and is not due. That is the head-of-line block, stated as
2441 // behaviour rather than as arithmetic.
2442 assert!(
2443 h.pending.pop_next_due(Instant::now()).is_none(),
2444 "a delayed drop head-of-line-blocks the undelayed unit behind it",
2445 );
2446
2447 let far = Instant::now() + Duration::from_secs(3600);
2448 let dropped = h.pending.pop_next_due(far).expect("the drop holds a slot");
2449 let passed = h.pending.pop_next_due(far).expect("the Pass is queued behind it");
2450 assert_eq!(*dropped.item(), Item::Elided, "the drop writes nothing...");
2451 assert!(dropped.due_at() >= at + DELAY, "...and not until its delay is up");
2452 assert_eq!(*passed.item(), Item::Write(object_bytes()));
2453 assert!(
2454 passed.expected_at() >= at + DELAY,
2455 "the queue expects to write the unit behind the drop no earlier than the drop: \
2456 {:?} is earlier than {:?}",
2457 passed.expected_at(),
2458 at + DELAY,
2459 );
2460 }
2461 }
2462
2463 /// The same ruling under a [`Gate`]. The gate is the observable here:
2464 /// the unit is not due while the gate holds, and is the moment it is
2465 /// released.
2466 #[test]
2467 fn a_held_drop_is_admitted_and_stays_undue_until_its_gate_is_released() {
2468 for &draft in COMPILED_DRAFTS {
2469 let mut h = Harness::new();
2470 let m = meta(draft);
2471 let at = Instant::now();
2472 let renumbered = elide_renumbers_successor(&object_unit(&m, at));
2473 let gate = Gate::new();
2474 let out = h.run(&object_unit(&m, at), Action::Drop(DropMode::Elide).held(gate.clone()));
2475 assert!(
2476 matches!(out.result, Ok(Effect::Queued { .. })),
2477 "[{draft:?}] a held Drop is admitted, not refused; got {:?}",
2478 out.result,
2479 );
2480 assert_eq!(h.counters.snapshot().actions_refused, 0);
2481 assert!(
2482 h.pending.pop_next_due(Instant::now()).is_none(),
2483 "nothing is due while the gate holds",
2484 );
2485 gate.release();
2486 let released =
2487 h.pending.pop_next_due(Instant::now()).expect("a released gate makes it due");
2488 assert_eq!(*released.item(), Item::Elided);
2489 assert_eq!(
2490 h.deferred.take_all(),
2491 vec![Deferred {
2492 action: ActionKind::DropElide,
2493 effect: Effect::Elided { renumbered_successor: renumbered },
2494 }],
2495 );
2496 }
2497 }
2498
2499 #[test]
2500 fn the_site_verdict_wins_over_the_composition_verdict() {
2501 // `Delay` is refused at the datagram site. A bad composition
2502 // inside it must not shadow that site verdict.
2503 let h = Harness::new();
2504 let unit = datagram_unit(DraftVersion::Draft11, Some(3));
2505 let report = h.datagram_report();
2506 let mut engine = h.datagram_engine();
2507 let out = execute(
2508 &unit,
2509 Action::ResetStream { code: 1 }.delayed(Duration::from_millis(5)),
2510 &mut engine,
2511 &report,
2512 );
2513 assert_eq!(
2514 out.result,
2515 Err(Refusal::WrongSite { site: Site::Datagram, action: ActionKind::Delay }),
2516 );
2517 }
2518
2519 // ── refusal propagation, verbatim from `classify` ────────────────
2520
2521 #[test]
2522 fn replace_at_the_object_site_propagates_classifys_replaceobject_refusal() {
2523 for &draft in COMPILED_DRAFTS {
2524 let mut h = Harness::new();
2525 let m = meta(draft);
2526 let out =
2527 h.run(&object_unit(&m, Instant::now()), Action::Replace(Bytes::from_static(b"x")));
2528 // The refusal is the table's — `ReplaceObject`, not `Replace`.
2529 assert_eq!(
2530 out.result,
2531 Err(Refusal::WrongSite { site: Site::Object, action: ActionKind::ReplaceObject }),
2532 "draft {draft:?}",
2533 );
2534 // The event's `action` is what the hook returned.
2535 assert_eq!(h.observer.refused()[0].1, ActionKind::Replace);
2536 // And it is byte-for-byte what the published table says.
2537 let published = crate::capability::Capabilities::for_draft(draft)
2538 .supports(Site::Object, ActionKind::ReplaceObject);
2539 assert_eq!(published, Support::No(out.result.unwrap_err()), "draft {draft:?}");
2540 }
2541 }
2542
2543 #[test]
2544 fn every_refusal_this_module_emits_is_classifys_or_one_of_its_own_three() {
2545 // The exhaustive statement of the module note: sweep a wide set of
2546 // (site, action) pairs and assert every refusal that comes back is
2547 // either one `classify` produced for the same pair, or one of the
2548 // three the executor owns.
2549 let mut seen: Vec<Refusal> = Vec::new();
2550 for draft in ALL_DRAFTS {
2551 let m = meta(draft);
2552 let actions = || {
2553 vec![
2554 Action::Pass,
2555 Action::Replace(Bytes::from_static(b"xxxx")),
2556 Action::ReplacePayload(Bytes::from_static(b"abcd")),
2557 Action::ReplacePayload(Bytes::from_static(b"toolong")),
2558 Action::Drop(DropMode::Elide),
2559 Action::Truncate { bytes: 2, code: 1 },
2560 Action::Truncate { bytes: 2, code: u64::MAX },
2561 Action::ResetStream { code: 1 },
2562 Action::ResetStream { code: u64::MAX },
2563 Action::CloseSession { code: 1, reason: Bytes::new() },
2564 Action::Pass.delayed(Duration::from_millis(1)),
2565 Action::Pass.held(Gate::new()),
2566 Action::ResetStream { code: 1 }.delayed(Duration::from_millis(1)),
2567 ]
2568 };
2569 for action in actions() {
2570 // As above: the object cell exists only where a decoder
2571 // does, so that the sweep collects the executor's refusals
2572 // and not the framer's `StreamNotFramed` on a draft this
2573 // build cannot address.
2574 let mut units = vec![
2575 control_unit(draft, Instant::now()),
2576 stream_end_unit(draft, false),
2577 stream_end_unit(draft, true),
2578 ];
2579 if COMPILED_DRAFTS.contains(&draft) {
2580 units.push(object_unit(&m, Instant::now()));
2581 }
2582 for unit in units {
2583 let mut h = Harness::new();
2584 let out = h.run(&unit, action.clone());
2585 if let Err(refusal) = out.result {
2586 assert_eq!(h.counters.snapshot().actions_refused, 1);
2587 seen.push(refusal);
2588 } else {
2589 assert_eq!(h.counters.snapshot().actions_refused, 0);
2590 }
2591 }
2592 let h = Harness::new();
2593 let unit = datagram_unit(draft, Some(3));
2594 let report = h.datagram_report();
2595 let mut engine = h.datagram_engine();
2596 let out = execute(&unit, action.clone(), &mut engine, &report);
2597 if let Err(refusal) = out.result {
2598 seen.push(refusal);
2599 }
2600 }
2601 }
2602 assert!(!seen.is_empty(), "the sweep must actually refuse things");
2603 for refusal in &seen {
2604 assert!(
2605 !matches!(refusal, Refusal::StreamNotFramed { .. }),
2606 "table-only refusal {refusal:?} escaped into an ActionRefused",
2607 );
2608 }
2609 // All three executor-owned refusals are reachable from the sweep.
2610 assert!(seen.iter().any(|r| matches!(r, Refusal::WrongComposition { .. })));
2611 assert!(seen.iter().any(|r| matches!(r, Refusal::ErrorCodeOutOfRange { .. })));
2612 }
2613
2614 #[test]
2615 fn a_second_close_is_refused_as_session_already_closing() {
2616 for &draft in COMPILED_DRAFTS {
2617 let mut h = Harness::new();
2618 let m = meta(draft);
2619 let first = h.run(
2620 &object_unit(&m, Instant::now()),
2621 Action::CloseSession { code: 3, reason: Bytes::from_static(b"bye") },
2622 );
2623 assert_eq!(first.result, Ok(Effect::SessionClosing { code: 3 }), "draft {draft:?}");
2624 assert_eq!(
2625 first.plan,
2626 Plan::CloseSession { code: 3, reason: Bytes::from_static(b"bye") },
2627 );
2628 let second = h.run(
2629 &object_unit(&m, Instant::now()),
2630 Action::CloseSession { code: 1, reason: Bytes::new() },
2631 );
2632 assert_eq!(second.result, Err(Refusal::SessionAlreadyClosing), "draft {draft:?}");
2633 assert_eq!(
2634 h.closer.close_args(),
2635 (3, Bytes::from_static(b"bye")),
2636 "the first request wins; the second does not overwrite the reason",
2637 );
2638 assert!(h.cancel.is_cancelled(), "execute cancels the session it recorded a close for");
2639 // The refused second close still forwarded its unit unchanged.
2640 assert_eq!(second.plan, Plan::WriteNow(object_bytes()));
2641 }
2642 }
2643
2644 /// A close is reported while the session is still running, and ends it
2645 /// straight afterwards — whether it won the latch or lost it.
2646 ///
2647 /// Cancelling wakes the session's other tasks on other worker threads,
2648 /// and each reports the teardown it does: a `Site::StreamEnd` decision on
2649 /// every stream the close cuts. If the token is already cancelled when
2650 /// the close's own event goes out, those reports can overtake it, which
2651 /// an observer reading events in order would see as a stream end with no
2652 /// cause, followed by the close.
2653 /// This observer reads the token at the moment each close event is
2654 /// emitted, so the ordering is asserted directly and does not depend on
2655 /// thread scheduling.
2656 ///
2657 /// The losing close is recorded behind a control-plane close still
2658 /// inside its drain window: refused, and the session still ends, but
2659 /// only after the refusal has been reported.
2660 #[test]
2661 fn a_close_is_reported_before_the_session_is_cancelled() {
2662 struct CancelledAtEvent {
2663 cancel: CancellationToken,
2664 seen: Mutex<Vec<bool>>,
2665 }
2666 impl ProxyObserver for CancelledAtEvent {
2667 fn on_event(&self, event: &ProxyEvent) {
2668 if matches!(
2669 event,
2670 ProxyEvent::ActionApplied { action: ActionKind::CloseSession, .. }
2671 | ProxyEvent::ActionRefused { action: ActionKind::CloseSession, .. }
2672 ) {
2673 self.seen.lock().unwrap().push(self.cancel.is_cancelled());
2674 }
2675 }
2676 }
2677
2678 for &draft in COMPILED_DRAFTS {
2679 let m = meta(draft);
2680 for behind_control_plane in [false, true] {
2681 let mut h = Harness::new();
2682 let watch =
2683 CancelledAtEvent { cancel: h.cancel.clone(), seen: Mutex::new(Vec::new()) };
2684 if behind_control_plane {
2685 assert!(h.closer.record(7, Bytes::from_static(b"draining")));
2686 }
2687 let report =
2688 Reporter::new(&watch, true, h.counters.as_ref(), SessionId(1), h.side, Some(4));
2689 let mut engine = Engine {
2690 queue: Some(Queue { pending: &mut h.pending, deferred: &mut h.deferred }),
2691 closer: &h.closer,
2692 };
2693 let out = execute(
2694 &object_unit(&m, Instant::now()),
2695 Action::CloseSession { code: 3, reason: Bytes::from_static(b"bye") },
2696 &mut engine,
2697 &report,
2698 );
2699 let what =
2700 format!("[{draft:?}] behind a control-plane close: {behind_control_plane}");
2701 let expected = if behind_control_plane {
2702 Err(Refusal::SessionAlreadyClosing)
2703 } else {
2704 Ok(Effect::SessionClosing { code: 3 })
2705 };
2706 assert_eq!(out.result, expected, "{what}");
2707 assert_eq!(
2708 *watch.seen.lock().unwrap(),
2709 vec![false],
2710 "{what}: exactly one close event, emitted before the session was cancelled",
2711 );
2712 assert!(h.cancel.is_cancelled(), "{what}: and the session is cancelled after it");
2713 }
2714 }
2715 }
2716
2717 #[test]
2718 fn an_out_of_range_code_is_refused_before_anything_is_queued() {
2719 for &draft in COMPILED_DRAFTS {
2720 for action in [
2721 Action::ResetStream { code: 1 << 62 },
2722 Action::Truncate { bytes: 1, code: u64::MAX },
2723 ] {
2724 let mut h = Harness::new();
2725 let m = meta(draft);
2726 let out = h.run(&object_unit(&m, Instant::now()), action.clone());
2727 let Err(Refusal::ErrorCodeOutOfRange { code }) = out.result else {
2728 panic!(
2729 "[{draft:?}] expected ErrorCodeOutOfRange for {action:?}, got {:?}",
2730 out.result,
2731 )
2732 };
2733 assert!(code > MAX_APPLICATION_ERROR_CODE);
2734 assert!(h.pending.is_empty(), "nothing was queued");
2735 }
2736 }
2737 // And at the stream sites, which take the other entry point.
2738 let h = Harness::new();
2739 let out = execute_stream(
2740 StreamSite::Open,
2741 DraftVersion::Draft11,
2742 StreamAction::Reject { code: u64::MAX },
2743 &h.report(),
2744 );
2745 assert_eq!(out.result, Err(Refusal::ErrorCodeOutOfRange { code: u64::MAX }));
2746 assert_eq!(out.plan, Plan::Nothing);
2747 }
2748
2749 // ── the object site ─────────────────────────────────────────────
2750
2751 #[test]
2752 fn replace_payload_splices_at_the_trailing_field() {
2753 for &draft in COMPILED_DRAFTS {
2754 let mut h = Harness::new();
2755 let m = meta(draft);
2756 let out = h.run(
2757 &object_unit(&m, Instant::now()),
2758 Action::ReplacePayload(Bytes::from_static(b"WXYZ")),
2759 );
2760 assert_eq!(out.result, Ok(Effect::Replaced { bytes: 10 }), "draft {draft:?}");
2761 let Plan::WriteNow(bytes) = out.plan else {
2762 panic!("[{draft:?}] expected an inline write")
2763 };
2764 assert_eq!(&bytes[..6], &object_bytes()[..6], "framing is untouched");
2765 assert_eq!(&bytes[6..], b"WXYZ");
2766 }
2767 }
2768
2769 #[test]
2770 fn replace_payload_with_a_different_length_is_refused_with_the_lengths() {
2771 for &draft in COMPILED_DRAFTS {
2772 let mut h = Harness::new();
2773 let m = meta(draft);
2774 let out = h.run(
2775 &object_unit(&m, Instant::now()),
2776 Action::ReplacePayload(Bytes::from_static(b"WXYZ!")),
2777 );
2778 assert_eq!(
2779 out.result,
2780 Err(Refusal::LengthChanged { from: 4, to: 5 }),
2781 "draft {draft:?}",
2782 );
2783 assert_eq!(out.plan, Plan::WriteNow(object_bytes()), "forwarded unchanged");
2784 }
2785 }
2786
2787 /// Draft-11 by name and by `#[cfg]`: the refusal exists only on the drafts
2788 /// with a *subgroup ID is the first object's ID* stream type (11-14 and
2789 /// 16-19 — not 07-10, not 15), so the fixture picks one and the test
2790 /// compiles exactly where that one was compiled. `capability::tests` owns
2791 /// the sweep over the whole set.
2792 #[cfg(feature = "draft11")]
2793 #[test]
2794 fn eliding_the_first_object_of_an_implicit_subgroup_is_refused() {
2795 let mut h = Harness::new();
2796 let mut m = meta(DraftVersion::Draft11);
2797 m.index_in_stream = 0;
2798 m.subgroup_id = None;
2799 let out = h.run(&object_unit(&m, Instant::now()), Action::Drop(DropMode::Elide));
2800 assert_eq!(out.result, Err(Refusal::WouldRedefineSubgroupId));
2801 assert!(!out.note_elided, "a refused elide must not move the cursor");
2802 assert_eq!(h.counters.snapshot().objects_elided, 0);
2803 }
2804
2805 /// The reserved mode is a draft-17-to-19 header field, and the fixture
2806 /// is a draft-19 header — so, like its neighbour, it compiles exactly
2807 /// where its draft did.
2808 #[cfg(feature = "draft19")]
2809 #[test]
2810 fn a_reserved_subgroup_id_mode_is_its_own_refusal() {
2811 let mut h = Harness::new();
2812 let mut m = meta(DraftVersion::Draft19);
2813 m.index_in_stream = 0;
2814 m.subgroup_id = None;
2815 let unit = Unit {
2816 target: Target::Object { meta: &m, subgroup_id_mode: Some(3), raw: object_bytes() },
2817 draft: DraftVersion::Draft19,
2818 arrived_at: Instant::now(),
2819 };
2820 let out = h.run(&unit, Action::Drop(DropMode::Elide));
2821 assert_eq!(out.result, Err(Refusal::ReservedHeaderMode { mode: 3 }));
2822 }
2823
2824 /// A shaper's tail-drop takes the same guards a hook's elide takes, and
2825 /// reports the same refusal — but no `ActionApplied`, because no hook
2826 /// asked for anything.
2827 ///
2828 /// The two halves are the two obligations on `DropTail`:
2829 /// an admitted drop moves the cursor and counts one elide, and a
2830 /// refused one leaves the cursor alone so the caller can admit the unit
2831 /// anyway. The `applied()` assertion is what separates this from
2832 /// `execute(.., Drop(Elide), ..)`: routing a configured drop through
2833 /// the hook path would emit a per-object `ActionApplied` naming a
2834 /// decision nobody made.
2835 #[test]
2836 fn a_shaper_tail_drop_takes_the_elide_guards_and_reports_only_refusals() {
2837 for &draft in COMPILED_DRAFTS {
2838 // Admitted: an ordinary object.
2839 let h = Harness::new();
2840 let m = meta(draft);
2841 assert!(
2842 shape_elide(&object_unit(&m, Instant::now()), &h.report()),
2843 "draft {draft:?}: an ordinary object elides"
2844 );
2845 assert_eq!(h.counters.snapshot().objects_elided, 1, "draft {draft:?}");
2846 assert_eq!(h.counters.snapshot().actions_refused, 0, "draft {draft:?}");
2847 assert!(h.observer.applied().is_empty(), "no hook asked, so nothing was applied");
2848
2849 // Refused: a status object, on every draft.
2850 let h = Harness::new();
2851 let mut m = meta(draft);
2852 m.status = Some(3);
2853 m.payload_len = 0;
2854 assert!(
2855 !shape_elide(&object_unit(&m, Instant::now()), &h.report()),
2856 "draft {draft:?}: a status object may not be elided, so the shaper \
2857 must admit the unit instead"
2858 );
2859 assert_eq!(h.counters.snapshot().objects_elided, 0, "draft {draft:?}");
2860 assert_eq!(
2861 h.observer.refused(),
2862 vec![(Site::Object, ActionKind::DropElide, Refusal::WouldDestroyStatusObject)],
2863 "draft {draft:?}: the refusal is reported, once",
2864 );
2865 assert_eq!(h.counters.snapshot().actions_refused, 1, "draft {draft:?}");
2866 }
2867 }
2868
2869 #[test]
2870 fn eliding_a_status_object_is_refused() {
2871 for &draft in COMPILED_DRAFTS {
2872 let mut h = Harness::new();
2873 let mut m = meta(draft);
2874 m.status = Some(3);
2875 m.payload_len = 0;
2876 let out = h.run(&object_unit(&m, Instant::now()), Action::Drop(DropMode::Elide));
2877 assert_eq!(out.result, Err(Refusal::WouldDestroyStatusObject), "draft {draft:?}");
2878 }
2879 }
2880
2881 #[test]
2882 fn an_admitted_elide_writes_nothing_counts_one_and_owes_a_cursor_move() {
2883 for &draft in COMPILED_DRAFTS {
2884 let mut h = Harness::new();
2885 let m = meta(draft);
2886 let at = Instant::now();
2887 let renumbered = elide_renumbers_successor(&object_unit(&m, at));
2888 let out = h.run(&object_unit(&m, at), Action::Drop(DropMode::Elide));
2889 assert_eq!(out.plan, Plan::Nothing, "draft {draft:?}");
2890 assert_eq!(
2891 out.result,
2892 Ok(Effect::Elided { renumbered_successor: renumbered }),
2893 "draft {draft:?}",
2894 );
2895 assert!(out.note_elided);
2896 assert_eq!(h.counters.snapshot().objects_elided, 1);
2897 }
2898 }
2899
2900 /// A deferral is counted where it is decided, and a forwarded unit is
2901 /// not counted at all.
2902 ///
2903 /// The figure sits on the instrument counters rather than on the
2904 /// shaping statistics, where every figure is gated on a configured
2905 /// profile — so a deferral counted there would read zero on the
2906 /// sessions a hook alone impairs, which need no profile whatever.
2907 #[test]
2908 fn a_deferred_unit_is_counted_and_a_forwarded_one_is_not() {
2909 for &draft in COMPILED_DRAFTS {
2910 let m = meta(draft);
2911 let mut h = Harness::new();
2912 let out = h.run(
2913 &object_unit(&m, Instant::now()),
2914 Action::Delay { by: Duration::from_millis(5), then: Box::new(Action::Pass) },
2915 );
2916 assert!(matches!(out.result, Ok(Effect::Queued { .. })), "draft {draft:?}");
2917 let counted = h.counters.snapshot();
2918 assert_eq!(
2919 counted.units_delayed, 1,
2920 "draft {draft:?}: the engine took the unit off the wire and queued it \
2921 for a later release, and the figure for what it deferred did not move",
2922 );
2923 assert_eq!(counted.actions_refused, 0, "draft {draft:?}");
2924 assert_eq!(
2925 counted.objects_truncated, 0,
2926 "draft {draft:?}: a deferral is not a truncation, and one figure \
2927 answering for both would be indistinguishable from either",
2928 );
2929
2930 let mut h = Harness::new();
2931 h.run(&object_unit(&m, Instant::now()), Action::Pass);
2932 assert_eq!(
2933 h.counters.snapshot().units_delayed,
2934 0,
2935 "draft {draft:?}: a unit that went straight out was never deferred",
2936 );
2937 }
2938 }
2939
2940 /// The figure is `units_delayed` and not `objects_delayed`, and a
2941 /// deferred **control frame** is the whole reason.
2942 ///
2943 /// `classify_control` honours `Delay` on every compiled draft, so a
2944 /// SUBSCRIBE held back is a real deferral with no object anywhere in it.
2945 /// A counter named for objects would have had to either miss this or
2946 /// count it under a name that does not describe it. Its neighbour keeps
2947 /// the object name honestly: a truncation is refused on a control
2948 /// stream and can land nowhere but an object, which the gate below
2949 /// checks rather than assumes.
2950 #[test]
2951 fn a_deferred_control_frame_moves_the_same_figure() {
2952 for &draft in COMPILED_DRAFTS {
2953 let mut h = Harness::new();
2954 let out = h.run(
2955 &control_unit(draft, Instant::now()),
2956 Action::Delay { by: Duration::from_millis(5), then: Box::new(Action::Pass) },
2957 );
2958 assert!(matches!(out.result, Ok(Effect::Queued { .. })), "draft {draft:?}");
2959 assert_eq!(
2960 h.counters.snapshot().units_delayed,
2961 1,
2962 "draft {draft:?}: a control frame is a unit, and it was deferred",
2963 );
2964 }
2965 }
2966
2967 /// A truncation is counted when it is applied, and never when it is
2968 /// refused.
2969 ///
2970 /// Two refusals, because they are refused by different code and a
2971 /// counter placed at the attempt rather than the application would pass
2972 /// one of them and fail the other. The error code is checked inside the
2973 /// `Truncate` arm itself; the site is checked by `classify`, before the
2974 /// arm is reached at all.
2975 #[test]
2976 fn a_truncation_counts_when_it_is_applied_and_never_when_it_is_refused() {
2977 for &draft in COMPILED_DRAFTS {
2978 let m = meta(draft);
2979 let mut h = Harness::new();
2980 let out =
2981 h.run(&object_unit(&m, Instant::now()), Action::Truncate { bytes: 3, code: 0x2 });
2982 assert!(matches!(out.result, Ok(Effect::Truncated { .. })), "draft {draft:?}");
2983 assert_eq!(
2984 h.counters.snapshot().objects_truncated,
2985 1,
2986 "draft {draft:?}: the object went out cut short to its first three \
2987 bytes and nothing counted it",
2988 );
2989
2990 let mut h = Harness::new();
2991 let out = h.run(
2992 &object_unit(&m, Instant::now()),
2993 Action::Truncate { bytes: 3, code: MAX_APPLICATION_ERROR_CODE + 1 },
2994 );
2995 assert!(out.result.is_err(), "draft {draft:?}");
2996 let counted = h.counters.snapshot();
2997 assert_eq!(
2998 counted.objects_truncated, 0,
2999 "draft {draft:?}: an out-of-range code refuses the truncation, and \
3000 a refused action cut nothing short",
3001 );
3002 assert_eq!(counted.actions_refused, 1, "draft {draft:?}");
3003
3004 let mut h = Harness::new();
3005 let out = h.run(
3006 &control_unit(draft, Instant::now()),
3007 Action::Truncate { bytes: 3, code: 0x2 },
3008 );
3009 assert_eq!(out.result, Err(Refusal::ControlStreamResetIllegal), "draft {draft:?}");
3010 assert_eq!(
3011 h.counters.snapshot().objects_truncated,
3012 0,
3013 "draft {draft:?}: the object name holds because the control site \
3014 refuses the action outright",
3015 );
3016 }
3017 }
3018
3019 /// A session nobody is watching still counts what it did.
3020 ///
3021 /// `Reporter` caches `observer.wants_events()` and gates **events** on
3022 /// it; the counters are outside that gate, on the same terms
3023 /// `Reporter::refused` states for its own. The claim is worth a gate
3024 /// rather than a comment because the failure is silent in the direction
3025 /// that matters: a counter bumped inside the gate agrees with its event
3026 /// in every test that has an observer attached, which is all of them,
3027 /// and reads zero only in production.
3028 #[test]
3029 fn a_session_with_nobody_watching_still_counts_what_it_applied() {
3030 for &draft in COMPILED_DRAFTS {
3031 let m = meta(draft);
3032 let mut h = Harness::new();
3033 h.run_unwatched(
3034 &object_unit(&m, Instant::now()),
3035 Action::Delay { by: Duration::from_millis(5), then: Box::new(Action::Pass) },
3036 );
3037 let mut h2 = Harness::new();
3038 h2.run_unwatched(
3039 &object_unit(&m, Instant::now()),
3040 Action::Truncate { bytes: 3, code: 0x2 },
3041 );
3042
3043 assert!(
3044 h.observer.events().is_empty() && h2.observer.events().is_empty(),
3045 "draft {draft:?}: nothing was emitted, which is what makes the \
3046 counters below a measurement rather than a restatement",
3047 );
3048 assert_eq!(
3049 h.counters.snapshot().units_delayed,
3050 1,
3051 "draft {draft:?}: a deferral on a session nobody attached to is still \
3052 a deferral, and this figure is the only thing that says so",
3053 );
3054 assert_eq!(
3055 h2.counters.snapshot().objects_truncated,
3056 1,
3057 "draft {draft:?}: and so is a truncation",
3058 );
3059 }
3060 }
3061
3062 /// Draft-14 by name and by `#[cfg]`: `renumbered_successor: true` is
3063 /// asserted as a literal here rather than computed, so the fixture has
3064 /// to be a draft that delta-encodes Object IDs, and 14 is the first of
3065 /// them.
3066 #[cfg(feature = "draft14")]
3067 #[test]
3068 fn a_deferred_elide_still_moves_the_cursor_at_the_decision() {
3069 let mut h = Harness::new();
3070 let m = meta(DraftVersion::Draft14);
3071 let out = h.run(
3072 &object_unit(&m, Instant::now()),
3073 Action::Drop(DropMode::Elide).delayed(Duration::from_millis(20)),
3074 );
3075 assert!(
3076 out.note_elided,
3077 "the framer's cursor is positional; note_elided cannot wait for the release",
3078 );
3079 assert_eq!(
3080 h.deferred.pop(),
3081 Some(Deferred {
3082 action: ActionKind::DropElide,
3083 effect: Effect::Elided { renumbered_successor: true },
3084 }),
3085 );
3086 }
3087
3088 /// The one predicate this module duplicates from `framer.rs`
3089 /// (`ObjectFramer::elide_owes_a_fixup`, private there).
3090 ///
3091 /// The two stream kinds are the two halves of the claim and the boundary
3092 /// moves between them — draft-14 for a subgroup stream, draft-15 for a
3093 /// fetch one. A single number restated for both would be a table that
3094 /// happened to agree with the code on twelve of the twenty-six rows.
3095 ///
3096 /// Asserted against an explicitly restated table rather than against the
3097 /// framer itself, and that is a limitation worth stating: `note_elided`
3098 /// `debug_assert`s that the object it is handed is the one the framer
3099 /// most recently emitted, so a standalone probe cannot ask the framer
3100 /// this question without driving drafts of real wire bytes
3101 /// through it. The compensating cover is
3102 /// `tests/actions_objects.rs`, which asserts the *bytes* of an elided
3103 /// run against an independent encoder — a wrong answer here shows up
3104 /// there as a wrong `renumbered_successor` on a stream whose bytes
3105 /// disagree.
3106 ///
3107 /// Swept over [`ALL_DRAFTS`] and not [`COMPILED_DRAFTS`] on purpose:
3108 /// `elide_renumbers_successor` reads the [`DraftVersion`] value and
3109 /// nothing else, so every row of the table is answerable in every
3110 /// build, and restating every draft is the whole point of the test.
3111 #[test]
3112 fn elide_renumbering_names_the_drafts_that_owe_a_fixup() {
3113 for draft in ALL_DRAFTS {
3114 for stream_kind in [DataStreamType::Subgroup, DataStreamType::Fetch] {
3115 let mut m = meta(draft);
3116 m.stream_kind = stream_kind;
3117 let unit = object_unit(&m, Instant::now());
3118 let expected = match stream_kind {
3119 DataStreamType::Subgroup => draft.number() >= 14,
3120 DataStreamType::Fetch => draft.number() >= 15,
3121 };
3122 assert_eq!(
3123 elide_renumbers_successor(&unit),
3124 expected,
3125 "draft {draft:?} / {stream_kind:?}",
3126 );
3127 }
3128 }
3129 // A non-object site never renumbers anything.
3130 assert!(!elide_renumbers_successor(&control_unit(DraftVersion::Draft19, Instant::now())));
3131 }
3132
3133 #[test]
3134 fn truncate_queues_a_prefix_then_a_reset_and_reports_the_prefix_length() {
3135 for &draft in COMPILED_DRAFTS {
3136 let mut h = Harness::new();
3137 let m = meta(draft);
3138 let out =
3139 h.run(&object_unit(&m, Instant::now()), Action::Truncate { bytes: 3, code: 0x2 });
3140 assert_eq!(out.plan, Plan::Terminal, "draft {draft:?}");
3141 // `code_defined` is the reset vocabulary's business, not this
3142 // test's; `drafts_07_to_10_report_the_reset_code_as_undefined`
3143 // restates that table against the draft numbers themselves.
3144 assert_eq!(
3145 out.result,
3146 Ok(Effect::Truncated {
3147 forwarded: 3,
3148 code: 0x2,
3149 code_defined: stream_reset_code_defined(draft),
3150 }),
3151 "draft {draft:?}",
3152 );
3153 assert_eq!(h.pending.len(), 1);
3154 assert!(h.pending.head_release().is_some());
3155 }
3156 }
3157
3158 #[test]
3159 fn truncate_past_the_end_of_the_unit_forwards_the_whole_unit() {
3160 for &draft in COMPILED_DRAFTS {
3161 let mut h = Harness::new();
3162 let m = meta(draft);
3163 let out =
3164 h.run(&object_unit(&m, Instant::now()), Action::Truncate { bytes: 9_999, code: 0 });
3165 assert_eq!(
3166 out.result,
3167 Ok(Effect::Truncated {
3168 forwarded: object_bytes().len(),
3169 code: 0,
3170 code_defined: stream_reset_code_defined(draft),
3171 }),
3172 "draft {draft:?}",
3173 );
3174 }
3175 }
3176
3177 #[test]
3178 fn drafts_07_to_10_report_the_reset_code_as_undefined() {
3179 for &draft in COMPILED_DRAFTS {
3180 // Restated here rather than read from `stream_reset_code_defined`,
3181 // which is the thing under test, and exhaustive for the reason
3182 // `capability.rs`'s `a_first_object_carrier_exists` gives: a
3183 // new draft must not join either side of the partition
3184 // without an answer being written down twice.
3185 let expected = match draft {
3186 DraftVersion::Draft07
3187 | DraftVersion::Draft08
3188 | DraftVersion::Draft09
3189 | DraftVersion::Draft10 => false,
3190 DraftVersion::Draft11
3191 | DraftVersion::Draft12
3192 | DraftVersion::Draft13
3193 | DraftVersion::Draft14
3194 | DraftVersion::Draft15
3195 | DraftVersion::Draft16
3196 | DraftVersion::Draft17
3197 | DraftVersion::Draft18
3198 | DraftVersion::Draft19
3199 | DraftVersion::Draft20
3200 | DraftVersion::Draft21
3201 | DraftVersion::Draft22
3202 | DraftVersion::Draft23 => true,
3203 };
3204 let mut h = Harness::new();
3205 let m = meta(draft);
3206 let out = h.run(&object_unit(&m, Instant::now()), Action::ResetStream { code: 5 });
3207 assert_eq!(
3208 out.result,
3209 Ok(Effect::StreamReset { code: 5, code_defined: expected }),
3210 "draft {draft:?}",
3211 );
3212 }
3213 }
3214
3215 // ── the control site ────────────────────────────────────────────
3216
3217 /// The draft the single-row control fixtures use: the first this build
3218 /// compiled.
3219 ///
3220 /// `None` only in a build with no draft at all, where there is no
3221 /// control decoder and the rows below are not claims about this module.
3222 /// A hardcoded draft-11 was what a `--features draft07` build read as
3223 /// an executor failure when it was really the control site reporting
3224 /// that it has no decoder for draft 11.
3225 fn a_compiled_draft() -> Option<DraftVersion> {
3226 COMPILED_DRAFTS.first().copied()
3227 }
3228
3229 #[test]
3230 fn the_control_site_replaces_the_whole_frame_and_drops_it_whole() {
3231 let Some(draft) = a_compiled_draft() else { return };
3232 let mut h = Harness::new();
3233 let unit = control_unit(draft, Instant::now());
3234 let out = h.run(&unit, Action::Replace(Bytes::from_static(b"other")));
3235 assert_eq!(out.plan, Plan::WriteNow(Bytes::from_static(b"other")));
3236 assert_eq!(out.result, Ok(Effect::Replaced { bytes: 5 }));
3237
3238 let mut h = Harness::new();
3239 let out = h.run(&control_unit(draft, Instant::now()), Action::Drop(DropMode::Elide));
3240 assert_eq!(out.result, Ok(Effect::Dropped), "no object slot to renumber");
3241 assert!(!out.note_elided);
3242 assert_eq!(h.counters.snapshot().objects_elided, 0);
3243 }
3244
3245 /// Sweeps [`COMPILED_DRAFTS`] rather than [`ALL_DRAFTS`]: a refusal is
3246 /// what the engine hands a hook, and on a draft with no decoder no hook
3247 /// is reached, so `classify` answers `Unreachable` there instead. The
3248 /// claim being made is about the executor's rule, not about the
3249 /// build's.
3250 #[test]
3251 fn resetting_a_control_stream_is_refused_on_every_draft() {
3252 for &draft in COMPILED_DRAFTS {
3253 for action in [Action::ResetStream { code: 1 }, Action::Truncate { bytes: 1, code: 1 }]
3254 {
3255 let mut h = Harness::new();
3256 let out = h.run(&control_unit(draft, Instant::now()), action.clone());
3257 assert_eq!(
3258 out.result,
3259 Err(Refusal::ControlStreamResetIllegal),
3260 "draft {draft:?} / {action:?}",
3261 );
3262 assert!(h.pending.is_empty());
3263 }
3264 }
3265 }
3266
3267 #[test]
3268 fn drafts_17_on_execute_a_control_action_like_every_other_draft() {
3269 // These carry the control plane on a pair of unidirectional
3270 // streams and requests on bidirectional ones. Both shapes reach this
3271 // site, so the column is `Yes` here exactly as it is on 07-16 and a
3272 // draft-conditional refusal would be wrong.
3273 //
3274 // Filtered to the compiled set, like every other control row: a
3275 // build without one of them has no decoder for it and no hook
3276 // is reached, which is a claim about the build rather than about
3277 // the control plane's shape.
3278 for draft in [
3279 DraftVersion::Draft17,
3280 DraftVersion::Draft18,
3281 DraftVersion::Draft19,
3282 DraftVersion::Draft20,
3283 DraftVersion::Draft21,
3284 DraftVersion::Draft22,
3285 DraftVersion::Draft23,
3286 ]
3287 .into_iter()
3288 .filter(|d| COMPILED_DRAFTS.contains(d))
3289 {
3290 let mut h = Harness::new();
3291 let out = h.run(
3292 &control_unit(draft, Instant::now()),
3293 Action::Replace(Bytes::from_static(b"z")),
3294 );
3295 assert_eq!(out.result, Ok(Effect::Replaced { bytes: 1 }), "draft {draft:?}");
3296 }
3297 }
3298
3299 // ── the datagram site ───────────────────────────────────────────
3300
3301 #[test]
3302 fn a_datagram_replace_is_admitted_and_its_failure_is_the_callers_to_report() {
3303 let h = Harness::new();
3304 let unit = datagram_unit(DraftVersion::Draft11, Some(3));
3305 let report = h.datagram_report();
3306 let mut engine = h.datagram_engine();
3307 let out =
3308 execute(&unit, Action::Replace(Bytes::from_static(b"bigger")), &mut engine, &report);
3309 assert_eq!(out.result, Ok(Effect::Replaced { bytes: 6 }));
3310 assert_eq!(out.plan, Plan::WriteNow(Bytes::from_static(b"bigger")));
3311
3312 // The transport then rejects it: exactly one ActionFailed, and no
3313 // ActionApplied is retracted.
3314 report.failed(Site::Datagram, ActionKind::Replace, "too large".to_owned());
3315 let failed: Vec<_> = h
3316 .observer
3317 .events()
3318 .into_iter()
3319 .filter(|e| matches!(e, ProxyEvent::ActionFailed { .. }))
3320 .collect();
3321 assert_eq!(failed.len(), 1);
3322 assert_eq!(h.counters.snapshot().actions_refused, 0);
3323 }
3324
3325 #[test]
3326 fn a_datagram_payload_splice_needs_a_real_boundary() {
3327 // Delimited: spliced after the header.
3328 let h = Harness::new();
3329 let unit = datagram_unit(DraftVersion::Draft11, Some(3));
3330 let report = h.datagram_report();
3331 let mut engine = h.datagram_engine();
3332 let out = execute(
3333 &unit,
3334 Action::ReplacePayload(Bytes::from_static(b"NEWP")),
3335 &mut engine,
3336 &report,
3337 );
3338 let Plan::WriteNow(bytes) = out.plan else { panic!("expected a datagram write") };
3339 assert_eq!(&bytes[..3], &[0x01, 0x02, 0x03]);
3340 assert_eq!(&bytes[3..], b"NEWP");
3341
3342 // The three cases where there is no boundary.
3343 let cases = [
3344 (DraftVersion::Draft14, Some(3), false, "draft-14 header decode consumes the payload"),
3345 (DraftVersion::Draft11, None, false, "datagram header did not decode"),
3346 (DraftVersion::Draft11, Some(3), true, "status datagram has no payload"),
3347 ];
3348 for (draft, header_len, is_status, detail) in cases {
3349 let h = Harness::new();
3350 let unit = Unit {
3351 target: Target::Datagram {
3352 raw: Bytes::from_static(&[0x01, 0x02, 0x03, b'p']),
3353 header_len,
3354 is_status,
3355 },
3356 draft,
3357 arrived_at: Instant::now(),
3358 };
3359 let report = h.datagram_report();
3360 let mut engine = h.datagram_engine();
3361 let out = execute(
3362 &unit,
3363 Action::ReplacePayload(Bytes::from_static(b"N")),
3364 &mut engine,
3365 &report,
3366 );
3367 assert_eq!(
3368 out.result,
3369 Err(Refusal::PayloadNotDelimited { detail }),
3370 "draft {draft:?} / header_len {header_len:?} / status {is_status}",
3371 );
3372 assert_eq!(out.plan, Plan::WriteNow(Bytes::from_static(&[0x01, 0x02, 0x03, b'p'])),);
3373 }
3374 }
3375
3376 #[test]
3377 fn timing_and_terminals_are_refused_at_the_datagram_site() {
3378 for action in [
3379 Action::Pass.delayed(Duration::from_millis(1)),
3380 Action::Pass.held(Gate::new()),
3381 Action::Truncate { bytes: 1, code: 1 },
3382 Action::ResetStream { code: 1 },
3383 ] {
3384 let h = Harness::new();
3385 let unit = datagram_unit(DraftVersion::Draft11, Some(3));
3386 let report = h.datagram_report();
3387 let mut engine = h.datagram_engine();
3388 let out = execute(&unit, action.clone(), &mut engine, &report);
3389 assert!(
3390 matches!(out.result, Err(Refusal::WrongSite { site: Site::Datagram, .. })),
3391 "{action:?} -> {:?}",
3392 out.result,
3393 );
3394 }
3395 }
3396
3397 // ── the stream-end site ─────────────────────────────────────────
3398
3399 #[test]
3400 fn close_session_is_honoured_at_both_stream_end_columns() {
3401 for is_control_stream in [false, true] {
3402 let mut h = Harness::new();
3403 let out = h.run(
3404 &stream_end_unit(DraftVersion::Draft11, is_control_stream),
3405 Action::CloseSession { code: 3, reason: Bytes::from_static(b"x") },
3406 );
3407 assert_eq!(
3408 out.result,
3409 Ok(Effect::SessionClosing { code: 3 }),
3410 "control={is_control_stream}",
3411 );
3412 }
3413 }
3414
3415 #[test]
3416 fn reset_at_stream_end_is_a_data_stream_capability_only() {
3417 let mut h = Harness::new();
3418 let out =
3419 h.run(&stream_end_unit(DraftVersion::Draft11, false), Action::ResetStream { code: 4 });
3420 assert_eq!(out.plan, Plan::Terminal);
3421 assert_eq!(out.result, Ok(Effect::StreamReset { code: 4, code_defined: true }),);
3422
3423 let mut h = Harness::new();
3424 let out =
3425 h.run(&stream_end_unit(DraftVersion::Draft11, true), Action::ResetStream { code: 4 });
3426 assert_eq!(out.result, Err(Refusal::ControlStreamResetIllegal));
3427 assert_eq!(out.plan, Plan::Nothing, "a stream end carries no unit to forward");
3428 }
3429
3430 #[test]
3431 fn everything_else_at_stream_end_is_wrong_site_except_the_two_reset_shapes() {
3432 // Every unsupported action at the stream-end site is refused as
3433 // `WrongSite`, on both the control and the data stream — except
3434 // Truncate and ResetStream on a control stream, which have a
3435 // refusal of their own.
3436 for is_control_stream in [false, true] {
3437 for action in [
3438 Action::Replace(Bytes::from_static(b"x")),
3439 Action::ReplacePayload(Bytes::from_static(b"x")),
3440 Action::Pass.delayed(Duration::from_millis(1)),
3441 Action::Pass.held(Gate::new()),
3442 Action::Drop(DropMode::Elide),
3443 ] {
3444 let mut h = Harness::new();
3445 let out = h.run(
3446 &stream_end_unit(DraftVersion::Draft11, is_control_stream),
3447 action.clone(),
3448 );
3449 assert!(
3450 matches!(out.result, Err(Refusal::WrongSite { site: Site::StreamEnd, .. })),
3451 "control={is_control_stream} {action:?} -> {:?}",
3452 out.result,
3453 );
3454 }
3455 let mut h = Harness::new();
3456 let out = h.run(
3457 &stream_end_unit(DraftVersion::Draft11, is_control_stream),
3458 Action::Truncate { bytes: 1, code: 1 },
3459 );
3460 let expected = if is_control_stream {
3461 Refusal::ControlStreamResetIllegal
3462 } else {
3463 Refusal::WrongSite { site: Site::StreamEnd, action: ActionKind::Truncate }
3464 };
3465 assert_eq!(out.result, Err(expected));
3466 }
3467 }
3468
3469 #[test]
3470 fn pass_at_stream_end_changes_nothing() {
3471 let mut h = Harness::new();
3472 let out = h.run(&stream_end_unit(DraftVersion::Draft11, true), Action::Pass);
3473 assert_eq!(out.plan, Plan::Nothing);
3474 assert_eq!(out.result, Ok(Effect::ForwardedVerbatim));
3475 assert_eq!(h.observer.applied().len(), 1);
3476 }
3477
3478 // ── the stream-decision sites ───────────────────────────────────
3479
3480 #[test]
3481 fn stream_open_and_reject_each_report_once() {
3482 for site in [StreamSite::Open, StreamSite::Header] {
3483 let h = Harness::new();
3484 let out = execute_stream(site, DraftVersion::Draft11, StreamAction::Open, &h.report());
3485 assert_eq!(out.plan, Plan::Nothing);
3486 assert_eq!(out.result, Ok(Effect::ForwardedVerbatim));
3487 assert_eq!(h.observer.applied().len(), 1);
3488 assert_eq!(h.observer.applied()[0].0, site.site());
3489
3490 let h = Harness::new();
3491 let out = execute_stream(
3492 site,
3493 DraftVersion::Draft11,
3494 StreamAction::Reject { code: 9 },
3495 &h.report(),
3496 );
3497 assert_eq!(out.plan, Plan::RejectStream { code: 9 });
3498 assert_eq!(out.result, Ok(Effect::StreamRejected { code: 9 }));
3499 assert_eq!(h.observer.applied().len(), 1);
3500 }
3501 }
3502
3503 // ── invariants the rest of the file leans on ────────────────────
3504
3505 #[test]
3506 fn no_fact_precondition_survives_execution() {
3507 // `admit_conditional`'s `debug_assert` is only a claim if this
3508 // passes: sweep every site with fully-populated targets and assert
3509 // `classify` never asks for a fact `Target` did not supply.
3510 let mut saw_conditional = 0usize;
3511 for draft in ALL_DRAFTS {
3512 for stream_kind in [DataStreamType::Subgroup, DataStreamType::Fetch] {
3513 for index_in_stream in [0u64, 3] {
3514 for subgroup_id in [None, Some(0u64)] {
3515 for status in [None, Some(3u64)] {
3516 for mode in [None, Some(0u8), Some(1), Some(3)] {
3517 let mut m = meta(draft);
3518 m.stream_kind = stream_kind;
3519 m.index_in_stream = index_in_stream;
3520 m.subgroup_id = subgroup_id;
3521 m.status = status;
3522 let unit = Unit {
3523 target: Target::Object {
3524 meta: &m,
3525 subgroup_id_mode: mode,
3526 raw: object_bytes(),
3527 },
3528 draft,
3529 arrived_at: Instant::now(),
3530 };
3531 for kind in [
3532 ActionKind::Pass,
3533 ActionKind::ReplacePayload,
3534 ActionKind::DropElide,
3535 ActionKind::Truncate,
3536 ActionKind::ResetStream,
3537 ActionKind::CloseSession,
3538 ] {
3539 let replacement_len =
3540 (kind == ActionKind::ReplacePayload).then_some(4);
3541 let cx = unit.target.cap_ctx(draft, replacement_len);
3542 if let Support::Conditional(p) =
3543 classify(Site::Object, kind, &cx)
3544 {
3545 saw_conditional += 1;
3546 assert!(
3547 matches!(p, Precondition::WithinMaxDatagramSize),
3548 "unsupplied fact {p:?} at Object/{kind:?} \
3549 draft {draft:?}",
3550 );
3551 }
3552 }
3553 }
3554 }
3555 }
3556 }
3557 }
3558
3559 for is_status in [false, true] {
3560 for header_len in [None, Some(3usize)] {
3561 let unit = Unit {
3562 target: Target::Datagram {
3563 raw: Bytes::from_static(&[1, 2, 3, 4]),
3564 header_len,
3565 is_status,
3566 },
3567 draft,
3568 arrived_at: Instant::now(),
3569 };
3570 for kind in [
3571 ActionKind::Pass,
3572 ActionKind::Replace,
3573 ActionKind::ReplacePayload,
3574 ActionKind::DropElide,
3575 ActionKind::CloseSession,
3576 ] {
3577 let cx = unit.target.cap_ctx(draft, Some(1));
3578 if let Support::Conditional(p) = classify(Site::Datagram, kind, &cx) {
3579 saw_conditional += 1;
3580 assert!(
3581 matches!(p, Precondition::WithinMaxDatagramSize),
3582 "unsupplied fact {p:?} at Datagram/{kind:?} draft {draft:?}",
3583 );
3584 }
3585 }
3586 }
3587 }
3588 }
3589 assert!(
3590 saw_conditional > 0,
3591 "the sweep must reach the environmental preconditions, or it proves nothing",
3592 );
3593 }
3594
3595 #[test]
3596 fn the_ledger_stays_the_same_length_as_the_queue() {
3597 for &draft in COMPILED_DRAFTS {
3598 let mut h = Harness::new();
3599 let m = meta(draft);
3600 let at = Instant::now();
3601 let actions = [
3602 Action::Pass.delayed(Duration::from_millis(30)),
3603 Action::Pass,
3604 Action::Drop(DropMode::Elide),
3605 Action::ReplacePayload(Bytes::from_static(b"abcd")),
3606 Action::Replace(Bytes::from_static(b"refused")),
3607 Action::ResetStream { code: 1 },
3608 ];
3609 for action in actions {
3610 h.run(&object_unit(&m, at), action);
3611 assert_eq!(
3612 h.deferred.len(),
3613 h.pending.len(),
3614 "[{draft:?}] one ledger entry per pushed unit, always",
3615 );
3616 }
3617 assert!(h.pending.len() >= 5, "draft {draft:?}");
3618 }
3619 }
3620
3621 #[test]
3622 fn backpressure_is_reported_once_per_stream() {
3623 for &draft in COMPILED_DRAFTS {
3624 let mut h = Harness::with_config(EgressConfig {
3625 max_pending_bytes: 16,
3626 max_hold: Duration::from_secs(30),
3627 ..EgressConfig::default()
3628 });
3629 let m = meta(draft);
3630 let at = Instant::now();
3631 h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_secs(5)));
3632 let mut transitions = 0;
3633 for _ in 0..6 {
3634 let out = h.run(&object_unit(&m, at), Action::Pass);
3635 if out.entered_backpressure {
3636 transitions += 1;
3637 }
3638 }
3639 assert_eq!(transitions, 1, "[{draft:?}] the transition is reported once");
3640 assert_eq!(
3641 h.observer
3642 .impairments()
3643 .iter()
3644 .filter(|k| matches!(k, ImpairmentKind::EgressQueueFull { .. }))
3645 .count(),
3646 1,
3647 );
3648 }
3649 }
3650
3651 #[test]
3652 fn a_delay_beyond_max_hold_is_clamped_and_reported_once() {
3653 for &draft in COMPILED_DRAFTS {
3654 let mut h = Harness::with_config(EgressConfig {
3655 max_pending_bytes: 1 << 20,
3656 max_hold: Duration::from_millis(50),
3657 ..EgressConfig::default()
3658 });
3659 let m = meta(draft);
3660 let at = Instant::now();
3661 let out = h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_secs(9)));
3662 let clamped = out.clamped.expect("a clamp happened");
3663 assert!(clamped.was_clamped(), "draft {draft:?}");
3664 assert_eq!(clamped.requested, Duration::from_secs(9));
3665 assert_eq!(clamped.applied, Duration::from_millis(50));
3666 assert_eq!(
3667 h.observer.impairments(),
3668 vec![ImpairmentKind::HoldClamped {
3669 requested: Some(Duration::from_secs(9)),
3670 applied: Duration::from_millis(50),
3671 }],
3672 );
3673
3674 // An unclamped delay reports nothing.
3675 let mut h = Harness::new();
3676 let out = h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_millis(5)));
3677 assert_eq!(out.clamped.map(|d| d.was_clamped()), Some(false), "draft {draft:?}");
3678 assert!(h.observer.impairments().is_empty());
3679 }
3680 }
3681
3682 #[test]
3683 fn the_ledger_forgets_what_a_failed_drain_could_not_write() {
3684 for &draft in COMPILED_DRAFTS {
3685 let mut h = Harness::new();
3686 let m = meta(draft);
3687 let at = Instant::now();
3688 h.run(
3689 &object_unit(&m, at),
3690 Action::ReplacePayload(Bytes::from_static(b"abcd"))
3691 .delayed(Duration::from_millis(10)),
3692 );
3693 assert_eq!(h.deferred.len(), 1, "draft {draft:?}");
3694 h.deferred.clear();
3695 assert!(h.deferred.is_empty(), "no Replaced is reported for bytes never written");
3696 assert!(h.deferred.take_all().is_empty());
3697 }
3698 }
3699
3700 #[test]
3701 fn take_all_yields_only_the_entries_that_owe_an_event() {
3702 for &draft in COMPILED_DRAFTS {
3703 let mut h = Harness::new();
3704 let m = meta(draft);
3705 let at = Instant::now();
3706 h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_millis(30)));
3707 h.run(&object_unit(&m, at), Action::Pass);
3708 h.run(
3709 &object_unit(&m, at),
3710 Action::ReplacePayload(Bytes::from_static(b"wxyz"))
3711 .delayed(Duration::from_millis(40)),
3712 );
3713 assert_eq!(h.deferred.len(), 3, "draft {draft:?}");
3714 let owed = h.deferred.take_all();
3715 assert_eq!(owed.len(), 2, "the ordering-only unit owes nothing");
3716 assert_eq!(owed[0].action, ActionKind::Pass);
3717 assert_eq!(owed[1].effect, Effect::Replaced { bytes: 10 });
3718 assert!(h.deferred.is_empty());
3719 }
3720 }
3721
3722 #[test]
3723 fn kind_of_agrees_with_the_published_attempt_mapping() {
3724 assert_eq!(kind_of(&Action::Pass), ActionKind::Pass);
3725 assert_eq!(kind_of(&Action::Replace(Bytes::new())), ActionKind::Replace);
3726 assert_eq!(kind_of(&Action::ReplacePayload(Bytes::new())), ActionKind::ReplacePayload,);
3727 assert_eq!(kind_of(&Action::Pass.delayed(Duration::ZERO)), ActionKind::Delay);
3728 assert_eq!(kind_of(&Action::Pass.held(Gate::new())), ActionKind::Hold);
3729 assert_eq!(kind_of(&Action::Drop(DropMode::Elide)), ActionKind::DropElide);
3730 assert_eq!(kind_of(&Action::Truncate { bytes: 0, code: 0 }), ActionKind::Truncate,);
3731 assert_eq!(kind_of(&Action::ResetStream { code: 0 }), ActionKind::ResetStream);
3732 assert_eq!(
3733 kind_of(&Action::CloseSession { code: 0, reason: Bytes::new() }),
3734 ActionKind::CloseSession,
3735 );
3736 }
3737
3738 // ── The impairment surface: ordering, and the leg ───────────────
3739 //
3740 // The three tests below are the gate for a single rule — an impairment
3741 // is emitted *after* what it reports, never before — and for the field
3742 // that says which of the proxy's two connections it is about. Both are
3743 // driven through `execute` and `Reporter`, the same two calls every
3744 // forwarding pipe makes, rather than by handing a `ProxyEvent` to an
3745 // observer directly: what is being checked is where the emission sits
3746 // relative to the work, which a hand-built event cannot show.
3747
3748 /// An action that is refused emits **no impairment at all**, even when
3749 /// the refused action's own arithmetic would have produced one.
3750 ///
3751 /// This is the rule in its sharpest form. `Delay { by: 9s }` against a
3752 /// 50 ms `max_hold` is a clamp by any reading of the numbers, and the
3753 /// clamp arithmetic is cheap enough that computing it early would look
3754 /// harmless. But the inner `ReplacePayload` is refused — seven bytes
3755 /// where the object's payload is four — so nothing is queued, nothing is
3756 /// held, and no wait is shortened. An observer told otherwise would have
3757 /// recorded a hold that was never applied to a unit that was forwarded
3758 /// unchanged, and there is no later event that takes an impairment back.
3759 ///
3760 /// The `Pass` case beside it is the control: the identical delay, with
3761 /// an inner action that is admitted, does clamp and does report. Without
3762 /// it the assertion would also pass against an engine that had stopped
3763 /// reporting clamps altogether.
3764 #[test]
3765 fn a_refused_action_reports_its_refusal_and_no_impairment() {
3766 for &draft in COMPILED_DRAFTS {
3767 let clamping = EgressConfig {
3768 max_pending_bytes: 1 << 20,
3769 max_hold: Duration::from_millis(50),
3770 ..EgressConfig::default()
3771 };
3772 let m = meta(draft);
3773 let at = Instant::now();
3774
3775 let mut h = Harness::with_config(clamping);
3776 let out = h.run(
3777 &object_unit(&m, at),
3778 // Seven bytes into a four-byte payload: `ReplacePayload` is
3779 // length-preserving at the object site, so the inner action
3780 // is refused before anything is queued.
3781 Action::ReplacePayload(Bytes::from_static(b"toolong"))
3782 .delayed(Duration::from_secs(9)),
3783 );
3784 assert!(!out.is_applied(), "[{draft:?}] the inner action is refused");
3785 assert_eq!(
3786 h.observer.impairments(),
3787 vec![],
3788 "[{draft:?}] a refused action changed nothing, so it impaired nothing",
3789 );
3790 assert_eq!(
3791 h.observer.refused().len(),
3792 1,
3793 "[{draft:?}] and the refusal itself is still reported",
3794 );
3795
3796 // The control: the same delay, admitted, does clamp and does say
3797 // so — so the emptiness above is the refusal and not silence.
3798 let mut h = Harness::with_config(clamping);
3799 let out = h.run(&object_unit(&m, at), Action::Pass.delayed(Duration::from_secs(9)));
3800 assert!(out.is_applied(), "[{draft:?}] a plain delay is admitted");
3801 assert_eq!(
3802 h.observer.impairments(),
3803 vec![ImpairmentKind::HoldClamped {
3804 requested: Some(Duration::from_secs(9)),
3805 applied: Duration::from_millis(50),
3806 }],
3807 );
3808 }
3809 }
3810
3811 /// Two impairments from one admitted action arrive in the order the
3812 /// engine did the work, both attributed to the connection being written
3813 /// to.
3814 ///
3815 /// A `Delay` beyond `max_hold` onto a queue smaller than the unit does
3816 /// two separate things — it shortens the wait, then it fills the queue —
3817 /// and each owes its own report. Asserted as a `Vec` rather than as two
3818 /// counts because the order is a claim: the clamp is decided while the
3819 /// unit is still being planned, and backpressure is only knowable once
3820 /// the push has happened. Reversed, the pair would say the queue was
3821 /// already full before the unit that filled it went in.
3822 ///
3823 /// Both name [`Leg::Upstream`] on a pipe reading from the client,
3824 /// because both are about the queue in front of the *relay* connection.
3825 /// A reader who took the event's `side` for a connection would attribute
3826 /// them to the client leg — the one this proxy was reading from and the
3827 /// one that is behaving perfectly.
3828 #[test]
3829 fn one_action_owes_two_impairments_in_the_order_it_earned_them() {
3830 for &draft in COMPILED_DRAFTS {
3831 let mut h = Harness::with_config(EgressConfig {
3832 // Below the ten-byte unit, so the very first push crosses
3833 // the limit and the transition is reported on it.
3834 max_pending_bytes: 4,
3835 max_hold: Duration::from_millis(50),
3836 ..EgressConfig::default()
3837 });
3838 let m = meta(draft);
3839 let out = h.run(
3840 &object_unit(&m, Instant::now()),
3841 Action::Pass.delayed(Duration::from_secs(9)),
3842 );
3843 assert!(out.is_applied(), "[{draft:?}] the delay is admitted");
3844 assert_eq!(
3845 h.observer.attributed_impairments(),
3846 vec![
3847 (
3848 Some(Leg::Upstream),
3849 ImpairmentKind::HoldClamped {
3850 requested: Some(Duration::from_secs(9)),
3851 applied: Duration::from_millis(50),
3852 },
3853 ),
3854 (Some(Leg::Upstream), ImpairmentKind::EgressQueueFull { stream_id: 4 }),
3855 ],
3856 "[{draft:?}] the clamp is decided before the push and both belong to the \
3857 connection being written to",
3858 );
3859 }
3860 }
3861
3862 /// The same impairment names the other connection when it is raised by
3863 /// the other pipe, and a report that is about neither connection names
3864 /// neither.
3865 ///
3866 /// The first half is what makes the field worth carrying: `HoldClamped`
3867 /// is `Leg::Upstream` on the pipe reading from the client and
3868 /// `Leg::Client` on the pipe reading from the relay, because in both
3869 /// cases it is the far side that is being written to. The second half is
3870 /// [`ImpairmentKind::CoarseReleaseTimer`], which is a fact about the
3871 /// host's clock: it is equally true of both legs, stays true if one goes
3872 /// away, and so answers `None` rather than being pinned to whichever
3873 /// pipe noticed the coarse tick first.
3874 #[test]
3875 fn the_leg_turns_with_the_pipe_and_is_absent_where_there_is_none() {
3876 let draft = COMPILED_DRAFTS[0];
3877 let m = meta(draft);
3878 let clamping = EgressConfig {
3879 max_pending_bytes: 1 << 20,
3880 max_hold: Duration::from_millis(50),
3881 ..EgressConfig::default()
3882 };
3883
3884 for (side, expected) in
3885 [(ProxySide::ClientToProxy, Leg::Upstream), (ProxySide::RelayToProxy, Leg::Client)]
3886 {
3887 let mut h = Harness::with_config(clamping).reading_from(side);
3888 h.run(&object_unit(&m, Instant::now()), Action::Pass.delayed(Duration::from_secs(9)));
3889 assert_eq!(
3890 h.observer.attributed_impairments(),
3891 vec![(
3892 Some(expected),
3893 ImpairmentKind::HoldClamped {
3894 requested: Some(Duration::from_secs(9)),
3895 applied: Duration::from_millis(50),
3896 },
3897 )],
3898 "a clamp on the pipe reading from {side:?} holds bytes off the {expected:?} leg",
3899 );
3900 }
3901
3902 // Both pipes, because *equally true of both legs* is the claim. A
3903 // single side would pass against a mapping that answers whichever
3904 // connection the reporting pipe happens to be on — which is the guess
3905 // this arm exists to refuse.
3906 for side in [ProxySide::ClientToProxy, ProxySide::RelayToProxy] {
3907 let h = Harness::new().reading_from(side);
3908 h.report().impairment(ImpairmentKind::CoarseReleaseTimer {
3909 backend: crate::instrument::TimerBackend::Condvar,
3910 detail: None,
3911 });
3912 let attributed = h.observer.attributed_impairments();
3913 assert_eq!(attributed.len(), 1);
3914 assert_eq!(
3915 attributed[0].0, None,
3916 "the release wheel belongs to the process, not to a connection, so the pipe \
3917 reading from {side:?} must not name one either",
3918 );
3919 }
3920 }
3921
3922 /// One pipe, three reports, three different answers — as an exact
3923 /// sequence rather than a set.
3924 ///
3925 /// This is the shape the whole surface is for. A single forwarding task
3926 /// reading from the client raises a parser failure about the bytes that
3927 /// arrived, a queue failure about the bytes it is trying to place, and a
3928 /// host fact about neither, and the three have to come back attributed
3929 /// to `Client`, `Upstream` and nothing respectively. Compared as a `Vec`
3930 /// because the order is part of the claim: an impairment is emitted
3931 /// after what it reports, so the sequence is the order the proxy did
3932 /// things in, and a set would pass against a proxy that reported them
3933 /// backwards.
3934 #[test]
3935 fn one_pipe_reports_the_near_leg_the_far_leg_and_neither_in_order() {
3936 let draft = COMPILED_DRAFTS[0];
3937 let h = Harness::new();
3938 let report = h.report();
3939
3940 report.impairment(ImpairmentKind::FramerBypass {
3941 stream_id: 4,
3942 draft,
3943 reason: crate::types::BypassReason::DecodeError,
3944 });
3945 report.impairment(ImpairmentKind::EgressQueueFull { stream_id: 4 });
3946 report.impairment(ImpairmentKind::CoarseReleaseTimer {
3947 backend: crate::instrument::TimerBackend::Condvar,
3948 detail: None,
3949 });
3950
3951 assert_eq!(
3952 h.observer.attributed_impairments(),
3953 vec![
3954 (
3955 Some(Leg::Client),
3956 ImpairmentKind::FramerBypass {
3957 stream_id: 4,
3958 draft,
3959 reason: crate::types::BypassReason::DecodeError,
3960 },
3961 ),
3962 (Some(Leg::Upstream), ImpairmentKind::EgressQueueFull { stream_id: 4 }),
3963 (
3964 None,
3965 ImpairmentKind::CoarseReleaseTimer {
3966 backend: crate::instrument::TimerBackend::Condvar,
3967 detail: None,
3968 },
3969 ),
3970 ],
3971 "one pipe, three answers: what arrived, what could not be written, and neither",
3972 );
3973 }
3974}