Factor out handler, allow strings as port numbers to simplify Jinja2 templates

This commit is contained in:
Dominik Werder
2022-02-22 16:54:14 +01:00
parent 2b49d67eed
commit a0bc67d3a3
4 changed files with 161 additions and 75 deletions

View File

@@ -220,8 +220,11 @@ pub struct ChannelArchiver {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Node {
pub host: String,
// TODO for `listen` and the ports, would be great to allow a default on Cluster level.
pub listen: String,
#[serde(deserialize_with = "port_from_any")]
pub port: u16,
#[serde(deserialize_with = "port_from_any")]
pub port_raw: u16,
pub cache_base_path: PathBuf,
pub sf_databuffer: Option<SfDatabuffer>,
@@ -229,6 +232,58 @@ pub struct Node {
pub channel_archiver: Option<ChannelArchiver>,
}
struct Visit1 {}
impl<'de> serde::de::Visitor<'de> for Visit1 {
type Value = u16;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a tcp port number, in numeric or string form.")
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if v > u16::MAX as u64 {
Err(serde::de::Error::invalid_type(
serde::de::Unexpected::Unsigned(v),
&self,
))
} else {
self.visit_i64(v as i64)
}
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if v < 1 || v > u16::MAX as i64 {
Err(serde::de::Error::invalid_type(serde::de::Unexpected::Signed(v), &self))
} else {
Ok(v as u16)
}
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match v.parse::<u16>() {
Err(_) => Err(serde::de::Error::invalid_type(serde::de::Unexpected::Str(v), &self)),
Ok(v) => Ok(v),
}
}
}
fn port_from_any<'de, D>(de: D) -> Result<u16, D::Error>
where
D: serde::Deserializer<'de>,
{
de.deserialize_any(Visit1 {})
}
impl Node {
// TODO needed? Could `sf_databuffer` be None?
pub fn dummy() -> Self {