Skip to main content

Server

Struct Server 

Source
pub struct Server { /* private fields */ }
Expand description

Server is the thread-safe handle to a running NWEP server.

Server is obtained from ServerBuilder::build alongside an EventLoop. It can be cloned and sent across threads freely; all mutating operations are communicated to the event loop via an internal channel.

Implementations§

Source§

impl Server

Source

pub fn node_id(&self) -> NodeId

node_id returns the server’s own 32-byte NWEP node identifier.

Source

pub fn addr(&self) -> SocketAddr

addr returns the local UDP socket address the server is listening on.

Examples found in repository?
examples/server.rs (line 70)
35fn main() {
36    nwep::init().unwrap_or_else(|e| {
37        eprintln!("init: {e}");
38        process::exit(1);
39    });
40
41    let key_file = std::env::var("NWEP_KEY_FILE").unwrap_or_else(|_| DEFAULT_KEY_FILE.into());
42    let keypair = load_or_generate_keypair(&key_file).unwrap_or_else(|e| {
43        eprintln!("keypair: {e}");
44        process::exit(1);
45    });
46
47    let node_id = keypair.node_id().unwrap_or_else(|e| {
48        eprintln!("node_id: {e}");
49        process::exit(1);
50    });
51    eprintln!("node id: {node_id}");
52
53    let mut router = Router::new();
54    router.handle_func("/hello", |w: &mut ResponseWriter, _r: &Request| {
55        let _ = w.respond("ok", b"hello from nwep-rust");
56    });
57
58    let addr = std::env::args().nth(1).unwrap_or_else(|| DEFAULT_ADDR.into());
59
60    let (server, event_loop) = ServerBuilder::new(&addr, keypair)
61        .on_connect(|info| eprintln!("connected: {}", info.node_id))
62        .on_disconnect(|info, code| eprintln!("disconnected: {} (code {code})", info.node_id))
63        .build(router)
64        .unwrap_or_else(|e| {
65            eprintln!("server: {e}");
66            process::exit(1);
67        });
68
69    let url = server.url("/hello");
70    eprintln!("listening on {}", server.addr());
71    println!("{url}"); // URL printed to stdout for the client to read
72
73    if let Err(e) = event_loop.run() {
74        eprintln!("server run: {e}");
75        process::exit(1);
76    }
77}
Source

pub fn url(&self, path: &str) -> String

url formats a web:// URL for the given path on this server.

If the server was bound to an unspecified address (0.0.0.0 or ::), the URL uses the loopback address instead, matching Go’s server.URL() behaviour.

§Example
println!("{}", server.url("/hello")); // e.g. "web://127.0.0.1:<node_id>:8080/hello"
Examples found in repository?
examples/server.rs (line 69)
35fn main() {
36    nwep::init().unwrap_or_else(|e| {
37        eprintln!("init: {e}");
38        process::exit(1);
39    });
40
41    let key_file = std::env::var("NWEP_KEY_FILE").unwrap_or_else(|_| DEFAULT_KEY_FILE.into());
42    let keypair = load_or_generate_keypair(&key_file).unwrap_or_else(|e| {
43        eprintln!("keypair: {e}");
44        process::exit(1);
45    });
46
47    let node_id = keypair.node_id().unwrap_or_else(|e| {
48        eprintln!("node_id: {e}");
49        process::exit(1);
50    });
51    eprintln!("node id: {node_id}");
52
53    let mut router = Router::new();
54    router.handle_func("/hello", |w: &mut ResponseWriter, _r: &Request| {
55        let _ = w.respond("ok", b"hello from nwep-rust");
56    });
57
58    let addr = std::env::args().nth(1).unwrap_or_else(|| DEFAULT_ADDR.into());
59
60    let (server, event_loop) = ServerBuilder::new(&addr, keypair)
61        .on_connect(|info| eprintln!("connected: {}", info.node_id))
62        .on_disconnect(|info, code| eprintln!("disconnected: {} (code {code})", info.node_id))
63        .build(router)
64        .unwrap_or_else(|e| {
65            eprintln!("server: {e}");
66            process::exit(1);
67        });
68
69    let url = server.url("/hello");
70    eprintln!("listening on {}", server.addr());
71    println!("{url}"); // URL printed to stdout for the client to read
72
73    if let Err(e) = event_loop.run() {
74        eprintln!("server run: {e}");
75        process::exit(1);
76    }
77}
Source

pub fn connection_count(&self) -> usize

connection_count returns the number of currently authenticated, connected peers.

The count is updated synchronously on the event loop thread when a peer connects or disconnects, so it may lag slightly behind the network state.

Source

pub fn connected_peers(&self) -> Vec<NodeId>

connected_peers returns a snapshot of the node IDs of all currently connected peers.

Source

pub fn shutdown(&self)

shutdown signals the event loop to stop accepting new connections and exit.

This call returns immediately; wait for EventLoop::run to return to confirm the server has fully stopped.

Source

pub fn notify( &self, peer_node_id: NodeId, event: &str, path: &str, body: Vec<u8>, ) -> Result<(), Error>

notify sends a server-initiated push message to a single connected peer.

The peer receives the notification in its on_notify callback. event is a free-form event type string; path is the resource path; body is the payload.

§Errors

Returns an error if the internal channel has been closed (i.e. the event loop has already stopped).

Source

pub fn notify_with_options( &self, peer_node_id: NodeId, event: &str, path: &str, body: Vec<u8>, options: NotifyOptions, ) -> Result<(), Error>

notify_with_options sends a server-initiated push message with additional metadata.

Like notify but also accepts a NotifyOptions to attach custom headers or a stable notification identifier to the wire message.

§Errors

Returns an error if the internal channel has been closed.

Source

pub fn notify_all( &self, event: &str, path: &str, body: Vec<u8>, ) -> Result<(), Error>

notify_all broadcasts a push notification to every currently connected peer.

The message is sent to the snapshot of connections held by the event loop at the time it processes the event; peers that disconnect between the call and processing are silently skipped.

§Errors

Returns an error if the internal channel has been closed.

Source

pub fn close_connection( &self, peer_node_id: NodeId, error: i32, ) -> Result<(), Error>

close_connection forcefully closes the connection to the identified peer.

The peer is removed from internal state immediately and the on_disconnect callback fires before the QUIC CONNECTION_CLOSE is sent. This is intentional: the C library’s QUIC CLOSING state is asynchronous and the disconnect callback would otherwise be delayed until the peer sends a packet.

§Errors

Returns an error if the internal channel has been closed.

Source

pub fn log_server(&self) -> Option<Arc<Mutex<LogServer>>>

log_server returns the shared LogServer registered during build, if any.

The returned Arc<Mutex<LogServer>> is the same instance intercepting /log/* requests, so callers can inspect or modify log state without additional coordination.

Source

pub fn anchor_server(&self) -> Option<Arc<Mutex<AnchorServer>>>

anchor_server returns the shared AnchorServer registered during build, if any.

The returned Arc<Mutex<AnchorServer>> is the same instance intercepting /checkpoint/* requests.

Auto Trait Implementations§

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<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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.