use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::time::Duration;
use rings_dns_relay::ProxyProtocol;
use serde::Deserialize;
use serde::Serialize;
use super::descriptor::ServedTxt;
use super::registration::ServiceOffer;
use crate::error::Error;
use crate::error::Result;
use crate::registration::validate_schedule;
use crate::registration::TimingKeys;
const DEFAULT_SERVICES_HEARTBEAT_INTERVAL_SECS: u64 = 30;
const DEFAULT_SERVICES_TTL_SECS: u64 = 90;
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ServedPortConfig {
pub port: u16,
pub target: SocketAddr,
#[serde(default)]
pub proxy_protocol: ProxyProtocol,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ServedTxtConfig {
#[serde(default)]
pub name: String,
pub values: Vec<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ServicesConfig {
#[serde(default)]
pub ports: Vec<ServedPortConfig>,
#[serde(default)]
pub txt: Vec<ServedTxtConfig>,
#[serde(default = "default_services_heartbeat_interval_secs")]
pub heartbeat_interval_secs: u64,
#[serde(default = "default_services_ttl_secs")]
pub ttl_secs: u64,
}
impl ServicesConfig {
pub fn offer(&self) -> Result<ServiceOffer> {
let heartbeat_interval = Duration::from_secs(self.heartbeat_interval_secs);
let ttl = Duration::from_secs(self.ttl_secs);
let keys = TimingKeys {
heartbeat_interval: "services.heartbeat_interval_secs",
ttl: "services.ttl_secs",
enabled_by: None,
};
validate_schedule(&keys, heartbeat_interval, ttl)?;
let mut ports = BTreeMap::new();
for served in &self.ports {
if ports.insert(served.port, served.proxy_protocol).is_some() {
return Err(Error::InvalidConfig(format!(
"services: port {} is served twice",
served.port
)));
}
}
let txt = self
.txt
.iter()
.map(|served| ServedTxt {
name: served.name.clone(),
values: served.values.clone(),
})
.collect();
ServiceOffer::new(ports, txt, heartbeat_interval, ttl)
.map_err(|error| Error::InvalidConfig(format!("services: {error}")))
}
pub fn targets(&self) -> impl Iterator<Item = (u16, SocketAddr)> + '_ {
self.ports.iter().map(|served| (served.port, served.target))
}
}
const fn default_services_heartbeat_interval_secs() -> u64 {
DEFAULT_SERVICES_HEARTBEAT_INTERVAL_SECS
}
const fn default_services_ttl_secs() -> u64 {
DEFAULT_SERVICES_TTL_SECS
}