Struct Node
pub struct Node { /* private fields */ }Expand description
A MoQ node on an iroh endpoint.
Cheap to clone, and shutdown ends it for every clone.
Mount it on a Router with mount.
§Examples
Publish a broadcast and serve it to whoever connects:
use iroh::{Endpoint, protocol::Router};
use iroh_live_node::{Audience, MinimalPreset, Node, NodeConfig};
let endpoint = Endpoint::bind(MinimalPreset).await?;
let node = Node::new(endpoint.clone(), NodeConfig::default());
let _router = node.mount(Router::builder(endpoint)).spawn();
let publication = node.publish("demo/camera", Audience::Granted)?;
// write tracks into the broadcast in the route table:
let _track = publication.broadcast().create_track("video", None).ok_or("the track exists")?;Implementations§
§impl Node
impl Node
pub fn claim_path(
&self,
peer: PublicKey,
path: &Path,
) -> Result<PathClaim, Error>
pub fn claim_path( &self, peer: PublicKey, path: &Path, ) -> Result<PathClaim, Error>
Widens what peer may publish on this node to path, for as long as the claim lives.
moq grants are prefixes, so the claim covers every path beneath path
too. This is how a ticket subscribe reads a path the node’s grant would not
let the peer publish. The claim is added on top of each session’s
grant, on every session with the peer, including ones that
start later. Dropping the last claim on a path narrows the grant again,
and moq then ends what local readers read at the path from the peer.
A live session applies the wider grant a moment after this returns, so a read of the path that starts at once may still be refused.
A claim on a path of this node’s own id is a no-op. A claim on a
path the peer owns is recorded even while the peer’s authorization
(see authorization_for) already lets it
publish there: it widens nothing then, and keeps the path if a
re-decide narrows the authorization. A path the peer does not own but its authorization
covers is a no-op claim.
Otherwise the peer has to own the path: the
Layout::owner of
NodeConfig::layout decides if it is
set. Otherwise exactly one segment of the path is the peer’s endpoint
id, and no other segment parses as one. The claimed path itself then
belongs to the peer. The paths beneath it that the claim also covers
belong to the peer or to no one, provided the layout’s ownership
carries down to sub-paths, as Layout
requires. Hop pinning and the route table rely on that.
§Errors
Fails with [Error::NotOwner] if the peer neither owns the path nor
may publish there, [Error::TooManyClaims] if the peer already holds
64 claimed paths or 16 KiB of them, and [Error::ShutDown] once the
node has shut down.
§impl Node
impl Node
pub fn new(endpoint: Endpoint, config: NodeConfig) -> Node
pub fn new(endpoint: Endpoint, config: NodeConfig) -> Node
pub fn mount(&self, router: RouterBuilder) -> RouterBuilder
pub fn mount(&self, router: RouterBuilder) -> RouterBuilder
Mounts the node on router under every ALPN in alpns.
Without a router, or an accept loop that hands connections to the node, the endpoint refuses every incoming connection.
Returns the authorization the policy gave the newest session with peer that holds one.
The node decides each session on its own, so two sessions with one
peer may hold different authorizations. Session::grant reads the
grant of one session, with the ticket claims that widen it. An expired
authorization stays here until the policy decides again, while
Session::grant already grants nothing. Returns None once the peer
has no session, or none that holds an authorization.
Asks the policy again about every live session with peer.
Call it when state the policy reads changes, such as a
filter predicate. The decisions run in the
background: a new authorization replaces a session’s, and a
rejection closes that session with its code.
A session of any peer whose first decision is still running when this is called is decided again once it registers, and holds nothing until then, so it never keeps rights from before the call.
Asks the policy again about every live session.
It does for every peer what reauthorize does for one.
pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static
pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static
Returns a future that resolves when the node shuts down.
Resolves once shutdown starts, or once the last
handle drops. Cancellation safe.
pub fn publish(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
) -> Result<Publication, Error>
pub fn publish(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
) -> Result<Publication, Error>
Creates a broadcast at path in the route table, for audience.
Fill it through Publication::broadcast. moq’s limits on a grant
bound how many publications one peer can see, as
[moq_ext_access::visible_paths] describes.
A link sees a path through a grant prefix, which covers every path
beneath it. A publication beneath another with a narrower audience
therefore hides the upper one from every link outside its own
audience, media relays included when the lower one is
Audience::Peers. The node logs a warning when that happens.
Publish a private broadcast beside a public one, not beneath it.
§Errors
Fails with [Error::Duplicate] if another publication has the path,
[Error::Moq] if path does not parse, [Error::InvalidPath] for an
empty path or one with a * segment, and [Error::ShutDown] once the
node has shut down.
§Panics
Panics when called outside a Tokio runtime.
pub fn publish_with<T, E>(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
fill: impl FnOnce(&Producer) -> Result<T, E>,
) -> Result<(Publication, T), Error>
pub fn publish_with<T, E>(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
fill: impl FnOnce(&Producer) -> Result<T, E>,
) -> Result<(Publication, T), Error>
Publishes as publish does, filling the broadcast before it is announced.
fill runs once, before anyone can see the broadcast, and its result
comes back with the publication. Create the tracks a reader needs
first there, such as a catalog. It runs before the node takes its
lock, so it may call back into the node. If the path turns out to be
taken, the broadcast is closed and what fill returned is dropped.
§Errors
As publish, and [Error::Fill] if fill fails,
which closes the broadcast. fill may fail with any error that boxes
into a std::error::Error, an anyhow::Error included.
§Panics
Panics when called outside a Tokio runtime.
pub fn publish_value<T>(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
name: &str,
) -> Result<(Publication, ValueWriter<T>), Error>
pub fn publish_value<T>(
&self,
path: impl TryInto>,
audience: Audience<PublicKey>,
name: &str,
) -> Result<(Publication, ValueWriter<T>), Error>
Publishes a broadcast at path whose one track name holds a latest-value JSON track.
For state such as a setting, a status or a result: each
update replaces the value, and a reader that
subscribes late gets the current one at once. The track counts
milliseconds, and the ValueWriter stamps each update with the time
it is made; update_at takes a time of the
caller’s choice instead. The last clone of the writer to drop finishes
the track. The track exists before the broadcast is announced, so no
reader misses it. Readers open it with Subscription::value_track.
To put the track next to others, create it in
publish_with’s fill and pass it to
ValueWriter::new.
§Errors
As publish_with.
§Panics
Panics when called outside a Tokio runtime.
§Examples
use iroh_live_node::Audience;
let (_publication, latency) =
node.publish_value::<u64>("live/control", Audience::Granted, "latency")?;
latency.update(&150)?;pub async fn subscribe(
&self,
path: impl TryInto>,
reach: Reach,
) -> Result<Subscription, Error>
pub async fn subscribe(
&self,
path: impl TryInto>,
reach: Reach,
) -> Result<Subscription, Error>
Resolves path in the route table.
If no route exists yet, reaches out as reach says. Cancellation safe:
a dial this call started continues for other callers.
The crate docs explain the trust model.
§Errors
Fails with:
- [
Error::Moq] or [Error::InvalidPath] for a path that cannot be published, aspublishdoes. - [
Error::NoRoute] ifreachallows no way to reach the path. - [
Error::Transport] if the publisher cannot be dialed and no media relay can stand in. - [
Error::NotGranted] if the publisher’s grant does not let it publish the path and no media relay can stand in. - [
Error::NotAnnounced] if the publisher’s session ends before it announces the path. - [
Error::Unresolved] if the route table refuses the path. - [
Error::ShutDown] once the node has shut down.
pub async fn subscribe_ticket(
&self,
ticket: &BroadcastTicket,
) -> Result<Subscription, Error>
pub async fn subscribe_ticket( &self, ticket: &BroadcastTicket, ) -> Result<Subscription, Error>
Resolves the broadcast ticket names, whatever grants this node has.
The node first claims the path for the ticket’s peer with
claim_path, and the subscription holds the claim
for as long as it lives. Then this is subscribe
with Reach::Both. When the last subscription of a path drops, the
grant narrows again, and moq ends what local readers read there.
§Errors
As claim_path, and as subscribe.
pub async fn connect(
&self,
peer: impl Into<EndpointAddr>,
) -> Result<Session, Error>
pub async fn connect( &self, peer: impl Into<EndpointAddr>, ) -> Result<Session, Error>
Returns the session with peer, dialing if there is none.
Concurrent calls share one dial, which continues if this future is
dropped. The dialer’s half of the handshake completes before the peer
decides whether to admit it, so a peer that refuses usually closes the
session right after this returns. Session::closed then says why.
§Errors
Fails with [Error::Rejected] if this node’s policy rejects the peer,
[Error::Transport] if the dial fails, [Error::Refused] if a peer on
an older protocol version refuses during the handshake, and
[Error::ShutDown] once the node has shut down. A handshake that takes
longer than HANDSHAKE_TIMEOUT fails with
[Error::Moq].
pub async fn connect_with(
&self,
peer: impl Into<EndpointAddr>,
options: ConnectOptions,
) -> Result<Session, Error>
pub async fn connect_with( &self, peer: impl Into<EndpointAddr>, options: ConnectOptions, ) -> Result<Session, Error>
pub fn sessions(&self) -> Direct<Vec<Session>>
pub fn sessions(&self) -> Direct<Vec<Session>>
Returns the open direct sessions, dialed and accepted, as they change.
pub fn accepted(&self) -> impl Stream<Item = Session> + Send + Unpin + 'static
pub fn accepted(&self) -> impl Stream<Item = Session> + Send + Unpin + 'static
Returns a stream of the sessions this node accepts.
Yields every accepted session open when it is called, then each new
one as it opens, each once, and ends when the node shuts down. It
leaves out the sessions this node dialed, which
sessions lists too. It reads the same list, so a
session that opens and closes between two polls may be skipped.
§Examples
Serve each peer that connects in a task of its own:
use n0_future::StreamExt;
let mut accepted = node.accepted();
while let Some(session) = accepted.next().await {
tokio::spawn(async move {
// Serve the peer, until the session ends.
let reason = session.closed().await;
println!("{} left: {reason:#}", session.peer());
});
}pub fn attach_relay(&self, config: RelayConfig) -> Result<RelayLink, Error>
pub fn attach_relay(&self, config: RelayConfig) -> Result<RelayLink, Error>
Attaches to the media relay at config.url, redialing it with backoff.
§Errors
Fails with [Error::InvalidRelayUrl] for an unsupported URL scheme or
an iroh:// URL without an endpoint id, [Error::Relay] if the client
cannot be set up, and [Error::ShutDown] once the node has shut down.
§Panics
Panics when called outside a Tokio runtime.
pub async fn shutdown(&self)
pub async fn shutdown(&self)
Shuts the node down for every clone.
Closes every session, detaches media relays and withdraws publications. Gives sessions a short grace to tell their peers, so the endpoint can be closed once this returns. Idempotent. Not cancellation safe: call it again to finish.
A node mounted on a router shuts down with
Router::shutdown, which calls this before it closes the endpoint, so
there is no need to call both. Call it for a node without a router, or
to stop the node while the router’s other protocols keep running.
Trait Implementations§
§impl ProtocolHandler for Node
impl ProtocolHandler for Node
§async fn shutdown(&self)
async fn shutdown(&self)
Shuts the node down with the router, as Node::shutdown does.
§async fn accept(&self, connection: Connection) -> Result<(), AcceptError>
async fn accept(&self, connection: Connection) -> Result<(), AcceptError>
Source§fn on_accepting(
&self,
accepting: Accepting,
) -> impl Future<Output = Result<Connection, AcceptError>> + Send
fn on_accepting( &self, accepting: Accepting, ) -> impl Future<Output = Result<Connection, AcceptError>> + Send
Accepting state. Read more