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 e23527b
Show file tree
Hide file tree
Showing 23 changed files with 222 additions and 170 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

145 changes: 110 additions & 35 deletions commons/zenoh-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,18 +228,108 @@ 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)]
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<'a> ValidatedMapAssociatedTypes<'a> for Config {
type Accessor = <InternalConfig as ValidatedMapAssociatedTypes<'a>>::Accessor;
}

// REVIEW(fuzzpixelz): should `validated_struct::ValidatedMap` be part of the public `Config` API?
impl ValidatedMap for Config {
fn insert<'d, D: serde::Deserializer<'d>>(
&mut self,
key: &str,
value: D,
) -> Result<(), validated_struct::InsertionError>
where
validated_struct::InsertionError: From<D::Error>,
{
self.0.insert(key, value)
}

fn get<'a>(
&'a self,
key: &str,
) -> Result<<Self as ValidatedMapAssociatedTypes<'a>>::Accessor, GetError> {
self.0.get(key)
}

fn get_json(&self, key: &str) -> Result<String, GetError> {
self.0.get_json(key)
}

type Keys = <InternalConfig as ValidatedMap>::Keys;

fn keys(&self) -> Self::Keys {
<InternalConfig as ValidatedMap>::keys(&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 +669,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 +696,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 +720,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 +737,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 +816,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 +832,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 +846,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 +858,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 +885,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 +902,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 +926,7 @@ 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
8 changes: 4 additions & 4 deletions examples/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! Check ../README.md for usage.
//!
use zenoh::config::Config;
use zenoh::{config::WhatAmI, Config};

#[derive(clap::ValueEnum, Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Wai {
Expand Down Expand Up @@ -59,9 +59,9 @@ impl From<&CommonArgs> for Config {
None => Config::default(),
};
match args.mode {
Some(Wai::Peer) => config.set_mode(Some(zenoh::config::WhatAmI::Peer)),
Some(Wai::Client) => config.set_mode(Some(zenoh::config::WhatAmI::Client)),
Some(Wai::Router) => config.set_mode(Some(zenoh::config::WhatAmI::Router)),
Some(Wai::Peer) => config.set_mode(Some(WhatAmI::Peer)),
Some(Wai::Client) => config.set_mode(Some(WhatAmI::Client)),
Some(Wai::Router) => config.set_mode(Some(WhatAmI::Router)),
None => Ok(None),
}
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions zenoh-ext/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ zenoh-macros = { workspace = true }

[dev-dependencies]
zenoh = { workspace = true, features = ["unstable"], default-features = true }
zenoh-config = { workspace = true }

[package.metadata.docs.rs]
features = ["unstable"]
1 change: 1 addition & 0 deletions zenoh-ext/examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ clap = { workspace = true, features = ["derive"] }
zenoh-ext = { workspace = true }

[dev-dependencies]
zenoh-config = { workspace = true }

[[example]]
name = "z_query_sub"
Expand Down
6 changes: 2 additions & 4 deletions zenoh-ext/examples/examples/z_pub_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@
use std::time::Duration;

use clap::{arg, Parser};
use zenoh::{
config::{Config, ModeDependentValue},
key_expr::KeyExpr,
};
use zenoh::{config::Config, key_expr::KeyExpr};
use zenoh_config::ModeDependentValue;
use zenoh_ext::*;
use zenoh_ext_examples::CommonArgs;

Expand Down
8 changes: 4 additions & 4 deletions zenoh-ext/examples/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! See the code in ../examples/
//! Check ../README.md for usage.
//!
use zenoh::config::Config;
use zenoh::{config::WhatAmI, Config};

#[derive(clap::ValueEnum, Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Wai {
Expand Down Expand Up @@ -43,9 +43,9 @@ impl From<&CommonArgs> for Config {
None => Config::default(),
};
match value.mode {
Some(Wai::Peer) => config.set_mode(Some(zenoh::config::WhatAmI::Peer)),
Some(Wai::Client) => config.set_mode(Some(zenoh::config::WhatAmI::Client)),
Some(Wai::Router) => config.set_mode(Some(zenoh::config::WhatAmI::Router)),
Some(Wai::Peer) => config.set_mode(Some(WhatAmI::Peer)),
Some(Wai::Client) => config.set_mode(Some(WhatAmI::Client)),
Some(Wai::Router) => config.set_mode(Some(WhatAmI::Router)),
None => Ok(None),
}
.unwrap();
Expand Down
Loading

0 comments on commit e23527b

Please sign in to comment.