use crate::std_shim::{String, ToString, Vec, format, vec};
pub const SERVICE_TYPE: &str = "_openadr3._tcp.local.";
pub mod txt {
pub const VERSION: &str = "version";
pub const BASE_PATH: &str = "base_path";
pub const LOCAL_URL: &str = "local_url";
pub const PROGRAM_NAMES: &str = "program_names";
pub const REQUIRES_AUTH: &str = "requires_auth";
pub const OPENAPI_URL: &str = "openapi_url";
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DiscoveryError {
#[error("invalid service description: {0}")]
Invalid(String),
#[error("mDNS is unavailable: {0}")]
Unavailable(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VtnService {
pub instance: String,
pub hostname: String,
pub port: u16,
pub version: String,
pub base_path: String,
pub tls: bool,
pub program_names: Vec<String>,
pub requires_auth: bool,
pub openapi_url: Option<String>,
}
impl VtnService {
pub fn new(instance: impl Into<String>, port: u16) -> Self {
let instance = instance.into();
Self {
hostname: format!("{instance}.local"),
instance,
port,
version: crate::SPEC_VERSION.to_string(),
base_path: crate::DEFAULT_BASE_PATH.trim_start_matches('/').to_string(),
tls: false,
program_names: Vec::new(),
requires_auth: true,
openapi_url: None,
}
}
pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self {
self.hostname = hostname.into();
self
}
pub fn with_base_path(mut self, base_path: &str) -> Self {
self.base_path = base_path.trim_start_matches('/').to_string();
self
}
pub fn with_tls(mut self) -> Self {
self.tls = true;
self
}
pub fn with_program_names<S: Into<String>>(
mut self,
names: impl IntoIterator<Item = S>,
) -> Self {
self.program_names = names.into_iter().map(Into::into).collect();
self
}
pub fn requiring_auth(mut self, required: bool) -> Self {
self.requires_auth = required;
self
}
pub fn with_openapi_url(mut self, url: impl Into<String>) -> Self {
self.openapi_url = Some(url.into());
self
}
pub fn local_url(&self) -> String {
let scheme = if self.tls { "https" } else { "http" };
let host = self.hostname.trim_end_matches('.');
format!("{scheme}://{host}:{}/{}", self.port, self.base_path)
}
pub fn openapi_url(&self) -> String {
format!("{}/openapi.json", self.local_url().trim_end_matches('/'))
}
pub fn txt_records(&self) -> Vec<(&'static str, String)> {
let mut out = vec![
(txt::VERSION, self.version.clone()),
(txt::BASE_PATH, self.base_path.clone()),
(txt::LOCAL_URL, self.local_url()),
(txt::PROGRAM_NAMES, self.program_names.join(",")),
(
txt::REQUIRES_AUTH,
if self.requires_auth { "True" } else { "False" }.to_string(),
),
];
if let Some(url) = &self.openapi_url {
out.push((txt::OPENAPI_URL, url.clone()));
}
out
}
pub fn full_name(&self) -> String {
format!("{}.{SERVICE_TYPE}", self.instance)
}
pub fn from_txt(
instance: impl Into<String>,
hostname: impl Into<String>,
port: u16,
properties: &[(String, String)],
) -> Result<Self, DiscoveryError> {
let get = |key: &str| {
properties
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(key))
.map(|(_, v)| v.clone())
};
let local_url = get(txt::LOCAL_URL).ok_or_else(|| {
DiscoveryError::Invalid(format!("the record carries no `{}`", txt::LOCAL_URL))
})?;
let base_path = get(txt::BASE_PATH).unwrap_or_else(|| {
local_url
.split_once("://")
.and_then(|(_, rest)| rest.split_once('/'))
.map(|(_, path)| path.to_string())
.unwrap_or_default()
});
Ok(Self {
instance: instance.into(),
hostname: hostname.into().trim_end_matches('.').to_string(),
port,
version: get(txt::VERSION).unwrap_or_else(|| crate::SPEC_VERSION.to_string()),
base_path,
tls: local_url.starts_with("https://"),
program_names: get(txt::PROGRAM_NAMES)
.map(|v| {
v.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(ToString::to_string)
.collect()
})
.unwrap_or_default(),
requires_auth: get(txt::REQUIRES_AUTH)
.map(|v| !v.eq_ignore_ascii_case("false"))
.unwrap_or(true),
openapi_url: get(txt::OPENAPI_URL).filter(|u| !u.is_empty()),
})
}
}
#[cfg(feature = "mdns")]
mod responder;
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub use responder::{Advertisement, discover};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_txt_record_uses_the_specifications_own_keys_and_order() {
let service = VtnService::new("My_VTN", 883)
.with_hostname("myvtn.local")
.with_base_path("/openadr3/3.1.0")
.with_tls()
.with_program_names(["local"])
.requiring_auth(false);
let records = service.txt_records();
let keys: Vec<&str> = records.iter().map(|(k, _)| *k).collect();
assert_eq!(
keys,
vec![
"version",
"base_path",
"local_url",
"program_names",
"requires_auth"
]
);
let value = |key: &str| {
records
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.as_str())
.unwrap()
};
assert_eq!(value("version"), "3.1.0");
assert_eq!(value("base_path"), "openadr3/3.1.0");
assert_eq!(value("local_url"), "https://myvtn.local:883/openadr3/3.1.0");
assert_eq!(value("program_names"), "local");
assert_eq!(value("requires_auth"), "False");
assert_eq!(service.full_name(), "My_VTN._openadr3._tcp.local.");
}
#[test]
fn the_openapi_url_follows_the_local_url() {
let service = VtnService::new("vtn", 8443)
.with_hostname("myvtn.local")
.with_base_path("/openadr3/3.1.0")
.with_tls();
assert_eq!(
service.openapi_url(),
"https://myvtn.local:8443/openadr3/3.1.0/openapi.json"
);
let root = VtnService::new("vtn", 3000)
.with_hostname("myvtn.local")
.with_base_path("");
assert_eq!(root.openapi_url(), "http://myvtn.local:3000/openapi.json");
}
#[test]
fn an_absent_openapi_url_is_absent_rather_than_empty() {
let service = VtnService::new("vtn", 3000);
assert!(
service
.txt_records()
.iter()
.all(|(k, _)| *k != txt::OPENAPI_URL),
"an empty value claims the document is at the empty URL"
);
let with = service.with_openapi_url("http://vtn.local:3000/openapi.json");
assert_eq!(
with.txt_records().last().map(|(k, _)| *k),
Some(txt::OPENAPI_URL)
);
}
#[test]
fn a_record_round_trips_through_its_own_txt() {
let original = VtnService::new("gateway", 3000)
.with_base_path("openadr3/3.1.0")
.with_program_names(["tariff", "curtailment"])
.requiring_auth(true)
.with_openapi_url("http://gateway.local:3000/openapi.json");
let properties: Vec<(String, String)> = original
.txt_records()
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let parsed = VtnService::from_txt("gateway", "gateway.local.", 3000, &properties).unwrap();
assert_eq!(parsed, original);
}
#[test]
fn a_record_without_a_local_url_names_no_vtn() {
let properties = [("version".to_string(), "3.1.0".to_string())];
assert!(matches!(
VtnService::from_txt("x", "x.local", 3000, &properties),
Err(DiscoveryError::Invalid(_))
));
}
#[test]
fn an_unstated_requires_auth_is_read_as_yes() {
let properties = [(
"local_url".to_string(),
"http://vtn.local:3000/openadr3/3.1.0".to_string(),
)];
let parsed = VtnService::from_txt("vtn", "vtn.local", 3000, &properties).unwrap();
assert!(parsed.requires_auth);
assert_eq!(parsed.base_path, "openadr3/3.1.0");
assert!(!parsed.tls);
}
#[test]
fn a_peers_capitalisation_does_not_decide_whether_it_is_found() {
let properties = [
(
"LOCAL_URL".to_string(),
"https://peer.local:8443/oadr".to_string(),
),
("Requires_Auth".to_string(), "FALSE".to_string()),
];
let parsed = VtnService::from_txt("peer", "peer.local", 8443, &properties).unwrap();
assert!(!parsed.requires_auth);
assert!(parsed.tls);
assert_eq!(parsed.base_path, "oadr");
}
}