Skip to main content

moq_net/
lib.rs

1//! # moq-net: Media over QUIC networking layer
2//!
3//! `moq-net` is the networking layer for Media over QUIC: real-time pub/sub with built-in
4//! caching, fan-out, and prioritization, on top of QUIC. Sub-second latency at massive scale.
5//! At session setup it negotiates one of two wire protocols: the simplified `moq-lite`
6//! protocol (the default) or the full IETF `moq-transport` protocol.
7//!
8//! ## Features
9//! The `async` feature, off by default, enables the generated async wrappers for the `poll_*`
10//! methods, the announcement `Stream` adapter, `time::run`, and the Lite/IETF sessions
11//! (`Client`, `Server`, `Session`, and the session `Driver`). Without it, use the model's
12//! `poll_*` methods and [`origin::Driver`] with explicit time. Origin serving stays available
13//! without a native runtime; no executor or clock is chosen by the model.
14//!
15//! ## API
16//! The API is built around Producer/Consumer pairs, with the hierarchy:
17//! - [origin::Consumer]: A collection of [broadcast::Consumer]s, produced by one or more sessions.
18//! - [broadcast::Consumer]: A collection of [track::Consumer]s, produced by a single publisher.
19//! - [track::Consumer]: A collection of [group::Info]s, delivered out-of-order until expired.
20//! - [group::Info]: A collection of [frame::Info]s, delivered in order until cancelled.
21//! - [frame::Info]: Chunks of data with an upfront size.
22//!
23//! Each level lives in its own module (`broadcast`, `track`, `group`, `frame`, `origin`,
24//! `announce`) that owns the short `Producer` / `Consumer` / `Info` names.
25//!
26//! [`meta`] reads a track's groups and each frame's header without the payload, as a
27//! subscription of its own beside payload subscriptions ([`broadcast::Consumer::meta`]).
28//!
29//! Traffic counters for the levels above live in [`stats`]: build a [`stats::Registry`]
30//! and hand each session a [`stats::Session`] via `Client::with_stats` /
31//! `Server::with_stats`. Publishing the counters as MoQ broadcasts lives in the
32//! `moq-stats` crate.
33//!
34//! ## Wire invariants
35//! - **Stream identities**: a subscription stays on its starting identity while that identity
36//!   has a route, even after a newer route wins the path. When none remains, it ends with an
37//!   error (never a clean end, never stitched onto another identity). A clean end means only a
38//!   deliberate publisher finish; apps restart on announcements, never request errors.
39//! - **Live position**: largest group / live edge comes only from an open upstream
40//!   subscription (`SUBSCRIBE_OK`); a copy with none open waits, and a partial group hit still
41//!   asks upstream for missing frames.
42//! - **Group expiry**: groups never overlap in time (frames within a group may reorder for
43//!   B-frames). Expire a group by timestamp (from `GROUP_END` once whole, else lowest timestamp
44//!   known in any higher group) and by wall clock once its successor arrived longer ago than
45//!   the budget; the latest group never expires.
46//! - **Route switch**: for the same identity, split at one boundary (largest group any copy
47//!   holds, past its contiguous frames): the new subscription starts there while the old caps
48//!   there and drains below within budget, delivering each frame once from whichever arrives
49//!   first.
50//!
51//! ## Compatibility
52//! The API exposes the intersection of features supported by both protocols, intentionally
53//! keeping it small rather than polluting it with half-baked features.
54//!
55//! The library is forwards-compatible with the full IETF specification and supports
56//! moq-transport drafts 18+ via version negotiation. Everything will work perfectly,
57//! so long as your application uses the API as defined above.
58//!
59//! For example, there's no concept of "sub-group". When connecting to a moq-transport
60//! implementation, we use `sub-group=0` for all frames and silently drop any received
61//! frames not in `sub-group=0`. If your application genuinely needs multiple sub-groups,
62//! tell me *why* and we can figure something out.
63//!
64//! ## Producers and Consumers
65//! Each level of the hierarchy is split into a Producer / Consumer pair:
66//! - The **Producer** is the writer: it appends new state (publishes a broadcast,
67//!   starts a group, writes frames, closes a track).
68//! - The **Consumer** is a reader: each consumer holds its own independent view
69//!   of the producer's state, with its own cursor through the stream.
70//!
71//! Both halves are cheaply clonable so you can hand out multiple handles. Cloning
72//! a consumer creates another reader (each at its own cursor); cloning a producer
73//! gives another writer that contributes to the same shared state. Closing the
74//! last producer signals consumers that no more updates are coming.
75//!
76//! ## Driving and time
77//! Session and origin drivers never spawn tasks or read the clock.
78//! Minting an [`Identity`] uses secure randomness. `Client::connect` and
79//! `Server::accept` take an initial [`time::Instant`] and return
80//! `(Session, Driver)`. Poll the `Driver` with the current instant and a
81//! [`kio::Waiter`], then wake on external activity or at the deadline it
82//! returns; `time::run` does exactly that on tokio or the browser. The last
83//! `Session` drop requests closure; dropping the driver cancels it.
84//!
85//! [`origin::Producer::new`] also returns a producer and driver. Its driver runs
86//! route changes, serving, linger, teardown, and the origin's cache expiration.
87//! Standalone caches expose [`cache::Pool::poll`]. Frame read/write methods
88//! clear their expiration timestamp for the next cleanup pass. Datagram tracks keep a
89//! short buffer and no cache; model read/write APIs take no time argument, though a frame write stamps
90//! its arrival from the ambient clock ([`frame::Frame::created`]).
91//!
92//! Both drivers implement [`time::Driver`]. `moq-uring` drives thread-local
93//! transports on its own timer heap. Tests advance time by supplying a later
94//! instant.
95
96#![warn(missing_docs)]
97#![cfg_attr(
98	test,
99	allow(
100		clippy::redundant_closure,
101		reason = "`Decode`'s buffer lifetime is a trait parameter, so `T::decode` names one lifetime, and only a closure passes where a test helper takes any"
102	)
103)]
104
105// Sessions hand out the auth, GOAWAY, and SETUP handles, so without `async` they are
106// unobtainable and stay private to the model and wire code that still uses them.
107#[cfg(feature = "async")]
108pub mod auth;
109#[cfg(not(feature = "async"))]
110#[allow(dead_code, unused_imports, reason = "async-only")]
111mod auth;
112#[cfg(feature = "async")]
113mod client;
114mod coding;
115#[cfg(feature = "async")]
116mod discovery;
117#[cfg(feature = "async")]
118mod driver;
119mod error;
120#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
121pub mod fuzz;
122#[cfg(feature = "async")]
123pub mod goaway;
124#[cfg(not(feature = "async"))]
125#[allow(dead_code, unused_imports, reason = "async-only")]
126mod goaway;
127mod identity;
128mod ietf;
129mod ledger;
130mod lite;
131mod model;
132pub mod path;
133#[cfg(feature = "async")]
134mod priority;
135#[cfg(feature = "async")]
136mod recv;
137mod route;
138#[cfg(feature = "async")]
139pub mod setup;
140#[cfg(not(feature = "async"))]
141#[allow(dead_code, unused_imports, reason = "async-only")]
142mod setup;
143#[cfg(feature = "async")]
144mod tail;
145#[cfg(all(test, feature = "async"))]
146mod test_interop;
147#[cfg(test)]
148mod test_tracing;
149mod util;
150mod version;
151
152#[cfg(feature = "async")]
153pub mod reconnect;
154#[cfg(feature = "async")]
155pub mod server;
156#[cfg(feature = "async")]
157pub mod session;
158pub mod stats;
159pub mod time;
160pub mod transport;
161
162#[cfg(feature = "async")]
163pub use client::*;
164pub use coding::{BoundsExceeded, DecodeError, EncodeError, varint};
165#[cfg(feature = "async")]
166pub use driver::Driver;
167pub use error::*;
168pub use identity::{Identity, InvalidIdentity};
169pub use model::*;
170pub use path::{InvalidPrefix, Path, Prefix, Prefixes};
171#[cfg(feature = "async")]
172pub use reconnect::Reconnect;
173#[cfg(feature = "async")]
174pub use server::Server;
175#[cfg(feature = "async")]
176pub use session::Session;
177pub use version::*;
178
179/// This crate's product token, `moq-net-rs/<version>`, which SETUP advertises by default.
180///
181/// A wrapper prepends its own token, space-separated, outermost first:
182/// `format!("moq-ffi/{v} {}", moq_net::IMPLEMENTATION)`.
183pub const IMPLEMENTATION: &str = concat!("moq-net-rs/", env!("CARGO_PKG_VERSION"));