Skip to content

Commit

Permalink
Hide zenoh_config internals
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzzypixelz committed Sep 16, 2024
1 parent 53ad313 commit 93fdbdf
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 47 deletions.
110 changes: 76 additions & 34 deletions commons/zenoh-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,18 +228,74 @@ fn config_keys() {
dbg!(Vec::from_iter(c.keys()));
}

/// Zenoh configuration.
///
/// Most options are optional as a way to keep defaults flexible. Some of the options have different
/// default values depending on the rest of the configuration.
///
/// To construct a configuration, we advise that you use a configuration file (JSON, JSON5 and YAML
/// are currently supported, please use the proper extension for your format as the deserializer
/// will be picked according to it).
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "internal", allow(dead_code))]
pub struct Config(InternalConfig);

impl Config {
pub fn from_env() -> ZResult<Self> {
Ok(Config(InternalConfig::from_env()?))
}

pub fn from_file<P: AsRef<Path>>(path: P) -> ZResult<Self> {
Ok(Config(InternalConfig::from_file(path)?))
}
}

#[doc(hidden)]
impl std::ops::Deref for Config {
type Target = InternalConfig;

fn deref(&self) -> &Self::Target {
&self.0
}
}

#[doc(hidden)]
impl std::ops::DerefMut for Config {
fn deref_mut(&mut self) -> &mut <Self as std::ops::Deref>::Target {
&mut self.0
}
}

impl fmt::Display for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.0)
}
}

impl Notifier<Config> {
// pub fn remove<K: AsRef<str>>(&self, key: K) -> ZResult<()> {
// let key = key.as_ref();
// self._remove(key)
// }

// fn _remove(&self, key: &str) -> ZResult<()> {
// {
// let mut guard = zlock!(self.inner.inner);
// guard.remove(key)?;
// }
// self.notify(key);
// Ok(())
// }
}

validated_struct::validator! {
/// The main configuration structure for Zenoh.
///
/// Most fields are optional as a way to keep defaults flexible. Some of the fields have different default values depending on the rest of the configuration.
///
/// To construct a configuration, we advise that you use a configuration file (JSON, JSON5 and YAML are currently supported, please use the proper extension for your format as the deserializer will be picked according to it).
#[derive(Default)]
#[recursive_attrs]
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug)]
#[serde(default)]
#[serde(deny_unknown_fields)]
Config {
#[doc(hidden)]
InternalConfig {
/// The Zenoh ID of the instance. This ID MUST be unique throughout your Zenoh infrastructure and cannot exceed 16 bytes of length. If left unset, a random u128 will be generated.
id: ZenohId,
/// The metadata of the instance. Arbitrary json data available from the admin space
Expand Down Expand Up @@ -579,7 +635,7 @@ fn set_false() -> bool {

#[test]
fn config_deser() {
let config = Config::from_deserializer(
let config = InternalConfig::from_deserializer(
&mut json5::Deserializer::from_str(
r#"{
scouting: {
Expand All @@ -606,7 +662,7 @@ fn config_deser() {
config.scouting().multicast().autoconnect().client(),
Some(&WhatAmIMatcher::empty().router().peer())
);
let config = Config::from_deserializer(
let config = InternalConfig::from_deserializer(
&mut json5::Deserializer::from_str(
r#"{
scouting: {
Expand All @@ -630,7 +686,7 @@ fn config_deser() {
Some(&WhatAmIMatcher::empty().router().peer())
);
assert_eq!(config.scouting().multicast().autoconnect().client(), None);
let config = Config::from_deserializer(
let config = InternalConfig::from_deserializer(
&mut json5::Deserializer::from_str(
r#"{transport: { auth: { usrpwd: { user: null, password: null, dictionary_file: "file" }}}}"#,
)
Expand All @@ -647,17 +703,17 @@ fn config_deser() {
.map(|s| s.as_ref()),
Some("file")
);
std::mem::drop(Config::from_deserializer(
std::mem::drop(InternalConfig::from_deserializer(
&mut json5::Deserializer::from_str(
r#"{transport: { auth: { usrpwd: { user: null, password: null, user_password_dictionary: "file" }}}}"#,
)
.unwrap(),
)
.unwrap_err());
dbg!(Config::from_file("../../DEFAULT_CONFIG.json5").unwrap());
dbg!(InternalConfig::from_file("../../DEFAULT_CONFIG.json5").unwrap());
}

impl Config {
impl InternalConfig {
pub fn insert<'d, D: serde::Deserializer<'d>>(
&mut self,
key: &str,
Expand Down Expand Up @@ -726,7 +782,7 @@ impl Config {
pub enum ConfigOpenErr {
IoError(std::io::Error),
JsonParseErr(json5::Error),
InvalidConfiguration(Box<Config>),
InvalidConfiguration(Box<InternalConfig>),
}
impl std::fmt::Display for ConfigOpenErr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand All @@ -742,7 +798,7 @@ impl std::fmt::Display for ConfigOpenErr {
}
}
impl std::error::Error for ConfigOpenErr {}
impl Config {
impl InternalConfig {
pub fn from_env() -> ZResult<Self> {
let path = std::env::var(defaults::ENV)
.map_err(|e| zerror!("Invalid ENV variable ({}): {}", defaults::ENV, e))?;
Expand All @@ -756,7 +812,7 @@ impl Config {
Ok(config)
}

fn _from_file(path: &Path) -> ZResult<Config> {
fn _from_file(path: &Path) -> ZResult<InternalConfig> {
match std::fs::File::open(path) {
Ok(mut f) => {
let mut content = String::new();
Expand All @@ -768,13 +824,13 @@ impl Config {
.map(|s| s.to_str().unwrap())
{
Some("json") | Some("json5") => match json5::Deserializer::from_str(&content) {
Ok(mut d) => Config::from_deserializer(&mut d).map_err(|e| match e {
Ok(mut d) => InternalConfig::from_deserializer(&mut d).map_err(|e| match e {
Ok(c) => zerror!("Invalid configuration: {}", c).into(),
Err(e) => zerror!("JSON error: {}", e).into(),
}),
Err(e) => bail!(e),
},
Some("yaml") | Some("yml") => Config::from_deserializer(serde_yaml::Deserializer::from_str(&content)).map_err(|e| match e {
Some("yaml") | Some("yml") => InternalConfig::from_deserializer(serde_yaml::Deserializer::from_str(&content)).map_err(|e| match e {
Ok(c) => zerror!("Invalid configuration: {}", c).into(),
Err(e) => zerror!("YAML error: {}", e).into(),
}),
Expand All @@ -795,7 +851,7 @@ impl Config {
}
}

impl std::fmt::Display for Config {
impl std::fmt::Display for InternalConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
serde_json::to_value(self)
.map(|mut json| {
Expand All @@ -812,7 +868,7 @@ impl std::fmt::Display for Config {
#[test]
fn config_from_json() {
let from_str = serde_json::Deserializer::from_str;
let mut config = Config::from_deserializer(&mut from_str(r#"{}"#)).unwrap();
let mut config = InternalConfig::from_deserializer(&mut from_str(r#"{}"#)).unwrap();
config
.insert("transport/link/tx/lease", &mut from_str("168"))
.unwrap();
Expand All @@ -836,22 +892,8 @@ impl<T> Clone for Notifier<T> {
}
}
}
impl Notifier<Config> {
pub fn remove<K: AsRef<str>>(&self, key: K) -> ZResult<()> {
let key = key.as_ref();
self._remove(key)
}

fn _remove(&self, key: &str) -> ZResult<()> {
{
let mut guard = zlock!(self.inner.inner);
guard.remove(key)?;
}
self.notify(key);
Ok(())
}
}
impl<T: ValidatedMap> Notifier<T> {
impl<T> Notifier<T> {
pub fn new(inner: T) -> Self {
Notifier {
inner: Arc::new(NotifierInner {
Expand Down
28 changes: 15 additions & 13 deletions zenoh/src/net/runtime/adminspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,16 +398,17 @@ impl Primitives for AdminSpace {
key,
json
);
if let Err(e) = self.context.runtime.state.config.insert_json5(key, json) {
error!(
"Error inserting conf value @/{}/{}/config/{} : {} - {}",
self.context.runtime.state.zid,
self.context.runtime.state.whatami,
key,
json,
e
);
}
// FIXME(fuzzypixelz): uncomment this
// if let Err(e) = self.context.runtime.state.config.insert_json5(key, json) {
// error!(
// "Error inserting conf value @/{}/{}/config/{} : {} - {}",
// self.context.runtime.state.zid,
// self.context.runtime.state.whatami,
// key,
// json,
// e
// );
// }
}
Err(e) => error!(
"Received non utf8 conf value on @/{}/{}/config/{} : {}",
Expand All @@ -421,9 +422,10 @@ impl Primitives for AdminSpace {
self.context.runtime.state.whatami,
key
);
if let Err(e) = self.context.runtime.state.config.remove(key) {
tracing::error!("Error deleting conf value {} : {}", msg.wire_expr, e)
}
// FIXME(fuzzypixelz): uncomment this
// if let Err(e) = self.context.runtime.state.config.remove(key) {
// tracing::error!("Error deleting conf value {} : {}", msg.wire_expr, e)
// }
}
}
}
Expand Down

0 comments on commit 93fdbdf

Please sign in to comment.