|
6 | 6 | // for full license information. |
7 | 7 |
|
8 | 8 | use rand::distr::{Alphanumeric, SampleString}; |
| 9 | +use std::{future::Future, io}; |
9 | 10 |
|
10 | 11 | pub struct IntifaceMdns { |
11 | 12 | _responder: libmdns::Responder, |
12 | 13 | _svc: libmdns::Service, |
13 | 14 | } |
14 | 15 |
|
15 | 16 | impl IntifaceMdns { |
16 | | - pub fn new() -> Self { |
| 17 | + pub fn new() -> Option<Self> { |
17 | 18 | let random_suffix = Alphanumeric.sample_string(&mut rand::rng(), 6); |
18 | 19 | let instance_name = format!("Intiface {}", random_suffix); |
19 | 20 | info!( |
20 | 21 | "Bringing up mDNS Advertisment using instance name {}", |
21 | 22 | instance_name |
22 | 23 | ); |
23 | 24 |
|
24 | | - let (_responder, task) = libmdns::Responder::with_default_handle().unwrap(); |
| 25 | + Self::from_responder_result(&instance_name, libmdns::Responder::with_default_handle()) |
| 26 | + } |
| 27 | + |
| 28 | + fn from_responder_result<T>( |
| 29 | + instance_name: &str, |
| 30 | + responder_result: io::Result<(libmdns::Responder, T)>, |
| 31 | + ) -> Option<Self> |
| 32 | + where |
| 33 | + T: Future<Output = ()> + Send + 'static, |
| 34 | + { |
| 35 | + let (_responder, task) = match responder_result { |
| 36 | + Ok(result) => result, |
| 37 | + Err(err) => { |
| 38 | + warn!("Unable to bring up mDNS advertisement: {}", err); |
| 39 | + return None; |
| 40 | + } |
| 41 | + }; |
25 | 42 | let _svc = _responder.register("_intiface_engine._tcp", &instance_name, 12345, &["path=/"]); |
26 | 43 | tokio::spawn(async move { |
27 | 44 | info!("Entering up mDNS task"); |
28 | 45 | task.await; |
29 | 46 | info!("Exiting mDNS task"); |
30 | 47 | }); |
31 | | - Self { _responder, _svc } |
| 48 | + Some(Self { _responder, _svc }) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn mdns_startup_error_disables_advertisement() { |
| 58 | + let result = IntifaceMdns::from_responder_result::<std::future::Pending<()>>( |
| 59 | + "Intiface Test", |
| 60 | + Err(io::Error::new( |
| 61 | + io::ErrorKind::AddrInUse, |
| 62 | + "Address already in use", |
| 63 | + )), |
| 64 | + ); |
| 65 | + |
| 66 | + assert!(result.is_none()); |
32 | 67 | } |
33 | 68 | } |
0 commit comments