Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api alignment: Config alignment #188

Merged
merged 4 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/src/main/kotlin/io.zenoh/Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ internal fun loadConfig(
Config.default()
} else {
configFile?.let {
Config.from(path = Path(it))
Config.fromFile(path = Path(it)).getOrThrow()
} ?: run {
val connect = Connect(connectEndpoints)
val listen = Listen(listenEndpoints)
val scouting = Scouting(Multicast(!noMulticastScouting))
val configData = ConfigData(connect, listen, mode, scouting)
val jsonConfig = Json.encodeToJsonElement(configData)
Config.from(jsonConfig)
Config.fromFile(jsonConfig).getOrThrow()
}
}
}
133 changes: 133 additions & 0 deletions zenoh-jni/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
// ZettaScale Zenoh Team, <[email protected]>
//

use std::{ptr::null, sync::Arc};

use jni::{
objects::{JClass, JString},
JNIEnv,
};
use zenoh::Config;

use crate::errors::Result;
use crate::{session_error, throw_exception, utils::decode_string};

/// Loads the default configuration, returning a raw pointer to it.
///
/// The pointer to the config is expected to be freed later on upon the destruction of the
/// Kotlin Config instance.
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_jni_JNIConfig_00024Companion_loadDefaultConfigViaJNI(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this an automatically generated code? The names look a bit strange.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, its not 😅 . It's strange because it's meant to be called from Kotlin through the JNI by a function named loadDefaultConfigViaJNI located at io/zenoh/jni/JNIConfig$Companion. It must have this weird looking signature for Java/Kotlin to locate the corresponding native function.

_env: JNIEnv,
_class: JClass,
) -> *const Config {
let config = Config::default();
Arc::into_raw(Arc::new(config))
}

/// Loads the config from a file, returning a pointer to the loaded config in case of success.
/// In case of failure, an exception is thrown via JNI.
///
/// The pointer to the config is expected to be freed later on upon the destruction of the
/// Kotlin Config instance.
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_jni_JNIConfig_00024Companion_loadConfigFileViaJNI(
mut env: JNIEnv,
_class: JClass,
config_path: JString,
) -> *const Config {
|| -> Result<*const Config> {
let config_file_path = decode_string(&mut env, &config_path)?;
let config = Config::from_file(config_file_path).map_err(|err| session_error!(err))?;
Ok(Arc::into_raw(Arc::new(config)))
}()
.unwrap_or_else(|err| {
throw_exception!(env, err);
null()
})
}

/// Loads the config from a json/json5 formatted string, returning a pointer to the loaded config
/// in case of success. In case of failure, an exception is thrown via JNI.
///
/// The pointer to the config is expected to be freed later on upon the destruction of the
/// Kotlin Config instance.
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_jni_JNIConfig_00024Companion_loadJsonConfigViaJNI(
mut env: JNIEnv,
_class: JClass,
json_config: JString,
) -> *const Config {
|| -> Result<*const Config> {
let json_config = decode_string(&mut env, &json_config)?;
let mut deserializer =
json5::Deserializer::from_str(&json_config).map_err(|err| session_error!(err))?;
let config = Config::from_deserializer(&mut deserializer).map_err(|err| match err {
Ok(c) => session_error!("Invalid configuration: {}", c),
Err(e) => session_error!("JSON error: {}", e),
})?;
Ok(Arc::into_raw(Arc::new(config)))
}()
.unwrap_or_else(|err| {
throw_exception!(env, err);
null()
})
}

/// Loads the config from a yaml-formatted string, returning a pointer to the loaded config
/// in case of success. In case of failure, an exception is thrown via JNI.
///
/// The pointer to the config is expected to be freed later on upon the destruction of the
/// Kotlin Config instance.
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_jni_JNIConfig_00024Companion_loadYamlConfigViaJNI(
mut env: JNIEnv,
_class: JClass,
yaml_config: JString,
) -> *const Config {
|| -> Result<*const Config> {
let yaml_config = decode_string(&mut env, &yaml_config)?;
let deserializer = serde_yaml::Deserializer::from_str(&yaml_config);
let config = Config::from_deserializer(deserializer).map_err(|err| match err {
Ok(c) => session_error!("Invalid configuration: {}", c),
Err(e) => session_error!("YAML error: {}", e),
})?;
Ok(Arc::into_raw(Arc::new(config)))
}()
.unwrap_or_else(|err| {
throw_exception!(env, err);
null()
})
}

/// Frees the pointer to the config. The pointer should be valid and should have been obtained through
/// one of the preceding `load` functions. This function should be called upon destruction of the kotlin
/// Config instance.
#[no_mangle]
#[allow(non_snake_case)]
pub(crate) unsafe extern "C" fn Java_io_zenoh_jni_JNIConfig_00024Companion_freePtrViaJNI(
_env: JNIEnv,
_: JClass,
config_ptr: *const Config,
) {
Arc::from_raw(config_ptr);
}
1 change: 1 addition & 0 deletions zenoh-jni/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// ZettaScale Zenoh Team, <[email protected]>
//

mod config;
mod errors;
mod key_expr;
mod logger;
Expand Down
49 changes: 9 additions & 40 deletions zenoh-jni/src/scouting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
use std::{ptr::null, sync::Arc};

use jni::{
objects::{JClass, JList, JObject, JString, JValue},
objects::{JClass, JList, JObject, JValue},
sys::jint,
JNIEnv,
};
use zenoh::{config::WhatAmIMatcher, prelude::Wait};
use zenoh::{scouting::Scout, Config};

use crate::{errors::Result, throw_exception, utils::decode_string};
use crate::{errors::Result, throw_exception};
use crate::{
session_error,
utils::{get_callback_global_ref, get_java_vm},
Expand All @@ -33,14 +33,7 @@ use crate::{
/// # Params
/// - `whatAmI`: Ordinal value of the WhatAmI enum.
/// - `callback`: Callback to be executed whenever a hello message is received.
/// - `config_string`: Optional embedded configuration as a string.
/// - `format`: format of the `config_string` param.
/// - `config_path`: Optional path to a config file.
///
/// Note: Either the config_string or the config_path or None can be provided.
/// If none is provided, then the default configuration is loaded. Otherwise
/// it's the config_string or the config_path that are loaded. This consistency
/// logic is granted by the kotlin layer.
/// - `config_ptr`: Optional config pointer.
///
/// Returns a pointer to the scout, which must be freed afterwards.
/// If starting the scout fails, an exception is thrown on the JVM, and a null pointer is returned.
Expand All @@ -52,43 +45,19 @@ pub unsafe extern "C" fn Java_io_zenoh_jni_JNIScout_00024Companion_scoutViaJNI(
_class: JClass,
whatAmI: jint,
callback: JObject,
config_string: /*nullable=*/ JString,
format: jint,
config_path: /*nullable=*/ JString,
config_ptr: /*nullable=*/ *const Config,
) -> *const Scout<()> {
|| -> Result<*const Scout<()>> {
let callback_global_ref = get_callback_global_ref(&mut env, callback)?;
let java_vm = Arc::new(get_java_vm(&mut env)?);
let whatAmIMatcher: WhatAmIMatcher = (whatAmI as u8).try_into().unwrap(); // The validity of the operation is guaranteed on the kotlin layer.
let config = if config_string.is_null() && config_path.is_null() {
let config = if config_ptr.is_null() {
Config::default()
} else if !config_string.is_null() {
let string_config = decode_string(&mut env, &config_string)?;
match format {
0 /*YAML*/ => {
let deserializer = serde_yaml::Deserializer::from_str(&string_config);
Config::from_deserializer(deserializer).map_err(|err| match err {
Ok(c) => session_error!("Invalid configuration: {}", c),
Err(e) => session_error!("YAML error: {}", e),
})?
}
1 | 2 /*JSON | JSON5*/ => {
let mut deserializer =
json5::Deserializer::from_str(&string_config).map_err(|err| session_error!(err))?;
Config::from_deserializer(&mut deserializer).map_err(|err| match err {
Ok(c) => session_error!("Invalid configuration: {}", c),
Err(e) => session_error!("JSON error: {}", e),
})?
}
_ => {
// This can never happen unless the Config.Format enum on Kotlin is wrongly modified!
Err(session_error!("Unexpected error: attempting to decode a config with a format other than Json,
Json5 or Yaml. Check Config.Format for eventual modifications..."))?
}
}
} else {
let config_file_path = decode_string(&mut env, &config_path)?;
Config::from_file(config_file_path).map_err(|err| session_error!(err))?
let arc_cfg = Arc::from_raw(config_ptr);
let config_clone = arc_cfg.as_ref().clone();
std::mem::forget(arc_cfg);
config_clone
};
zenoh::scout(whatAmIMatcher, config)
.callback(move |hello| {
Expand Down
21 changes: 9 additions & 12 deletions zenoh-jni/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ use zenoh::session::{Session, SessionDeclarations};
///
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn Java_io_zenoh_jni_JNISession_openSessionViaJNI(
pub unsafe extern "C" fn Java_io_zenoh_jni_JNISession_openSessionViaJNI(
mut env: JNIEnv,
_class: JClass,
config_path: /*nullable*/ JString,
config_ptr: *const Config,
) -> *const Session {
let session = open_session(&mut env, config_path);
let session = open_session(config_ptr);
match session {
Ok(session) => Arc::into_raw(Arc::new(session)),
Err(err) => {
Expand All @@ -69,16 +69,13 @@ pub extern "C" fn Java_io_zenoh_jni_JNISession_openSessionViaJNI(
///
/// If the config path provided is null then the default configuration is loaded.
///
fn open_session(env: &mut JNIEnv, config_path: JString) -> Result<Session> {
let config = if config_path.is_null() {
Config::default()
} else {
let config_file_path = decode_string(env, &config_path)?;
Config::from_file(config_file_path).map_err(|err| session_error!(err))?
};
zenoh::open(config)
unsafe fn open_session(config_ptr: *const Config) -> Result<Session> {
let config = Arc::from_raw(config_ptr);
let result = zenoh::open(config.as_ref().clone())
.wait()
.map_err(|err| session_error!(err))
.map_err(|err| session_error!(err));
mem::forget(config);
result
}

/// Open a Zenoh session with a JSON configuration.
Expand Down
Loading