Skip to main content

moqtap_client/draft19/
endpoint.rs

1#![allow(missing_docs)]
2//! Draft-19 MoQT endpoint.
3//!
4//! Major changes from draft-18:
5//!
6//! * `GoAway` drops the `request_id` field entirely; the control-stream and
7//!   request-stream forms are now identical on the wire.
8//! * `PublishBlocked` renamed to `PublishSkipped` (still type 0x0F, wire
9//!   identical).
10//! * `GROUP_ORDER` (parameter 0x22) moves from PUBLISH_OK to SUBSCRIBE_TRACKS.
11//! * New Range Filter parameters (SUBGROUP_FILTER 0x25, OBJECTID_FILTER 0x26,
12//!   PRIORITY_FILTER 0x27, OBJECT_PROPERTY_FILTER 0x28, TRACK_PROPERTY_FILTER
13//!   0x29) may appear on SUBSCRIBE / FETCH / SUBSCRIBE_TRACKS / REQUEST_UPDATE.
14//! * `RequestError` adds CONFLICTING_FILTERS (0x35) and INVALID_FILTER (0x36);
15//!   DUPLICATE_SUBSCRIPTION (0x19) is removed.
16
17use std::collections::{HashMap, HashSet};
18use std::sync::{Arc, Mutex};
19
20use crate::draft19::fetch::{FetchError, FetchState, FetchStateMachine};
21use crate::draft19::namespace::{
22    NamespaceError, PublishNamespaceState, PublishNamespaceStateMachine, SubscribeNamespaceState,
23    SubscribeNamespaceStateMachine,
24};
25use crate::draft19::publish::{
26    PublishError as PublishFlowError, PublishState, PublishStateMachine,
27};
28use crate::draft19::session::request_id::{RequestIdAllocator, RequestIdError, Role};
29use crate::draft19::session::setup::{self, SetupError};
30
31use moqtap_codec::kvp::KvpValue;
32use moqtap_codec::range_filter::{self, RangeFilterError};
33use moqtap_codec::varint::Moqt18;
34
35/// The MAX_REQUEST_UPDATES Setup Option, Section 10.3.1.7.
36const MAX_REQUEST_UPDATES: u64 = 0x08;
37
38/// The MAX_FILTER_RANGES Setup Option, Section 10.3.1.6.
39const MAX_FILTER_RANGES: u64 = 0x06;
40
41/// The Message Parameters a request carries, or nothing for a message that is
42/// not a request.
43///
44/// Every one of the seven request kinds carries a parameter list, so the empty
45/// arm is only reached by a caller that is not looking at a request. Section
46/// 5.1.3 names five message types a Range Filter may appear in, and this does
47/// not narrow to them: a filter parameter arriving where the section does not
48/// list it is a scope question, and scope is answered by the parameter registry
49/// rather than here. What matters for the ceiling is that a filter this endpoint
50/// has no budget for is not accepted, wherever it turned up.
51fn request_parameters(msg: &ControlMessage) -> &[KeyValuePair] {
52    match msg {
53        ControlMessage::Subscribe(m) => &m.parameters,
54        ControlMessage::Publish(m) => &m.parameters,
55        ControlMessage::Fetch(m) => &m.parameters,
56        ControlMessage::PublishNamespace(m) => &m.parameters,
57        ControlMessage::SubscribeNamespace(m) => &m.parameters,
58        ControlMessage::SubscribeTracks(m) => &m.parameters,
59        ControlMessage::TrackStatus(m) => &m.parameters,
60        _ => &[],
61    }
62}
63
64/// The Range Filter parameters in `parameters`, dropping the removals.
65///
66/// A Range Filter whose value is empty is Section 5.1.3's removal form — "Length
67/// can be 0 to remove a filter parameter" — so it names a filter rather than
68/// being one, and carrying it forward would leave a filter of no ranges in force
69/// for the life of the request.
70fn range_filter_parameters(parameters: &[KeyValuePair]) -> Vec<KeyValuePair> {
71    parameters
72        .iter()
73        .filter(|p| range_filter::is_range_filter(p.key.into_inner()))
74        .filter(|p| !matches!(&p.value, KvpValue::Bytes(bytes) if bytes.is_empty()))
75        .cloned()
76        .collect()
77}
78
79/// Apply a REQUEST_UPDATE's filter parameters to the set already in force.
80///
81/// Replacement is by Parameter Type and takes the whole type with it: "non-zero
82/// to replace that entire filter parameter including all sets and Property
83/// Types". A type the update does not mention is left alone, which is the other
84/// half of the same sentence — "If a filter parameter is omitted from
85/// REQUEST_UPDATE, the value is unchanged" — and is why this merges rather than
86/// measuring the update on its own.
87fn apply_filter_update(in_force: &mut Vec<KeyValuePair>, update: &[KeyValuePair]) {
88    let mentioned: Vec<u64> = update
89        .iter()
90        .map(|p| p.key.into_inner())
91        .filter(|key| range_filter::is_range_filter(*key))
92        .collect();
93    in_force.retain(|p| !mentioned.contains(&p.key.into_inner()));
94    in_force.extend(range_filter_parameters(update));
95}
96
97/// Read a Setup Option's value as a variable-length integer, or 0 if it is
98/// absent.
99///
100/// Zero is also the default every numeric option in Section 10.3.1 takes when
101/// it is not sent, so an absent option and an explicit zero mean the same thing
102/// and do not need to be told apart.
103fn setup_varint(options: &[KeyValuePair], key: u64) -> u64 {
104    let key = VarInt::from_u64(key).expect("option key fits a varint");
105    options
106        .iter()
107        .find(|o| o.key == key)
108        .and_then(|o| match &o.value {
109            KvpValue::Varint(v) => Some(v.into_inner()),
110            KvpValue::Bytes(bytes) => {
111                let mut cursor = &bytes[..];
112                let parsed = VarInt::decode_moqt::<Moqt18>(&mut cursor).ok()?;
113                cursor.is_empty().then(|| parsed.into_inner())
114            }
115        })
116        .unwrap_or(0)
117}
118use crate::draft19::session::state::{SessionError, SessionState, SessionStateMachine};
119use crate::draft19::subscription::{
120    SubscriptionError, SubscriptionState, SubscriptionStateMachine,
121};
122use crate::draft19::track_status::{TrackStatusError, TrackStatusState, TrackStatusStateMachine};
123use crate::malformed_tracks::{MalformedTrackCondition, MalformedTracks};
124use crate::track_locations::{ObjectLocation, ObjectRole, TrackLocations, TrackObjects};
125use moqtap_codec::draft19::error_codes::{
126    PublishDoneStatusCode, RequestErrorCode, SessionErrorCode,
127};
128use moqtap_codec::draft19::message::{
129    self, ControlMessage, Fetch, FetchPayload, FetchType, GoAway, MessageType, Publish,
130    PublishDone, PublishNamespace, PublishSkipped, RequestError, RequestOk, RequestUpdate, Setup,
131    Subscribe, SubscribeNamespace, SubscribeOk, SubscribeTracks,
132};
133use moqtap_codec::kvp::KeyValuePair;
134use moqtap_codec::types::*;
135use moqtap_codec::varint::VarInt;
136
137/// Why a peer's request must be answered with REQUEST_ERROR and INVALID_FILTER.
138///
139/// Draft-19 gives the Range Filters four rules and answers every one of them
140/// the same way — "MUST be rejected with REQUEST_ERROR with error code
141/// INVALID_FILTER" — so this says which rule was broken rather than which code
142/// to send. [`FilterRejection::request_error_code`] is the code, and it is the
143/// same for all four.
144///
145/// None of these is a session close, which is the whole reason the type exists.
146/// A rejection is a reply, and a reply names the Request ID of the request it
147/// answers, so the endpoint has to have taken the request in order to refuse it.
148/// The rejection is recorded against that id and spent by the REQUEST_ERROR that
149/// answers it.
150#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
151pub enum FilterRejection {
152    /// The peer sent a Range Filter and this endpoint advertised no budget.
153    ///
154    /// Section 10.3.1.6: "The default value is 0, so if not specified, the peer
155    /// MUST NOT send any such filter parameters." Zero is the default and it
156    /// means none allowed — the opposite of what zero means in the option
157    /// beside it, MAX_REQUEST_UPDATES, where it means no limit. The two sit in
158    /// consecutive subsections and read opposite ways.
159    #[error("this endpoint advertised no MAX_FILTER_RANGES, so no range filter is allowed")]
160    NoBudgetAdvertised,
161    /// More Ranges than MAX_FILTER_RANGES allows, counted across every filter.
162    #[error("{ranges} ranges across the request's filters, where {limit} were advertised")]
163    TooManyRanges {
164        /// The total the request carried.
165        ranges: usize,
166        /// The total this endpoint advertised.
167        limit: u64,
168    },
169    /// Two filters with the same Parameter Type, SetID and Property Type.
170    ///
171    /// Repeats of a type are otherwise expected, so the key is the whole triple:
172    /// "The Track Property filter parameter MAY appear multiple times in a
173    /// SUBSCRIBE_TRACKS message"
174    #[error("two filters share parameter type {0:#x}, set {1} and property type {2:?}")]
175    RepeatedFilter(u64, u8, Option<u64>),
176    /// A filter this codec could not read, or one that broke a rule of its own.
177    #[error("a range filter is not usable: {0}")]
178    Unreadable(#[from] RangeFilterError),
179}
180
181impl FilterRejection {
182    /// The REQUEST_ERROR code every one of these is answered with.
183    pub fn request_error_code(&self) -> RequestErrorCode {
184        RequestErrorCode::InvalidFilter
185    }
186}
187
188/// Errors that can occur during endpoint operations.
189#[derive(Debug, thiserror::Error)]
190pub enum EndpointError {
191    #[error("session error: {0}")]
192    Session(#[from] SessionError),
193    #[error("request ID error: {0}")]
194    RequestId(#[from] RequestIdError),
195    #[error("subscription error: {0}")]
196    Subscription(#[from] SubscriptionError),
197    #[error("fetch error: {0}")]
198    Fetch(#[from] FetchError),
199    #[error("namespace error: {0}")]
200    Namespace(#[from] NamespaceError),
201    #[error("track status error: {0}")]
202    TrackStatus(#[from] TrackStatusError),
203    #[error("publish flow error: {0}")]
204    PublishFlow(#[from] PublishFlowError),
205    #[error("setup error: {0}")]
206    Setup(#[from] SetupError),
207    #[error("unknown request ID: {0}")]
208    UnknownRequest(u64),
209    #[error(
210        "response message received on control stream; draft-19 responses belong on bidi request streams"
211    )]
212    ResponseOnControlStream,
213    /// A REQUEST_UPDATE arrived on the control stream.
214    ///
215    /// Draft-19 Table 5 gives REQUEST_UPDATE the Stream value "Request", and
216    /// Section 10.9 requires it on the same bidi stream as the request it
217    /// modifies. One on the control stream modifies nothing, which makes it a
218    /// case Section 10.9 says MUST close the session.
219    #[error(
220        "REQUEST_UPDATE received on the control stream; it belongs on its request's own stream"
221    )]
222    RequestUpdateOnControlStream,
223    /// A NAMESPACE, NAMESPACE_DONE or PUBLISH_SKIPPED arrived on the control
224    /// stream.
225    ///
226    /// Draft-19 Table 5 gives all three the Stream value "Request": NAMESPACE
227    /// (0x8, Section 10.16) and NAMESPACE_DONE (0xE, Section 10.17) belong on
228    /// the SUBSCRIBE_NAMESPACE request stream whose namespace they report, and
229    /// PUBLISH_SKIPPED (0xF, Section 10.20) on the SUBSCRIBE_TRACKS stream
230    /// whose namespace it names a skipped track in — "All PUBLISH_SKIPPED
231    /// messages are in response to a SUBSCRIBE_TRACKS". Only SETUP is
232    /// "Control" alone; GOAWAY is the one message the
233    /// table lists as "Control, Request". One of these three on the control
234    /// stream names no request, so nothing can be done with it.
235    #[error("{0} received on the control stream; draft-19 Table 5 places it on a request stream")]
236    RequestMessageOnControlStream(&'static str),
237    /// A REQUEST_UPDATE named a request that cannot be updated, or none.
238    ///
239    /// Draft-19 Section 10.9: "An endpoint that receives a REQUEST_UPDATE
240    /// other than in the two cases above MUST close the session with a
241    /// PROTOCOL_VIOLATION." TRACK_STATUS is called out in Section 10.14 as one
242    /// such case: "the subscriber cannot send REQUEST_UPDATE."
243    #[error("REQUEST_UPDATE for request {0}, which is not an updatable outstanding request")]
244    UnexpectedRequestUpdate(u64),
245    /// Track Properties on a REQUEST_OK answering something other than a
246    /// TRACK_STATUS.
247    ///
248    /// Draft-19 Section 10.5: they "are empty in PUBLISH_OK,
249    /// REQUEST_UPDATE_OK, SUBSCRIBE_NAMESPACE_OK and PUBLISH_NAMESPACE_OK. If
250    /// an endpoint receives Track Properties in one of these messages it MUST
251    /// close the session with a PROTOCOL_VIOLATION."
252    #[error(
253        "track properties on the REQUEST_OK answering request {0}, which is not a TRACK_STATUS"
254    )]
255    TrackPropertiesOnNonTrackStatus(u64),
256    /// A server received a Redirect naming a Connect URI.
257    ///
258    /// Draft-19 Section 10.6.1: "If a server receives a Redirect with a
259    /// non-zero Connect URI Length it MUST close the session with a
260    /// PROTOCOL_VIOLATION." As with GOAWAY, only a client is redirected.
261    #[error("Redirect carrying a Connect URI received at a server")]
262    RedirectUriAtServer,
263    /// A Redirect answering a namespace-scoped request carried a Track Name.
264    ///
265    /// Draft-19 Section 10.6.1: "Track Name is not meaningful for
266    /// namespace-scoped requests (SUBSCRIBE_NAMESPACE, PUBLISH_NAMESPACE,
267    /// SUBSCRIBE_TRACKS) and MUST be empty; an endpoint that receives a
268    /// non-empty Track Name in a Redirect for a namespace-scoped request MUST
269    /// close the session with a PROTOCOL_VIOLATION." Draft-18 names the same
270    /// rule with SUBSCRIBE_TRACKS left out of the list.
271    #[error("Redirect for namespace-scoped request {0} carries a track name")]
272    RedirectTrackNameOnNamespaceRequest(u64),
273    /// A server received a GOAWAY carrying a New Session URI.
274    ///
275    /// Draft-19 Section 10.4: "If a server receives a GOAWAY with a non-zero
276    /// New Session URI Length it MUST close the session with a
277    /// PROTOCOL_VIOLATION." Only a client can be redirected.
278    #[error("GOAWAY carrying a New Session URI received at a server")]
279    GoAwayUriAtServer,
280    /// The peer reused a Request ID it had already spent.
281    ///
282    /// Draft-19 Section 10.1: "If an endpoint receives a Request ID where the
283    /// least significant bit is incorrect for the sender, or a duplicate
284    /// Request ID, it MUST close the session with INVALID_REQUEST_ID."
285    #[error("request {0} was already used by the peer")]
286    DuplicateRequestId(u64),
287    /// A bidirectional stream the peer opened began with a message that does
288    /// not open a request stream.
289    ///
290    /// Draft-19 Section 3.3: "Bidirectional streams MUST NOT begin with any
291    /// other message type unless negotiated. If they do, the peer MUST close
292    /// the Session with a PROTOCOL_VIOLATION."
293    #[error("{0:?} does not begin a request stream")]
294    NotARequest(MessageType),
295    /// A message that this endpoint may not write on a request stream the peer
296    /// opened was handed to the responder path. Nothing was written and no
297    /// state moved.
298    #[error("{0:?} is not a message a responder writes on a peer's request stream")]
299    NotAResponse(MessageType),
300    /// A message arrived on a request stream the peer opened that may not
301    /// follow a request there.
302    ///
303    /// This endpoint is the responder on such a stream, so a response arriving
304    /// on it is the peer answering its own request.
305    #[error("{0:?} may not follow a request on a stream the peer opened")]
306    UnexpectedOnPeerRequestStream(MessageType),
307    /// A namespace-scoped request's response half opened with something other
308    /// than REQUEST_OK or REQUEST_ERROR.
309    ///
310    /// Draft-19 Sections 10.18 and 10.19, of SUBSCRIBE_NAMESPACE and
311    /// SUBSCRIBE_TRACKS alike: "The publisher will respond with REQUEST_OK or
312    /// REQUEST_ERROR on the response half of the stream. If the subscriber
313    /// receives any message other than a REQUEST_OK or a REQUEST_ERROR as the
314    /// first message on the response half of the stream, then it MUST close the
315    /// session with a PROTOCOL_VIOLATION."
316    #[error("request {0} answered with {1:?} before its REQUEST_OK or REQUEST_ERROR")]
317    ResponseBeforeTheFirstResponse(u64, MessageType),
318    /// Track Properties were put on a REQUEST_OK answering something other
319    /// than a TRACK_STATUS, on the way out. Nothing was written.
320    ///
321    /// The send-side mirror of
322    /// [`TrackPropertiesOnNonTrackStatus`](Self::TrackPropertiesOnNonTrackStatus):
323    /// Section 10.5 answers receiving them with a session close, so writing
324    /// them would hand a conforming peer a reason to close this session. This
325    /// one is not fatal — nothing reached the wire, so there is nothing for the
326    /// peer to object to.
327    #[error("request {0} is not a TRACK_STATUS; only its response carries track properties")]
328    TrackPropertiesOnOutgoingRequestOk(u64),
329    /// A REQUEST_UPDATE arrived on a stream that had already used up the
330    /// concurrency this endpoint advertised.
331    ///
332    /// Draft-19 Section 10.3.1.7: "If an endpoint receives a REQUEST_UPDATE on
333    /// a stream that already has MAX_REQUEST_UPDATES outstanding
334    /// REQUEST_UPDATEs, it MUST close the session with
335    /// TOO_MANY_REQUEST_UPDATES."
336    #[error("request {0} already has the {1} outstanding REQUEST_UPDATEs it was allowed")]
337    TooManyRequestUpdates(u64, u64),
338    /// A REQUEST_OK was offered for a request whose Range Filters this endpoint
339    /// is required to reject.
340    ///
341    /// Not fatal, and deliberately not raised where the filter arrives. Every
342    /// Range Filter rule in Section 5.1.3 is answered with a REQUEST_ERROR, and
343    /// a REQUEST_ERROR names the Request ID of the request it answers — so the
344    /// request has to be taken before it can be refused. What this stops is the
345    /// other answer: accepting the request the draft says to reject leaves the
346    /// subscriber with a subscription whose filters this endpoint never agreed
347    /// to apply, and a publisher that then forwards by its own reading of them.
348    #[error("request {0} must be answered with REQUEST_ERROR: {1}")]
349    FilterMustBeRejected(u64, FilterRejection),
350    /// A REQUEST_OK or REQUEST_ERROR was offered as the answer to a
351    /// REQUEST_UPDATE on a stream with no update waiting for one.
352    ///
353    /// Section 10.9 requires "exactly one REQUEST_OK or REQUEST_ERROR message
354    /// indicating if the update was successful", so an answer with nothing to
355    /// answer is one the peer will read as belonging to an update it never
356    /// sent. Not fatal: nothing was written.
357    ///
358    /// A SUBSCRIBE is answered with SUBSCRIBE_OK and a FETCH with FETCH_OK, so
359    /// on those two streams a REQUEST_OK can be nothing but an update's answer
360    /// and this is what a mistimed one produces. On the five kinds REQUEST_OK
361    /// answers itself, the first one is the request's and only the ones after
362    /// it can reach here.
363    #[error("request {0} has no REQUEST_UPDATE waiting for an answer")]
364    NoUpdateToAnswer(u64),
365    /// An update was refused and the subscription it belongs to was then ended
366    /// under some status other than the one that names why.
367    ///
368    /// Section 10.9.1: "When a REQUEST_UPDATE is unsuccessful, the publisher MUST
369    /// also terminate the subscription by sending a PUBLISH_DONE with error
370    /// code UPDATE_FAILED." The REQUEST_ERROR is half of what that sentence
371    /// asks for and the termination is the other half, so this endpoint holds
372    /// the request to it: whatever else the caller writes first, the
373    /// termination it does write says so.
374    #[error("request {request}'s update was refused, so its PUBLISH_DONE must carry {required}")]
375    WrongUpdateFailureStatus {
376        /// The request whose update was refused.
377        request: u64,
378        /// The status code the termination must carry.
379        required: u64,
380    },
381    #[error("session not active")]
382    NotActive,
383    #[error("session is draining, no new requests allowed")]
384    Draining,
385    /// A second GOAWAY arrived on the control stream.
386    ///
387    /// The GOAWAY that says the peer is going away is one message, and the
388    /// draft answers a repeat of it with a session close rather than with an
389    /// error about the second message: there is no state a second one could
390    /// move that the first has not already moved.
391    #[error("a second GOAWAY arrived on the control stream")]
392    RepeatedGoAway,
393    /// A second GOAWAY arrived on one request's stream.
394    ///
395    /// The count is per stream rather than per session: this draft lets a
396    /// GOAWAY migrate a single request, so one on each of two request streams
397    /// is two first GOAWAYs and not a repeat.
398    #[error("a second GOAWAY arrived on request {0}'s stream")]
399    RepeatedGoAwayOnRequestStream(
400        /// The Request ID of the stream that carried both.
401        u64,
402    ),
403    /// The peer named a Track Alias it is already using for another track.
404    ///
405    /// Draft-19 Section 11.1: "The same Track Alias MUST NOT be used by a
406    /// publisher to refer to two different Tracks simultaneously in the same
407    /// session. If a subscriber receives a PUBLISH or SUBSCRIBE_OK that uses
408    /// the same Track Alias as a different Track with an Established
409    /// subscription, it MUST close the session with error
410    /// DUPLICATE_TRACK_ALIAS."
411    ///
412    /// The session is over: this endpoint's own state has moved to Closed and
413    /// the code the transport should close with is in
414    /// [`EndpointError::session_error_code`].
415    #[error("track alias {alias} already names request {established}'s track; request {offered} names a different one")]
416    DuplicateTrackAlias {
417        /// The alias both tracks are named by.
418        alias: u64,
419        /// The request whose Established subscription holds the alias.
420        established: u64,
421        /// The request whose message arrived naming it for another track.
422        offered: u64,
423    },
424    /// This endpoint was asked to give a Track Alias to a second track.
425    ///
426    /// The same rule as [`EndpointError::DuplicateTrackAlias`] read at the end
427    /// that chooses the alias. Section 11.1 states it as a prohibition on the
428    /// publisher before it states what the subscriber does about one: "The
429    /// same Track Alias MUST NOT be used by a publisher to refer to two different Tracks
430    /// simultaneously in the same session."
431    ///
432    /// The message is refused instead of built, and nothing else moves: no
433    /// Request ID is spent, no publish flow is created, and the session stays
434    /// as it was. The alias never reaches the peer, so there is nothing for
435    /// the peer to close over.
436    #[error("track alias {alias} already names request {held}'s track")]
437    TrackAliasInUse {
438        /// The alias that is already spoken for.
439        alias: u64,
440        /// The request whose live flow holds it.
441        held: u64,
442    },
443    /// An object arriving after the track's final object.
444    ///
445    /// Section 2.4.2 lists the condition: "An Object is received whose
446    /// Group and Object ID are larger
447    /// than the final Object in the Track.
448    /// The final Object in a Track is the Object with Status END_OF_TRACK or
449    /// the last Object sent in a FETCH whose response indicated End of Track."
450    ///
451    /// **Larger is Section 1.4.2's comparison and not a reading of the
452    /// words.** That section puts one Location below another when "A.Group <
453    /// B.Group || (A.Group == B.Group && A.Object < B.Object)", so an Object in
454    /// a later group is past the end whatever its own Object ID is.
455    ///
456    /// **A Malformed Track and not a session error**, and on this draft not a
457    /// message either. Section 2.4.2 answers its whole list at once with "it
458    /// MUST cancel any corresponding subscription or fetches for that Track
459    /// from that publisher", where cancelling a request is the transport
460    /// operation Section 3.3.3 describes. This is the error half; the
461    /// requests to cancel are named by
462    /// [`Endpoint::requests_for_malformed_track`].
463    #[error(
464        "the object at group {group}, object {object} on track alias {alias} arrived \
465         after the track's final object at group {final_group}, object {final_object}"
466    )]
467    ObjectPastFinalObject {
468        /// The Track Alias the offending object named.
469        alias: u64,
470        /// The Group ID it named.
471        group: u64,
472        /// The Object ID it named.
473        object: u64,
474        /// The Group ID of the object the track ended at.
475        final_group: u64,
476        /// The Object ID of the object the track ended at.
477        final_object: u64,
478    },
479
480    /// A Joining Fetch named a subscription this session cannot join.
481    ///
482    /// Section 10.12.2:
483    /// "If a publisher receives a Joining Fetch with a Request ID that
484    /// does not correspond to a subscription in the same session in the
485    /// Established or Pending (subscriber) states, it MUST return a
486    /// REQUEST_ERROR with error code INVALID_JOINING_REQUEST_ID."
487    ///
488    /// A refusal and not a session close, so the session runs on and the error
489    /// names both identifiers: the fetch to refuse, and the subscription it
490    /// asked to join.
491    #[error("FETCH {fetch} joins request {joining}, which is no live subscription of the peer's")]
492    UnjoinableSubscription {
493        /// The fetch that named it.
494        fetch: u64,
495        /// The identifier it named.
496        joining: u64,
497    },
498
499    /// A Joining Fetch was refused under a code other than the one the same
500    /// sentence names for it.
501    ///
502    /// The reason travels with the refusal, so a subscriber told the wrong one
503    /// retries the wrong thing: it can rebuild a fetch whose range was refused,
504    /// and cannot rebuild one whose subscription is gone.
505    #[error("refusing FETCH {fetch} for the subscription it joins takes error code {required}")]
506    WrongJoiningRefusal {
507        /// The fetch being refused.
508        fetch: u64,
509        /// The code the draft names for that refusal.
510        required: u64,
511    },
512    /// The peer subscribed to a namespace prefix overlapping one it is
513    /// already subscribed to.
514    ///
515    /// Section 10.18: "Within a session, if a publisher receives a
516    /// SUBSCRIBE_NAMESPACE with a Track Namespace Prefix that shares a common
517    /// prefix with an established SUBSCRIBE_NAMESPACE, it MUST respond with
518    /// REQUEST_ERROR with error code PREFIX_OVERLAP."
519    ///
520    /// Section 10.19: "Within a session, if a publisher receives a
521    /// SUBSCRIBE_TRACKS with a Track Namespace Prefix that shares a common
522    /// prefix with an established SUBSCRIBE_TRACKS, it MUST respond with
523    /// REQUEST_ERROR with error code PREFIX_OVERLAP."
524    ///
525    /// Section 10.6.2: "SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS have
526    /// independent overlap spaces, so a SUBSCRIBE_NAMESPACE and a
527    /// SUBSCRIBE_TRACKS may share the same prefix."
528    ///
529    /// Taken when the message arrives, which is the moment the sentence
530    /// names, and read again when an answer is built: a request this endpoint
531    /// may not accept is one no later call can accept.
532    ///
533    /// The refusal itself is not this error. It is a message the peer is
534    /// owed, so the request is recorded like any other and refused through
535    /// the same call that refuses any other, under the code the sentence
536    /// names.
537    #[error(
538        "request {request} subscribes to a namespace prefix overlapping request {established}"
539    )]
540    PeerPrefixOverlap {
541        /// The request that arrived.
542        request: u64,
543        /// The namespace subscription it overlaps.
544        established: u64,
545    },
546    /// A namespace subscription that overlaps another was refused under a
547    /// code other than the one the sentence names.
548    ///
549    /// The same shape as [`EndpointError::WrongJoiningRefusal`]: a rule that
550    /// names the code its refusal carries is not satisfied by a refusal under
551    /// any other, because the peer reads the code to learn what went wrong.
552    #[error("request {request} overlaps a namespace subscription and must be refused with code {required:#x}")]
553    WrongOverlapRefusal {
554        /// The request being refused.
555        request: u64,
556        /// The code the sentence names for it.
557        required: u64,
558    },
559}
560
561/// Whether two namespace prefixes overlap.
562///
563/// Section 10.18: "Within a session, if a publisher receives a
564/// SUBSCRIBE_NAMESPACE with a Track Namespace Prefix that shares a common
565/// prefix with an established SUBSCRIBE_NAMESPACE, it MUST respond with
566/// REQUEST_ERROR with error code PREFIX_OVERLAP."
567///
568/// Section 10.19: "Within a session, if a publisher receives a
569/// SUBSCRIBE_TRACKS with a Track Namespace Prefix that shares a common prefix
570/// with an established SUBSCRIBE_TRACKS, it MUST respond with REQUEST_ERROR
571/// with error code PREFIX_OVERLAP."
572///
573/// Section 10.6.2: "SUBSCRIBE_NAMESPACE and SUBSCRIBE_TRACKS have independent
574/// overlap spaces, so a SUBSCRIBE_NAMESPACE and a SUBSCRIBE_TRACKS may share
575/// the same prefix."
576///
577/// A namespace matches a namespace subscription when the subscription's
578/// prefix is a prefix of it, so two prefixes select overlapping sets of
579/// namespaces exactly when one of them is a prefix of the other. Equal
580/// prefixes are that case as well: every prefix is a prefix of itself, and
581/// two equal ones select the same set.
582///
583/// "Shares a common prefix with" is read as the relation drafts 07 through 14
584/// spell out at greater length. Taken at its word it would forbid every
585/// second namespace subscription in a session, since any two prefixes share
586/// the empty one, and nothing else in this draft supports that.
587fn prefixes_overlap(a: &[Vec<u8>], b: &[Vec<u8>]) -> bool {
588    let shared = a.len().min(b.len());
589    a[..shared] == b[..shared]
590}
591
592/// Parameter Type of TRACK_NAMESPACE_PREFIX.
593const TRACK_NAMESPACE_PREFIX: u64 = 0x34;
594
595/// The Track Namespace Prefix a REQUEST_UPDATE asks a namespace subscription
596/// to move to, and `None` when it asks for no such move.
597///
598/// Section 10.2.19: "The TRACK_NAMESPACE_PREFIX parameter (Parameter Type
599/// 0x34) uses the Track Namespace encoding described in Section 2.4.1. It MAY
600/// appear in REQUEST_UPDATE for a SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS
601/// request. It updates the Track Namespace Prefix for that subscription."
602///
603/// A prefix of no fields is a value rather than a removal. Section 2.4.1 puts
604/// a Track Namespace at "between 0 and 32 Track Namespace Fields", an empty
605/// prefix selects every namespace, and Section 10.9 leaves no other reading
606/// open: "There is no mechanism to remove a parameter from a request."
607///
608/// The last one wins when a message carries the parameter twice. That is the
609/// rule Section 10.9 gives for two messages -- "Parameter values from later
610/// REQUEST_UPDATE messages override values from earlier ones" -- applied
611/// inside one, which is the only reading under which a repeat means anything.
612///
613/// A value that is not a whole Track Namespace answers `None`, so an update
614/// carrying one leaves the prefix where it was. The decoder that built the
615/// message has already refused a malformed one; this is the arm that keeps a
616/// hand-built message from moving a subscription to half a prefix.
617fn updated_prefix(parameters: &[KeyValuePair]) -> Option<TrackNamespace> {
618    parameters.iter().rfind(|p| p.key.into_inner() == TRACK_NAMESPACE_PREFIX).and_then(|p| match &p
619        .value
620    {
621        KvpValue::Bytes(bytes) => {
622            let mut cursor = &bytes[..];
623            let prefix = TrackNamespace::decode_allow_empty_moqt::<Moqt18>(&mut cursor).ok()?;
624            cursor.is_empty().then_some(prefix)
625        }
626        KvpValue::Varint(_) => None,
627    })
628}
629
630impl EndpointError {
631    /// The code to close the session with, when draft-19 says this error is
632    /// fatal to the session rather than to one request.
633    ///
634    /// `None` means the error is recoverable: the caller may report it and
635    /// keep the session running. `Some` means the draft requires a close, and
636    /// the endpoint has already moved its own session state to
637    /// [`SessionState::Closed`] — the code is what the transport should carry.
638    ///
639    /// The two codes are not interchangeable. Section 3.3 gives
640    /// PROTOCOL_VIOLATION for a bidirectional stream that begins with the wrong
641    /// message type; Section 10.1 gives INVALID_REQUEST_ID for a Request ID
642    /// with the wrong least significant bit or a duplicate one. A peer checking
643    /// close codes can tell the two apart, so this must too.
644    pub fn session_error_code(&self) -> Option<SessionErrorCode> {
645        match self {
646            EndpointError::RequestUpdateOnControlStream
647            | EndpointError::RequestMessageOnControlStream(_)
648            | EndpointError::UnexpectedRequestUpdate(_)
649            | EndpointError::TrackPropertiesOnNonTrackStatus(_)
650            | EndpointError::RedirectUriAtServer
651            | EndpointError::RedirectTrackNameOnNamespaceRequest(_)
652            | EndpointError::ResponseBeforeTheFirstResponse(..)
653            | EndpointError::NotARequest(_)
654            | EndpointError::GoAwayUriAtServer
655            | EndpointError::RepeatedGoAway
656            | EndpointError::RepeatedGoAwayOnRequestStream(_) => {
657                Some(SessionErrorCode::ProtocolViolation)
658            }
659            EndpointError::DuplicateRequestId(_)
660            | EndpointError::RequestId(RequestIdError::WrongParity(..)) => {
661                Some(SessionErrorCode::InvalidRequestId)
662            }
663            EndpointError::TooManyRequestUpdates(..) => {
664                Some(SessionErrorCode::TooManyRequestUpdates)
665            }
666            // Section 11.1 names this code in the sentence that states the
667            // rule, and names no other. A close carrying PROTOCOL_VIOLATION
668            // would tell the peer a different thing went wrong.
669            EndpointError::DuplicateTrackAlias { .. } => {
670                Some(SessionErrorCode::DuplicateTrackAlias)
671            }
672            // Stated rather than left to the arm below, because the neighbour
673            // above makes the opposite choice about a rule of the same shape.
674            // MAX_REQUEST_UPDATES is a ceiling the draft answers with a session
675            // close; MAX_FILTER_RANGES is a ceiling it answers with a
676            // REQUEST_ERROR. Two consecutive subsections, two different answers,
677            // and nothing about either sentence signals which.
678            EndpointError::FilterMustBeRejected(..) => None,
679            _ => None,
680        }
681    }
682}
683
684pub struct Endpoint {
685    role: Role,
686    session: SessionStateMachine,
687    request_ids: RequestIdAllocator,
688    subscriptions: HashMap<u64, SubscriptionStateMachine>,
689    fetches: HashMap<u64, FetchStateMachine>,
690    /// Every Joining Fetch the peer sent naming a subscription this session
691    /// had none live for, and the identifier each one named.
692    ///
693    /// Judged as the FETCH arrives, because that is the moment the rule about
694    /// it names, and kept for as long as the fetch is: a subscription that
695    /// ends between the FETCH and its answer does not turn a fetch that could
696    /// be joined into one that could not.
697    unjoinable_fetches: HashMap<u64, u64>,
698    subscribe_namespaces: HashMap<u64, SubscribeNamespaceStateMachine>,
699    subscribe_tracks: HashMap<u64, SubscribeNamespaceStateMachine>,
700    publish_namespaces: HashMap<u64, PublishNamespaceStateMachine>,
701    track_statuses: HashMap<u64, TrackStatusStateMachine>,
702    publishes: HashMap<u64, PublishStateMachine>,
703    goaway_uri: Option<Vec<u8>>,
704    /// The peer's requests whose stream has already carried a GOAWAY.
705    ///
706    /// Section 10.4 makes the second GOAWAY on one request stream a session
707    /// close while leaving a first one on every other stream legal, so the
708    /// count cannot live on the session. Held apart from the per-kind request
709    /// maps because a GOAWAY says nothing about which kind of request it
710    /// migrates.
711    goaway_request_streams: HashSet<u64>,
712    /// Every Request ID the peer has spent, whether or not the request it
713    /// opened is still live.
714    ///
715    /// Draft-19 Section 10.1 makes a duplicate Request ID a session close, and
716    /// "duplicate" is about the id ever having been used, not about the
717    /// request still being open. Deriving it from the per-kind maps instead
718    /// would answer wrongly the moment those maps are ever pruned, so the rule
719    /// is stated once, here, and this set is never pruned.
720    peer_request_ids: HashSet<u64>,
721    /// Every request the **peer** opened a stream with, as it arrived, keyed
722    /// by the Request ID it carries.
723    ///
724    ///
725    /// One map for all seven kinds, because one entry point takes all seven:
726    /// [`receive_request_on_stream`](Self::receive_request_on_stream) is the
727    /// only thing that writes here, so what is in here is a request, and it
728    /// is the peer's, by construction. How far each one has got stays in the
729    /// per-kind map beside this endpoint's own requests, which is where every
730    /// later message on the stream reads it and where the parity of a Request
731    /// ID keeps the two ends apart.
732    ///
733    /// What a map of state machines cannot hold is the request. Section 5.1 has
734    /// the subscriber "either accepts or rejects the subscription", and what is
735    /// being accepted or rejected -- the track, the namespace prefix, the
736    /// parameters -- is named in the request and nowhere else once the message
737    /// has been dropped.
738    inbound_requests: HashMap<u64, ControlMessage>,
739    /// The request each namespace subscription of the peer's overlapped when
740    /// it arrived, keyed by the Request ID of the one that arrived.
741    ///
742    /// The prefix is judged where the sentence says it is judged, on receipt,
743    /// and the verdict is read again when the answer is written. An entry
744    /// means this endpoint owes that request a REQUEST_ERROR and may send it
745    /// nothing else.
746    overlapping_namespace_subscriptions: HashMap<u64, u64>,
747    /// The Track Namespace Prefix a REQUEST_UPDATE asks one of the peer's
748    /// namespace subscriptions to move to, held until that update is
749    /// answered.
750    ///
751    /// Section 10.9.2 ties the move to the acceptance: "If the update is
752    /// accepted, NAMESPACE and NAMESPACE_DONE messages following the
753    /// REQUEST_OK will contain Track Namespace suffixes relative to the
754    /// updated prefix." Until then the subscription still selects what the
755    /// peer opened it with, so a later request is weighed against the prefix
756    /// in `inbound_requests` and not against this one.
757    updated_namespace_prefixes: HashMap<u64, TrackNamespace>,
758    /// The subscription an unanswered prefix update would collide with, when
759    /// it would, keyed by the Request ID of the one being moved.
760    ///
761    /// Separate from `overlapping_namespace_subscriptions` because one
762    /// Request ID can be carrying both verdicts at once: the request that
763    /// opened the stream has one and an update on it has another, and they
764    /// are settled by different messages on that same stream.
765    overlapping_prefix_updates: HashMap<u64, u64>,
766    /// The MAX_REQUEST_UPDATES this endpoint put in its own SETUP.
767    ///
768    /// The peer's value is a different number and belongs to the sending side,
769    /// which this type has no path for: draft-19 gives the endpoint no
770    /// REQUEST_UPDATE builder, so there is nothing here to hold back.
771    ///
772    /// Zero means no limit rather than none allowed, which is the opposite of
773    /// how MAX_REQUEST_ID reads. Section 10.3.1.7 says so outright - "A value
774    /// of 0 means the endpoint does not limit REQUEST_UPDATE concurrency. If
775    /// not present, the default value is 0" - so an endpoint that never sends
776    /// the option is not limiting anything, and a check that read zero as a
777    /// ceiling would refuse the first update of every session.
778    advertised_max_request_updates: u64,
779    /// Per request stream, how many REQUEST_UPDATEs the peer has sent that this
780    /// endpoint has not yet answered.
781    ///
782    /// "Outstanding" is Section 10.3.1.7's word and it is per stream, not per
783    /// session: "Each REQUEST_OK or REQUEST_ERROR response restores one credit
784    /// on that stream."
785    outstanding_peer_updates: HashMap<u64, u64>,
786    /// Per request stream, how many REQUEST_UPDATEs are still waiting for the
787    /// answer Section 10.9 requires.
788    ///
789    /// A second count rather than a reading of the one above, because the two
790    /// sentences count different things and disagree on exactly one response.
791    /// Section 10.3.1.7 says "Each REQUEST_OK or REQUEST_ERROR response
792    /// restores one credit on that stream" — every response, including the
793    /// REQUEST_OK that answers a SUBSCRIBE_NAMESPACE rather than an update. That
794    /// is the sender's accounting rule as much as the receiver's, and an
795    /// endpoint that credited more carefully than the peer does would close a
796    /// conforming session, so the credit above stays literal.
797    ///
798    /// This one is about which response answers which message, and there the
799    /// request's own REQUEST_OK answers the request. Keeping them apart is what
800    /// lets a response be recognised as an update's answer without changing
801    /// what the peer is allowed to send.
802    unanswered_peer_updates: HashMap<u64, u64>,
803    /// The requests whose refused update has not been followed by the
804    /// PUBLISH_DONE that ends them.
805    ///
806    /// Emptied as each is written. A request is in here for exactly as long as
807    /// this endpoint owes the peer the second half of a refusal.
808    owed_update_failures: HashSet<u64>,
809    /// The peer's requests whose own response has already been written.
810    ///
811    /// Section 10.9 gives an update the same two answers a request has, and on
812    /// the five kinds REQUEST_OK answers, the message that answers the request
813    /// and the message that answers an update are the same message. Nothing on
814    /// the wire tells them apart, so both endpoints resolve it by order: the
815    /// first response on a stream answers the request that opened it and the
816    /// ones after it answer updates. This set is that order, recorded.
817    answered_peer_requests: HashSet<u64>,
818    /// The MAX_FILTER_RANGES this endpoint put in its own SETUP.
819    ///
820    /// Section 10.3.1.6: "The MAX_FILTER_RANGES option (Type 0x06) limits the
821    /// peer's total number of Ranges (Start/End pairs) allowed concurrently in
822    /// all Range filter parameters for a given subscription or fetch. The
823    /// default value is 0, so if not specified, the peer MUST NOT send any such
824    /// filter parameters."
825    ///
826    /// So zero is none allowed, and it is the default. The option in the
827    /// subsection after this one, MAX_REQUEST_UPDATES, reads its zero the other
828    /// way — no limit — and the two are otherwise the same shape. Reading either
829    /// with the other's rule is a working implementation that is wrong in one
830    /// direction or the other for every session.
831    advertised_max_filter_ranges: u64,
832    /// Requests whose Range Filters this endpoint owes the peer a REQUEST_ERROR
833    /// about.
834    ///
835    /// Keyed by Request ID, because that is what the reply names. Entries are
836    /// spent by the REQUEST_ERROR that answers them, and a REQUEST_OK offered
837    /// for one is refused: taking the request in and then accepting it would
838    /// leave the peer with a subscription whose filters were never agreed.
839    peer_filter_rejections: HashMap<u64, FilterRejection>,
840    /// The Range Filter parameters currently in force on each of the peer's
841    /// requests.
842    ///
843    /// Section 5.1.3 makes the ceiling a property of the request rather than of
844    /// the message that carried it — "the total number of Ranges allowed
845    /// concurrently in all Range filter parameters for a given subscription or
846    /// fetch" — and lets a REQUEST_UPDATE rewrite the set: "Length can be 0 to
847    /// remove a filter parameter or non-zero to replace that entire filter
848    /// parameter including all sets and Property Types. If a filter parameter is
849    /// omitted from REQUEST_UPDATE, the value is unchanged."
850    ///
851    /// So the count that matters is of what is in force after the update, and
852    /// the parameters an update leaves alone are part of it. Held as the
853    /// parameters rather than as decoded filters because replacement is by
854    /// Parameter Type, which is the key of the pair.
855    peer_request_filters: HashMap<u64, Vec<KeyValuePair>>,
856    /// What Full Track Name the peer has attached each Track Alias to, per
857    /// Request ID.
858    ///
859    /// Section 11.1 forbids one alias naming two tracks at once, and the "at
860    /// once" is what makes this a table rather than a set: an alias the peer
861    /// used for a track whose subscription has ended is free again. The table
862    /// therefore records the binding and reads liveness back off the request's
863    /// own state machine, rather than keeping a second copy of it that every
864    /// path ending a subscription would have to remember to prune.
865    track_bindings: HashMap<u64, TrackBinding>,
866    /// The track each fetch this endpoint made is for.
867    ///
868    /// Not in `track_bindings`, because that table exists to answer questions
869    /// about Track Aliases and a fetch has none: its objects arrive on a stream
870    /// that opens by naming the Request ID. A Joining Fetch names no track
871    /// either and takes the joined subscription's, resolved as the fetch is
872    /// made rather than at the withdrawal - one fills a buffer behind the live
873    /// edge and outlives the subscription it joined, so a lookup through the
874    /// join would come up empty exactly while there was still a fetch to
875    /// cancel.
876    fetch_tracks: HashMap<u64, FetchTrack>,
877    /// Which tracks this endpoint has given up on, and what for.
878    ///
879    /// Behind a lock because the note is taken on the data plane, where this
880    /// endpoint is reached through `&self`.
881    malformed: Mutex<MalformedTracks>,
882    /// How far each track's objects have reached, and where a track ended.
883    ///
884    /// An `Arc` because a subgroup stream measures its objects against one
885    /// track for as long as it runs, and the handle it holds outlives any
886    /// single call into this endpoint.
887    locations: Arc<Mutex<TrackLocations>>,
888}
889
890/// The track one fetch is for, which the fetch's own state machine does not
891/// hold.
892#[derive(Debug, Clone)]
893struct FetchTrack {
894    namespace: TrackNamespace,
895    name: Vec<u8>,
896}
897
898/// A Track Alias the peer has attached to a Full Track Name, and the request
899/// whose lifetime the attachment follows.
900#[derive(Debug, Clone)]
901struct TrackBinding {
902    namespace: TrackNamespace,
903    name: Vec<u8>,
904    /// The alias, once the peer has named one.
905    ///
906    /// A SUBSCRIBE this endpoint sends names a track and waits for its alias,
907    /// so the binding exists with no alias in it from the moment the request
908    /// is made until its SUBSCRIBE_OK arrives. A PUBLISH carries both at once
909    /// and is never in that state.
910    alias: Option<u64>,
911    kind: BindingKind,
912}
913
914/// Which of the two sequences Section 5.1 names established the subscription
915/// that owns a binding, and so which state machine says whether it still has
916/// one.
917#[derive(Debug, Clone, Copy, PartialEq, Eq)]
918enum BindingKind {
919    /// This endpoint's SUBSCRIBE, established by the peer's SUBSCRIBE_OK.
920    Subscribe,
921    /// A PUBLISH, established by the PUBLISH_OK answering it - whichever end
922    /// sent which. Both are held in the same map, which Request ID parity
923    /// keeps from colliding.
924    Publish,
925}
926
927impl Endpoint {
928    pub fn new(role: Role) -> Self {
929        Self {
930            role,
931            session: SessionStateMachine::new(),
932            request_ids: RequestIdAllocator::new(role),
933            subscriptions: HashMap::new(),
934            fetches: HashMap::new(),
935            unjoinable_fetches: HashMap::new(),
936            subscribe_namespaces: HashMap::new(),
937            subscribe_tracks: HashMap::new(),
938            publish_namespaces: HashMap::new(),
939            track_statuses: HashMap::new(),
940            publishes: HashMap::new(),
941            goaway_uri: None,
942            goaway_request_streams: HashSet::new(),
943            peer_request_ids: HashSet::new(),
944            inbound_requests: HashMap::new(),
945            overlapping_namespace_subscriptions: HashMap::new(),
946            updated_namespace_prefixes: HashMap::new(),
947            overlapping_prefix_updates: HashMap::new(),
948            advertised_max_request_updates: 0,
949            outstanding_peer_updates: HashMap::new(),
950            unanswered_peer_updates: HashMap::new(),
951            owed_update_failures: HashSet::new(),
952            answered_peer_requests: HashSet::new(),
953            advertised_max_filter_ranges: 0,
954            peer_filter_rejections: HashMap::new(),
955            peer_request_filters: HashMap::new(),
956            track_bindings: HashMap::new(),
957            fetch_tracks: HashMap::new(),
958            malformed: Mutex::new(MalformedTracks::new()),
959            locations: Arc::new(Mutex::new(TrackLocations::new())),
960        }
961    }
962
963    /// The Track Alias the peer attached to `request_id`, once it has named
964    /// one.
965    ///
966    /// Answers for a subscription this endpoint asked for from the moment its
967    /// SUBSCRIBE_OK arrives, and for one the peer offered from the moment its
968    /// PUBLISH does. `None` before that, and for a Request ID this session has
969    /// no track for.
970    pub fn track_alias_for(&self, request_id: VarInt) -> Option<VarInt> {
971        let alias = self.track_bindings.get(&request_id.into_inner())?.alias?;
972        VarInt::from_u64(alias).ok()
973    }
974
975    /// The refusal Section 11.1 requires when `alias` already names a
976    /// different track that still has an Established subscription, or `None`
977    /// when it is free.
978    ///
979    /// # Why the set is read rather than kept
980    ///
981    /// "Established" is a subscription state Section 5.1 defines, and both
982    /// state machines here already hold it: a subscription reaches it on
983    /// SUBSCRIBE_OK and a publish on PUBLISH_OK, and each leaves it on the
984    /// message that ends the flow. Asking them is what makes an alias free
985    /// again the moment its track's subscription ends, with nothing to prune
986    /// on the way out - and a path that ended a subscription without telling
987    /// this table would otherwise leave the alias held forever and refuse the
988    /// peer's next, conforming, use of it.
989    ///
990    /// # Why the request's own binding is skipped
991    ///
992    /// A SUBSCRIBE_OK is judged before its own alias is written down, so the
993    /// skip is not what keeps it from finding itself. A PUBLISH is not: a
994    /// second PUBLISH under a Request ID already bound is refused by the
995    /// duplicate-Request-ID rule before it reaches here, and comparing a
996    /// request against its own binding would answer the wrong rule if that one
997    /// ever moved.
998    fn conflicting_track_alias(
999        &self,
1000        request_id: u64,
1001        alias: u64,
1002        namespace: &TrackNamespace,
1003        name: &[u8],
1004    ) -> Option<EndpointError> {
1005        for (&id, binding) in &self.track_bindings {
1006            if id == request_id || binding.alias != Some(alias) {
1007                continue;
1008            }
1009            if binding.namespace == *namespace && binding.name == name {
1010                continue;
1011            }
1012            if self.binding_is_established(id, binding.kind) {
1013                return Some(EndpointError::DuplicateTrackAlias {
1014                    alias,
1015                    established: id,
1016                    offered: request_id,
1017                });
1018            }
1019        }
1020        None
1021    }
1022
1023    /// The request already using `alias` for a track other than (`namespace`,
1024    /// `name`), or `None` when this endpoint may give the alias to that track.
1025    ///
1026    /// Separate from [`Self::conflicting_track_alias`] because the two answer
1027    /// different questions about the same table. That one judges a message
1028    /// that has arrived and ends the session over it; this one judges one that
1029    /// has not been built and declines to build it.
1030    fn alias_held_elsewhere(
1031        &self,
1032        alias: u64,
1033        namespace: &TrackNamespace,
1034        name: &[u8],
1035    ) -> Option<EndpointError> {
1036        self.track_bindings.iter().find_map(|(&id, binding)| {
1037            let other_track = binding.namespace != *namespace || binding.name != name;
1038            (binding.alias == Some(alias)
1039                && other_track
1040                && self.binding_is_in_use(id, binding.kind))
1041            .then_some(EndpointError::TrackAliasInUse { alias, held: id })
1042        })
1043    }
1044
1045    /// Whether a binding's request has put its alias in play at all. Broader
1046    /// than [`Self::binding_is_established`], and the two sentences are why.
1047    /// What a subscriber must close over is qualified - "the same Track Alias
1048    /// as a different Track with an Established subscription" - and the
1049    /// prohibition on the publisher is not: "The same Track Alias MUST NOT be
1050    /// used by a publisher to refer to two different Tracks simultaneously in
1051    /// the same session." Once a PUBLISH carrying an alias has been sent,
1052    /// giving that alias to a second track is what that sentence forbids,
1053    /// answered or not.
1054    fn binding_is_in_use(&self, id: u64, kind: BindingKind) -> bool {
1055        match kind {
1056            BindingKind::Subscribe => {
1057                self.subscriptions.get(&id).is_some_and(|sm| sm.state() != SubscriptionState::Done)
1058            }
1059            BindingKind::Publish => {
1060                self.publishes.get(&id).is_some_and(|sm| sm.state() != PublishState::Done)
1061            }
1062        }
1063    }
1064
1065    /// Whether the request that owns a binding still has an Established
1066    /// subscription.
1067    fn binding_is_established(&self, id: u64, kind: BindingKind) -> bool {
1068        match kind {
1069            BindingKind::Subscribe => self
1070                .subscriptions
1071                .get(&id)
1072                .is_some_and(|sm| sm.state() == SubscriptionState::Active),
1073            BindingKind::Publish => {
1074                self.publishes.get(&id).is_some_and(|sm| sm.state() == PublishState::Active)
1075            }
1076        }
1077    }
1078
1079    /// The track a live binding has given `alias` to.
1080    ///
1081    /// Read rather than kept: a binding whose request has ended holds nothing,
1082    /// and an alias that is free again may name a different track next.
1083    fn track_for_alias(&self, alias: u64) -> Option<(&TrackNamespace, &[u8])> {
1084        self.track_bindings.iter().find_map(|(&id, binding)| {
1085            (binding.alias == Some(alias) && self.binding_is_in_use(id, binding.kind))
1086                .then_some((&binding.namespace, binding.name.as_slice()))
1087        })
1088    }
1089
1090    /// Whether this endpoint *receives* the track a request names.
1091    ///
1092    /// The sentence to be answered is a subscriber's - "cancel any
1093    /// corresponding subscription or fetches for that Track from that
1094    /// publisher" - so a request that makes this endpoint the publisher is not
1095    /// one of them. A SUBSCRIBE in the table is always this endpoint's own,
1096    /// because a SUBSCRIBE the peer sends makes this endpoint the publisher and
1097    /// leaves no binding. A PUBLISH is in the table either way round, and
1098    /// Request ID parity is what separates them: the offer the peer made is the
1099    /// one this endpoint receives a track through.
1100    fn receives_through(&self, id: u64, kind: BindingKind) -> bool {
1101        match kind {
1102            BindingKind::Subscribe => true,
1103            BindingKind::Publish => self.request_ids.validate_peer_id(id).is_ok(),
1104        }
1105    }
1106
1107    /// The record a stream carrying `alias`'s objects measures them against.
1108    ///
1109    /// `None` for an alias no live binding names: an object for one breaks a
1110    /// different rule, and measuring it against a track this endpoint never
1111    /// asked for would answer that one with the wrong sentence.
1112    pub fn track_objects(&self, alias: u64) -> Option<TrackObjects> {
1113        let (namespace, name) = self.track_for_alias(alias)?;
1114        Some(TrackObjects::new(
1115            Arc::clone(&self.locations),
1116            namespace.clone(),
1117            name.to_vec(),
1118            alias,
1119        ))
1120    }
1121
1122    /// Record or judge one object that arrived outside a subgroup stream, and
1123    /// report Section 2.4.2's Malformed Track when it arrived after the place
1124    /// an end-of-track object put the end.
1125    ///
1126    /// One rule and not two. The placement rule drafts 08 through 13 state
1127    /// about an end-of-track object is not in this draft, so an object that
1128    /// ends a track here is judged against nothing and only settles where the
1129    /// track stopped.
1130    ///
1131    /// `&self`, because the call site is the data plane's.
1132    pub fn note_received_object(
1133        &self,
1134        alias: u64,
1135        at: ObjectLocation,
1136        role: ObjectRole,
1137    ) -> Result<(), EndpointError> {
1138        let Some(objects) = self.track_objects(alias) else { return Ok(()) };
1139        objects.note_past_final(at, role).map_err(|end| EndpointError::ObjectPastFinalObject {
1140            alias,
1141            group: at.group,
1142            object: at.object,
1143            final_group: end.group,
1144            final_object: end.object,
1145        })
1146    }
1147
1148    /// The condition a track was withdrawn for, or `None` for a track this
1149    /// endpoint has found nothing wrong with.
1150    ///
1151    /// # Why this takes a track and not the alias the object carried
1152    ///
1153    /// An alias only means anything through a live binding, and the withdrawal
1154    /// ends the binding it would have been resolved through. An accessor taking
1155    /// an alias would therefore answer `None` from the instant it had something
1156    /// to say. The record is keyed on the track, and so is this.
1157    pub fn malformed_track(
1158        &self,
1159        namespace: &TrackNamespace,
1160        name: &[u8],
1161    ) -> Option<MalformedTrackCondition> {
1162        self.malformed
1163            .lock()
1164            .unwrap_or_else(|poisoned| poisoned.into_inner())
1165            .condition(namespace, name)
1166    }
1167
1168    /// Note a track as malformed and name every request through which this
1169    /// endpoint is receiving it, so the caller can cancel them.
1170    ///
1171    /// **This is the whole of what this crate can do here, and the reason is
1172    /// structural rather than a shortfall.** Section 2.4.2 asks a subscriber
1173    /// that detects a Malformed Track to "cancel any corresponding subscription
1174    /// or fetches for that Track from that publisher", and on this draft
1175    /// cancelling a request means resetting the request's own bidirectional
1176    /// stream - Section 3.3.3. Every request lives at the front of a
1177    /// stream of its own, and `Connection::recv_on_request_stream` hands that
1178    /// stream to the caller as a `RequestStream`. So the stream this answer
1179    /// operates on is not the endpoint's to touch, and no amount of state here
1180    /// changes that. What the endpoint can do is say which requests they are.
1181    ///
1182    /// # Nothing here ends a request
1183    ///
1184    /// Deliberately, and it is what keeps the answer to one. The flows are read
1185    /// and not moved, so a caller that passes each id to
1186    /// `Connection::cancel_request_stream` ends the request there - and the
1187    /// binding stops being in use, so a second object past the end finds no
1188    /// track for the alias and names nothing. The request ending is still what
1189    /// closes the loop, exactly as it is on the drafts that answer with a
1190    /// message; what changed is which side ends it. A caller that ignores the
1191    /// list gets named the same requests again, which is honest: the condition
1192    /// really did fire again.
1193    ///
1194    /// # What is named, and what is not
1195    ///
1196    /// Requests through which this endpoint *receives* the track: a SUBSCRIBE
1197    /// this endpoint sent, a PUBLISH the peer sent, and a fetch this endpoint
1198    /// made. A request that makes this endpoint the publisher is not one of
1199    /// them. Empty for an alias no live binding names,
1200    /// and empty for a track whose only requests are ones this endpoint
1201    /// publishes.
1202    ///
1203    /// Sorted, because a `HashMap` iterates in no order and two requests for
1204    /// one track is a shape a peer can produce.
1205    pub fn requests_for_malformed_track(
1206        &self,
1207        alias: u64,
1208        condition: MalformedTrackCondition,
1209    ) -> Vec<VarInt> {
1210        let Some((namespace, name)) = self.track_for_alias(alias) else { return Vec::new() };
1211        let (namespace, name) = (namespace.clone(), name.to_vec());
1212        self.malformed
1213            .lock()
1214            .unwrap_or_else(|poisoned| poisoned.into_inner())
1215            .note(&namespace, &name, condition);
1216        let mut ids: Vec<u64> = self
1217            .track_bindings
1218            .iter()
1219            .filter(|(&id, binding)| {
1220                binding.namespace == namespace
1221                    && binding.name == name
1222                    && self.binding_is_in_use(id, binding.kind)
1223                    && self.receives_through(id, binding.kind)
1224            })
1225            .map(|(&id, _)| id)
1226            .chain(self.fetch_tracks.iter().filter_map(|(&id, track)| {
1227                (track.namespace == namespace
1228                    && track.name == name
1229                    && self.fetches.get(&id).is_some_and(|sm| sm.state() != FetchState::Done))
1230                .then_some(id)
1231            }))
1232            .collect();
1233        ids.sort_unstable();
1234        ids.into_iter().filter_map(|id| VarInt::from_u64(id).ok()).collect()
1235    }
1236
1237    /// The conflict a SUBSCRIBE_OK's alias has with the tracks already bound.
1238    ///
1239    /// Separate from [`Self::conflicting_track_alias`] because the track a
1240    /// SUBSCRIBE_OK is about is not in the SUBSCRIBE_OK: it is the one this
1241    /// endpoint's own SUBSCRIBE asked for, which is why the request has to be
1242    /// looked up before the alias can be judged.
1243    fn conflicting_alias_for_subscribe_ok(&self, id: u64, alias: u64) -> Option<EndpointError> {
1244        let binding = self.track_bindings.get(&id)?;
1245        self.conflicting_track_alias(id, alias, &binding.namespace, &binding.name)
1246    }
1247
1248    pub fn role(&self) -> Role {
1249        self.role
1250    }
1251
1252    /// Returns the role of the peer, which is the other one.
1253    pub fn peer_role(&self) -> Role {
1254        match self.role {
1255            Role::Client => Role::Server,
1256            Role::Server => Role::Client,
1257        }
1258    }
1259
1260    /// Hold a refused update's ending to the status the draft names, and
1261    /// retire the obligation once that ending is written.
1262    ///
1263    /// Both routes to a PUBLISH_DONE come through here. A subscription this
1264    /// endpoint accepted is ended by a response on the peer's stream; a PUBLISH
1265    /// this endpoint sent is ended on its own, which does not go through the
1266    /// response path at all. The rule is the same either way, so it is stated
1267    /// once and called twice rather than written where each route happened to
1268    /// need it.
1269    fn require_update_failure_status(
1270        &mut self,
1271        id: u64,
1272        status_code: VarInt,
1273    ) -> Result<(), EndpointError> {
1274        if !self.owed_update_failures.contains(&id) {
1275            return Ok(());
1276        }
1277        let required = PublishDoneStatusCode::UpdateFailed as u64;
1278        if status_code.into_inner() != required {
1279            return Err(EndpointError::WrongUpdateFailureStatus { request: id, required });
1280        }
1281        self.owed_update_failures.remove(&id);
1282        Ok(())
1283    }
1284
1285    /// Whether the peer has sent a REQUEST_UPDATE on this request that has not
1286    /// been answered yet.
1287    ///
1288    /// Draft-19 Section 10.9: "A subscriber can also send REQUEST_UPDATE to
1289    /// modify parameters of a subscription established with PUBLISH", and the
1290    /// receiver of one "MUST respond with exactly one REQUEST_OK or
1291    /// REQUEST_ERROR message indicating if the update was successful".
1292    ///
1293    /// Asked by the connection layer, which otherwise writes nothing on a
1294    /// stream this endpoint opened. An update the peer sent on a PUBLISH is
1295    /// the one thing on such a stream that this endpoint has to answer, and
1296    /// this is what tells it apart from a response to its own request.
1297    pub fn has_unanswered_update(&self, request_id: VarInt) -> bool {
1298        self.unanswered_peer_updates.get(&request_id.into_inner()).is_some_and(|&n| n > 0)
1299    }
1300
1301    /// Whether the request `id` names a subscription this endpoint publishes.
1302    ///
1303    /// Draft-19 Section 10.9.1 gives a refused REQUEST_UPDATE three different
1304    /// consequences and picks between them by what was being updated: "When a
1305    /// REQUEST_UPDATE is unsuccessful, the publisher MUST also terminate the
1306    /// subscription by sending a PUBLISH_DONE with error code UPDATE_FAILED.
1307    /// When a REQUEST_UPDATE fails for a FETCH, the publisher MUST reset the
1308    /// FETCH data stream. When a REQUEST_UPDATE fails for a SUBSCRIBE_NAMESPACE,
1309    /// SUBSCRIBE_TRACKS or PUBLISH_NAMESPACE, the responder MUST close the bidi
1310    /// stream (see Section 3.3.2)."
1311    ///
1312    /// Only the first of the three is a message, and only the first is owed
1313    /// here. Recording it for the other two is what would hold their streams
1314    /// open past the close the third sentence requires.
1315    ///
1316    /// Two requests leave this endpoint publishing: a SUBSCRIBE the peer sent,
1317    /// and a PUBLISH this endpoint sent. Either can carry an update from the
1318    /// other side, and either is ended by a PUBLISH_DONE written from here. A
1319    /// peer's PUBLISH is neither, because the peer is the publisher on it, and
1320    /// it is told apart by having arrived rather than been sent.
1321    fn publishes_a_subscription(&self, id: u64) -> bool {
1322        matches!(self.inbound_requests.get(&id), Some(ControlMessage::Subscribe(_)))
1323            || (self.publishes.contains_key(&id) && !self.inbound_requests.contains_key(&id))
1324    }
1325
1326    /// Whether this request's refused update still owes the peer the
1327    /// PUBLISH_DONE that ends it.
1328    ///
1329    /// Asked by the connection layer, which owns the stream that termination
1330    /// has to be written on and therefore has to know not to close it. A
1331    /// REQUEST_ERROR answering the request itself ends the exchange and takes
1332    /// the stream with it; one answering an update does not, and nothing in
1333    /// the message tells the two apart.
1334    pub fn owes_update_failure(&self, request_id: VarInt) -> bool {
1335        self.owed_update_failures.contains(&request_id.into_inner())
1336    }
1337
1338    pub fn session_state(&self) -> SessionState {
1339        self.session.state()
1340    }
1341
1342    pub fn goaway_uri(&self) -> Option<&[u8]> {
1343        self.goaway_uri.as_deref()
1344    }
1345
1346    pub fn active_subscription_count(&self) -> usize {
1347        self.subscriptions.len()
1348    }
1349
1350    pub fn active_fetch_count(&self) -> usize {
1351        self.fetches.len()
1352    }
1353
1354    pub fn active_subscribe_namespace_count(&self) -> usize {
1355        self.subscribe_namespaces.len()
1356    }
1357
1358    pub fn active_subscribe_tracks_count(&self) -> usize {
1359        self.subscribe_tracks.len()
1360    }
1361
1362    pub fn active_publish_namespace_count(&self) -> usize {
1363        self.publish_namespaces.len()
1364    }
1365
1366    pub fn active_track_status_count(&self) -> usize {
1367        self.track_statuses.len()
1368    }
1369
1370    pub fn active_publish_count(&self) -> usize {
1371        self.publishes.len()
1372    }
1373
1374    /// How many Request IDs the peer has spent on this session.
1375    ///
1376    /// Nothing here removes an entry, so this only grows. A responder that
1377    /// wants a ceiling on peer-created state has to impose one itself — see
1378    /// the note on [`receive_request_on_stream`](Self::receive_request_on_stream).
1379    pub fn peer_request_count(&self) -> usize {
1380        self.peer_request_ids.len()
1381    }
1382
1383    // -- Session lifecycle ------------------------------------------
1384
1385    pub fn connect(&mut self) -> Result<(), EndpointError> {
1386        self.session.on_connect()?;
1387        Ok(())
1388    }
1389
1390    pub fn close(&mut self) -> Result<(), EndpointError> {
1391        self.session.on_close()?;
1392        Ok(())
1393    }
1394
1395    // -- Unified SETUP ----------------------------------------------
1396
1397    /// Generate a SETUP message. Both client and server use the same message
1398    /// type; only the role (and the order of send/receive) distinguishes them.
1399    pub fn send_setup(
1400        &mut self,
1401        options: Vec<KeyValuePair>,
1402    ) -> Result<ControlMessage, EndpointError> {
1403        let msg = Setup { options };
1404        setup::validate_setup(&msg, self.role)?;
1405        self.advertised_max_request_updates = setup_varint(&msg.options, MAX_REQUEST_UPDATES);
1406        self.advertised_max_filter_ranges = setup_varint(&msg.options, MAX_FILTER_RANGES);
1407        Ok(ControlMessage::Setup(msg))
1408    }
1409
1410    /// Process an incoming SETUP message. Transitions the session to Active.
1411    pub fn receive_setup(&mut self, msg: &Setup) -> Result<(), EndpointError> {
1412        setup::validate_setup(msg, self.peer_role())?;
1413        self.session.on_setup_complete()?;
1414        Ok(())
1415    }
1416
1417    // -- GoAway -----------------------------------------------------
1418
1419    pub fn receive_goaway(&mut self, msg: &GoAway) -> Result<(), EndpointError> {
1420        // Draft-19 Section 10.4: "If a server receives a GOAWAY with a
1421        // non-zero New Session URI Length it MUST close the session with a
1422        // PROTOCOL_VIOLATION." Migration is something a server offers a
1423        // client, never the other way round, so the URI is refused here rather
1424        // than stored and later followed.
1425        if self.role == Role::Server && !msg.new_session_uri.is_empty() {
1426            return Err(self.fail_session(EndpointError::GoAwayUriAtServer));
1427        }
1428        // Draft-19 Section 10.4: "The endpoint MUST close the session with a
1429        // PROTOCOL_VIOLATION (Section 3.5) if it receives more than one GOAWAY on the
1430        // control stream or on a single request stream." Draining is reached
1431        // from nowhere else - `on_goaway` is its only entry and this method is
1432        // that method's only caller - so the session state is the record of
1433        // the first GOAWAY having arrived. This is the control-stream half;
1434        // the per-stream half is in `receive_goaway_on_request_stream`.
1435        if self.session.state() == SessionState::Draining {
1436            return Err(self.fail_session(EndpointError::RepeatedGoAway));
1437        }
1438        self.session.on_goaway()?;
1439        self.goaway_uri = Some(msg.new_session_uri.clone());
1440        Ok(())
1441    }
1442
1443    /// Record that the session is over because the peer broke a rule the draft
1444    /// answers with a session close, and hand the error back unchanged.
1445    ///
1446    /// The state move is what makes the violation stick: every request entry
1447    /// point goes through [`require_active_or_err`](Self::require_active_or_err),
1448    /// so a caller that ignores the returned error still cannot start anything
1449    /// new. The close on the wire is the connection layer's job — see
1450    /// [`EndpointError::session_error_code`] for the code it should use.
1451    fn fail_session(&mut self, err: EndpointError) -> EndpointError {
1452        // `on_close` accepts SetupExchange, Active and Draining. A violation
1453        // seen in Connecting or Closed leaves the state machine alone: there
1454        // is no session to close, and the error itself is still the answer.
1455        //
1456        // SetupExchange is in that set because the Termination section says
1457        // "The Transport Session can be terminated at any point", and the
1458        // Setup exchange is a point. So a violation caught while the setup is
1459        // still in flight does close the session rather than being recorded
1460        // and forgotten, which is what this discarded result used to mean.
1461        let _ = self.session.on_close();
1462        err
1463    }
1464
1465    fn require_active_or_err(&self) -> Result<(), EndpointError> {
1466        match self.session.state() {
1467            SessionState::Active => Ok(()),
1468            SessionState::Draining => Err(EndpointError::Draining),
1469            _ => Err(EndpointError::NotActive),
1470        }
1471    }
1472
1473    // -- Subscribe flow ---------------------------------------------
1474
1475    pub fn subscribe(
1476        &mut self,
1477        track_namespace: TrackNamespace,
1478        track_name: Vec<u8>,
1479        parameters: Vec<KeyValuePair>,
1480    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1481        self.require_active_or_err()?;
1482        let req_id = self.request_ids.allocate()?;
1483
1484        let mut sm = SubscriptionStateMachine::new();
1485        sm.on_subscribe_sent()?;
1486        self.subscriptions.insert(req_id.into_inner(), sm);
1487        // The track is recorded here because this is the only place it is
1488        // known: a SUBSCRIBE_OK names an alias and not the track it is for.
1489        self.track_bindings.insert(
1490            req_id.into_inner(),
1491            TrackBinding {
1492                namespace: track_namespace.clone(),
1493                name: track_name.clone(),
1494                alias: None,
1495                kind: BindingKind::Subscribe,
1496            },
1497        );
1498
1499        let msg = ControlMessage::Subscribe(Subscribe {
1500            request_id: req_id,
1501            track_namespace,
1502            track_name,
1503            parameters,
1504        });
1505        Ok((req_id, msg))
1506    }
1507
1508    /// Process an incoming SUBSCRIBE_OK. Draft-19: no request_id on wire; the
1509    /// caller supplies the `request_id` of the bidi stream on which the
1510    /// response arrived.
1511    pub fn receive_subscribe_ok(
1512        &mut self,
1513        request_id: VarInt,
1514        msg: &SubscribeOk,
1515    ) -> Result<(), EndpointError> {
1516        let id = request_id.into_inner();
1517        if !self.subscriptions.contains_key(&id) {
1518            return Err(EndpointError::UnknownRequest(id));
1519        }
1520        let alias = msg.track_alias.into_inner();
1521        // Judged before the transition, so that the subscription this message
1522        // is about is not yet Established and cannot be found as its own
1523        // conflict, and so that a refused SUBSCRIBE_OK leaves no alias behind.
1524        if let Some(conflict) = self.conflicting_alias_for_subscribe_ok(id, alias) {
1525            return Err(self.fail_session(conflict));
1526        }
1527        let sm = self.subscriptions.get_mut(&id).expect("checked above");
1528        sm.on_subscribe_ok()?;
1529        if let Some(binding) = self.track_bindings.get_mut(&id) {
1530            binding.alias = Some(alias);
1531        }
1532        Ok(())
1533    }
1534
1535    /// Take one of the REQUEST_UPDATE credits this endpoint advertised for
1536    /// `id`'s stream.
1537    ///
1538    /// Section 10.3.1.7 puts the limit on the number *outstanding*, so the
1539    /// count is a running balance rather than a total: it goes up on each
1540    /// REQUEST_UPDATE received and down on each REQUEST_OK or REQUEST_ERROR
1541    /// this endpoint writes back, and a peer that keeps pace never reaches the
1542    /// ceiling however many updates it sends.
1543    ///
1544    /// # Errors
1545    ///
1546    /// [`EndpointError::TooManyRequestUpdates`], which answers
1547    /// `Some(TooManyRequestUpdates)` - its own close code, not the general
1548    /// PROTOCOL_VIOLATION - and the session is failed before it returns.
1549    fn spend_update_credit(&mut self, id: u64) -> Result<(), EndpointError> {
1550        let limit = self.advertised_max_request_updates;
1551        if limit == 0 {
1552            return Ok(());
1553        }
1554        let outstanding = self.outstanding_peer_updates.entry(id).or_insert(0);
1555        if *outstanding >= limit {
1556            return Err(self.fail_session(EndpointError::TooManyRequestUpdates(id, limit)));
1557        }
1558        *outstanding += 1;
1559        Ok(())
1560    }
1561
1562    /// Give back the credit a REQUEST_OK or REQUEST_ERROR restores.
1563    ///
1564    /// Called for every response this endpoint writes, whether or not the
1565    /// stream ever carried an update: a stream with no outstanding updates has
1566    /// nothing to restore and the saturating subtraction says so, which is
1567    /// cheaper than deciding first whether the response is answering an update
1568    /// or the original request.
1569    fn restore_update_credit(&mut self, id: u64) {
1570        if let Some(outstanding) = self.outstanding_peer_updates.get_mut(&id) {
1571            *outstanding = outstanding.saturating_sub(1);
1572        }
1573    }
1574
1575    /// Process a REQUEST_UPDATE that arrived on the bidi request stream
1576    /// identified by `request_id`.
1577    ///
1578    /// Draft-19 Section 10.9: "The sender of a request (SUBSCRIBE, PUBLISH,
1579    /// FETCH, PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS) can
1580    /// later send a REQUEST_UPDATE on the same bidi stream as the request to
1581    /// modify it. A subscriber can also send REQUEST_UPDATE to modify
1582    /// parameters of a subscription established with PUBLISH." Anything else
1583    /// "MUST close the session with a PROTOCOL_VIOLATION", which is what
1584    /// [`EndpointError::UnexpectedRequestUpdate`] carries — TRACK_STATUS most
1585    /// of all, since Section 10.14 says outright that "the subscriber cannot
1586    /// send REQUEST_UPDATE".
1587    ///
1588    /// The message carries a Request ID of its own and the stream carries one
1589    /// too. They name the same request when the peer is conforming; a
1590    /// disagreement means the update was sent on a stream that is not its
1591    /// request's, which is the same violation, so it is refused rather than
1592    /// silently resolved to one of the two.
1593    ///
1594    /// Only SUBSCRIBE-established subscriptions have a state-machine event for
1595    /// this. That is not an omission: an update changes a request's parameters
1596    /// and not its lifecycle, so for the other five kinds the update is a
1597    /// self-transition with nothing to record.
1598    pub fn receive_request_update(
1599        &mut self,
1600        request_id: VarInt,
1601        msg: &RequestUpdate,
1602    ) -> Result<(), EndpointError> {
1603        let id = request_id.into_inner();
1604        if msg.request_id.into_inner() != id {
1605            return Err(self.fail_session(EndpointError::UnexpectedRequestUpdate(
1606                msg.request_id.into_inner(),
1607            )));
1608        }
1609        self.spend_update_credit(id)?;
1610        // The two cases are about who is sending, and only one of them is
1611        // about which request. Case one is the peer updating a request the
1612        // peer made, whatever its kind; case two is a subscriber updating a
1613        // subscription this endpoint established with PUBLISH. A SUBSCRIBE, a
1614        // FETCH or a namespace request this endpoint made is in neither, and
1615        // an update on one is a violation rather than a request to apply.
1616        //
1617        // They are not symmetrical about timing either. Case one allows an
1618        // update "later" and says nothing about the answer, so a request of
1619        // the peer's may be updated before this endpoint has answered it.
1620        // Case two rests on the subscription existing, and Section 5.1 says
1621        // when it does: "Once either of these sequences is successful, the
1622        // subscription moves to the Established state and can be updated by
1623        // the subscriber using REQUEST_UPDATE." A PUBLISH still waiting for
1624        // its answer is Pending, and an update on one is outside both cases.
1625        //
1626        // Checked before the state machine below moves, so a session that is
1627        // closing does not leave a subscription updated on the way out.
1628        let one_of_the_two_cases = self.inbound_requests.contains_key(&id)
1629            || self.binding_is_established(id, BindingKind::Publish);
1630        if !one_of_the_two_cases {
1631            return Err(self.fail_session(EndpointError::UnexpectedRequestUpdate(id)));
1632        }
1633        let updatable = if let Some(sm) = self.subscriptions.get_mut(&id) {
1634            sm.on_subscribe_update()?;
1635            true
1636        } else {
1637            self.publishes.contains_key(&id)
1638                || self.fetches.contains_key(&id)
1639                || self.subscribe_namespaces.contains_key(&id)
1640                || self.subscribe_tracks.contains_key(&id)
1641                || self.publish_namespaces.contains_key(&id)
1642        };
1643        if !updatable {
1644            return Err(self.fail_session(EndpointError::UnexpectedRequestUpdate(id)));
1645        }
1646        *self.unanswered_peer_updates.entry(id).or_insert(0) += 1;
1647
1648        // The ceiling is on what the request carries after the update, so the
1649        // update is merged into the set in force and the whole set measured.
1650        // Recorded rather than refused for the reason the request itself is:
1651        // the answer is a REQUEST_ERROR, which names a Request ID.
1652        let mut in_force = self.peer_request_filters.remove(&id).unwrap_or_default();
1653        apply_filter_update(&mut in_force, &msg.parameters);
1654        if let Some(rejection) = self.filter_verdict(&in_force) {
1655            self.peer_filter_rejections.insert(id, rejection);
1656        }
1657        self.peer_request_filters.insert(id, in_force);
1658
1659        // Section 10.9.2 gives an update one thing to move that no draft before
1660        // this one lets a request change: "A subscriber can update the Track
1661        // Namespace Prefix of an established SUBSCRIBE_NAMESPACE or
1662        // SUBSCRIBE_TRACKS by including the TRACK_NAMESPACE_PREFIX parameter
1663        // (Section 10.2.19) in a REQUEST_UPDATE."
1664        //
1665        // The two kinds keep their own ground -- "The overlap restriction
1666        // applies independently per type" -- so which set the new prefix is
1667        // weighed against is decided by what the peer opened the stream with.
1668        //
1669        // A request of any other kind has no prefix for the parameter to move,
1670        // and nothing in this draft says what to do with the parameter when it
1671        // turns up on one, so it is left alone rather than guessed at.
1672        if let Some(prefix) = updated_prefix(&msg.parameters) {
1673            let namespace = matches!(
1674                self.inbound_requests.get(&id),
1675                Some(ControlMessage::SubscribeNamespace(_))
1676            );
1677            let tracks =
1678                matches!(self.inbound_requests.get(&id), Some(ControlMessage::SubscribeTracks(_)));
1679            if namespace || tracks {
1680                let collides = if tracks {
1681                    self.peer_tracks_overlap(&prefix, Some(id))
1682                } else {
1683                    self.peer_namespace_overlap(&prefix, Some(id))
1684                };
1685                match collides {
1686                    Some(established) => {
1687                        self.overlapping_prefix_updates.insert(id, established);
1688                    }
1689                    // A later update clears an earlier one's verdict along with
1690                    // its prefix, which is what a receiver "applying only the
1691                    // cumulative result" is entitled to do.
1692                    None => {
1693                        self.overlapping_prefix_updates.remove(&id);
1694                    }
1695                }
1696                self.updated_namespace_prefixes.insert(id, prefix);
1697            }
1698        }
1699        Ok(())
1700    }
1701
1702    pub fn receive_publish_done(
1703        &mut self,
1704        request_id: VarInt,
1705        _msg: &PublishDone,
1706    ) -> Result<(), EndpointError> {
1707        let id = request_id.into_inner();
1708        let sm = self.subscriptions.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
1709        sm.on_publish_done()?;
1710        Ok(())
1711    }
1712
1713    // -- Fetch flow -------------------------------------------------
1714
1715    /// `parameters` are the request's own, as they are on every other request
1716    /// this endpoint makes. FETCH carried an empty list on all five of these
1717    /// drafts while SUBSCRIBE, TRACK_STATUS, PUBLISH_NAMESPACE and PUBLISH
1718    /// took the caller's, which made it the only one an application could not
1719    /// attach an authorization token to.
1720    #[allow(clippy::too_many_arguments)]
1721    pub fn fetch(
1722        &mut self,
1723        track_namespace: TrackNamespace,
1724        track_name: Vec<u8>,
1725        start_group: VarInt,
1726        start_object: VarInt,
1727        end_group: VarInt,
1728        end_object: VarInt,
1729        parameters: Vec<KeyValuePair>,
1730    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1731        self.require_active_or_err()?;
1732        let req_id = self.request_ids.allocate()?;
1733
1734        let mut sm = FetchStateMachine::new();
1735        sm.on_fetch_sent()?;
1736        self.fetches.insert(req_id.into_inner(), sm);
1737        // Before the two of them are moved into the message below: a fetch
1738        // that has left no track behind is one no withdrawal can name.
1739        self.fetch_tracks.insert(
1740            req_id.into_inner(),
1741            FetchTrack { namespace: track_namespace.clone(), name: track_name.clone() },
1742        );
1743
1744        let msg = ControlMessage::Fetch(Fetch {
1745            request_id: req_id,
1746            fetch_type: FetchType::Standalone,
1747            fetch_payload: FetchPayload::Standalone {
1748                track_namespace,
1749                track_name,
1750                start_group,
1751                start_object,
1752                end_group,
1753                end_object,
1754            },
1755            parameters,
1756        });
1757        Ok((req_id, msg))
1758    }
1759
1760    /// Send a Relative Joining Fetch (Fetch Type 0x2).
1761    ///
1762    /// `joining_start` counts groups back from the subscription's Largest
1763    /// Group. To name the group directly, use
1764    /// [`absolute_joining_fetch`](Self::absolute_joining_fetch).
1765    ///
1766    /// `parameters` are the request's own, as they are on every other request
1767    /// this endpoint makes.
1768    pub fn joining_fetch(
1769        &mut self,
1770        joining_request_id: VarInt,
1771        joining_start: VarInt,
1772        parameters: Vec<KeyValuePair>,
1773    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1774        self.joining_fetch_of_type(
1775            FetchType::RelativeJoining,
1776            joining_request_id,
1777            joining_start,
1778            parameters,
1779        )
1780    }
1781
1782    /// Send an Absolute Joining Fetch (Fetch Type 0x3).
1783    ///
1784    /// Draft-19 Section 10.12.2.1: "For an Absolute Joining Fetch, the
1785    /// publisher sets the Start Location to {Joining Start, 0}." So
1786    /// `joining_start` is the group to begin at, not an offset — which is what
1787    /// an application that knows the group it wants actually has. Expressing
1788    /// it as a relative fetch would need the Largest Group, which the
1789    /// subscriber may not know.
1790    pub fn absolute_joining_fetch(
1791        &mut self,
1792        joining_request_id: VarInt,
1793        joining_start: VarInt,
1794        parameters: Vec<KeyValuePair>,
1795    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1796        self.joining_fetch_of_type(
1797            FetchType::AbsoluteJoining,
1798            joining_request_id,
1799            joining_start,
1800            parameters,
1801        )
1802    }
1803
1804    fn joining_fetch_of_type(
1805        &mut self,
1806        fetch_type: FetchType,
1807        joining_request_id: VarInt,
1808        joining_start: VarInt,
1809        parameters: Vec<KeyValuePair>,
1810    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1811        self.require_active_or_err()?;
1812        let req_id = self.request_ids.allocate()?;
1813
1814        let mut sm = FetchStateMachine::new();
1815        sm.on_fetch_sent()?;
1816        self.fetches.insert(req_id.into_inner(), sm);
1817        // Resolved through the join, once, here. A Joining Fetch names no
1818        // track; the publisher takes the Track Namespace and Track Name from
1819        // the subscription it names, so that is the track. A Request ID this
1820        // session holds no track for leaves the fetch out of the record
1821        // entirely rather than putting a guess in it.
1822        if let Some(binding) = self.track_bindings.get(&joining_request_id.into_inner()) {
1823            let track =
1824                FetchTrack { namespace: binding.namespace.clone(), name: binding.name.clone() };
1825            self.fetch_tracks.insert(req_id.into_inner(), track);
1826        }
1827
1828        let msg = ControlMessage::Fetch(Fetch {
1829            request_id: req_id,
1830            fetch_type,
1831            fetch_payload: FetchPayload::Joining { joining_request_id, joining_start },
1832            parameters,
1833        });
1834        Ok((req_id, msg))
1835    }
1836
1837    pub fn receive_fetch_ok(
1838        &mut self,
1839        request_id: VarInt,
1840        _msg: &message::FetchOk,
1841    ) -> Result<(), EndpointError> {
1842        let id = request_id.into_inner();
1843        let sm = self.fetches.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
1844        sm.on_fetch_ok()?;
1845        Ok(())
1846    }
1847
1848    pub fn on_fetch_stream_fin(&mut self, request_id: VarInt) -> Result<(), EndpointError> {
1849        let id = request_id.into_inner();
1850        let sm = self.fetches.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
1851        sm.on_stream_fin()?;
1852        Ok(())
1853    }
1854
1855    pub fn on_fetch_stream_reset(&mut self, request_id: VarInt) -> Result<(), EndpointError> {
1856        let id = request_id.into_inner();
1857        let sm = self.fetches.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
1858        sm.on_stream_reset()?;
1859        Ok(())
1860    }
1861
1862    // -- Subscribe Namespace flow -----------------------------------
1863
1864    pub fn subscribe_namespace(
1865        &mut self,
1866        namespace_prefix: TrackNamespace,
1867        parameters: Vec<KeyValuePair>,
1868    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1869        self.require_active_or_err()?;
1870        let req_id = self.request_ids.allocate()?;
1871
1872        let mut sm = SubscribeNamespaceStateMachine::new();
1873        sm.on_subscribe_namespace_sent()?;
1874        self.subscribe_namespaces.insert(req_id.into_inner(), sm);
1875
1876        let msg = ControlMessage::SubscribeNamespace(SubscribeNamespace {
1877            request_id: req_id,
1878            namespace_prefix,
1879            parameters,
1880        });
1881        Ok((req_id, msg))
1882    }
1883
1884    // -- Subscribe Tracks flow (new in draft-18) --------------------
1885
1886    pub fn subscribe_tracks(
1887        &mut self,
1888        namespace_prefix: TrackNamespace,
1889        parameters: Vec<KeyValuePair>,
1890    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1891        self.require_active_or_err()?;
1892        let req_id = self.request_ids.allocate()?;
1893
1894        // Reuse the SubscribeNamespace state machine — the lifecycle is the
1895        // same (request → ok/error → done) and adding a parallel state
1896        // machine purely to disambiguate would be churn.
1897        let mut sm = SubscribeNamespaceStateMachine::new();
1898        sm.on_subscribe_namespace_sent()?;
1899        self.subscribe_tracks.insert(req_id.into_inner(), sm);
1900
1901        let msg = ControlMessage::SubscribeTracks(SubscribeTracks {
1902            request_id: req_id,
1903            namespace_prefix,
1904            parameters,
1905        });
1906        Ok((req_id, msg))
1907    }
1908
1909    // -- Publish Namespace flow -------------------------------------
1910
1911    pub fn publish_namespace(
1912        &mut self,
1913        track_namespace: TrackNamespace,
1914        parameters: Vec<KeyValuePair>,
1915    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1916        self.require_active_or_err()?;
1917        let req_id = self.request_ids.allocate()?;
1918
1919        let mut sm = PublishNamespaceStateMachine::new();
1920        sm.on_publish_namespace_sent()?;
1921        self.publish_namespaces.insert(req_id.into_inner(), sm);
1922
1923        let msg = ControlMessage::PublishNamespace(PublishNamespace {
1924            request_id: req_id,
1925            track_namespace,
1926            parameters,
1927        });
1928        Ok((req_id, msg))
1929    }
1930
1931    // -- Track Status flow ------------------------------------------
1932
1933    pub fn track_status(
1934        &mut self,
1935        track_namespace: TrackNamespace,
1936        track_name: Vec<u8>,
1937        parameters: Vec<KeyValuePair>,
1938    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1939        self.require_active_or_err()?;
1940        let req_id = self.request_ids.allocate()?;
1941        let mut sm = TrackStatusStateMachine::new();
1942        sm.on_track_status_sent()?;
1943        self.track_statuses.insert(req_id.into_inner(), sm);
1944
1945        let msg = ControlMessage::TrackStatus(message::TrackStatus {
1946            request_id: req_id,
1947            track_namespace,
1948            track_name,
1949            parameters,
1950        });
1951        Ok((req_id, msg))
1952    }
1953
1954    // -- Publish flow (publisher side) ------------------------------
1955
1956    pub fn publish(
1957        &mut self,
1958        track_namespace: TrackNamespace,
1959        track_name: Vec<u8>,
1960        track_alias: VarInt,
1961        parameters: Vec<KeyValuePair>,
1962        track_properties: Vec<KeyValuePair>,
1963    ) -> Result<(VarInt, ControlMessage), EndpointError> {
1964        self.require_active_or_err()?;
1965        // Section 11.1: "The same Track Alias MUST NOT be used by a publisher to refer to
1966        // two different Tracks simultaneously in the same session." Refused before the
1967        // Request ID is allocated, so a refusal spends nothing.
1968        let alias = track_alias.into_inner();
1969        if let Some(refusal) = self.alias_held_elsewhere(alias, &track_namespace, &track_name) {
1970            return Err(refusal);
1971        }
1972        let req_id = self.request_ids.allocate()?;
1973        let mut sm = PublishStateMachine::new();
1974        sm.on_publish_sent()?;
1975        self.publishes.insert(req_id.into_inner(), sm);
1976        // The alias and the track travel together in a PUBLISH, so the binding
1977        // is complete the moment the message is built.
1978        self.track_bindings.insert(
1979            req_id.into_inner(),
1980            TrackBinding {
1981                namespace: track_namespace.clone(),
1982                name: track_name.clone(),
1983                alias: Some(alias),
1984                kind: BindingKind::Publish,
1985            },
1986        );
1987
1988        let msg = ControlMessage::Publish(Publish {
1989            request_id: req_id,
1990            track_namespace,
1991            track_name,
1992            track_alias,
1993            parameters,
1994            track_properties,
1995        });
1996        Ok((req_id, msg))
1997    }
1998
1999    pub fn send_publish_done(
2000        &mut self,
2001        request_id: VarInt,
2002        status_code: VarInt,
2003        stream_count: VarInt,
2004        reason_phrase: Vec<u8>,
2005    ) -> Result<ControlMessage, EndpointError> {
2006        let id = request_id.into_inner();
2007        // Before the state machine moves, so an ending under the wrong status
2008        // leaves the publication where it was. A PUBLISH this endpoint sent is
2009        // ended here rather than through the response path, and a refused
2010        // update on it owes the same ending as one on a peer's SUBSCRIBE.
2011        self.require_update_failure_status(id, status_code)?;
2012        let sm = self.publishes.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
2013        sm.on_publish_done_sent()?;
2014        Ok(ControlMessage::PublishDone(PublishDone { status_code, stream_count, reason_phrase }))
2015    }
2016
2017    // -- Consolidated responses (per-bidi-stream routing) -----------
2018
2019    /// Process an incoming REQUEST_OK on the bidi stream identified by
2020    /// `request_id`. Draft-19: PUBLISH_OK is a REQUEST_OK alias, so this
2021    /// handler also resolves outstanding PUBLISH requests.
2022    ///
2023    /// # Track Properties are refused except on TRACK_STATUS_OK
2024    ///
2025    /// Draft-19 Section 10.5: Track Properties "are populated in
2026    /// TRACK_STATUS_OK; they are empty in PUBLISH_OK, REQUEST_UPDATE_OK,
2027    /// SUBSCRIBE_NAMESPACE_OK and PUBLISH_NAMESPACE_OK. If an endpoint
2028    /// receives Track Properties in one of these messages it MUST close the
2029    /// session with a PROTOCOL_VIOLATION." The codec cannot make that check —
2030    /// REQUEST_OK is one wire form and only the request stream says which of
2031    /// the five shapes it is. This is the layer that knows, because finding
2032    /// the request id in one of the maps below is what names the shape.
2033    pub fn receive_request_ok(
2034        &mut self,
2035        request_id: VarInt,
2036        msg: &RequestOk,
2037    ) -> Result<(), EndpointError> {
2038        let id = request_id.into_inner();
2039        if !msg.track_properties.is_empty() && !self.track_statuses.contains_key(&id) {
2040            return Err(self.fail_session(EndpointError::TrackPropertiesOnNonTrackStatus(id)));
2041        }
2042        if let Some(sm) = self.publishes.get_mut(&id) {
2043            sm.on_publish_ok()?;
2044            return Ok(());
2045        }
2046        if let Some(sm) = self.subscribe_namespaces.get_mut(&id) {
2047            sm.on_subscribe_namespace_ok()?;
2048            return Ok(());
2049        }
2050        if let Some(sm) = self.subscribe_tracks.get_mut(&id) {
2051            sm.on_subscribe_namespace_ok()?;
2052            return Ok(());
2053        }
2054        if let Some(sm) = self.publish_namespaces.get_mut(&id) {
2055            sm.on_publish_namespace_ok()?;
2056            return Ok(());
2057        }
2058        if let Some(sm) = self.track_statuses.get_mut(&id) {
2059            sm.on_track_status_ok()?;
2060            return Ok(());
2061        }
2062        Err(EndpointError::UnknownRequest(id))
2063    }
2064
2065    /// Process an incoming REQUEST_ERROR on the bidi stream identified by
2066    /// `request_id`.
2067    pub fn receive_request_error(
2068        &mut self,
2069        request_id: VarInt,
2070        msg: &RequestError,
2071    ) -> Result<(), EndpointError> {
2072        let id = request_id.into_inner();
2073        if let Some(redirect) = &msg.redirect {
2074            // Draft-19 Section 10.6.1: "If a server receives a Redirect with a
2075            // non-zero Connect URI Length it MUST close the session with a
2076            // PROTOCOL_VIOLATION." Left unchecked, a Redirect sends a server
2077            // chasing a URI a client picked.
2078            if self.role == Role::Server && !redirect.connect_uri.is_empty() {
2079                return Err(self.fail_session(EndpointError::RedirectUriAtServer));
2080            }
2081            // Same section: "Track Name is not meaningful for namespace-scoped
2082            // requests (SUBSCRIBE_NAMESPACE, PUBLISH_NAMESPACE,
2083            // SUBSCRIBE_TRACKS) and MUST be empty; an endpoint that receives a
2084            // non-empty Track Name in a Redirect for a namespace-scoped request
2085            // MUST close the session with a PROTOCOL_VIOLATION." Which request
2086            // this answers is known only here, from the map the stream's id is
2087            // in.
2088            let namespace_scoped = self.subscribe_namespaces.contains_key(&id)
2089                || self.subscribe_tracks.contains_key(&id)
2090                || self.publish_namespaces.contains_key(&id);
2091            if namespace_scoped && !redirect.track_name.is_empty() {
2092                return Err(
2093                    self.fail_session(EndpointError::RedirectTrackNameOnNamespaceRequest(id))
2094                );
2095            }
2096        }
2097        if let Some(sm) = self.subscriptions.get_mut(&id) {
2098            sm.on_subscribe_error()?;
2099            return Ok(());
2100        }
2101        if let Some(sm) = self.fetches.get_mut(&id) {
2102            sm.on_fetch_error()?;
2103            return Ok(());
2104        }
2105        if let Some(sm) = self.publishes.get_mut(&id) {
2106            sm.on_publish_error()?;
2107            return Ok(());
2108        }
2109        if let Some(sm) = self.subscribe_namespaces.get_mut(&id) {
2110            sm.on_subscribe_namespace_error()?;
2111            return Ok(());
2112        }
2113        if let Some(sm) = self.subscribe_tracks.get_mut(&id) {
2114            sm.on_subscribe_namespace_error()?;
2115            return Ok(());
2116        }
2117        if let Some(sm) = self.publish_namespaces.get_mut(&id) {
2118            sm.on_publish_namespace_error()?;
2119            return Ok(());
2120        }
2121        if let Some(sm) = self.track_statuses.get_mut(&id) {
2122            sm.on_track_status_error()?;
2123            return Ok(());
2124        }
2125        Err(EndpointError::UnknownRequest(id))
2126    }
2127
2128    /// Record that a request was cancelled at its stream.
2129    ///
2130    /// This draft withdraws a request by terminating the bidirectional stream
2131    /// it was made on rather than by sending a message. Section 3.3.3: "Once
2132    /// a request stream has been opened, the request MAY be cancelled by either
2133    /// endpoint. Senders cancel requests if the response is no longer of
2134    /// interest; Receivers cancel requests if they are unable to or choose not
2135    /// to respond."
2136    ///
2137    /// Both of those reach here. A request the peer opened and one this
2138    /// endpoint opened share a map and cannot collide, because their Request
2139    /// IDs have opposite least significant bits, so one method records a cancel
2140    /// from whichever side performed it.
2141    ///
2142    /// The request moves to its end state, which is what makes the record worth
2143    /// keeping: a response arriving afterwards is refused rather than applied to
2144    /// a request that is over. The Request ID is not released — nothing here
2145    /// reuses one — and the per-request bookkeeping keyed by it is left alone,
2146    /// since a cancelled request's stream carries nothing more.
2147    ///
2148    /// Nothing is written on the wire. The reset that goes with this is
2149    /// [`Connection::cancel_request_stream`], which calls this first and
2150    /// terminates the stream only if it returns `Ok`.
2151    ///
2152    /// # Errors
2153    ///
2154    /// [`EndpointError::UnknownRequest`] when no request of any kind carries
2155    /// that id, and the kind's own `InvalidTransition` when the request has not
2156    /// been written yet.
2157    ///
2158    /// [`Connection::cancel_request_stream`]: crate::draft19::connection::Connection::cancel_request_stream
2159    pub fn cancel_request(&mut self, request_id: VarInt) -> Result<(), EndpointError> {
2160        let id = request_id.into_inner();
2161        if let Some(sm) = self.subscriptions.get_mut(&id) {
2162            sm.on_request_cancelled()?;
2163            return Ok(());
2164        }
2165        if let Some(sm) = self.fetches.get_mut(&id) {
2166            sm.on_request_cancelled()?;
2167            return Ok(());
2168        }
2169        if let Some(sm) = self.publishes.get_mut(&id) {
2170            sm.on_request_cancelled()?;
2171            return Ok(());
2172        }
2173        if let Some(sm) = self.subscribe_namespaces.get_mut(&id) {
2174            sm.on_request_cancelled()?;
2175            return Ok(());
2176        }
2177        if let Some(sm) = self.subscribe_tracks.get_mut(&id) {
2178            sm.on_request_cancelled()?;
2179            return Ok(());
2180        }
2181        if let Some(sm) = self.publish_namespaces.get_mut(&id) {
2182            sm.on_request_cancelled()?;
2183            return Ok(());
2184        }
2185        if let Some(sm) = self.track_statuses.get_mut(&id) {
2186            sm.on_request_cancelled()?;
2187            return Ok(());
2188        }
2189        Err(EndpointError::UnknownRequest(id))
2190    }
2191
2192    // -- PublishSkipped / Namespace announcements -------------------
2193
2194    pub fn receive_namespace(&mut self, _msg: &message::Namespace) -> Result<(), EndpointError> {
2195        Ok(())
2196    }
2197
2198    pub fn receive_namespace_done(
2199        &mut self,
2200        _msg: &message::NamespaceDone,
2201    ) -> Result<(), EndpointError> {
2202        Ok(())
2203    }
2204
2205    pub fn receive_publish_skipped(&mut self, _msg: &PublishSkipped) -> Result<(), EndpointError> {
2206        Ok(())
2207    }
2208
2209    // -- Unified message dispatch -----------------------------------
2210
2211    /// Dispatch a message that arrived on the control stream.
2212    ///
2213    /// Draft-19 Table 5 gives every message a Stream value, and only two of
2214    /// them name the control stream: SETUP is "Control", GOAWAY is "Control,
2215    /// Request". Everything else is "Request", so this method's job is to take
2216    /// those two and refuse the messages that identify a request they have no
2217    /// stream to name.
2218    ///
2219    /// Four are refused for that reason. REQUEST_UPDATE modifies the request
2220    /// its stream carries (Section 10.9). NAMESPACE and NAMESPACE_DONE report
2221    /// namespaces on the SUBSCRIBE_NAMESPACE request stream that asked for them
2222    /// (Sections 10.16 and 10.17), and PUBLISH_SKIPPED names a track that will
2223    /// not be published on the SUBSCRIBE_TRACKS stream that asked for it
2224    /// (Section 10.20). All four route through
2225    /// [`receive_response_on_stream`](Self::receive_response_on_stream), which
2226    /// has the request ID they need.
2227    pub fn receive_message(&mut self, msg: ControlMessage) -> Result<(), EndpointError> {
2228        match msg {
2229            ControlMessage::Setup(ref m) => self.receive_setup(m),
2230            ControlMessage::GoAway(ref m) => self.receive_goaway(m),
2231            ControlMessage::RequestUpdate(_) => {
2232                Err(self.fail_session(EndpointError::RequestUpdateOnControlStream))
2233            }
2234            ControlMessage::Namespace(_) => {
2235                Err(self.fail_session(EndpointError::RequestMessageOnControlStream("NAMESPACE")))
2236            }
2237            ControlMessage::NamespaceDone(_) => {
2238                Err(self
2239                    .fail_session(EndpointError::RequestMessageOnControlStream("NAMESPACE_DONE")))
2240            }
2241            ControlMessage::PublishSkipped(_) => {
2242                Err(self
2243                    .fail_session(EndpointError::RequestMessageOnControlStream("PUBLISH_SKIPPED")))
2244            }
2245            ControlMessage::SubscribeOk(_)
2246            | ControlMessage::PublishDone(_)
2247            | ControlMessage::FetchOk(_)
2248            | ControlMessage::RequestOk(_)
2249            | ControlMessage::RequestError(_) => Err(EndpointError::ResponseOnControlStream),
2250            _ => Ok(()),
2251        }
2252    }
2253
2254    /// Hold the response half of a namespace-scoped request to the rule that
2255    /// its first message answers the request.
2256    ///
2257    /// Sections 10.18 and 10.19 state it once each, for SUBSCRIBE_NAMESPACE
2258    /// and for SUBSCRIBE_TRACKS: "The publisher will respond with REQUEST_OK or
2259    /// REQUEST_ERROR on the response half of the stream. If the subscriber
2260    /// receives any message other than a REQUEST_OK or a REQUEST_ERROR as the
2261    /// first message on the response half of the stream, then it MUST close the
2262    /// session with a PROTOCOL_VIOLATION." Draft-18's own change log records it
2263    /// as new work rather than as a clarification, so drafts 17 and earlier are
2264    /// deliberately not held to it: they say nothing about which message comes
2265    /// first, and refusing one there would close a session over traffic those
2266    /// drafts permit.
2267    ///
2268    /// # Why only these two requests
2269    ///
2270    /// They are the two whose response half carries more than an answer.
2271    /// SUBSCRIBE_NAMESPACE goes on to carry NAMESPACE and NAMESPACE_DONE and
2272    /// SUBSCRIBE_TRACKS goes on to carry PUBLISH_SKIPPED, and those are exactly the
2273    /// messages that could arrive before the answer and be taken for it. A
2274    /// SUBSCRIBE has SUBSCRIBE_OK as its own first message and no such
2275    /// ambiguity, which is why the rule is written where it is.
2276    ///
2277    /// # What "first" is read from
2278    ///
2279    /// The request's own state machine. `Pending` means the request went out
2280    /// and nothing has come back, so it is the same question asked of the state
2281    /// rather than of a second counter that could disagree with it. A request
2282    /// this endpoint did not open, or one already answered, is not this rule's
2283    /// subject and passes through.
2284    ///
2285    /// # Errors
2286    ///
2287    /// [`EndpointError::ResponseBeforeTheFirstResponse`], which answers
2288    /// `Some(ProtocolViolation)`, and the session is failed before it returns.
2289    fn require_the_first_response_first(
2290        &mut self,
2291        id: u64,
2292        msg: &ControlMessage,
2293    ) -> Result<(), EndpointError> {
2294        let awaiting = [self.subscribe_namespaces.get(&id), self.subscribe_tracks.get(&id)]
2295            .into_iter()
2296            .flatten()
2297            .any(|sm| sm.state() == SubscribeNamespaceState::Pending);
2298        if !awaiting {
2299            return Ok(());
2300        }
2301        if matches!(msg, ControlMessage::RequestOk(_) | ControlMessage::RequestError(_)) {
2302            return Ok(());
2303        }
2304        let ty = msg.message_type();
2305        Err(self.fail_session(EndpointError::ResponseBeforeTheFirstResponse(id, ty)))
2306    }
2307
2308    /// Dispatch a message that arrived on the bidi request stream identified
2309    /// by `request_id`.
2310    ///
2311    /// Beyond the five responses this also takes the messages draft-19 Table 5
2312    /// places on a request stream without their being answers to it.
2313    ///
2314    /// REQUEST_UPDATE modifies the request the stream carries (Section 10.9).
2315    /// GOAWAY is listed "Control, Request" because "A GOAWAY MAY also be sent
2316    /// on a request stream to initiate migration of that individual request"
2317    /// (Section 10.4); draft-19 is the draft where its receive path matters,
2318    /// since it removed GOAWAY's Request ID and left one wire form for both
2319    /// places.
2320    ///
2321    /// NAMESPACE (0x8) and NAMESPACE_DONE (0xE) arrive on the
2322    /// SUBSCRIBE_NAMESPACE request stream that asked for the namespaces they
2323    /// report, and PUBLISH_SKIPPED (0xF) on the SUBSCRIBE_TRACKS stream that
2324    /// asked for the track it says will not be published. Table 5 marks all
2325    /// three "Request", so this is where they land; the control stream refuses
2326    /// them.
2327    pub fn receive_response_on_stream(
2328        &mut self,
2329        request_id: VarInt,
2330        msg: ControlMessage,
2331    ) -> Result<(), EndpointError> {
2332        self.require_the_first_response_first(request_id.into_inner(), &msg)?;
2333        match msg {
2334            ControlMessage::SubscribeOk(ref m) => self.receive_subscribe_ok(request_id, m),
2335            ControlMessage::PublishDone(ref m) => self.receive_publish_done(request_id, m),
2336            ControlMessage::FetchOk(ref m) => self.receive_fetch_ok(request_id, m),
2337            ControlMessage::RequestOk(ref m) => self.receive_request_ok(request_id, m),
2338            ControlMessage::RequestError(ref m) => self.receive_request_error(request_id, m),
2339            ControlMessage::RequestUpdate(ref m) => self.receive_request_update(request_id, m),
2340            ControlMessage::GoAway(ref m) => self.receive_goaway_on_request_stream(request_id, m),
2341            ControlMessage::Namespace(ref m) => self.receive_namespace(m),
2342            ControlMessage::NamespaceDone(ref m) => self.receive_namespace_done(m),
2343            ControlMessage::PublishSkipped(ref m) => self.receive_publish_skipped(m),
2344            _ => Err(EndpointError::ResponseOnControlStream),
2345        }
2346    }
2347
2348    /// Process a GOAWAY that arrived on one request stream rather than on the
2349    /// control stream.
2350    ///
2351    /// Draft-19 Section 10.4: "A GOAWAY MAY also be sent on a request stream
2352    /// to initiate migration of that individual request. Upon receiving a
2353    /// GOAWAY on a request stream, the endpoint SHOULD re-issue that specific
2354    /// request on a session at the specified URI". The session keeps running —
2355    /// only this request is being moved — so the session state machine is not
2356    /// touched and no draining event follows. The server-side URI rule of the
2357    /// same section still applies.
2358    ///
2359    /// # Errors
2360    ///
2361    /// [`EndpointError::RepeatedGoAwayOnRequestStream`] if this request's
2362    /// stream has already carried one. The session is over: this endpoint's own
2363    /// state has moved to Closed and the code the transport should close with
2364    /// is in [`EndpointError::session_error_code`].
2365    pub fn receive_goaway_on_request_stream(
2366        &mut self,
2367        request_id: VarInt,
2368        msg: &GoAway,
2369    ) -> Result<(), EndpointError> {
2370        if self.role == Role::Server && !msg.new_session_uri.is_empty() {
2371            return Err(self.fail_session(EndpointError::GoAwayUriAtServer));
2372        }
2373        let id = request_id.into_inner();
2374        if self.subscriptions.contains_key(&id)
2375            || self.publishes.contains_key(&id)
2376            || self.fetches.contains_key(&id)
2377            || self.subscribe_namespaces.contains_key(&id)
2378            || self.subscribe_tracks.contains_key(&id)
2379            || self.publish_namespaces.contains_key(&id)
2380            || self.track_statuses.contains_key(&id)
2381        {
2382            // Section 10.4 counts per stream, so this is a separate first
2383            // GOAWAY on every request and a repeat only on the one that has
2384            // already carried one. The set is fed only by GOAWAYs accepted
2385            // here, and never pruned: a Request ID is spent once, so an entry
2386            // can never come to describe a different request.
2387            if self.goaway_request_streams.insert(id) {
2388                Ok(())
2389            } else {
2390                Err(self.fail_session(EndpointError::RepeatedGoAwayOnRequestStream(id)))
2391            }
2392        } else {
2393            Err(EndpointError::UnknownRequest(id))
2394        }
2395    }
2396
2397    // -- Responder side: requests the peer opened a stream with -----
2398
2399    /// Refuse a bidirectional stream the peer opened with a message type that
2400    /// does not begin a request, and end the session.
2401    ///
2402    /// Draft-19 Section 3.3: "Bidirectional streams MUST NOT begin with any
2403    /// other message type unless negotiated. If they do, the peer MUST close
2404    /// the Session with a PROTOCOL_VIOLATION." The returned error answers
2405    /// `Some(ProtocolViolation)` from
2406    /// [`EndpointError::session_error_code`], which is what tells the
2407    /// connection layer to put the close on the wire.
2408    pub fn refuse_non_request(&mut self, ty: MessageType) -> EndpointError {
2409        self.fail_session(EndpointError::NotARequest(ty))
2410    }
2411
2412    /// Register a request the **peer** opened a bidirectional stream with, and
2413    /// hand back the Request ID it carries.
2414    ///
2415    /// The mirror of [`receive_response_on_stream`](Self::receive_response_on_stream):
2416    /// that one is fed what comes back on a stream this endpoint opened, this
2417    /// one is fed the first message on a stream the peer opened.
2418    ///
2419    /// # What it enforces, and with which code
2420    ///
2421    /// Draft-19 Section 10.1: "If an endpoint receives a Request ID where the
2422    /// least significant bit is incorrect for the sender, or a duplicate
2423    /// Request ID, it MUST close the session with INVALID_REQUEST_ID." Both
2424    /// halves are checked here and both are returned as errors that answer
2425    /// `Some(InvalidRequestId)` from
2426    /// [`EndpointError::session_error_code`]. A message that opens no request
2427    /// stream at all is a different rule with a different code — see
2428    /// [`refuse_non_request`](Self::refuse_non_request).
2429    ///
2430    /// # Why there are no separate inbound maps
2431    ///
2432    /// The peer's ids and this endpoint's ids have opposite least significant
2433    /// bits, so they cannot collide. A peer's request goes into the same
2434    /// `HashMap` its outbound twin would, keyed the same way, and only the
2435    /// transition names differ — `on_subscribe_received` where the outbound
2436    /// path calls `on_subscribe_sent`.
2437    ///
2438    /// # Peer-controlled growth
2439    ///
2440    /// Every accepted request adds an entry that nothing removes, and the peer
2441    /// chooses how many to open. [`peer_request_count`](Self::peer_request_count)
2442    /// is what a responder can watch to impose its own ceiling; this method
2443    /// imposes none.
2444    pub fn receive_request_on_stream(
2445        &mut self,
2446        msg: &ControlMessage,
2447    ) -> Result<VarInt, EndpointError> {
2448        let request_id = match msg {
2449            ControlMessage::Subscribe(m) => m.request_id,
2450            ControlMessage::Publish(m) => m.request_id,
2451            ControlMessage::Fetch(m) => m.request_id,
2452            ControlMessage::PublishNamespace(m) => m.request_id,
2453            ControlMessage::SubscribeNamespace(m) => m.request_id,
2454            ControlMessage::SubscribeTracks(m) => m.request_id,
2455            ControlMessage::TrackStatus(m) => m.request_id,
2456            other => return Err(self.refuse_non_request(other.message_type())),
2457        };
2458        self.require_active_or_err()?;
2459
2460        let id = request_id.into_inner();
2461        if let Err(e) = self.request_ids.validate_peer_id(id) {
2462            return Err(self.fail_session(EndpointError::RequestId(e)));
2463        }
2464        // `insert` answers false when the id was already present, which is
2465        // exactly the duplicate the section names. Doing the check and the
2466        // record in one step means no path can record an id it did not check.
2467        if !self.peer_request_ids.insert(id) {
2468            return Err(self.fail_session(EndpointError::DuplicateRequestId(id)));
2469        }
2470
2471        match msg {
2472            ControlMessage::Subscribe(_) => {
2473                let mut sm = SubscriptionStateMachine::new();
2474                sm.on_subscribe_received()?;
2475                self.subscriptions.insert(id, sm);
2476            }
2477            ControlMessage::Publish(m) => {
2478                let alias = m.track_alias.into_inner();
2479                if let Some(conflict) =
2480                    self.conflicting_track_alias(id, alias, &m.track_namespace, &m.track_name)
2481                {
2482                    return Err(self.fail_session(conflict));
2483                }
2484                let mut sm = PublishStateMachine::new();
2485                sm.on_publish_received()?;
2486                self.publishes.insert(id, sm);
2487                // A PUBLISH names its track and its alias in the one message,
2488                // so the binding is complete on arrival. It counts against the
2489                // next one only once this endpoint has answered PUBLISH_OK,
2490                // which is what moves its state machine to Active.
2491                self.track_bindings.insert(
2492                    id,
2493                    TrackBinding {
2494                        namespace: m.track_namespace.clone(),
2495                        name: m.track_name.clone(),
2496                        alias: Some(alias),
2497                        kind: BindingKind::Publish,
2498                    },
2499                );
2500            }
2501            ControlMessage::Fetch(m) => {
2502                if let Some(joining) = self.joining_subscription_missing(m) {
2503                    self.unjoinable_fetches.insert(id, joining);
2504                }
2505                let mut sm = FetchStateMachine::new();
2506                sm.on_fetch_received()?;
2507                self.fetches.insert(id, sm);
2508            }
2509            ControlMessage::PublishNamespace(_) => {
2510                let mut sm = PublishNamespaceStateMachine::new();
2511                sm.on_publish_namespace_received()?;
2512                self.publish_namespaces.insert(id, sm);
2513            }
2514            ControlMessage::SubscribeNamespace(m) => {
2515                if let Some(established) = self.peer_namespace_overlap(&m.namespace_prefix, None) {
2516                    self.overlapping_namespace_subscriptions.insert(id, established);
2517                }
2518                let mut sm = SubscribeNamespaceStateMachine::new();
2519                sm.on_subscribe_namespace_received()?;
2520                self.subscribe_namespaces.insert(id, sm);
2521            }
2522            // The seventh request kind, and the one draft-17 does not have.
2523            // It gets its own map for the same reason the outbound path gives
2524            // it one: Section 10.19 makes SUBSCRIBE_TRACKS and
2525            // SUBSCRIBE_NAMESPACE independent overlap spaces, so a responder
2526            // that merged them would answer the wrong request.
2527            ControlMessage::SubscribeTracks(m) => {
2528                // Its own space: a SUBSCRIBE_TRACKS is weighed against the
2529                // SUBSCRIBE_TRACKS the peer has open and against nothing else,
2530                // so one prefix may carry one of each.
2531                if let Some(established) = self.peer_tracks_overlap(&m.namespace_prefix, None) {
2532                    self.overlapping_namespace_subscriptions.insert(id, established);
2533                }
2534                let mut sm = SubscribeNamespaceStateMachine::new();
2535                sm.on_subscribe_namespace_received()?;
2536                self.subscribe_tracks.insert(id, sm);
2537            }
2538            ControlMessage::TrackStatus(_) => {
2539                let mut sm = TrackStatusStateMachine::new();
2540                sm.on_track_status_received()?;
2541                self.track_statuses.insert(id, sm);
2542            }
2543            // Unreachable: the match above returned for every other variant.
2544            other => return Err(self.refuse_non_request(other.message_type())),
2545        }
2546
2547        // The request as it arrived, recorded last so that nothing above it
2548        // can leave one behind for a request it went on to refuse.
2549        self.inbound_requests.insert(id, msg.clone());
2550
2551        // After the request is recorded, never before. The answer to every
2552        // Range Filter rule is a REQUEST_ERROR, which names the Request ID of
2553        // the request it answers, so refusing here would leave nothing to
2554        // answer with.
2555        let parameters = request_parameters(msg);
2556        if let Some(rejection) = self.filter_verdict(parameters) {
2557            self.peer_filter_rejections.insert(id, rejection);
2558        }
2559        self.peer_request_filters.insert(id, range_filter_parameters(parameters));
2560        Ok(request_id)
2561    }
2562
2563    // -- What the peer asked for ------------------------------------
2564
2565    /// The SUBSCRIBE the peer sent under `request_id` and this endpoint has
2566    /// not answered yet.
2567    ///
2568    /// `None` once it has been answered, for an identifier this session has
2569    /// carried no SUBSCRIBE under, and for one this endpoint spent on a
2570    /// request of its own -- whose state is in the same map, but which never
2571    /// arrived here. The record itself lives on past the answer, because the
2572    /// subscription it opened runs on after it, for as long as the request
2573    /// stream does.
2574    pub fn pending_subscribe(&self, request_id: VarInt) -> Option<&Subscribe> {
2575        let id = request_id.into_inner();
2576        let unanswered = self
2577            .subscriptions
2578            .get(&id)
2579            .is_some_and(|sm| sm.state() == SubscriptionState::Subscribing);
2580        match self.inbound_requests.get(&id) {
2581            Some(ControlMessage::Subscribe(msg)) if unanswered => Some(msg),
2582            _ => None,
2583        }
2584    }
2585
2586    /// How many SUBSCRIBEs the peer has sent that are still waiting for an
2587    /// answer.
2588    pub fn pending_subscribe_count(&self) -> usize {
2589        self.inbound_requests
2590            .iter()
2591            .filter(|(id, msg)| {
2592                matches!(msg, ControlMessage::Subscribe(_))
2593                    && self
2594                        .subscriptions
2595                        .get(*id)
2596                        .is_some_and(|sm| sm.state() == SubscriptionState::Subscribing)
2597            })
2598            .count()
2599    }
2600
2601    /// The PUBLISH the peer sent under `request_id` and this endpoint has not
2602    /// answered yet.
2603    ///
2604    /// `None` once it has been answered, for an identifier this session has
2605    /// carried no PUBLISH under, and for one this endpoint spent on a request
2606    /// of its own -- whose state is in the same map, but which never arrived
2607    /// here. The record itself lives on past the answer, because the
2608    /// subscription the offer opened runs on after it, for as long as the
2609    /// request stream does.
2610    pub fn pending_publish(&self, request_id: VarInt) -> Option<&message::Publish> {
2611        let id = request_id.into_inner();
2612        let unanswered =
2613            self.publishes.get(&id).is_some_and(|sm| sm.state() == PublishState::Publishing);
2614        match self.inbound_requests.get(&id) {
2615            Some(ControlMessage::Publish(msg)) if unanswered => Some(msg),
2616            _ => None,
2617        }
2618    }
2619
2620    /// How many offers the peer has sent that are still waiting for an
2621    /// answer.
2622    pub fn pending_publish_count(&self) -> usize {
2623        self.inbound_requests
2624            .iter()
2625            .filter(|(id, msg)| {
2626                matches!(msg, ControlMessage::Publish(_))
2627                    && self
2628                        .publishes
2629                        .get(*id)
2630                        .is_some_and(|sm| sm.state() == PublishState::Publishing)
2631            })
2632            .count()
2633    }
2634
2635    /// The FETCH the peer sent under `request_id` and this endpoint has not
2636    /// answered yet.
2637    ///
2638    /// `None` once it has been answered, for an identifier this session has
2639    /// carried no FETCH under, and for one this endpoint spent on a request
2640    /// of its own -- whose state is in the same map, but which never arrived
2641    /// here. The record itself lives on past the answer, because the fetch is
2642    /// not over until its response stream is.
2643    pub fn pending_fetch(&self, request_id: VarInt) -> Option<&Fetch> {
2644        let id = request_id.into_inner();
2645        let unanswered = self
2646            .fetches
2647            .get(&id)
2648            .is_some_and(|sm| matches!(sm.state(), FetchState::Pending | FetchState::Unanswered));
2649        match self.inbound_requests.get(&id) {
2650            Some(ControlMessage::Fetch(msg)) if unanswered => Some(msg),
2651            _ => None,
2652        }
2653    }
2654
2655    /// How many FETCHes the peer has sent that are still waiting for an
2656    /// answer.
2657    pub fn pending_fetch_count(&self) -> usize {
2658        self.inbound_requests
2659            .iter()
2660            .filter(|(id, msg)| {
2661                matches!(msg, ControlMessage::Fetch(_))
2662                    && self.fetches.get(*id).is_some_and(|sm| {
2663                        matches!(sm.state(), FetchState::Pending | FetchState::Unanswered)
2664                    })
2665            })
2666            .count()
2667    }
2668
2669    /// The PUBLISH_NAMESPACE the peer sent under `request_id` and this
2670    /// endpoint has not answered yet.
2671    ///
2672    /// `None` once it has been answered, for an identifier this session has
2673    /// carried no PUBLISH_NAMESPACE under, and for one this endpoint spent on
2674    /// a request of its own -- whose state is in the same map, but which
2675    /// never arrived here. The record itself lives on past the answer,
2676    /// because an announcement that was accepted stands until it is
2677    /// withdrawn.
2678    pub fn pending_publish_namespace(&self, request_id: VarInt) -> Option<&PublishNamespace> {
2679        let id = request_id.into_inner();
2680        let unanswered = self
2681            .publish_namespaces
2682            .get(&id)
2683            .is_some_and(|sm| sm.state() == PublishNamespaceState::Pending);
2684        match self.inbound_requests.get(&id) {
2685            Some(ControlMessage::PublishNamespace(msg)) if unanswered => Some(msg),
2686            _ => None,
2687        }
2688    }
2689
2690    /// How many announcements the peer has sent that are still waiting for an
2691    /// answer.
2692    pub fn pending_publish_namespace_count(&self) -> usize {
2693        self.inbound_requests
2694            .iter()
2695            .filter(|(id, msg)| {
2696                matches!(msg, ControlMessage::PublishNamespace(_))
2697                    && self
2698                        .publish_namespaces
2699                        .get(*id)
2700                        .is_some_and(|sm| sm.state() == PublishNamespaceState::Pending)
2701            })
2702            .count()
2703    }
2704
2705    /// The earliest namespace subscription the peer has made whose prefix
2706    /// overlaps `prefix`, and `None` when there is none.
2707    ///
2708    /// Only ones that have not ended count: the sentence weighs the arriving
2709    /// prefix against an "established" one, so one the peer has withdrawn and
2710    /// one this endpoint refused are both past. Drafts 07 through 11 say "an
2711    /// earlier" instead and count those too.
2712    ///
2713    /// One that has arrived and has not been answered does count. It is not
2714    /// established yet, but this endpoint is the one about to establish it,
2715    /// and accepting both would leave the session holding exactly the pair
2716    /// the sentence exists to prevent.
2717    ///
2718    /// The record of what the peer sent is what tells the two directions
2719    /// apart. The state machines live in one map per kind whichever end
2720    /// opened the request, so a prefix this endpoint asked about would be
2721    /// indistinguishable there; only requests that arrived are written into
2722    /// `inbound_requests`.
2723    ///
2724    /// The lowest Request ID wins when more than one overlaps, so the answer
2725    /// does not depend on the order a map happens to iterate in.
2726    ///
2727    /// `except` is the subscription a REQUEST_UPDATE is moving, which Section
2728    /// 10.2.19 weighs against "another active subscription of the same type"
2729    /// and therefore not against the prefix it is leaving behind.
2730    fn peer_namespace_overlap(&self, prefix: &TrackNamespace, except: Option<u64>) -> Option<u64> {
2731        self.inbound_requests
2732            .iter()
2733            .filter(|(&id, _)| Some(id) != except)
2734            .filter_map(|(&id, msg)| match msg {
2735                ControlMessage::SubscribeNamespace(m) => Some((id, &m.namespace_prefix)),
2736                _ => None,
2737            })
2738            .filter(|(id, _)| {
2739                self.subscribe_namespaces
2740                    .get(id)
2741                    .is_some_and(|sm| sm.state() != SubscribeNamespaceState::Done)
2742            })
2743            .filter_map(|(id, p)| prefixes_overlap(&p.0, &prefix.0).then_some(id))
2744            .min()
2745    }
2746
2747    /// The earliest track subscription the peer has made whose prefix
2748    /// overlaps `prefix`, and `None` when there is none.
2749    ///
2750    /// Only ones that have not ended count: the sentence weighs the arriving
2751    /// prefix against an "established" one, so one the peer has withdrawn and
2752    /// one this endpoint refused are both past. Drafts 07 through 11 say "an
2753    /// earlier" instead and count those too.
2754    ///
2755    /// One that has arrived and has not been answered does count. It is not
2756    /// established yet, but this endpoint is the one about to establish it,
2757    /// and accepting both would leave the session holding exactly the pair
2758    /// the sentence exists to prevent.
2759    ///
2760    /// The record of what the peer sent is what tells the two directions
2761    /// apart. The state machines live in one map per kind whichever end
2762    /// opened the request, so a prefix this endpoint asked about would be
2763    /// indistinguishable there; only requests that arrived are written into
2764    /// `inbound_requests`.
2765    ///
2766    /// The lowest Request ID wins when more than one overlaps, so the answer
2767    /// does not depend on the order a map happens to iterate in.
2768    ///
2769    /// `except` is the subscription a REQUEST_UPDATE is moving, which Section
2770    /// 10.2.19 weighs against "another active subscription of the same type"
2771    /// and therefore not against the prefix it is leaving behind.
2772    fn peer_tracks_overlap(&self, prefix: &TrackNamespace, except: Option<u64>) -> Option<u64> {
2773        self.inbound_requests
2774            .iter()
2775            .filter(|(&id, _)| Some(id) != except)
2776            .filter_map(|(&id, msg)| match msg {
2777                ControlMessage::SubscribeTracks(m) => Some((id, &m.namespace_prefix)),
2778                _ => None,
2779            })
2780            .filter(|(id, _)| {
2781                self.subscribe_tracks
2782                    .get(id)
2783                    .is_some_and(|sm| sm.state() != SubscribeNamespaceState::Done)
2784            })
2785            .filter_map(|(id, p)| prefixes_overlap(&p.0, &prefix.0).then_some(id))
2786            .min()
2787    }
2788
2789    /// The SUBSCRIBE_NAMESPACE the peer sent under `request_id` and this
2790    /// endpoint has not answered yet.
2791    ///
2792    /// `None` once it has been answered, for an identifier this session has
2793    /// carried no SUBSCRIBE_NAMESPACE under, and for one this endpoint spent
2794    /// on a request of its own -- whose state is in the same map, but which
2795    /// never arrived here. The record itself lives on past the answer,
2796    /// because a namespace subscription lasts as long as its stream does.
2797    pub fn pending_subscribe_namespace(&self, request_id: VarInt) -> Option<&SubscribeNamespace> {
2798        let id = request_id.into_inner();
2799        let unanswered = self
2800            .subscribe_namespaces
2801            .get(&id)
2802            .is_some_and(|sm| sm.state() == SubscribeNamespaceState::Pending);
2803        match self.inbound_requests.get(&id) {
2804            Some(ControlMessage::SubscribeNamespace(msg)) if unanswered => Some(msg),
2805            _ => None,
2806        }
2807    }
2808
2809    /// How many namespace subscriptions the peer has sent that are still
2810    /// waiting for an answer.
2811    pub fn pending_subscribe_namespace_count(&self) -> usize {
2812        self.inbound_requests
2813            .iter()
2814            .filter(|(id, msg)| {
2815                matches!(msg, ControlMessage::SubscribeNamespace(_))
2816                    && self
2817                        .subscribe_namespaces
2818                        .get(*id)
2819                        .is_some_and(|sm| sm.state() == SubscribeNamespaceState::Pending)
2820            })
2821            .count()
2822    }
2823
2824    /// The SUBSCRIBE_TRACKS the peer sent under `request_id` and this
2825    /// endpoint has not answered yet.
2826    ///
2827    /// `None` once it has been answered, for an identifier this session has
2828    /// carried no SUBSCRIBE_TRACKS under, and for one this endpoint spent on
2829    /// a request of its own -- whose state is in the same map, but which
2830    /// never arrived here. The record itself lives on past the answer,
2831    /// because the subscription it opened lasts as long as its stream does.
2832    pub fn pending_subscribe_tracks(&self, request_id: VarInt) -> Option<&SubscribeTracks> {
2833        let id = request_id.into_inner();
2834        let unanswered = self
2835            .subscribe_tracks
2836            .get(&id)
2837            .is_some_and(|sm| sm.state() == SubscribeNamespaceState::Pending);
2838        match self.inbound_requests.get(&id) {
2839            Some(ControlMessage::SubscribeTracks(msg)) if unanswered => Some(msg),
2840            _ => None,
2841        }
2842    }
2843
2844    /// How many track subscriptions the peer has sent that are still waiting
2845    /// for an answer.
2846    pub fn pending_subscribe_tracks_count(&self) -> usize {
2847        self.inbound_requests
2848            .iter()
2849            .filter(|(id, msg)| {
2850                matches!(msg, ControlMessage::SubscribeTracks(_))
2851                    && self
2852                        .subscribe_tracks
2853                        .get(*id)
2854                        .is_some_and(|sm| sm.state() == SubscribeNamespaceState::Pending)
2855            })
2856            .count()
2857    }
2858
2859    /// The TRACK_STATUS the peer sent under `request_id` and this endpoint
2860    /// has not answered yet.
2861    ///
2862    /// `None` once it has been answered, for an identifier this session has
2863    /// carried no TRACK_STATUS under, and for one this endpoint spent on a
2864    /// request of its own -- whose state is in the same map, but which never
2865    /// arrived here. The record itself lives on past the answer, because an
2866    /// update may still name it once it has been answered.
2867    pub fn pending_track_status(&self, request_id: VarInt) -> Option<&message::TrackStatus> {
2868        let id = request_id.into_inner();
2869        let unanswered =
2870            self.track_statuses.get(&id).is_some_and(|sm| sm.state() == TrackStatusState::Pending);
2871        match self.inbound_requests.get(&id) {
2872            Some(ControlMessage::TrackStatus(msg)) if unanswered => Some(msg),
2873            _ => None,
2874        }
2875    }
2876
2877    /// How many track statuses the peer has sent that are still waiting for
2878    /// an answer.
2879    pub fn pending_track_status_count(&self) -> usize {
2880        self.inbound_requests
2881            .iter()
2882            .filter(|(id, msg)| {
2883                matches!(msg, ControlMessage::TrackStatus(_))
2884                    && self
2885                        .track_statuses
2886                        .get(*id)
2887                        .is_some_and(|sm| sm.state() == TrackStatusState::Pending)
2888            })
2889            .count()
2890    }
2891
2892    /// Whether the Range Filters in `parameters` are ones this endpoint may
2893    /// accept.
2894    ///
2895    /// The three rules that need more than one parameter to see, in the order
2896    /// that reports the most specific fault: whether the filters read at all,
2897    /// then whether any budget was advertised, then whether the request stays
2898    /// inside it, then whether two filters share a key. A request with no Range
2899    /// Filter at all is not measured against the ceiling, so an endpoint that
2900    /// advertised nothing still takes ordinary requests — which is the whole of
2901    /// the traffic today, since draft-19 is the first draft with these
2902    /// parameters.
2903    fn filter_verdict(&self, parameters: &[KeyValuePair]) -> Option<FilterRejection> {
2904        let filters = match range_filter::decode_all_moqt::<Moqt18>(parameters) {
2905            Ok(filters) => filters,
2906            Err(e) => return Some(FilterRejection::Unreadable(e)),
2907        };
2908        if filters.is_empty() {
2909            return None;
2910        }
2911        if self.advertised_max_filter_ranges == 0 {
2912            return Some(FilterRejection::NoBudgetAdvertised);
2913        }
2914        let ranges = range_filter::total_ranges(&filters);
2915        if ranges as u64 > self.advertised_max_filter_ranges {
2916            return Some(FilterRejection::TooManyRanges {
2917                ranges,
2918                limit: self.advertised_max_filter_ranges,
2919            });
2920        }
2921        if let Some((parameter_type, set_id, property_type)) =
2922            range_filter::first_repeated_key(&filters)
2923        {
2924            return Some(FilterRejection::RepeatedFilter(parameter_type, set_id, property_type));
2925        }
2926        None
2927    }
2928
2929    /// Why request `id` must be answered with a REQUEST_ERROR, if it must.
2930    ///
2931    /// The caller builds the message; [`FilterRejection::request_error_code`]
2932    /// gives the code and the variant gives the reason phrase. Answering it
2933    /// clears the record.
2934    pub fn filter_rejection(&self, id: VarInt) -> Option<&FilterRejection> {
2935        self.peer_filter_rejections.get(&id.into_inner())
2936    }
2937
2938    /// Whether this response answers a REQUEST_UPDATE rather than the request
2939    /// that opened the stream. Section 10.9 gives an update the same two
2940    /// answers a request has: "The receiver of a REQUEST_UPDATE MUST respond
2941    /// with exactly one REQUEST_OK or REQUEST_ERROR message indicating if the
2942    /// update was successful, unless it is coalescing failed updates to produce
2943    /// just one REQUEST_ERROR for multiple REQUEST_UPDATE messages." Nothing in
2944    /// either message says which of the two it is answering, so the question is
2945    /// settled twice over.
2946    ///
2947    /// A SUBSCRIBE is answered with SUBSCRIBE_OK and a FETCH with FETCH_OK, so a
2948    /// REQUEST_OK on one of those streams has no other message it could be
2949    /// answering. That is the half that needs no ordering.
2950    ///
2951    /// Everywhere else it is ordering: the first REQUEST_OK or REQUEST_ERROR on
2952    /// a stream answers the request that opened it, and the ones after it answer
2953    /// updates. Both endpoints have to resolve it the same way and neither has
2954    /// anything else to resolve it with.
2955    fn answers_an_update(&self, id: u64, msg: &ControlMessage) -> bool {
2956        if !matches!(msg, ControlMessage::RequestOk(_) | ControlMessage::RequestError(_)) {
2957            return false;
2958        }
2959        // A request this endpoint made is answered by the peer, so a response
2960        // written here can only be answering an update the peer sent on it.
2961        // Section 10.9 names the one request that works that way: "A subscriber
2962        // can also send REQUEST_UPDATE to modify parameters of a subscription
2963        // established with PUBLISH."
2964        if self.publishes.contains_key(&id) && !self.inbound_requests.contains_key(&id) {
2965            return true;
2966        }
2967        if matches!(msg, ControlMessage::RequestOk(_))
2968            && (self.subscriptions.contains_key(&id) || self.fetches.contains_key(&id))
2969        {
2970            return true;
2971        }
2972        self.answered_peer_requests.contains(&id)
2973    }
2974
2975    /// Record a response as the answer to one or more outstanding updates.
2976    ///
2977    /// A REQUEST_OK answers exactly one: "The receiver MUST still send a
2978    /// REQUEST_OK for each successful update". A REQUEST_ERROR may answer every
2979    /// update still waiting, because Section 10.9.1 permits the receiver to
2980    /// coalesce them — "If the coalesced REQUEST_UPDATE results in
2981    /// REQUEST_ERROR, only a single REQUEST_ERROR will be sent and the sender of
2982    /// the REQUEST_UPDATEs will not always be able to determine which caused an
2983    /// error." Draft-17 has no such paragraph, and its endpoint answers one
2984    /// update per message in both directions.
2985    ///
2986    /// The credit MAX_REQUEST_UPDATES counts is restored once whatever the
2987    /// answer covered, which is Section 10.3.1.7 read literally: "Each
2988    /// REQUEST_OK or REQUEST_ERROR response restores one credit on that stream."
2989    /// The peer restores by the same sentence, so an endpoint that gave back one
2990    /// per coalesced update would be crediting a peer that is not.
2991    ///
2992    /// No state machine moves. An update changes a request's parameters and not
2993    /// its lifecycle, so a subscription that was Active before its update was
2994    /// answered is Active after it, whichever answer went out.
2995    ///
2996    /// # Errors
2997    ///
2998    /// [`EndpointError::NoUpdateToAnswer`], and nothing is written or spent.
2999    ///
3000    /// [`EndpointError::PeerPrefixOverlap`] and
3001    /// [`EndpointError::WrongOverlapRefusal`] when the update asked to move a
3002    /// namespace subscription onto a prefix that overlaps another of its kind
3003    /// and the answer is not the REQUEST_ERROR the sentence names. The same
3004    /// two the request itself is refused with, because it is the same rule
3005    /// under the same code; which of the two moments raised it is told apart
3006    /// by which call returned.
3007    fn answer_an_update(&mut self, id: u64, msg: &ControlMessage) -> Result<(), EndpointError> {
3008        let unanswered = self.unanswered_peer_updates.get(&id).copied().unwrap_or(0);
3009        if unanswered == 0 {
3010            return Err(EndpointError::NoUpdateToAnswer(id));
3011        }
3012        // The update's half of the overlap rule, and the reason it needs a
3013        // verdict of its own: an update is answered by the same two messages
3014        // on the same stream as the request, so the moment one of them is
3015        // about to be written is the one place both the answer and the code
3016        // the sentence names are known. Section 10.2.19: "If the new prefix
3017        // would share a common prefix with another active subscription of the
3018        // same type in the same session, the receiver MUST respond with
3019        // REQUEST_ERROR with error code PREFIX_OVERLAP."
3020        if let Some(&established) = self.overlapping_prefix_updates.get(&id) {
3021            let ControlMessage::RequestError(err) = msg else {
3022                return Err(EndpointError::PeerPrefixOverlap { request: id, established });
3023            };
3024            let required = RequestErrorCode::PrefixOverlap as u64;
3025            if err.error_code.into_inner() != required {
3026                return Err(EndpointError::WrongOverlapRefusal { request: id, required });
3027            }
3028        }
3029        let answered = if matches!(msg, ControlMessage::RequestError(_)) { unanswered } else { 1 };
3030        self.unanswered_peer_updates.insert(id, unanswered - answered);
3031        self.restore_update_credit(id);
3032        // The same rule the request's own REQUEST_ERROR spends: a filter this
3033        // endpoint owes an error about has been answered.
3034        if matches!(msg, ControlMessage::RequestError(_)) {
3035            self.peer_filter_rejections.remove(&id);
3036        }
3037        // The prefix moves on the acceptance and not before: "If the update is
3038        // accepted, NAMESPACE and NAMESPACE_DONE messages following the
3039        // REQUEST_OK will contain Track Namespace suffixes relative to the
3040        // updated prefix." A REQUEST_ERROR drops it and the subscription goes
3041        // on selecting what it selected before the update was sent.
3042        //
3043        // Nothing else is recomputed. A subscription this endpoint has already
3044        // refused keeps that verdict when ground it wanted comes free, because
3045        // the sentence that refused it names the moment it arrived and that
3046        // moment has passed.
3047        let accepted = matches!(msg, ControlMessage::RequestOk(_));
3048        if let Some(prefix) = self.updated_namespace_prefixes.remove(&id) {
3049            if accepted {
3050                match self.inbound_requests.get_mut(&id) {
3051                    Some(ControlMessage::SubscribeNamespace(m)) => m.namespace_prefix = prefix,
3052                    Some(ControlMessage::SubscribeTracks(m)) => m.namespace_prefix = prefix,
3053                    // Unreachable: nothing else is ever written above.
3054                    _ => {}
3055                }
3056            }
3057        }
3058        if !accepted {
3059            self.overlapping_prefix_updates.remove(&id);
3060        }
3061        Ok(())
3062    }
3063
3064    /// Drive the state machine for a message this endpoint is about to write
3065    /// on a request stream the peer opened.
3066    ///
3067    /// The mirror of [`receive_response_on_stream`](Self::receive_response_on_stream),
3068    /// and the reason the transitions are named `*_sent` rather than reusing
3069    /// the received-side ones: the state edges coincide, so a mis-dispatch
3070    /// would otherwise succeed silently instead of naming the wrong event in
3071    /// an `InvalidTransition`.
3072    ///
3073    /// Beyond the four responses this also takes the three messages draft-19
3074    /// Table 5 places on a request stream that a responder writes after its
3075    /// response: NAMESPACE and NAMESPACE_DONE on a SUBSCRIBE_NAMESPACE stream
3076    /// (Sections 10.16 and 10.17) and PUBLISH_SKIPPED on a SUBSCRIBE_TRACKS
3077    /// stream (Section 10.20). All three require the request to have been
3078    /// accepted first, because each machine only leaves Pending on its
3079    /// REQUEST_OK.
3080    ///
3081    /// The caller writes `msg` only after this returns `Ok`. What it cannot
3082    /// undo is the opposite order: a write that fails afterwards leaves the
3083    /// state machine one step ahead of the wire, the same asymmetry the
3084    /// outbound request path already carries.
3085    /// The identifier an arriving Joining Fetch names, when this session has
3086    /// no subscription it may join.
3087    ///
3088    /// Section 10.12.2:
3089    /// "If a publisher receives a Joining Fetch with a Request ID that
3090    /// does not correspond to a subscription in the same session in the
3091    /// Established or Pending (subscriber) states, it MUST return a
3092    /// REQUEST_ERROR with error code INVALID_JOINING_REQUEST_ID."
3093    /// A standalone fetch names none and answers `None`, and so does a joining
3094    /// one whose subscription is live. Either message can establish the one it
3095    /// joins: Section 5.1 says the Largest Location a Joining FETCH works from
3096    /// is the one saved "communicated in SUBSCRIBE_OK, PUBLISH or
3097    /// REQUEST_UPDATE_OK that changes the Forward State from 0 to 1".
3098    fn joining_subscription_missing(&self, msg: &Fetch) -> Option<u64> {
3099        let message::FetchPayload::Joining { joining_request_id: joined, .. } = &msg.fetch_payload
3100        else {
3101            return None;
3102        };
3103        let joined = joined.into_inner();
3104        let live =
3105            self.subscriptions.get(&joined).is_some_and(|s| s.state() != SubscriptionState::Done)
3106                || self.publishes.get(&joined).is_some_and(|p| p.state() != PublishState::Done);
3107        if live {
3108            None
3109        } else {
3110            Some(joined)
3111        }
3112    }
3113
3114    /// Drive the state machines for a response this endpoint is about to write
3115    /// on a request stream the peer opened.
3116    ///
3117    /// The caller writes the message only after this returns `Ok`, so a
3118    /// response the endpoint refuses never reaches the wire.
3119    ///
3120    /// # Errors
3121    ///
3122    /// [`EndpointError::UnknownRequest`] when no request of the answering kind
3123    /// carries that identifier, [`EndpointError::NotAResponse`] when the
3124    /// message is not one, [`EndpointError::UnjoinableSubscription`] and
3125    /// [`EndpointError::WrongJoiningRefusal`] for a Joining Fetch that named no
3126    /// live subscription, [`EndpointError::PeerPrefixOverlap`] and
3127    /// [`EndpointError::WrongOverlapRefusal`] for a namespace subscription that
3128    /// overlapped one already open or that a REQUEST_UPDATE asked to move onto
3129    /// an overlapping prefix, [`EndpointError::FilterMustBeRejected`] for a request whose Range Filters this draft says to reject, and each flow's own
3130    /// `InvalidTransition` for a request already answered.
3131    pub fn send_response_on_stream(
3132        &mut self,
3133        request_id: VarInt,
3134        msg: &ControlMessage,
3135    ) -> Result<(), EndpointError> {
3136        let id = request_id.into_inner();
3137        // A request whose Range Filters the draft says to reject may be
3138        // answered with a REQUEST_ERROR and with nothing else. Checked across
3139        // every acceptance rather than inside the REQUEST_OK arm, because
3140        // SUBSCRIBE and FETCH — the two requests that most obviously carry these
3141        // filters — are accepted with SUBSCRIBE_OK and FETCH_OK instead.
3142        if matches!(
3143            msg,
3144            ControlMessage::SubscribeOk(_)
3145                | ControlMessage::FetchOk(_)
3146                | ControlMessage::RequestOk(_)
3147        ) {
3148            if let Some(rejection) = self.peer_filter_rejections.get(&id) {
3149                return Err(EndpointError::FilterMustBeRejected(id, rejection.clone()));
3150            }
3151        }
3152        // An answer to an update reaches none of the arms below: the request it
3153        // belongs to has its own lifecycle and an update does not move it.
3154        // A refused update leaves this endpoint owing the peer a termination,
3155        // and the draft names the status that termination must carry. So the
3156        // request's ending is what the debt governs: a PUBLISH_DONE under any
3157        // other status is refused, and everything else the caller may still
3158        // have to write for this request - the answer to a second update it
3159        // has not answered yet - is left alone, because the sentence orders
3160        // nothing.
3161        if let ControlMessage::PublishDone(done) = msg {
3162            self.require_update_failure_status(id, done.status_code)?;
3163        }
3164        if self.answers_an_update(id, msg) {
3165            self.answer_an_update(id, msg)?;
3166            // Refusing an update is half of what the draft asks for, and which
3167            // half it is depends on what was being updated. A subscription is
3168            // owed the PUBLISH_DONE that ends it, recorded here so that the
3169            // next ending written for this request has to be that one. A
3170            // namespace request, a fetch and a track status are owed no
3171            // message at all, and recording one for them would keep a stream
3172            // open that has nothing left to carry.
3173            if matches!(msg, ControlMessage::RequestError(_)) && self.publishes_a_subscription(id) {
3174                self.owed_update_failures.insert(id);
3175            }
3176            return Ok(());
3177        }
3178        // A namespace subscription that overlapped one already open when it
3179        // arrived has one answer available to it, and this is where both the
3180        // answer and its code are known. An update's answer returned above, so
3181        // nothing here judges one.
3182        if let Some(&established) = self.overlapping_namespace_subscriptions.get(&id) {
3183            let ControlMessage::RequestError(err) = msg else {
3184                return Err(EndpointError::PeerPrefixOverlap { request: id, established });
3185            };
3186            let required = RequestErrorCode::PrefixOverlap as u64;
3187            if err.error_code.into_inner() != required {
3188                return Err(EndpointError::WrongOverlapRefusal { request: id, required });
3189            }
3190        }
3191        match msg {
3192            ControlMessage::SubscribeOk(_) => {
3193                let sm =
3194                    self.subscriptions.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3195                sm.on_subscribe_ok_sent()?;
3196            }
3197            ControlMessage::FetchOk(_) => {
3198                if let Some(&joining) = self.unjoinable_fetches.get(&id) {
3199                    return Err(EndpointError::UnjoinableSubscription { fetch: id, joining });
3200                }
3201                let sm = self.fetches.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3202                sm.on_fetch_ok_sent()?;
3203            }
3204            ControlMessage::PublishDone(_) => {
3205                let sm =
3206                    self.subscriptions.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3207                sm.on_publish_done_sent()?;
3208            }
3209            // REQUEST_OK answers the kinds that have no response message of
3210            // their own, PUBLISH among them since draft-18 folded PUBLISH_OK
3211            // into it. The probe order does not matter: the maps are keyed by
3212            // Request ID and one id belongs to one request.
3213            ControlMessage::RequestOk(m) => {
3214                // Section 10.5 makes receiving Track Properties on anything but
3215                // a TRACK_STATUS response a session close, so putting them on
3216                // one of the others would be handing the peer a reason to close
3217                // this session. Refused before the write rather than after.
3218                if !m.track_properties.is_empty() && !self.track_statuses.contains_key(&id) {
3219                    return Err(EndpointError::TrackPropertiesOnOutgoingRequestOk(id));
3220                }
3221                if let Some(sm) = self.publishes.get_mut(&id) {
3222                    sm.on_publish_ok_sent()?;
3223                } else if let Some(sm) = self.subscribe_namespaces.get_mut(&id) {
3224                    sm.on_subscribe_namespace_ok_sent()?;
3225                } else if let Some(sm) = self.subscribe_tracks.get_mut(&id) {
3226                    sm.on_subscribe_namespace_ok_sent()?;
3227                } else if let Some(sm) = self.publish_namespaces.get_mut(&id) {
3228                    sm.on_publish_namespace_ok_sent()?;
3229                } else if let Some(sm) = self.track_statuses.get_mut(&id) {
3230                    sm.on_track_status_ok_sent()?;
3231                } else {
3232                    return Err(EndpointError::UnknownRequest(id));
3233                }
3234            }
3235            ControlMessage::RequestError(err) => {
3236                if let Some(sm) = self.subscriptions.get_mut(&id) {
3237                    sm.on_subscribe_error_sent()?;
3238                } else if self.fetches.contains_key(&id) {
3239                    if self.unjoinable_fetches.contains_key(&id) {
3240                        let required = RequestErrorCode::InvalidJoiningRequestId as u64;
3241                        if err.error_code.into_inner() != required {
3242                            return Err(EndpointError::WrongJoiningRefusal { fetch: id, required });
3243                        }
3244                    }
3245                    let sm = self.fetches.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3246                    sm.on_fetch_error_sent()?;
3247                } else if let Some(sm) = self.publishes.get_mut(&id) {
3248                    sm.on_publish_error_sent()?;
3249                } else if let Some(sm) = self.subscribe_namespaces.get_mut(&id) {
3250                    sm.on_subscribe_namespace_error_sent()?;
3251                } else if let Some(sm) = self.subscribe_tracks.get_mut(&id) {
3252                    sm.on_subscribe_namespace_error_sent()?;
3253                } else if let Some(sm) = self.publish_namespaces.get_mut(&id) {
3254                    sm.on_publish_namespace_error_sent()?;
3255                } else if let Some(sm) = self.track_statuses.get_mut(&id) {
3256                    sm.on_track_status_error_sent()?;
3257                } else {
3258                    return Err(EndpointError::UnknownRequest(id));
3259                }
3260            }
3261            ControlMessage::Namespace(_) => {
3262                let sm = self
3263                    .subscribe_namespaces
3264                    .get_mut(&id)
3265                    .ok_or(EndpointError::UnknownRequest(id))?;
3266                sm.on_namespace_sent()?;
3267            }
3268            ControlMessage::NamespaceDone(_) => {
3269                let sm = self
3270                    .subscribe_namespaces
3271                    .get_mut(&id)
3272                    .ok_or(EndpointError::UnknownRequest(id))?;
3273                sm.on_namespace_done_sent()?;
3274            }
3275            ControlMessage::PublishSkipped(_) => {
3276                let sm =
3277                    self.subscribe_tracks.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3278                sm.on_publish_skipped_sent()?;
3279            }
3280            other => return Err(EndpointError::NotAResponse(other.message_type())),
3281        }
3282        // After the match, not before it: the caller writes `msg` only once
3283        // this returns `Ok`, so a response that was refused restores nothing.
3284        if matches!(msg, ControlMessage::RequestOk(_) | ControlMessage::RequestError(_)) {
3285            self.restore_update_credit(id);
3286        }
3287        // Reached only by a response that answered the request itself, since an
3288        // update's answer returned above. From here on, a REQUEST_OK or
3289        // REQUEST_ERROR on this stream can only be answering an update.
3290        if matches!(
3291            msg,
3292            ControlMessage::SubscribeOk(_)
3293                | ControlMessage::FetchOk(_)
3294                | ControlMessage::RequestOk(_)
3295                | ControlMessage::RequestError(_)
3296        ) {
3297            self.answered_peer_requests.insert(id);
3298        }
3299        // For the same reason, and it matters more here: a rejection cleared by
3300        // a REQUEST_ERROR that was itself refused would leave the request
3301        // acceptable on the next attempt.
3302        if matches!(msg, ControlMessage::RequestError(_)) {
3303            self.peer_filter_rejections.remove(&id);
3304        }
3305        Ok(())
3306    }
3307
3308    /// Dispatch a message that arrived on a request stream the **peer** opened,
3309    /// after the request that opened it.
3310    ///
3311    /// Nothing that arrives here is a response: this endpoint is the responder
3312    /// on such a stream, so a SUBSCRIBE_OK or REQUEST_ERROR turning up is the
3313    /// peer answering its own request, and it is refused with
3314    /// [`EndpointError::UnexpectedOnPeerRequestStream`].
3315    ///
3316    /// Three messages are expected instead.
3317    ///
3318    /// REQUEST_UPDATE, because draft-19 Section 10.9 puts it on the request's
3319    /// own stream: "The sender of a request (SUBSCRIBE, PUBLISH, FETCH,
3320    /// PUBLISH_NAMESPACE, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS) can later send
3321    /// a REQUEST_UPDATE on the same bidi stream as the request to modify it."
3322    /// It goes through the same [`receive_request_update`](Self::receive_request_update)
3323    /// the requester side uses, so the peer's update is held to the same rule
3324    /// its own would be: the message's Request ID must name the stream's
3325    /// request, and a kind the section does not allow to be updated —
3326    /// TRACK_STATUS, by Section 10.14 — closes the session.
3327    ///
3328    /// GOAWAY, because Section 10.4 lets one arrive on a request stream to
3329    /// migrate that request alone, in either direction.
3330    ///
3331    /// PUBLISH_DONE, because a peer that sent PUBLISH is the publisher and ends
3332    /// the publication it opened.
3333    pub fn receive_on_peer_request_stream(
3334        &mut self,
3335        request_id: VarInt,
3336        msg: ControlMessage,
3337    ) -> Result<(), EndpointError> {
3338        let id = request_id.into_inner();
3339        match msg {
3340            ControlMessage::RequestUpdate(ref m) => self.receive_request_update(request_id, m),
3341            // Section 10.4 puts no direction on it: "A GOAWAY MAY also be
3342            // sent on a request stream to initiate migration of that individual
3343            // request." A request the peer opened is a request stream, so a
3344            // GOAWAY on one migrates it the same way.
3345            ControlMessage::GoAway(ref m) => self.receive_goaway_on_request_stream(request_id, m),
3346            ControlMessage::PublishDone(_) => {
3347                let sm = self.publishes.get_mut(&id).ok_or(EndpointError::UnknownRequest(id))?;
3348                sm.on_publish_done_received()?;
3349                Ok(())
3350            }
3351            other => Err(EndpointError::UnexpectedOnPeerRequestStream(other.message_type())),
3352        }
3353    }
3354}
3355
3356// -- Responder-side state machine transitions -----------------------
3357//
3358// Each one is the same edge as an existing requester-side transition — the
3359// graph does not change with the direction — but under a name that says which
3360// way the message went, so a mis-dispatch names the responder event in the
3361// `InvalidTransition` it produces instead of quietly succeeding.
3362//
3363// They are written against the public surface of the machines rather than
3364// against the state field, so the rejected-state error has to be rebuilt to
3365// carry the responder event name.
3366
3367impl SubscriptionStateMachine {
3368    /// Idle -> Subscribing (SUBSCRIBE received from the peer).
3369    pub fn on_subscribe_received(&mut self) -> Result<(), SubscriptionError> {
3370        self.on_subscribe_sent().map_err(|_| SubscriptionError::InvalidTransition {
3371            from: self.state(),
3372            event: "on_subscribe_received".to_string(),
3373        })
3374    }
3375
3376    /// Subscribing -> Active (SUBSCRIBE_OK written on the peer's stream).
3377    pub fn on_subscribe_ok_sent(&mut self) -> Result<(), SubscriptionError> {
3378        self.on_subscribe_ok().map_err(|_| SubscriptionError::InvalidTransition {
3379            from: self.state(),
3380            event: "on_subscribe_ok_sent".to_string(),
3381        })
3382    }
3383
3384    /// Subscribing -> Done (REQUEST_ERROR written on the peer's stream).
3385    pub fn on_subscribe_error_sent(&mut self) -> Result<(), SubscriptionError> {
3386        self.on_subscribe_error().map_err(|_| SubscriptionError::InvalidTransition {
3387            from: self.state(),
3388            event: "on_subscribe_error_sent".to_string(),
3389        })
3390    }
3391
3392    /// Active -> Done (PUBLISH_DONE written on the peer's stream).
3393    pub fn on_publish_done_sent(&mut self) -> Result<(), SubscriptionError> {
3394        self.on_publish_done().map_err(|_| SubscriptionError::InvalidTransition {
3395            from: self.state(),
3396            event: "on_publish_done_sent".to_string(),
3397        })
3398    }
3399}
3400
3401impl FetchStateMachine {
3402    /// Idle -> Pending (FETCH received from the peer).
3403    pub fn on_fetch_received(&mut self) -> Result<(), FetchError> {
3404        self.on_fetch_sent().map_err(|_| FetchError::InvalidTransition {
3405            from: self.state(),
3406            event: "on_fetch_received".to_string(),
3407        })
3408    }
3409
3410    /// Pending -> Receiving, Unanswered -> Done (FETCH_OK written on the
3411    /// peer's stream).
3412    ///
3413    /// The state is named for the requester's view; for a responder the same
3414    /// node means the objects are being served rather than received. It is the
3415    /// same node in the graph, with the same edges, so it keeps its name.
3416    pub fn on_fetch_ok_sent(&mut self) -> Result<(), FetchError> {
3417        self.on_fetch_ok().map_err(|_| FetchError::InvalidTransition {
3418            from: self.state(),
3419            event: "on_fetch_ok_sent".to_string(),
3420        })
3421    }
3422
3423    /// Pending | Unanswered -> Done (REQUEST_ERROR written on the peer's
3424    /// stream).
3425    pub fn on_fetch_error_sent(&mut self) -> Result<(), FetchError> {
3426        self.on_fetch_error().map_err(|_| FetchError::InvalidTransition {
3427            from: self.state(),
3428            event: "on_fetch_error_sent".to_string(),
3429        })
3430    }
3431
3432    /// Receiving -> Done, Pending -> Unanswered (this endpoint finished the
3433    /// fetch data stream).
3434    pub fn on_stream_fin_sent(&mut self) -> Result<(), FetchError> {
3435        self.on_stream_fin().map_err(|_| FetchError::InvalidTransition {
3436            from: self.state(),
3437            event: "on_stream_fin_sent".to_string(),
3438        })
3439    }
3440}
3441
3442impl PublishStateMachine {
3443    /// Idle -> Publishing (PUBLISH received from the peer).
3444    pub fn on_publish_received(&mut self) -> Result<(), PublishFlowError> {
3445        self.on_publish_sent().map_err(|_| PublishFlowError::InvalidTransition {
3446            from: self.state(),
3447            event: "on_publish_received".to_string(),
3448        })
3449    }
3450
3451    /// Publishing -> Active (REQUEST_OK written on the peer's stream).
3452    ///
3453    /// Draft-18 folded PUBLISH_OK into REQUEST_OK and draft-19 keeps it that
3454    /// way, so the message that walks this edge is a REQUEST_OK here where on
3455    /// draft-17 it was a PUBLISH_OK of its own.
3456    pub fn on_publish_ok_sent(&mut self) -> Result<(), PublishFlowError> {
3457        self.on_publish_ok().map_err(|_| PublishFlowError::InvalidTransition {
3458            from: self.state(),
3459            event: "on_publish_ok_sent".to_string(),
3460        })
3461    }
3462
3463    /// Publishing -> Done (REQUEST_ERROR written on the peer's stream).
3464    pub fn on_publish_error_sent(&mut self) -> Result<(), PublishFlowError> {
3465        self.on_publish_error().map_err(|_| PublishFlowError::InvalidTransition {
3466            from: self.state(),
3467            event: "on_publish_error_sent".to_string(),
3468        })
3469    }
3470
3471    /// Active -> Done (PUBLISH_DONE received from the publishing peer).
3472    pub fn on_publish_done_received(&mut self) -> Result<(), PublishFlowError> {
3473        self.on_publish_done_sent().map_err(|_| PublishFlowError::InvalidTransition {
3474            from: self.state(),
3475            event: "on_publish_done_received".to_string(),
3476        })
3477    }
3478}
3479
3480impl PublishNamespaceStateMachine {
3481    /// Idle -> Pending (PUBLISH_NAMESPACE received from the peer).
3482    pub fn on_publish_namespace_received(&mut self) -> Result<(), NamespaceError> {
3483        self.on_publish_namespace_sent().map_err(|_| NamespaceError::InvalidTransition {
3484            from: format!("{:?}", self.state()),
3485            event: "on_publish_namespace_received".to_string(),
3486        })
3487    }
3488
3489    /// Pending -> Active (REQUEST_OK written on the peer's stream).
3490    pub fn on_publish_namespace_ok_sent(&mut self) -> Result<(), NamespaceError> {
3491        self.on_publish_namespace_ok().map_err(|_| NamespaceError::InvalidTransition {
3492            from: format!("{:?}", self.state()),
3493            event: "on_publish_namespace_ok_sent".to_string(),
3494        })
3495    }
3496
3497    /// Pending -> Done (REQUEST_ERROR written on the peer's stream).
3498    pub fn on_publish_namespace_error_sent(&mut self) -> Result<(), NamespaceError> {
3499        self.on_publish_namespace_error().map_err(|_| NamespaceError::InvalidTransition {
3500            from: format!("{:?}", self.state()),
3501            event: "on_publish_namespace_error_sent".to_string(),
3502        })
3503    }
3504}
3505
3506impl SubscribeNamespaceStateMachine {
3507    /// Idle -> Pending (SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS received from
3508    /// the peer).
3509    pub fn on_subscribe_namespace_received(&mut self) -> Result<(), NamespaceError> {
3510        self.on_subscribe_namespace_sent().map_err(|_| NamespaceError::InvalidTransition {
3511            from: format!("{:?}", self.state()),
3512            event: "on_subscribe_namespace_received".to_string(),
3513        })
3514    }
3515
3516    /// Pending -> Active (REQUEST_OK written on the peer's stream).
3517    pub fn on_subscribe_namespace_ok_sent(&mut self) -> Result<(), NamespaceError> {
3518        self.on_subscribe_namespace_ok().map_err(|_| NamespaceError::InvalidTransition {
3519            from: format!("{:?}", self.state()),
3520            event: "on_subscribe_namespace_ok_sent".to_string(),
3521        })
3522    }
3523
3524    /// Pending -> Done (REQUEST_ERROR written on the peer's stream).
3525    pub fn on_subscribe_namespace_error_sent(&mut self) -> Result<(), NamespaceError> {
3526        self.on_subscribe_namespace_error().map_err(|_| NamespaceError::InvalidTransition {
3527            from: format!("{:?}", self.state()),
3528            event: "on_subscribe_namespace_error_sent".to_string(),
3529        })
3530    }
3531
3532    /// Active -> Active (NAMESPACE written on the peer's SUBSCRIBE_NAMESPACE
3533    /// stream).
3534    ///
3535    /// Draft-19 Section 10.16 puts NAMESPACE "on the response stream of a
3536    /// SUBSCRIBE_NAMESPACE request", and Section 10.18 has the publisher send
3537    /// them only once the request has been accepted — "If the
3538    /// SUBSCRIBE_NAMESPACE is successful, the publisher will send matching
3539    /// NAMESPACE messages on the response stream." Requiring Active is what
3540    /// makes one written ahead of the REQUEST_OK an error rather than a frame
3541    /// on the wire.
3542    ///
3543    /// Draft-17 has no such edge: its message table has no Stream column and
3544    /// nothing there moves NAMESPACE off the control stream.
3545    pub fn on_namespace_sent(&mut self) -> Result<(), NamespaceError> {
3546        self.require_active("on_namespace_sent")
3547    }
3548
3549    /// Active -> Active (NAMESPACE_DONE written on the peer's
3550    /// SUBSCRIBE_NAMESPACE stream).
3551    ///
3552    /// Section 10.17: "All NAMESPACE_DONE messages are in response to a
3553    /// SUBSCRIBE_NAMESPACE". The namespace subscription outlives it — Section
3554    /// 10.18 has the publisher go on sending NAMESPACE and NAMESPACE_DONE "when
3555    /// there are changes to the namespaces being published" — so this ends one
3556    /// namespace, not the request, and the state does not move.
3557    pub fn on_namespace_done_sent(&mut self) -> Result<(), NamespaceError> {
3558        self.require_active("on_namespace_done_sent")
3559    }
3560
3561    /// Active -> Active (PUBLISH_SKIPPED written on the peer's
3562    /// SUBSCRIBE_TRACKS stream).
3563    ///
3564    /// Section 10.20: "All PUBLISH_SKIPPED messages are in response to a
3565    /// SUBSCRIBE_TRACKS". One skipped track says nothing about the rest, so
3566    /// like the two above this is a self-transition on an accepted request.
3567    pub fn on_publish_skipped_sent(&mut self) -> Result<(), NamespaceError> {
3568        self.require_active("on_publish_skipped_sent")
3569    }
3570
3571    /// The shared body of the three self-transitions above: accept the event
3572    /// when the request has been answered with REQUEST_OK, and name the event
3573    /// that was refused otherwise.
3574    fn require_active(&self, event: &str) -> Result<(), NamespaceError> {
3575        if self.state() == SubscribeNamespaceState::Active {
3576            Ok(())
3577        } else {
3578            Err(NamespaceError::InvalidTransition {
3579                from: format!("{:?}", self.state()),
3580                event: event.to_string(),
3581            })
3582        }
3583    }
3584}
3585
3586impl TrackStatusStateMachine {
3587    /// Idle -> Pending (TRACK_STATUS received from the peer).
3588    pub fn on_track_status_received(&mut self) -> Result<(), TrackStatusError> {
3589        self.on_track_status_sent().map_err(|_| TrackStatusError::InvalidTransition {
3590            from: self.state(),
3591            event: "on_track_status_received".to_string(),
3592        })
3593    }
3594
3595    /// Pending -> Done (REQUEST_OK written on the peer's stream).
3596    pub fn on_track_status_ok_sent(&mut self) -> Result<(), TrackStatusError> {
3597        self.on_track_status_ok().map_err(|_| TrackStatusError::InvalidTransition {
3598            from: self.state(),
3599            event: "on_track_status_ok_sent".to_string(),
3600        })
3601    }
3602
3603    /// Pending -> Done (REQUEST_ERROR written on the peer's stream).
3604    pub fn on_track_status_error_sent(&mut self) -> Result<(), TrackStatusError> {
3605        self.on_track_status_error().map_err(|_| TrackStatusError::InvalidTransition {
3606            from: self.state(),
3607            event: "on_track_status_error_sent".to_string(),
3608        })
3609    }
3610}
3611
3612#[cfg(test)]
3613mod responder_tests {
3614    use super::*;
3615    use crate::draft19::namespace::SubscribeNamespaceState;
3616    use crate::draft19::publish::PublishState;
3617    use crate::draft19::subscription::SubscriptionState;
3618    use moqtap_codec::kvp::KvpValue;
3619
3620    fn active_client() -> Endpoint {
3621        let mut ep = Endpoint::new(Role::Client);
3622        ep.connect().unwrap();
3623        let _ = ep.send_setup(vec![]).unwrap();
3624        ep.receive_setup(&Setup { options: vec![] }).unwrap();
3625        ep
3626    }
3627
3628    fn v(n: u64) -> VarInt {
3629        VarInt::from_u64(n).unwrap()
3630    }
3631
3632    fn ns() -> TrackNamespace {
3633        TrackNamespace(vec![b"live".to_vec()])
3634    }
3635
3636    fn peer_subscribe(id: u64) -> ControlMessage {
3637        ControlMessage::Subscribe(Subscribe {
3638            request_id: v(id),
3639            track_namespace: ns(),
3640            track_name: b"video".to_vec(),
3641            parameters: vec![],
3642        })
3643    }
3644
3645    fn peer_publish(id: u64) -> ControlMessage {
3646        ControlMessage::Publish(Publish {
3647            request_id: v(id),
3648            track_namespace: ns(),
3649            track_name: b"video".to_vec(),
3650            track_alias: v(7),
3651            parameters: vec![],
3652            track_properties: vec![],
3653        })
3654    }
3655
3656    fn request_ok() -> ControlMessage {
3657        ControlMessage::RequestOk(RequestOk { parameters: vec![], track_properties: vec![] })
3658    }
3659
3660    fn publish_done() -> ControlMessage {
3661        ControlMessage::PublishDone(PublishDone {
3662            status_code: v(0),
3663            stream_count: v(0),
3664            reason_phrase: Vec::new(),
3665        })
3666    }
3667
3668    /// The peer's requests and this endpoint's share one map per kind, and the
3669    /// opposite Request ID parity is what keeps them apart. Both directions
3670    /// are registered here and both are still there afterwards, which is the
3671    /// consequence a collision would destroy.
3672    #[test]
3673    fn a_peers_request_lives_beside_our_own_in_the_same_map() {
3674        let mut ep = active_client();
3675        let (ours, _) = ep.subscribe(ns(), b"video".to_vec(), vec![]).unwrap();
3676        assert_eq!(ours.into_inner(), 0, "a client allocates even Request IDs");
3677
3678        let theirs = ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3679        assert_eq!(theirs.into_inner(), 1);
3680        assert_eq!(
3681            ep.active_subscription_count(),
3682            2,
3683            "the peer's subscription displaced ours in the map",
3684        );
3685        assert_eq!(ep.peer_request_count(), 1);
3686    }
3687
3688    /// Draft-19 Section 10.1: a Request ID whose least significant bit is
3689    /// wrong for the sender MUST close the session with INVALID_REQUEST_ID.
3690    /// The close is observable twice over — the endpoint stops accepting
3691    /// requests, and the code the connection layer will put on the wire is the
3692    /// one the section names.
3693    #[test]
3694    fn a_peer_id_with_our_own_parity_closes_the_session() {
3695        let mut ep = active_client();
3696        // 2 is even, so it is an id this client allocates, not one the server
3697        // may send.
3698        let err = ep.receive_request_on_stream(&peer_subscribe(2)).unwrap_err();
3699        assert_eq!(err.session_error_code(), Some(SessionErrorCode::InvalidRequestId));
3700        assert_eq!(err.to_string(), "request ID error: request ID 2 has wrong parity for Server");
3701        assert_eq!(ep.session_state(), SessionState::Closed);
3702        assert_eq!(ep.active_subscription_count(), 0, "a refused request was registered anyway");
3703        assert!(matches!(
3704            ep.receive_request_on_stream(&peer_subscribe(1)),
3705            Err(EndpointError::NotActive),
3706        ));
3707    }
3708
3709    /// The other half of the same sentence: a duplicate Request ID is also
3710    /// INVALID_REQUEST_ID. The id is remembered even though the first request
3711    /// is still open, which is why the second is caught.
3712    #[test]
3713    fn a_repeated_peer_request_id_closes_the_session() {
3714        let mut ep = active_client();
3715        ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3716        let err = ep.receive_request_on_stream(&peer_publish(1)).unwrap_err();
3717        assert_eq!(err.session_error_code(), Some(SessionErrorCode::InvalidRequestId));
3718        assert_eq!(err.to_string(), "request 1 was already used by the peer");
3719        assert_eq!(ep.session_state(), SessionState::Closed);
3720        assert_eq!(ep.active_publish_count(), 0, "the duplicate was registered anyway");
3721    }
3722
3723    /// Draft-19 Section 3.3 gives a different code for a different rule: a
3724    /// bidirectional stream that begins with the wrong message type is a
3725    /// PROTOCOL_VIOLATION, not an INVALID_REQUEST_ID.
3726    #[test]
3727    fn a_stream_that_opens_no_request_closes_the_session_with_protocol_violation() {
3728        let mut ep = active_client();
3729        let not_a_request =
3730            ControlMessage::GoAway(GoAway { new_session_uri: Vec::new(), timeout: v(0) });
3731        let err = ep.receive_request_on_stream(&not_a_request).unwrap_err();
3732        assert_eq!(err.session_error_code(), Some(SessionErrorCode::ProtocolViolation));
3733        assert_eq!(err.to_string(), "GoAway does not begin a request stream");
3734        assert_eq!(ep.session_state(), SessionState::Closed);
3735    }
3736
3737    /// A peer's SUBSCRIBE runs the same graph our own does, in the other
3738    /// direction: received, then answered, then ended with PUBLISH_DONE by
3739    /// this endpoint rather than by the peer.
3740    #[test]
3741    fn answering_a_peers_subscribe_walks_the_subscription_to_done() {
3742        let mut ep = active_client();
3743        let id = ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3744
3745        let ok = ControlMessage::SubscribeOk(SubscribeOk {
3746            track_alias: v(7),
3747            parameters: vec![],
3748            track_properties: vec![],
3749        });
3750        ep.send_response_on_stream(id, &ok).unwrap();
3751        assert_eq!(ep.subscriptions[&1].state(), SubscriptionState::Active);
3752
3753        ep.send_response_on_stream(id, &publish_done()).unwrap();
3754        assert_eq!(ep.subscriptions[&1].state(), SubscriptionState::Done);
3755    }
3756
3757    /// The responder transitions are separate from the requester ones so a
3758    /// mis-dispatch names the responder event rather than succeeding quietly.
3759    #[test]
3760    fn a_responder_transition_out_of_order_names_the_responder_event() {
3761        let mut ep = active_client();
3762        let id = ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3763        // PUBLISH_DONE before SUBSCRIBE_OK: the subscription is not Active.
3764        let err = ep.send_response_on_stream(id, &publish_done()).unwrap_err();
3765        assert_eq!(
3766            err.to_string(),
3767            "subscription error: invalid transition from Subscribing on event on_publish_done_sent",
3768        );
3769    }
3770
3771    /// Draft-18 folded PUBLISH_OK into REQUEST_OK and draft-19 keeps the fold,
3772    /// so a peer's PUBLISH is accepted with REQUEST_OK here where draft-17
3773    /// answers with a PUBLISH_OK of its own. The peer is then the publisher,
3774    /// so PUBLISH_DONE comes back from it on the same stream — the one
3775    /// direction the requester path never has to handle, because there we are
3776    /// the publisher.
3777    #[test]
3778    fn a_peers_publish_is_accepted_with_request_ok_and_ended_by_the_peer() {
3779        let mut ep = active_client();
3780        let id = ep.receive_request_on_stream(&peer_publish(1)).unwrap();
3781        ep.send_response_on_stream(id, &request_ok()).unwrap();
3782        assert_eq!(ep.publishes[&1].state(), PublishState::Active);
3783
3784        ep.receive_on_peer_request_stream(id, publish_done()).unwrap();
3785        assert_eq!(ep.publishes[&1].state(), PublishState::Done);
3786        assert!(
3787            ep.receive_on_peer_request_stream(id, publish_done()).is_err(),
3788            "a second PUBLISH_DONE was accepted on a publication already Done",
3789        );
3790    }
3791
3792    /// This endpoint is the responder on a stream the peer opened, so a
3793    /// response arriving there is the peer answering itself. Routing it to the
3794    /// response dispatcher would look up a request we never made; refusing it
3795    /// is what the origin marker buys.
3796    #[test]
3797    fn a_response_on_a_peer_opened_stream_is_refused() {
3798        let mut ep = active_client();
3799        let id = ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3800        let ok = ControlMessage::SubscribeOk(SubscribeOk {
3801            track_alias: v(7),
3802            parameters: vec![],
3803            track_properties: vec![],
3804        });
3805        let err = ep.receive_on_peer_request_stream(id, ok).unwrap_err();
3806        assert_eq!(
3807            err.to_string(),
3808            "SubscribeOk may not follow a request on a stream the peer opened",
3809        );
3810    }
3811
3812    /// A peer's REQUEST_UPDATE is held to the same rule the requester side is:
3813    /// draft-19 Section 10.9 puts it on its request's own stream, and the
3814    /// audited receive path already refuses one whose Request ID names a
3815    /// different request. Routing the peer's updates through that same handler
3816    /// is what keeps the two directions from disagreeing.
3817    #[test]
3818    fn a_peers_request_update_is_held_to_its_own_stream() {
3819        let mut ep = active_client();
3820        let id = ep.receive_request_on_stream(&peer_subscribe(1)).unwrap();
3821        let ok = ControlMessage::SubscribeOk(SubscribeOk {
3822            track_alias: v(7),
3823            parameters: vec![],
3824            track_properties: vec![],
3825        });
3826        ep.send_response_on_stream(id, &ok).unwrap();
3827
3828        let update = |named: u64| {
3829            ControlMessage::RequestUpdate(RequestUpdate {
3830                request_id: v(named),
3831                parameters: vec![],
3832            })
3833        };
3834        ep.receive_on_peer_request_stream(id, update(1)).unwrap();
3835        assert_eq!(ep.subscriptions[&1].state(), SubscriptionState::Active);
3836
3837        // An update naming a different request than its stream is the
3838        // violation the section answers with a close.
3839        let err = ep.receive_on_peer_request_stream(id, update(3)).unwrap_err();
3840        assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(3)), "{err}");
3841        assert_eq!(ep.session_state(), SessionState::Closed);
3842    }
3843
3844    /// SUBSCRIBE_TRACKS (0x51) is the seventh request kind, added in draft-18
3845    /// and absent from draft-17. A responder that carried draft-17's six over
3846    /// would refuse it as a non-request and close the session, so the
3847    /// consequence checked is that it is registered and answerable.
3848    ///
3849    /// Section 10.19 keeps its overlap space independent of
3850    /// SUBSCRIBE_NAMESPACE's, which is why it lands in its own map.
3851    #[test]
3852    fn a_peers_subscribe_tracks_is_a_request_of_its_own() {
3853        let mut ep = active_client();
3854        let tracks = ControlMessage::SubscribeTracks(SubscribeTracks {
3855            request_id: v(1),
3856            namespace_prefix: ns(),
3857            parameters: vec![],
3858        });
3859        let id = ep.receive_request_on_stream(&tracks).unwrap();
3860        assert_eq!(ep.active_subscribe_tracks_count(), 1);
3861        assert_eq!(
3862            ep.active_subscribe_namespace_count(),
3863            0,
3864            "SUBSCRIBE_TRACKS landed among the namespace subscriptions",
3865        );
3866        ep.send_response_on_stream(id, &request_ok()).unwrap();
3867        assert_eq!(ep.subscribe_tracks[&1].state(), SubscribeNamespaceState::Active);
3868
3869        // Section 10.20 puts PUBLISH_SKIPPED on this stream, and only on this
3870        // stream: a SUBSCRIBE_NAMESPACE has no such message.
3871        let skipped = ControlMessage::PublishSkipped(PublishSkipped {
3872            namespace_suffix: ns(),
3873            track_name: b"video".to_vec(),
3874        });
3875        ep.send_response_on_stream(id, &skipped).unwrap();
3876
3877        let mut other = active_client();
3878        let sub_ns = other
3879            .receive_request_on_stream(&ControlMessage::SubscribeNamespace(SubscribeNamespace {
3880                request_id: v(1),
3881                namespace_prefix: ns(),
3882                parameters: vec![],
3883            }))
3884            .unwrap();
3885        other.send_response_on_stream(sub_ns, &request_ok()).unwrap();
3886        assert!(
3887            other.send_response_on_stream(sub_ns, &skipped).is_err(),
3888            "PUBLISH_SKIPPED was accepted on a SUBSCRIBE_NAMESPACE stream",
3889        );
3890    }
3891
3892    /// Draft-19 Table 5 gives NAMESPACE and NAMESPACE_DONE the Stream value
3893    /// "Request", and Section 10.18 has the publisher send them only once the
3894    /// SUBSCRIBE_NAMESPACE has been accepted: "If the SUBSCRIBE_NAMESPACE is
3895    /// successful, the publisher will send matching NAMESPACE messages on the
3896    /// response stream."
3897    ///
3898    /// Draft-17 has neither edge — its message table has no Stream column — so
3899    /// this is the half of the responder a port from draft-17 would leave out.
3900    #[test]
3901    fn namespaces_are_announced_on_the_peers_subscribe_namespace_stream() {
3902        let mut ep = active_client();
3903        let id = ep
3904            .receive_request_on_stream(&ControlMessage::SubscribeNamespace(SubscribeNamespace {
3905                request_id: v(1),
3906                namespace_prefix: ns(),
3907                parameters: vec![],
3908            }))
3909            .unwrap();
3910
3911        let namespace = ControlMessage::Namespace(message::Namespace { namespace_suffix: ns() });
3912        let err = ep.send_response_on_stream(id, &namespace).unwrap_err();
3913        assert_eq!(
3914            err.to_string(),
3915            "namespace error: invalid transition from Pending on event on_namespace_sent",
3916            "a NAMESPACE was allowed ahead of the REQUEST_OK that accepts the request",
3917        );
3918
3919        ep.send_response_on_stream(id, &request_ok()).unwrap();
3920        ep.send_response_on_stream(id, &namespace).unwrap();
3921        ep.send_response_on_stream(
3922            id,
3923            &ControlMessage::NamespaceDone(message::NamespaceDone { namespace_suffix: ns() }),
3924        )
3925        .unwrap();
3926        // One namespace ending does not end the subscription to the prefix.
3927        assert_eq!(ep.subscribe_namespaces[&1].state(), SubscribeNamespaceState::Active);
3928    }
3929
3930    /// Draft-19 Section 10.5 answers Track Properties on a REQUEST_OK that is
3931    /// not a TRACK_STATUS response with a session close. The receive path
3932    /// already refuses them; a responder that writes them would be handing a
3933    /// conforming peer that reason, so the send path refuses them too — and
3934    /// without closing this session, because nothing reached the wire.
3935    #[test]
3936    fn track_properties_are_refused_on_the_way_out_too() {
3937        let properties = vec![KeyValuePair { key: v(0x04), value: KvpValue::Varint(v(1000)) }];
3938        let with_properties = ControlMessage::RequestOk(RequestOk {
3939            parameters: vec![],
3940            track_properties: properties.clone(),
3941        });
3942
3943        let mut ep = active_client();
3944        let id = ep
3945            .receive_request_on_stream(&ControlMessage::SubscribeNamespace(SubscribeNamespace {
3946                request_id: v(1),
3947                namespace_prefix: ns(),
3948                parameters: vec![],
3949            }))
3950            .unwrap();
3951        let err = ep.send_response_on_stream(id, &with_properties).unwrap_err();
3952        assert!(matches!(err, EndpointError::TrackPropertiesOnOutgoingRequestOk(1)), "{err}");
3953        assert_eq!(err.session_error_code(), None, "refusing our own write closed the session");
3954        assert_eq!(
3955            ep.subscribe_namespaces[&1].state(),
3956            SubscribeNamespaceState::Pending,
3957            "the refused response moved the state machine anyway",
3958        );
3959        // The request is still answerable without them.
3960        ep.send_response_on_stream(id, &request_ok()).unwrap();
3961
3962        // TRACK_STATUS_OK is the shape that carries them.
3963        let mut ep = active_client();
3964        let id = ep
3965            .receive_request_on_stream(&ControlMessage::TrackStatus(message::TrackStatus {
3966                request_id: v(1),
3967                track_namespace: ns(),
3968                track_name: b"video".to_vec(),
3969                parameters: vec![],
3970            }))
3971            .unwrap();
3972        ep.send_response_on_stream(id, &with_properties).unwrap();
3973    }
3974}
3975
3976#[cfg(test)]
3977mod tests {
3978    use super::*;
3979    use moqtap_codec::kvp::KvpValue;
3980
3981    fn v(n: u64) -> VarInt {
3982        VarInt::from_u64_moqt(n)
3983    }
3984
3985    fn ns(label: &str) -> TrackNamespace {
3986        TrackNamespace(vec![label.as_bytes().to_vec()])
3987    }
3988
3989    fn peer_subscribe(id: u64, label: &str) -> ControlMessage {
3990        ControlMessage::Subscribe(Subscribe {
3991            request_id: v(id),
3992            track_namespace: ns(label),
3993            track_name: b"video".to_vec(),
3994            parameters: vec![],
3995        })
3996    }
3997
3998    fn peer_fetch(id: u64, label: &str) -> ControlMessage {
3999        ControlMessage::Fetch(Fetch {
4000            request_id: v(id),
4001            fetch_type: FetchType::Standalone,
4002            fetch_payload: FetchPayload::Standalone {
4003                track_namespace: ns(label),
4004                track_name: b"video".to_vec(),
4005                start_group: v(0),
4006                start_object: v(0),
4007                end_group: v(1),
4008                end_object: v(0),
4009            },
4010            parameters: vec![],
4011        })
4012    }
4013
4014    fn peer_subscribe_namespace(id: u64, label: &str) -> ControlMessage {
4015        ControlMessage::SubscribeNamespace(SubscribeNamespace {
4016            request_id: v(id),
4017            namespace_prefix: ns(label),
4018            parameters: vec![],
4019        })
4020    }
4021
4022    fn peer_subscribe_tracks(id: u64, label: &str) -> ControlMessage {
4023        ControlMessage::SubscribeTracks(SubscribeTracks {
4024            request_id: v(id),
4025            namespace_prefix: ns(label),
4026            parameters: vec![],
4027        })
4028    }
4029
4030    fn peer_publish_namespace(id: u64, label: &str) -> ControlMessage {
4031        ControlMessage::PublishNamespace(PublishNamespace {
4032            request_id: v(id),
4033            track_namespace: ns(label),
4034            parameters: vec![],
4035        })
4036    }
4037
4038    fn peer_publish(id: u64, label: &str) -> ControlMessage {
4039        ControlMessage::Publish(Publish {
4040            request_id: v(id),
4041            track_namespace: ns(label),
4042            track_name: b"video".to_vec(),
4043            track_alias: v(id + 100),
4044            parameters: vec![],
4045            track_properties: vec![],
4046        })
4047    }
4048
4049    fn active(role: Role) -> Endpoint {
4050        let mut ep = Endpoint::new(role);
4051        ep.connect().unwrap();
4052        ep.receive_setup(&Setup { options: vec![] }).unwrap();
4053        assert_eq!(ep.session_state(), SessionState::Active);
4054        ep
4055    }
4056
4057    fn update(id: u64) -> RequestUpdate {
4058        RequestUpdate { request_id: v(id), parameters: vec![] }
4059    }
4060
4061    /// A session-fatal error must leave the endpoint unable to carry on: the
4062    /// state machine is Closed and every new request is refused. Asserting the
4063    /// error alone would let a caller ignore it and keep the session running,
4064    /// which is the behaviour draft-19 Section 10.9 forbids.
4065    fn assert_session_failed(ep: &mut Endpoint, err: EndpointError) {
4066        assert_eq!(
4067            err.session_error_code(),
4068            Some(SessionErrorCode::ProtocolViolation),
4069            "{err} should be fatal to the session"
4070        );
4071        assert_eq!(ep.session_state(), SessionState::Closed);
4072        assert!(matches!(
4073            ep.subscribe(ns("a"), b"b".to_vec(), vec![]),
4074            Err(EndpointError::NotActive)
4075        ));
4076    }
4077
4078    /// Draft-19 Table 5 gives REQUEST_UPDATE the Stream value "Request", and
4079    /// Section 10.9 has it sent "on the same bidi stream as the request".
4080    ///
4081    /// Before the placement was corrected the control stream accepted it and
4082    /// the request stream refused it. Routing the request-stream case back
4083    /// through the catch-all arm produces, at the first call below:
4084    ///
4085    /// ```text
4086    /// called `Result::unwrap()` on an `Err` value: ResponseOnControlStream
4087    /// ```
4088    ///
4089    /// and leaving the control-stream arm in place produces, at the assertion
4090    /// after it:
4091    ///
4092    /// ```text
4093    /// assertion failed: matches!(err, EndpointError::RequestUpdateOnControlStream)
4094    /// ```
4095    #[test]
4096    fn a_request_update_belongs_on_its_request_stream_and_not_the_control_stream() {
4097        let mut ep = active(Role::Client);
4098        // A PUBLISH this endpoint made and the peer accepted. Section 10.9
4099        // allows an update on exactly that among the requests made here, so
4100        // this drives the routing question without also being a violation.
4101        let (id, _) = ep.publish(ns("live"), b"video".to_vec(), v(7), vec![], vec![]).unwrap();
4102        ep.receive_request_ok(id, &RequestOk { parameters: vec![], track_properties: vec![] })
4103            .unwrap();
4104
4105        // The request stream is where it belongs, and the request-stream
4106        // dispatcher is the route that has to accept it.
4107        ep.receive_response_on_stream(id, ControlMessage::RequestUpdate(update(id.into_inner())))
4108            .unwrap();
4109
4110        // The control stream is not, and the draft answers that with a close.
4111        let err =
4112            ep.receive_message(ControlMessage::RequestUpdate(update(id.into_inner()))).unwrap_err();
4113        assert!(matches!(err, EndpointError::RequestUpdateOnControlStream), "{err}");
4114        assert_session_failed(&mut ep, err);
4115    }
4116
4117    /// The three messages draft-19 Table 5 places on a request stream that are
4118    /// not responses: NAMESPACE (0x8), NAMESPACE_DONE (0xE) and PUBLISH_SKIPPED
4119    /// (0xF).
4120    ///
4121    /// Table 5's Stream column reads "Request" for all three, the same value it
4122    /// gives REQUEST_UPDATE. Only SETUP is "Control" on its own; GOAWAY is
4123    /// "Control, Request". The placement had all three exactly inverted — the
4124    /// control stream accepted them and returned `Ok`, and the request stream
4125    /// fell through to the catch-all and refused them — so a conforming peer
4126    /// sending NAMESPACE on the SUBSCRIBE_NAMESPACE stream that asked for it
4127    /// had its announcement dropped.
4128    ///
4129    /// Restoring the control-stream arms (`Namespace(ref m) =>
4130    /// self.receive_namespace(m)` and its two siblings) fails this test at the
4131    /// second half with:
4132    ///
4133    /// ```text
4134    /// NAMESPACE must be refused on the control stream: Ok(())
4135    /// ```
4136    ///
4137    /// and removing the request-stream arms fails it at the first half with:
4138    ///
4139    /// ```text
4140    /// NAMESPACE belongs on a request stream: ResponseOnControlStream
4141    /// ```
4142    #[test]
4143    fn namespace_and_publish_skipped_belong_on_a_request_stream() {
4144        /// A message name paired with a way to build a fresh one, since each
4145        /// case needs two copies and `ControlMessage` is consumed by both
4146        /// dispatchers.
4147        type Case = (&'static str, fn() -> ControlMessage);
4148
4149        let cases: [Case; 3] = [
4150            ("NAMESPACE", || {
4151                ControlMessage::Namespace(message::Namespace { namespace_suffix: ns("live") })
4152            }),
4153            ("NAMESPACE_DONE", || {
4154                ControlMessage::NamespaceDone(message::NamespaceDone {
4155                    namespace_suffix: ns("live"),
4156                })
4157            }),
4158            ("PUBLISH_SKIPPED", || {
4159                ControlMessage::PublishSkipped(PublishSkipped {
4160                    namespace_suffix: ns("live"),
4161                    track_name: b"video".to_vec(),
4162                })
4163            }),
4164        ];
4165
4166        for (name, build) in cases {
4167            let mut ep = active(Role::Client);
4168            let id = ep.subscribe_namespace(ns("live"), vec![]).unwrap().0;
4169
4170            // Sections 10.18 and 10.19 make REQUEST_OK or REQUEST_ERROR the
4171            // first message on this stream, so the answer comes before the
4172            // messages that follow it. Sending the NAMESPACE first is a
4173            // different rule's violation and would answer this test's question
4174            // with that rule's error.
4175            ep.receive_response_on_stream(
4176                id,
4177                ControlMessage::RequestOk(RequestOk {
4178                    parameters: vec![],
4179                    track_properties: vec![],
4180                }),
4181            )
4182            .expect("REQUEST_OK answers the namespace subscription");
4183
4184            // Where Table 5 puts it.
4185            ep.receive_response_on_stream(id, build())
4186                .unwrap_or_else(|e| panic!("{name} belongs on a request stream: {e:?}"));
4187
4188            // Where it does not, which the draft answers with a close.
4189            let err = match ep.receive_message(build()) {
4190                Err(e) => e,
4191                Ok(()) => panic!("{name} must be refused on the control stream: Ok(())"),
4192            };
4193            assert!(
4194                matches!(err, EndpointError::RequestMessageOnControlStream(m) if m == name),
4195                "{name} on the control stream gave {err}"
4196            );
4197            assert_session_failed(&mut ep, err);
4198        }
4199    }
4200
4201    /// Draft-19 Section 10.9: "An endpoint that receives a REQUEST_UPDATE
4202    /// other than in the two cases above MUST close the session with a
4203    /// PROTOCOL_VIOLATION." Section 10.14 names TRACK_STATUS as one such case:
4204    /// "the subscriber cannot send REQUEST_UPDATE."
4205    ///
4206    /// The old handler consulted only `subscriptions` and answered both of
4207    /// these with a recoverable per-request error, so the session lived on.
4208    /// Restoring that gives, at the first assertion below:
4209    ///
4210    /// ```text
4211    /// unknown request ID: 40
4212    /// ```
4213    #[test]
4214    fn a_request_update_naming_a_non_updatable_request_closes_the_session() {
4215        // An id nothing was ever issued under.
4216        let mut ep = active(Role::Client);
4217        let err = ep.receive_request_update(v(40), &update(40)).unwrap_err();
4218        assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(40)), "{err}");
4219        assert_session_failed(&mut ep, err);
4220
4221        // TRACK_STATUS, which the draft rules out by name.
4222        let mut ep = active(Role::Client);
4223        let (id, _) = ep.track_status(ns("live"), b"video".to_vec(), vec![]).unwrap();
4224        let err = ep.receive_request_update(id, &update(id.into_inner())).unwrap_err();
4225        assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(_)), "{err}");
4226        assert_session_failed(&mut ep, err);
4227    }
4228
4229    /// Draft-19 Section 10.9's first case reaches every request kind: "The
4230    /// sender of a request (SUBSCRIBE, PUBLISH, FETCH, PUBLISH_NAMESPACE,
4231    /// SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS) can later send a REQUEST_UPDATE
4232    /// on the same bidi stream as the request to modify it."
4233    ///
4234    /// # What it catches
4235    ///
4236    /// Removing the five-map lookup, so that only a SUBSCRIBE resolves:
4237    ///
4238    /// ```text
4239    /// request 3 should be updatable: REQUEST_UPDATE for request 3, which is
4240    /// not an updatable outstanding request
4241    /// ```
4242    ///
4243    /// That cut is not evidence for this gate on its own. It reddens
4244    /// twenty-eight tests across the crate, because every update on a fetch or
4245    /// a namespace request comes through the same lookup — which makes it a
4246    /// poor ablation and a fair measure of how much rests on the line.
4247    #[test]
4248    fn an_update_from_the_requester_resolves_against_every_request_kind() {
4249        let mut ep = active(Role::Client);
4250        let mut ids = Vec::new();
4251        for msg in [
4252            peer_subscribe(1, "a"),
4253            peer_fetch(3, "b"),
4254            peer_subscribe_namespace(5, "c"),
4255            peer_subscribe_tracks(7, "d"),
4256            peer_publish_namespace(9, "e"),
4257            peer_publish(11, "f"),
4258        ] {
4259            ids.push(ep.receive_request_on_stream(&msg).unwrap());
4260        }
4261        for id in ids {
4262            ep.receive_request_update(id, &update(id.into_inner()))
4263                .unwrap_or_else(|e| panic!("request {} should be updatable: {e}", id.into_inner()));
4264        }
4265        assert_eq!(ep.session_state(), SessionState::Active);
4266    }
4267
4268    /// Section 10.9's second case: "A subscriber can also send REQUEST_UPDATE
4269    /// to modify parameters of a subscription established with PUBLISH."
4270    ///
4271    /// The publication is this endpoint's, so this is the one request of its
4272    /// own that it may be sent an update on, and the one place the sender rule
4273    /// and the request-kind rule disagree.
4274    #[test]
4275    fn an_update_on_a_publish_this_endpoint_made_is_the_second_case() {
4276        let mut ep = active(Role::Client);
4277        let (id, _) = ep.publish(ns("live"), b"video".to_vec(), v(7), vec![], vec![]).unwrap();
4278        ep.receive_request_ok(id, &RequestOk { parameters: vec![], track_properties: vec![] })
4279            .unwrap();
4280        ep.receive_request_update(id, &update(id.into_inner())).unwrap();
4281        assert_eq!(ep.session_state(), SessionState::Active);
4282    }
4283
4284    /// The second case needs the subscription to exist before it can be
4285    /// updated, and the first case does not.
4286    ///
4287    /// Section 5.1: "Once either of these sequences is successful, the
4288    /// subscription moves to the Established state and can be updated by the
4289    /// subscriber using REQUEST_UPDATE." A PUBLISH this endpoint has sent and
4290    /// the peer has not answered is Pending, so a subscriber updating it is
4291    /// updating a subscription that does not exist yet.
4292    ///
4293    /// The first case rests on something else and keeps its own timing:
4294    /// Section 10.9 lets the sender of a request update it "later" with
4295    /// nothing said about the answer, and five of the six kinds it names are
4296    /// not subscriptions at all. Both halves are here so that the asymmetry is
4297    /// the thing asserted rather than a side effect of one of them.
4298    ///
4299    /// # What it catches
4300    ///
4301    /// Asking only whether the request exists, which is all the map on its own
4302    /// can answer: it holds a PUBLISH from the moment it is sent, and the
4303    /// peer's answer is what makes it a subscription.
4304    ///
4305    /// ```text
4306    /// a PUBLISH still waiting for its answer is not an established one: ()
4307    /// ```
4308    ///
4309    /// It reddens this gate and nothing else in the client or the proxy, and
4310    /// the gate's second half stays green under it — which is what that
4311    /// half is for. A cut that tightened both cases would redden it too.
4312    #[test]
4313    fn only_an_established_publication_may_be_updated_by_its_subscriber() {
4314        // Case two, before the answer: the subscription is not established.
4315        let mut ep = active(Role::Client);
4316        let (id, _) = ep.publish(ns("live"), b"video".to_vec(), v(7), vec![], vec![]).unwrap();
4317        let err = ep
4318            .receive_request_update(id, &update(id.into_inner()))
4319            .expect_err("a PUBLISH still waiting for its answer is not an established one");
4320        assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(_)), "{err}");
4321        assert_session_failed(&mut ep, err);
4322
4323        // Case one, before the answer: allowed, and on the same beat.
4324        let mut ep = active(Role::Client);
4325        let peer = ep.receive_request_on_stream(&peer_subscribe(1, "live")).unwrap();
4326        ep.receive_request_update(peer, &update(peer.into_inner()))
4327            .expect("the sender of a request may update it before it is answered");
4328        assert_eq!(ep.session_state(), SessionState::Active);
4329    }
4330
4331    /// Section 10.9: "An endpoint that receives a REQUEST_UPDATE other than in
4332    /// the two cases above MUST close the session with a PROTOCOL_VIOLATION."
4333    ///
4334    /// Neither case reaches a SUBSCRIBE, FETCH or namespace request this
4335    /// endpoint made. Those are modified by the endpoint that made them, which
4336    /// is this one, and an update arriving on one came from the side that has
4337    /// no say over it.
4338    ///
4339    /// # What it catches
4340    ///
4341    /// Reading the Request ID's map and not the direction the update came
4342    /// from, which is what this draft did: all five request kinds this
4343    /// endpoint can make were updatable by whoever asked.
4344    ///
4345    /// ```text
4346    /// an update on a request this endpoint made is neither case: ()
4347    /// ```
4348    ///
4349    /// It reddens this gate and nothing else in the client or the proxy. The
4350    /// `()` is the `Ok` the call returned, which is the whole defect: the
4351    /// update was applied and the session carried on.
4352    #[test]
4353    fn an_update_on_a_request_this_endpoint_made_closes_the_session() {
4354        for which in 0..5 {
4355            let mut ep = active(Role::Client);
4356            let (id, _) = match which {
4357                0 => ep.subscribe(ns("live"), b"video".to_vec(), vec![]).unwrap(),
4358                1 => {
4359                    ep.fetch(ns("live"), b"video".to_vec(), v(0), v(0), v(1), v(0), vec![]).unwrap()
4360                }
4361                2 => ep.subscribe_namespace(ns("live"), vec![]).unwrap(),
4362                3 => ep.subscribe_tracks(ns("live"), vec![]).unwrap(),
4363                _ => ep.publish_namespace(ns("live"), vec![]).unwrap(),
4364            };
4365            let err = ep
4366                .receive_request_update(id, &update(id.into_inner()))
4367                .expect_err("an update on a request this endpoint made is neither case");
4368            assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(_)), "{which}: {err}");
4369            assert_session_failed(&mut ep, err);
4370        }
4371    }
4372
4373    /// A REQUEST_UPDATE whose own Request ID names a different request than
4374    /// the stream it arrived on was sent on a stream that is not its
4375    /// request's, which is the same violation.
4376    #[test]
4377    fn a_request_update_whose_id_disagrees_with_its_stream_closes_the_session() {
4378        let mut ep = active(Role::Client);
4379        let (a, _) = ep.subscribe(ns("live"), b"video".to_vec(), vec![]).unwrap();
4380        let (b, _) = ep.subscribe(ns("live"), b"audio".to_vec(), vec![]).unwrap();
4381        let err = ep.receive_request_update(a, &update(b.into_inner())).unwrap_err();
4382        assert!(matches!(err, EndpointError::UnexpectedRequestUpdate(_)), "{err}");
4383        assert_session_failed(&mut ep, err);
4384    }
4385
4386    /// Draft-19 Section 10.5: Track Properties "are populated in
4387    /// TRACK_STATUS_OK; they are empty in PUBLISH_OK, REQUEST_UPDATE_OK,
4388    /// SUBSCRIBE_NAMESPACE_OK and PUBLISH_NAMESPACE_OK. If an endpoint
4389    /// receives Track Properties in one of these messages it MUST close the
4390    /// session with a PROTOCOL_VIOLATION."
4391    ///
4392    /// `receive_request_ok` used to bind the message as `_msg`. Restoring that
4393    /// gives:
4394    ///
4395    /// ```text
4396    /// called `Result::unwrap_err()` on an `Ok` value: ()
4397    /// ```
4398    #[test]
4399    fn track_properties_on_a_request_ok_that_is_not_a_track_status_close_the_session() {
4400        let properties = vec![KeyValuePair { key: v(0x04), value: KvpValue::Varint(v(1000)) }];
4401
4402        let mut ep = active(Role::Client);
4403        let (id, _) = ep.subscribe_namespace(ns("live"), vec![]).unwrap();
4404        let err = ep
4405            .receive_request_ok(
4406                id,
4407                &RequestOk { parameters: vec![], track_properties: properties.clone() },
4408            )
4409            .unwrap_err();
4410        assert!(matches!(err, EndpointError::TrackPropertiesOnNonTrackStatus(_)), "{err}");
4411        assert_session_failed(&mut ep, err);
4412
4413        // TRACK_STATUS_OK is the shape that carries them, and still does.
4414        let mut ep = active(Role::Client);
4415        let (id, _) = ep.track_status(ns("live"), b"video".to_vec(), vec![]).unwrap();
4416        ep.receive_request_ok(id, &RequestOk { parameters: vec![], track_properties: properties })
4417            .unwrap();
4418        assert_eq!(ep.session_state(), SessionState::Active);
4419    }
4420
4421    /// Draft-19 Section 10.4: "A GOAWAY MAY also be sent on a request stream
4422    /// to initiate migration of that individual request." Table 5 gives GOAWAY
4423    /// the Stream value "Control, Request".
4424    ///
4425    /// Without the `GoAway` arm in `receive_response_on_stream` the message
4426    /// falls through to the catch-all:
4427    ///
4428    /// ```text
4429    /// called `Result::unwrap()` on an `Err` value: ResponseOnControlStream
4430    /// ```
4431    ///
4432    /// The session must survive it — only the one request is being moved.
4433    #[test]
4434    fn a_goaway_on_a_request_stream_migrates_that_request_and_not_the_session() {
4435        let mut ep = active(Role::Client);
4436        let (id, _) = ep.subscribe(ns("live"), b"video".to_vec(), vec![]).unwrap();
4437
4438        let goaway =
4439            GoAway { new_session_uri: b"https://elsewhere.example/moq".to_vec(), timeout: v(0) };
4440        ep.receive_response_on_stream(id, ControlMessage::GoAway(goaway)).unwrap();
4441
4442        assert_eq!(ep.session_state(), SessionState::Active);
4443        // Per-request migration leaves the session-wide URI unset; the control
4444        // stream is what sets that.
4445        assert_eq!(ep.goaway_uri(), None);
4446        // And a new request is still allowed.
4447        ep.subscribe(ns("live"), b"audio".to_vec(), vec![]).unwrap();
4448    }
4449
4450    /// Draft-19 Section 10.4: "If a server receives a GOAWAY with a non-zero
4451    /// New Session URI Length it MUST close the session with a
4452    /// PROTOCOL_VIOLATION."
4453    ///
4454    /// Without the role check the URI is stored and a server-role endpoint
4455    /// will follow a redirect it should have refused:
4456    ///
4457    /// ```text
4458    /// called `Result::unwrap_err()` on an `Ok` value: ()
4459    /// ```
4460    #[test]
4461    fn a_server_refuses_a_goaway_carrying_a_new_session_uri() {
4462        let mut ep = active(Role::Server);
4463        let goaway =
4464            GoAway { new_session_uri: b"https://elsewhere.example/moq".to_vec(), timeout: v(0) };
4465        let err = ep.receive_goaway(&goaway).unwrap_err();
4466        assert!(matches!(err, EndpointError::GoAwayUriAtServer), "{err}");
4467        assert_eq!(ep.goaway_uri(), None);
4468        assert_session_failed(&mut ep, err);
4469
4470        // An empty URI is the form a server may legitimately receive: it says
4471        // the peer is going away, not where to go.
4472        let mut ep = active(Role::Server);
4473        ep.receive_goaway(&GoAway { new_session_uri: vec![], timeout: v(0) }).unwrap();
4474        assert_eq!(ep.session_state(), SessionState::Draining);
4475
4476        // A client is the side that may be redirected.
4477        let mut ep = active(Role::Client);
4478        ep.receive_goaway(&goaway).unwrap();
4479        assert_eq!(ep.goaway_uri(), Some(&b"https://elsewhere.example/moq"[..]));
4480    }
4481
4482    /// Draft-19 Section 10.12, Table 6: Fetch Type 0x2 is a Relative Joining
4483    /// Fetch and 0x3 an Absolute Joining Fetch. The client could only build
4484    /// the relative form, so an application that knew the group it wanted had
4485    /// to express it as an offset from a Largest Group it may not know.
4486    #[test]
4487    fn both_joining_fetch_types_can_be_built() {
4488        let mut ep = active(Role::Client);
4489        let (_, relative) = ep.joining_fetch(v(0), v(2), Vec::new()).unwrap();
4490        let (_, absolute) = ep.absolute_joining_fetch(v(0), v(9), Vec::new()).unwrap();
4491
4492        let types: Vec<FetchType> = [relative, absolute]
4493            .iter()
4494            .map(|m| match m {
4495                ControlMessage::Fetch(f) => f.fetch_type,
4496                other => panic!("expected a FETCH, got {other:?}"),
4497            })
4498            .collect();
4499        assert_eq!(types, vec![FetchType::RelativeJoining, FetchType::AbsoluteJoining]);
4500
4501        // Both are tracked as fetches, so their responses resolve.
4502        assert_eq!(ep.active_fetch_count(), 2);
4503    }
4504}