//! 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); struct RouterInner { endpoint: Endpoint, cancel: watch::Sender, finished: watch::Receiver, task: Mutex>>, } 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, Arc>, } 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 { 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)), })) } }