Skip to main content

moqtap_client/draft21/
endpoint.rs

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