Something went wrong. Try again.
And Iroh inspired WebRTC experiment
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120//! Iroh-style application protocol routing.use crate::{Connection, Endpoint};use anyhow::{Result, ensure};use async_trait::async_trait;use std::{ collections::HashMap, sync::{Arc, Mutex},};use tokio::{ sync::watch, task::{JoinHandle, JoinSet},};pub type AcceptError = anyhow::Error;/// Handlers run concurrently, and must cooperate with cancellation at router shutdown.#[async_trait]pub trait ProtocolHandler: Send + Sync + 'static { async fn accept(&self, connection: Connection) -> Result<(), AcceptError>; async fn shutdown(&self) {}}#[derive(Clone)]pub struct Router(Arc<RouterInner>);struct RouterInner { endpoint: Endpoint, cancel: watch::Sender<bool>, finished: watch::Receiver<bool>, task: Mutex<Option<JoinHandle<()>>>,}impl Drop for RouterInner { fn drop(&mut self) { self.cancel.send_replace(true); // The bounded shutdown task owns its resources and finishes even after the last Router drops. }}pub struct RouterBuilder { endpoint: Endpoint, protocols: HashMap<Vec<u8>, Arc<dyn ProtocolHandler>>,}impl Router { pub fn builder(endpoint: Endpoint) -> RouterBuilder { RouterBuilder { endpoint, protocols: HashMap::new(), } } pub fn endpoint(&self) -> &Endpoint { &self.0.endpoint } pub async fn shutdown(&self) -> Result<()> { self.0.cancel.send_replace(true); let task = self.0.task.lock().unwrap().take(); if let Some(task) = task { task.await?; } else { let mut finished = self.0.finished.clone(); let _ = finished.wait_for(|done| *done).await; } Ok(()) }}impl RouterBuilder { pub fn accept(mut self, alpn: impl AsRef<[u8]>, handler: impl ProtocolHandler) -> Self { self.protocols .insert(alpn.as_ref().to_vec(), Arc::new(handler)); self } pub fn try_spawn(self) -> Result<Router> { ensure!( !self.protocols.is_empty(), "router must register at least one protocol" ); ensure!( self.protocols .keys() .all(|a| !a.is_empty() && a.len() <= 255), "invalid router ALPN" ); Ok(self.spawn()) } pub fn spawn(self) -> Router { self.endpoint .set_alpns(self.protocols.keys().cloned().collect()); let endpoint = self.endpoint.clone(); let (cancel, mut cancelled) = watch::channel(false); let (finished_tx, finished) = watch::channel(false); let task = tokio::spawn(async move { let mut handlers = JoinSet::new(); loop { tokio::select! {biased; _=cancelled.wait_for(|c|*c)=>break, incoming=endpoint.accept()=>{ let Some(incoming)=incoming else {break;}; let Some(handler)=self.protocols.get(incoming.alpn()).cloned() else {continue;}; if handlers.len()>=128 {continue;} handlers.spawn(async move { if let Ok(connection)=incoming.await { let guard=connection.clone(); if let Err(error)=handler.accept(connection).await {guard.close(1,error.to_string().as_bytes());} } }); } _=handlers.join_next(),if !handlers.is_empty()=>{}, } } endpoint.close().await; handlers.abort_all(); while handlers.join_next().await.is_some() {} let shutdown = futures_util::future::join_all(self.protocols.values().map(|h| h.shutdown())); let _ = tokio::time::timeout(std::time::Duration::from_secs(2), shutdown).await; finished_tx.send_replace(true); }); Router(Arc::new(RouterInner { endpoint: self.endpoint, cancel, finished, task: Mutex::new(Some(task)), })) }}