1use std::{
44 collections::HashMap,
45 future::Future,
46 pin::Pin,
47 sync::{Arc, Mutex},
48};
49
50use n0_error::{AnyError, e, stack_error};
51use n0_future::{
52 join_all,
53 task::{self, AbortOnDropHandle, JoinSet},
54};
55use tokio_util::sync::CancellationToken;
56use tracing::{Instrument, debug, error, field::Empty, info_span, trace, warn};
57
58use crate::{
59 Endpoint,
60 endpoint::{Accepting, Connection, RemoteEndpointIdError, quic},
61};
62
63#[derive(Clone, Debug)]
97pub struct Router {
98 endpoint: Endpoint,
99 task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>,
101 cancel_token: CancellationToken,
102}
103
104#[derive(derive_more::Debug)]
106pub struct RouterBuilder {
107 endpoint: Endpoint,
108 protocols: ProtocolMap,
109 #[debug(skip)]
110 incoming_filter: Option<IncomingFilter>,
111}
112
113#[allow(missing_docs)]
114#[stack_error(derive, add_meta, from_sources, std_sources)]
115#[non_exhaustive]
116pub enum AcceptError {
117 #[error(transparent)]
118 Connecting {
119 source: crate::endpoint::ConnectingError,
120 },
121 #[error(transparent)]
122 Connection {
123 source: crate::endpoint::ConnectionError,
124 },
125 #[error(transparent)]
126 MissingRemoteEndpointId { source: RemoteEndpointIdError },
127 #[error("Not allowed.")]
128 NotAllowed {},
129 #[error(transparent)]
130 User { source: AnyError },
131}
132
133impl AcceptError {
134 #[track_caller]
137 pub fn from_err<T: std::error::Error + Send + Sync + 'static>(value: T) -> Self {
138 e!(AcceptError::User {
139 source: AnyError::from_std(value)
140 })
141 }
142
143 #[track_caller]
145 pub fn from_boxed(value: Box<dyn std::error::Error + Send + Sync>) -> Self {
146 e!(AcceptError::User {
147 source: AnyError::from_std_box(value)
148 })
149 }
150}
151
152impl From<std::io::Error> for AcceptError {
153 fn from(err: std::io::Error) -> Self {
154 Self::from_err(err)
155 }
156}
157
158impl From<quic::ClosedStream> for AcceptError {
159 fn from(err: quic::ClosedStream) -> Self {
160 Self::from_err(err)
161 }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169#[non_exhaustive]
170pub enum IncomingFilterOutcome {
171 Accept,
173 Retry,
203 Reject,
206 Ignore,
209}
210
211pub type IncomingFilter =
215 Arc<dyn Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static>;
216
217pub trait ProtocolHandler: Send + Sync + std::fmt::Debug + 'static {
229 fn on_accepting(
249 &self,
250 accepting: Accepting,
251 ) -> impl Future<Output = Result<Connection, AcceptError>> + Send {
252 async move {
253 let conn = accepting.await?;
254 Ok(conn)
255 }
256 }
257
258 fn accept(
274 &self,
275 connection: Connection,
276 ) -> impl Future<Output = Result<(), AcceptError>> + Send;
277
278 fn shutdown(&self) -> impl Future<Output = ()> + Send {
285 async move {}
286 }
287}
288
289impl<T: ProtocolHandler> ProtocolHandler for Arc<T> {
290 async fn on_accepting(&self, accepting: Accepting) -> Result<Connection, AcceptError> {
291 self.as_ref().on_accepting(accepting).await
292 }
293
294 async fn accept(&self, conn: Connection) -> Result<(), AcceptError> {
295 self.as_ref().accept(conn).await
296 }
297
298 async fn shutdown(&self) {
299 self.as_ref().shutdown().await
300 }
301}
302
303impl<T: ProtocolHandler> ProtocolHandler for Box<T> {
304 async fn on_accepting(&self, accepting: Accepting) -> Result<Connection, AcceptError> {
305 self.as_ref().on_accepting(accepting).await
306 }
307
308 async fn accept(&self, conn: Connection) -> Result<(), AcceptError> {
309 self.as_ref().accept(conn).await
310 }
311
312 async fn shutdown(&self) {
313 self.as_ref().shutdown().await
314 }
315}
316
317impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler> {
318 fn from(value: T) -> Self {
319 Box::new(value)
320 }
321}
322
323pub trait DynProtocolHandler: Send + Sync + std::fmt::Debug + 'static {
332 fn on_accepting(
334 &self,
335 accepting: Accepting,
336 ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> {
337 Box::pin(async move {
338 let conn = accepting.await?;
339 Ok(conn)
340 })
341 }
342
343 fn accept(
345 &self,
346 connection: Connection,
347 ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>>;
348
349 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
351 Box::pin(async move {})
352 }
353}
354
355impl<P: ProtocolHandler> DynProtocolHandler for P {
356 fn accept(
357 &self,
358 connection: Connection,
359 ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>> {
360 Box::pin(<Self as ProtocolHandler>::accept(self, connection))
361 }
362
363 fn on_accepting(
364 &self,
365 accepting: Accepting,
366 ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> {
367 Box::pin(<Self as ProtocolHandler>::on_accepting(self, accepting))
368 }
369
370 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
371 Box::pin(<Self as ProtocolHandler>::shutdown(self))
372 }
373}
374
375#[derive(Debug, Default)]
377pub(crate) struct ProtocolMap {
378 alpns: Vec<Vec<u8>>,
380 map: HashMap<Vec<u8>, Box<dyn DynProtocolHandler>>,
382}
383
384impl ProtocolMap {
385 pub(crate) fn get(&self, alpn: &[u8]) -> Option<&dyn DynProtocolHandler> {
387 self.map.get(alpn).map(|p| &**p)
388 }
389
390 pub(crate) fn insert(&mut self, alpn: Vec<u8>, handler: Box<dyn DynProtocolHandler>) {
392 self.alpns.push(alpn.clone());
393 self.map.insert(alpn, handler);
394 }
395
396 pub(crate) fn alpns(&self) -> impl Iterator<Item = &Vec<u8>> {
398 self.alpns.iter()
399 }
400
401 pub(crate) async fn shutdown(&self) {
405 let handlers = self.map.values().map(|p| p.shutdown());
406 join_all(handlers).await;
407 }
408}
409
410impl Router {
411 pub fn builder(endpoint: Endpoint) -> RouterBuilder {
413 RouterBuilder::new(endpoint)
414 }
415
416 pub fn endpoint(&self) -> &Endpoint {
418 &self.endpoint
419 }
420
421 pub fn is_shutdown(&self) -> bool {
423 self.cancel_token.is_cancelled()
424 }
425
426 pub async fn shutdown(&self) -> Result<(), n0_future::task::JoinError> {
436 if self.is_shutdown() {
437 return Ok(());
438 }
439
440 self.cancel_token.cancel();
442
443 let task = self.task.lock().expect("poisoned").take();
447 if let Some(task) = task {
448 task.await?;
449 }
450
451 Ok(())
452 }
453}
454
455impl RouterBuilder {
456 pub fn new(endpoint: Endpoint) -> Self {
458 Self {
459 endpoint,
460 protocols: ProtocolMap::default(),
461 incoming_filter: None,
462 }
463 }
464
465 pub fn incoming_filter(mut self, filter: IncomingFilter) -> Self {
479 self.incoming_filter = Some(filter);
480 self
481 }
482
483 pub fn accept(
496 mut self,
497 alpn: impl AsRef<[u8]>,
498 handler: impl Into<Box<dyn DynProtocolHandler>>,
499 ) -> Self {
500 self.protocols
501 .insert(alpn.as_ref().to_vec(), handler.into());
502 self
503 }
504
505 pub fn endpoint(&self) -> &Endpoint {
507 &self.endpoint
508 }
509
510 #[must_use = "Router aborts when dropped, use Router::shutdown to shut the router down cleanly"]
512 pub fn spawn(self) -> Router {
513 let alpns = self
515 .protocols
516 .alpns()
517 .map(|alpn| alpn.to_vec())
518 .collect::<Vec<_>>();
519
520 let protocols = Arc::new(self.protocols);
521 let incoming_filter = self.incoming_filter;
522 self.endpoint.set_alpns(alpns);
523
524 let mut join_set = JoinSet::new();
525 let endpoint = self.endpoint.clone();
526
527 let cancel = CancellationToken::new();
529 let cancel_token = cancel.clone();
530
531 let run_loop_fut = async move {
532 let _cancel_guard = cancel_token.clone().drop_guard();
534 let handler_cancel_token = CancellationToken::new();
537
538 loop {
539 tokio::select! {
540 biased;
541 _ = cancel_token.cancelled() => {
542 break;
543 },
544 Some(res) = join_set.join_next() => {
546 match res {
547 Err(outer) => {
548 if outer.is_panic() {
549 error!("Task panicked: {outer:?}");
550 break;
551 } else if outer.is_cancelled() {
552 trace!("Task cancelled: {outer:?}");
553 } else {
554 error!("Task failed: {outer:?}");
555 break;
556 }
557 }
558 Ok(Some(())) => {
559 trace!("Task finished");
560 }
561 Ok(None) => {
562 trace!("Task cancelled");
563 }
564 }
565 },
566
567 incoming = endpoint.accept() => {
569 let Some(incoming) = incoming else {
570 break; };
572
573 if let Some(filter) = &incoming_filter {
574 match filter(&incoming) {
575 IncomingFilterOutcome::Accept => {}
576 IncomingFilterOutcome::Retry => {
577 if incoming.remote_addr_validated() {
578 debug!(
579 "filter returned Retry for an already validated connection",
580 );
581 }
582 if let Err(err) = incoming.retry() {
583 err.into_incoming().refuse();
584 }
585 continue;
586 }
587 IncomingFilterOutcome::Reject => {
588 incoming.refuse();
589 continue;
590 }
591 IncomingFilterOutcome::Ignore => {
592 incoming.ignore();
593 continue;
594 }
595 }
596 }
597
598 let protocols = protocols.clone();
599 let token = handler_cancel_token.child_token();
600 let span = info_span!("router.accept", me=%endpoint.id().fmt_short(), remote=Empty, alpn=Empty);
601 join_set.spawn(async move {
602 token.run_until_cancelled(handle_connection(incoming, protocols)).await
603 }.instrument(span));
604 },
605 }
606 }
607
608 protocols.shutdown().await;
610 handler_cancel_token.cancel();
612 endpoint.close().await;
614 tracing::debug!("Shutting down remaining tasks");
617 join_set.abort_all();
618 while let Some(res) = join_set.join_next().await {
619 match res {
620 Err(err) if err.is_panic() => error!("Task panicked: {err:?}"),
621 _ => {}
622 }
623 }
624 };
625 let task = task::spawn(run_loop_fut.instrument(tracing::Span::current()));
626 let task = AbortOnDropHandle::new(task);
627
628 Router {
629 endpoint: self.endpoint,
630 task: Arc::new(Mutex::new(Some(task))),
631 cancel_token: cancel,
632 }
633 }
634}
635
636async fn handle_connection(incoming: crate::endpoint::Incoming, protocols: Arc<ProtocolMap>) {
637 let mut accepting = match incoming.accept() {
638 Ok(conn) => conn,
639 Err(err) => {
640 warn!("Ignoring connection: accepting failed: {err:#}");
641 return;
642 }
643 };
644 let alpn = match accepting.alpn().await {
645 Ok(alpn) => alpn,
646 Err(err) => {
647 warn!("Ignoring connection: invalid handshake: {err:#}");
648 return;
649 }
650 };
651 tracing::Span::current().record("alpn", String::from_utf8_lossy(&alpn).to_string());
652
653 let Some(handler) = protocols.get(&alpn) else {
654 warn!("Ignoring connection: unsupported ALPN protocol");
655 return;
656 };
657 match handler.on_accepting(accepting).await {
658 Ok(connection) => {
659 tracing::Span::current().record(
660 "remote",
661 tracing::field::display(connection.remote_id().fmt_short()),
662 );
663
664 if let Err(err) = handler.accept(connection).await {
665 warn!("Handling incoming connection ended with error: {err}");
666 }
667 }
668 Err(err) => {
669 warn!("Accepting incoming connection ended with error: {err}");
670 }
671 }
672}
673
674#[cfg(all(test, with_crypto_provider))]
675mod tests {
676 use std::{sync::Mutex, time::Duration};
677
678 use n0_error::{Result, StdResultExt};
679 use n0_tracing_test::traced_test;
680
681 use super::*;
682 use crate::endpoint::{
683 ApplicationClose, BeforeConnectOutcome, ConnectError, ConnectOptions, ConnectWithOptsError,
684 ConnectionError, EndpointHooks, presets,
685 };
686
687 #[tokio::test]
688 async fn test_shutdown() -> Result {
689 let endpoint = Endpoint::bind(presets::Minimal).await?;
690 let router = Router::builder(endpoint.clone()).spawn();
691
692 assert!(!router.is_shutdown());
693 assert!(!endpoint.is_closed());
694
695 router.shutdown().await.anyerr()?;
696
697 assert!(router.is_shutdown());
698 assert!(endpoint.is_closed());
699
700 Ok(())
701 }
702
703 #[derive(Debug, Clone)]
705 struct Echo;
706
707 const ECHO_ALPN: &[u8] = b"/iroh/echo/1";
708
709 impl ProtocolHandler for Echo {
710 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
711 println!("accepting echo");
712 let (mut send, mut recv) = connection.accept_bi().await?;
713
714 let _bytes_sent = tokio::io::copy(&mut recv, &mut send).await?;
716
717 send.finish()?;
718 connection.closed().await;
719
720 Ok(())
721 }
722 }
723
724 #[tokio::test]
725 async fn test_limiter_hook() -> Result {
726 #[derive(Debug, Default)]
728 struct LimitHook;
729 impl EndpointHooks for LimitHook {
730 async fn before_connect<'a>(
731 &'a self,
732 _remote_addr: &'a iroh_base::EndpointAddr,
733 alpn: &'a [u8],
734 ) -> BeforeConnectOutcome {
735 assert_eq!(alpn, ECHO_ALPN);
736
737 BeforeConnectOutcome::Reject
739 }
740 }
741
742 let e1 = Endpoint::bind(presets::Minimal).await?;
743
744 let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, Echo).spawn();
745
746 let addr1 = r1.endpoint().addr();
747 dbg!(&addr1);
748 let e2 = Endpoint::builder(presets::Minimal)
749 .hooks(LimitHook)
750 .bind()
751 .await?;
752
753 println!("connecting");
754 let conn_err = e2.connect(addr1, ECHO_ALPN).await.unwrap_err();
755
756 assert!(matches!(
757 conn_err,
758 ConnectError::Connect {
759 source: ConnectWithOptsError::LocallyRejected { .. },
760 ..
761 }
762 ));
763
764 r1.shutdown().await.anyerr()?;
765 e2.close().await;
766
767 Ok(())
768 }
769
770 #[tokio::test]
772 #[traced_test]
773 async fn test_accepting_remote_addr() -> Result {
774 use crate::endpoint::{IncomingAddr, presets};
775
776 let e1 = Endpoint::builder(presets::Minimal)
777 .alpns(vec![ECHO_ALPN.to_vec()])
778 .bind()
779 .await?;
780 let addr1 = e1.addr();
781
782 let e2 = Endpoint::bind(presets::Minimal).await?;
783
784 let connect_task = tokio::spawn({
786 let addr1 = addr1.clone();
787 let e2 = e2.clone();
788 async move { e2.connect(addr1, ECHO_ALPN).await }
789 });
790
791 let incoming = e1.accept().await.expect("accept");
792 let incoming_addr = incoming.remote_addr();
793 assert!(matches!(incoming_addr, IncomingAddr::Ip(_)));
794
795 let accepting = incoming.accept().anyerr()?;
796 assert_eq!(incoming_addr, accepting.remote_addr());
797
798 drop(accepting);
800 drop(connect_task);
801 e1.close().await;
802 e2.close().await;
803 Ok(())
804 }
805
806 mod incoming_filter {
807 use std::{
808 sync::{
809 Arc,
810 atomic::{AtomicBool, Ordering::Relaxed},
811 },
812 time::Duration,
813 };
814
815 use n0_error::{Result, StdResultExt};
816 use n0_tracing_test::traced_test;
817
818 use crate::{
819 Endpoint, EndpointAddr,
820 endpoint::presets,
821 protocol::{
822 IncomingFilterOutcome, Router,
823 tests::{ECHO_ALPN, Echo},
824 },
825 };
826
827 async fn direct_pair<F>(filter: F) -> Result<(Router, Endpoint, EndpointAddr)>
832 where
833 F: Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static,
834 {
835 let e1 = Endpoint::builder(presets::Minimal)
836 .clear_ip_transports()
837 .bind_addr((std::net::Ipv4Addr::LOCALHOST, 0))
838 .anyerr()?
839 .bind()
840 .await?;
841 let r1 = Router::builder(e1.clone())
842 .incoming_filter(Arc::new(filter))
843 .accept(ECHO_ALPN, Echo)
844 .spawn();
845 let addr = r1.endpoint().addr();
846 let e2 = Endpoint::builder(presets::Minimal)
847 .clear_ip_transports()
848 .bind_addr((std::net::Ipv4Addr::LOCALHOST, 0))
849 .anyerr()?
850 .bind()
851 .await?;
852 Ok((r1, e2, addr))
853 }
854
855 async fn relay_pair<F>(
857 filter: F,
858 ) -> Result<(Router, Endpoint, EndpointAddr, impl std::any::Any)>
859 where
860 F: Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static,
861 {
862 let (_relay_map, relay_url, guard) =
863 crate::test_utils::run_relay_server().await.anyerr()?;
864 let relay_mode = crate::RelayMode::Custom(crate::RelayMap::from(relay_url.clone()));
865
866 let e1 = Endpoint::builder(presets::Minimal)
867 .relay_mode(relay_mode.clone())
868 .ca_tls_config(crate::tls::CaTlsConfig::insecure_skip_verify())
869 .bind()
870 .await?;
871 let r1 = Router::builder(e1.clone())
872 .incoming_filter(Arc::new(filter))
873 .accept(ECHO_ALPN, Echo)
874 .spawn();
875 let addr = EndpointAddr::new(e1.id()).with_relay_url(relay_url);
876 let e2 = Endpoint::builder(presets::Minimal)
877 .relay_mode(relay_mode)
878 .ca_tls_config(crate::tls::CaTlsConfig::insecure_skip_verify())
879 .bind()
880 .await?;
881 Ok((r1, e2, addr, guard))
882 }
883
884 #[tokio::test]
885 #[traced_test]
886 async fn addr_retry() -> Result {
887 let (r1, e2, addr) = direct_pair(|incoming| {
888 if !incoming.remote_addr_validated() {
889 IncomingFilterOutcome::Retry
890 } else {
891 IncomingFilterOutcome::Accept
892 }
893 })
894 .await?;
895 assert!(e2.connect(addr, ECHO_ALPN).await.is_ok());
897 r1.shutdown().await.anyerr()?;
898 e2.close().await;
899 Ok(())
900 }
901
902 #[tokio::test]
903 #[traced_test]
904 async fn addr_reject() -> Result {
905 let (r1, e2, addr) = direct_pair(|_| IncomingFilterOutcome::Reject).await?;
906 assert!(e2.connect(addr, ECHO_ALPN).await.is_err());
907 r1.shutdown().await.anyerr()?;
908 e2.close().await;
909 Ok(())
910 }
911
912 #[tokio::test]
913 #[traced_test]
914 async fn addr_ignore() -> Result {
915 let (r1, e2, addr) = direct_pair(|_| IncomingFilterOutcome::Ignore).await?;
916 let result =
918 tokio::time::timeout(Duration::from_millis(500), e2.connect(addr, ECHO_ALPN)).await;
919 assert!(result.is_err(), "expected timeout");
920 r1.shutdown().await.anyerr()?;
921 e2.close().await;
922 Ok(())
923 }
924
925 #[tokio::test]
926 #[traced_test]
927 async fn relay_reject() -> Result {
928 let (r1, e2, addr, _guard) = relay_pair(|_| IncomingFilterOutcome::Reject).await?;
929 assert!(e2.connect(addr, ECHO_ALPN).await.is_err());
930 r1.shutdown().await.anyerr()?;
931 e2.close().await;
932 Ok(())
933 }
934
935 #[tokio::test]
936 #[traced_test]
937 async fn relay_ignore() -> Result {
938 let (r1, e2, addr, _guard) = relay_pair(|_| IncomingFilterOutcome::Ignore).await?;
939 let result =
940 tokio::time::timeout(Duration::from_millis(500), e2.connect(addr, ECHO_ALPN)).await;
941 assert!(result.is_err(), "expected timeout");
942 r1.shutdown().await.anyerr()?;
943 e2.close().await;
944 Ok(())
945 }
946
947 #[tokio::test]
950 #[traced_test]
951 async fn addr_retry_then_validated() -> Result {
952 let saw_validated = Arc::<AtomicBool>::default();
953 let saw_unvalidated = Arc::<AtomicBool>::default();
954 let (sv, su) = (saw_validated.clone(), saw_unvalidated.clone());
955
956 let (r1, e2, addr) = direct_pair(move |incoming| {
957 if incoming.remote_addr_validated() {
958 sv.store(true, Relaxed);
959 IncomingFilterOutcome::Accept
960 } else {
961 su.store(true, Relaxed);
962 IncomingFilterOutcome::Retry
963 }
964 })
965 .await?;
966
967 let _conn = e2.connect(addr, ECHO_ALPN).await?;
971
972 assert!(saw_unvalidated.load(Relaxed));
973 assert!(saw_validated.load(Relaxed));
974
975 r1.shutdown().await.anyerr()?;
976 e2.close().await;
977 Ok(())
978 }
979
980 #[tokio::test]
985 #[traced_test]
986 async fn relay_retry_then_validated() -> Result {
987 let saw_validated = Arc::<AtomicBool>::default();
988 let saw_unvalidated = Arc::<AtomicBool>::default();
989 let (sv, su) = (saw_validated.clone(), saw_unvalidated.clone());
990
991 let (r1, e2, addr, _guard) = relay_pair(move |incoming| {
992 if incoming.remote_addr_validated() {
993 sv.store(true, Relaxed);
994 IncomingFilterOutcome::Accept
995 } else {
996 su.store(true, Relaxed);
997 IncomingFilterOutcome::Retry
998 }
999 })
1000 .await?;
1001
1002 let _conn = e2.connect(addr, ECHO_ALPN).await?;
1003
1004 assert!(
1005 saw_unvalidated.load(Relaxed),
1006 "expected unvalidated incoming"
1007 );
1008 assert!(
1009 saw_validated.load(Relaxed),
1010 "expected validated incoming after retry"
1011 );
1012
1013 r1.shutdown().await.anyerr()?;
1014 e2.close().await;
1015 Ok(())
1016 }
1017 }
1018
1019 #[tokio::test]
1020 async fn test_graceful_shutdown() -> Result {
1021 #[derive(Debug, Clone, Default)]
1022 struct TestProtocol {
1023 connections: Arc<Mutex<Vec<Connection>>>,
1024 }
1025
1026 const TEST_ALPN: &[u8] = b"/iroh/test/1";
1027
1028 impl ProtocolHandler for TestProtocol {
1029 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
1030 self.connections.lock().expect("poisoned").push(connection);
1031 Ok(())
1032 }
1033
1034 async fn shutdown(&self) {
1035 tokio::time::sleep(Duration::from_millis(100)).await;
1036 let mut connections = self.connections.lock().expect("poisoned");
1037 for conn in connections.drain(..) {
1038 conn.close(42u32.into(), b"shutdown");
1039 }
1040 }
1041 }
1042
1043 eprintln!("creating ep1");
1044 let endpoint = Endpoint::bind(presets::Minimal).await?;
1045 let router = Router::builder(endpoint)
1046 .accept(TEST_ALPN, TestProtocol::default())
1047 .spawn();
1048 eprintln!("waiting for endpoint addr");
1049 let addr = router.endpoint().addr();
1050
1051 eprintln!("creating ep2");
1052 let endpoint2 = Endpoint::bind(presets::Minimal).await?;
1053 eprintln!("connecting to {addr:?}");
1054 let conn = endpoint2.connect(addr, TEST_ALPN).await?;
1055
1056 eprintln!("starting shutdown");
1057 router.shutdown().await.anyerr()?;
1058
1059 eprintln!("waiting for closed conn");
1060 let reason = conn.closed().await;
1061 assert_eq!(
1062 reason,
1063 ConnectionError::ApplicationClosed(ApplicationClose {
1064 error_code: 42u32.into(),
1065 reason: b"shutdown".to_vec().into()
1066 })
1067 );
1068 Ok(())
1069 }
1070
1071 #[tokio::test]
1072 async fn protocol_negotiation() -> n0_error::Result<()> {
1073 const ALPN_1: &[u8] = b"myproto/1";
1075 const ALPN_2: &[u8] = b"myproto/2";
1076
1077 #[derive(Debug, Clone)]
1078 struct Handler1;
1079
1080 #[derive(Debug, Clone)]
1081 struct Handler2;
1082
1083 impl ProtocolHandler for Handler1 {
1084 async fn accept(&self, _connection: Connection) -> Result<(), AcceptError> {
1085 Ok(())
1086 }
1087 }
1088
1089 impl ProtocolHandler for Handler2 {
1090 async fn accept(&self, _connection: Connection) -> Result<(), AcceptError> {
1091 Ok(())
1092 }
1093 }
1094
1095 let server = Endpoint::bind(presets::N0).await?;
1096 let server_addr = server.addr();
1097
1098 let router = Router::builder(server)
1099 .accept(ALPN_2, Handler2)
1101 .accept(ALPN_1, Handler1)
1102 .spawn();
1103
1104 let client = Endpoint::bind(presets::N0).await?;
1105
1106 let conn = client
1108 .connect_with_opts(
1109 server_addr.clone(),
1110 ALPN_1,
1111 ConnectOptions::new().with_additional_alpns(vec![ALPN_2.to_vec()]),
1112 )
1113 .await?
1114 .await?;
1115 assert_eq!(conn.alpn(), ALPN_2);
1116
1117 let conn = client
1119 .connect_with_opts(
1120 server_addr,
1121 ALPN_2,
1122 ConnectOptions::new().with_additional_alpns(vec![ALPN_1.to_vec()]),
1123 )
1124 .await?
1125 .await?;
1126 assert_eq!(conn.alpn(), ALPN_2);
1127
1128 client.close().await;
1129 router.shutdown().await.unwrap();
1130 Ok(())
1131 }
1132}