Skip to main content

Node

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

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

pub fn new(endpoint: Endpoint, config: NodeConfig) -> Node

Creates a node on endpoint.

§Panics

Panics when called outside a Tokio runtime.

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.

pub fn id(&self) -> PublicKey

Returns the endpoint id of the node.

pub fn authorization_for(&self, peer: PublicKey) -> Option<Authorization>

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.

pub fn reauthorize(&self, peer: PublicKey)

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.

pub fn reauthorize_all(&self)

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

Returns a future that resolves when the node shuts down.

Resolves once shutdown starts, or once the last handle drops. Cancellation safe.

pub fn endpoint(&self) -> &Endpoint

Returns the endpoint the node runs on.

pub fn publish( &self, path: impl TryInto>, audience: Audience<PublicKey>, ) -> Result<Publication, Error>
where <impl TryInto<Path> as TryInto<Path>>::Error: Into<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>
where E: Into<Box<dyn Error + Send + Sync>>, <impl TryInto<Path> as TryInto<Path>>::Error: Into<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>
where T: Serialize, <impl TryInto<Path> as TryInto<Path>>::Error: Into<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>
where <impl TryInto<Path> as TryInto<Path>>::Error: Into<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, as publish does.
  • [Error::NoRoute] if reach allows 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>

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 fn origin(&self) -> Consumer

Returns the route table.

It holds what subscribe resolves in, and its announced stream lists the paths.

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>

Dials peer with a token, a path, a cost, or iroh’s connect options.

An existing session with the peer, or a dial in flight to it, is returned as it is, and the options go unused. A token then reaches the peer only if you close that session first.

§Errors

As connect.

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

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>

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)

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 Clone for Node

§

fn clone(&self) -> Node

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for Node

§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl ProtocolHandler for Node

§

async fn shutdown(&self)

Shuts the node down with the router, as Node::shutdown does.

§

async fn accept(&self, connection: Connection) -> Result<(), AcceptError>

Handle an incoming connection. Read more
Source§

fn on_accepting( &self, accepting: Accepting, ) -> impl Future<Output = Result<Connection, AcceptError>> + Send

Optional interception point to handle the Accepting state. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Node

§

impl !UnwindSafe for Node

§

impl Freeze for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl UnsafeUnpin for Node

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<P> DynProtocolHandler for P
where P: ProtocolHandler,

Source§

fn accept( &self, connection: Connection, ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>>

Source§

fn on_accepting( &self, accepting: Accepting, ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>>

Source§

fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more