Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
thebino committed Jul 4, 2023
1 parent 9fae17f commit 0756b14
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 51 deletions.
4 changes: 1 addition & 3 deletions crates/plugin_interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use abi_stable::{
external_types::crossbeam_channel::RSender,
library::RootModule,
package_version_strings, sabi_trait,
sabi_types::{VersionStrings},
sabi_types::VersionStrings,
std_types::{RBox, RResult, RString},
StableAbi,
};
Expand Down Expand Up @@ -53,8 +53,6 @@ impl RootModule for PluginFactory_Ref {
const VERSION_STRINGS: VersionStrings = package_version_strings!();
}



#[repr(u8)]
#[derive(Debug, StableAbi)]
pub enum Error {
Expand Down
11 changes: 5 additions & 6 deletions src/config/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ pub struct OAuthClientConfig {
pub name: String,
pub client_id: String,
pub client_secret: String,
pub redirect_uris: Vec<String>
pub redirect_uris: Vec<String>,
}

impl fmt::Display for OAuthClientConfig {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"{}, redirect: {:?}", self.name, self.redirect_uris)
write!(f, "{}, redirect: {:?}", self.name, self.redirect_uris)
}
}

Expand Down Expand Up @@ -60,8 +59,8 @@ mod tests {
redirect_uris: vec![
"https://demo.photos.network/callback".into(),
"http://127.0.0.1:7777/callback".into(),
"photosapp://authenticate".into()
]
"photosapp://authenticate".into(),
],
};

assert_eq!(data, serde_json::from_str(json).unwrap());
Expand All @@ -81,7 +80,7 @@ mod tests {
name: "Client".into(),
client_id: "clientId".into(),
client_secret: "clientSecret".into(),
redirect_uris: vec![]
redirect_uris: vec![],
};

assert_eq!(data, serde_json::from_str(json).unwrap());
Expand Down
57 changes: 31 additions & 26 deletions src/config/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
*/

//! This defines the app configuration
use std::{fs, fmt};
use std::{fmt, fs};

use serde::Deserialize;
use tracing::info;

use super::{client::OAuthClientConfig, plugin::Plugin};


#[derive(Debug, PartialEq, Deserialize, Clone)]
pub struct Configuration {
pub internal_url: String,
Expand All @@ -36,8 +35,9 @@ impl Configuration {
pub fn new(path: &str) -> Option<Self> {
info!("Load configuration file {}", path);
let data = fs::read_to_string(path).expect("Unable to read configuration file!");
let config: Configuration = serde_json::from_str(&data).expect("Configuration file could not be parsed as JSON!");

let config: Configuration =
serde_json::from_str(&data).expect("Configuration file could not be parsed as JSON!");

Some(config)
}
}
Expand All @@ -50,27 +50,30 @@ impl fmt::Display for Configuration {
write!(f, "{{")?;
write!(f, "\n\tinternal: {}", self.internal_url)?;
write!(f, "\n\texternal: {}", self.external_url)?;

// clients
write!(f, "\n\tclients: [ ")?;
for (count, v) in clients.iter().enumerate() {
if count != 0 { write!(f, ", ")?; }
if count != 0 {
write!(f, ", ")?;
}
write!(f, "\n\t\t{}", v)?;
}
write!(f, "\n\t] ")?;

// plugins
write!(f, "\n\tplugins: [ ")?;
for (count, v) in plugins.iter().enumerate() {
if count != 0 { write!(f, ", ")?; }
if count != 0 {
write!(f, ", ")?;
}
write!(f, "\n\t\t{}", v)?;
}
write!(f, "\n\t]")?;
write!(f, "\n}}")
}
}


#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -106,26 +109,28 @@ mod tests {
let mut config = Map::new();
config.insert("property1".to_string(), serde_json::Value::Null);
config.insert("property2".to_string(), serde_json::Value::Bool(true));
config.insert("property3".to_string(), serde_json::Value::String("aBc".into()));
config.insert("property4".to_string(), serde_json::Value::Number(42.into()));

config.insert(
"property3".to_string(),
serde_json::Value::String("aBc".into()),
);
config.insert(
"property4".to_string(),
serde_json::Value::Number(42.into()),
);

let data = Configuration {
internal_url: "192.168.0.1".into(),
external_url: "demo.photos.network".into(),
clients: vec![
OAuthClientConfig {
name: "Client".into(),
client_id: "clientId".into(),
client_secret: "clientSecret".into(),
redirect_uris: vec![]
}
],
plugins: vec![
Plugin {
name: "Plugin".into(),
config: Some(config),
}
]
clients: vec![OAuthClientConfig {
name: "Client".into(),
client_id: "clientId".into(),
client_secret: "clientSecret".into(),
redirect_uris: vec![],
}],
plugins: vec![Plugin {
name: "Plugin".into(),
config: Some(config),
}],
};

assert_eq!(data, serde_json::from_str(json).unwrap());
Expand Down
2 changes: 1 addition & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod client;
pub mod plugin;
pub mod configuration;
pub mod plugin;
14 changes: 10 additions & 4 deletions src/config/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
//! This describes a plugin with a key-value pair configuration
use std::fmt;

use serde::{Deserialize};
use serde::Deserialize;
use serde_json::Map;

#[derive(Debug, PartialEq, Deserialize, Clone)]
pub struct Plugin {
pub name: String,
pub config: Option<Map<String, serde_json::Value>>
pub config: Option<Map<String, serde_json::Value>>,
}

impl fmt::Display for Plugin {
Expand Down Expand Up @@ -53,8 +53,14 @@ mod tests {
let mut config = Map::new();
config.insert("property1".to_string(), serde_json::Value::Null);
config.insert("property2".to_string(), serde_json::Value::Bool(true));
config.insert("property3".to_string(), serde_json::Value::String("aBc".into()));
config.insert("property4".to_string(), serde_json::Value::Number(42.into()));
config.insert(
"property3".to_string(),
serde_json::Value::String("aBc".into()),
);
config.insert(
"property4".to_string(),
serde_json::Value::Number(42.into()),
);

let data = Plugin {
name: "Plugin".into(),
Expand Down
12 changes: 3 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use photos_network_plugin::{PluginFactory_Ref, PluginId};
use serde::{Deserialize, Serialize};
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use tracing::{error, info, debug};
use tracing::{debug, error, info};
use tracing_subscriber::{fmt, layer::SubscriberExt};

use config::configuration::Configuration;
Expand Down Expand Up @@ -68,18 +68,15 @@ pub async fn start_server() -> Result<()> {

info!("Photos.network core is starting...");


// create mandatory application directories if necessary
fs::create_dir_all("data")?;
fs::create_dir_all("config")?;
fs::create_dir_all("plugins")?;


// read config file
let config = Configuration::new(CONFIG_PATH).expect("Could not parse configuration!");
debug!("Configuration: {}", config);


// init application state
let mut app_state = ApplicationState::new(config.clone());

Expand All @@ -98,17 +95,16 @@ pub async fn start_server() -> Result<()> {
;
app_state.router = Some(router);


// initialize plugin manager
let mut plugin_manager = PluginManager::new(config.clone(), PLUGIN_PATH.to_string(), &mut app_state)?;
let mut plugin_manager =
PluginManager::new(config.clone(), PLUGIN_PATH.to_string(), &mut app_state)?;

match plugin_manager.init().await {
Ok(_) => info!("PluginManager: initialization succed."),
Err(e) => error!("PluginManager: initialization failed! {}", e),
}
plugin_manager.trigger_on_init().await;


// trigger `on_core_init` on all loaded plugins
for (plugin_id, factory) in app_state.plugins {
info!("Plugin '{}' found in AppState.", plugin_id);
Expand All @@ -133,14 +129,12 @@ pub async fn start_server() -> Result<()> {
plugin.on_core_init();
}


// TODO: add routes lazy (e.g. from plugin)
router = app_state
.router
.unwrap()
.route("/test", get(|| async { "Test from within plugin" }));


// start server with all routes
let addr: SocketAddr = SocketAddr::from(([0, 0, 0, 0], 7777));
tracing::debug!("listening on {}", addr);
Expand Down
7 changes: 5 additions & 2 deletions src/plugin/plugin_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,15 @@ impl<'a> PluginManager<'a> {
let plugin_name = configured_plugin.name.to_lowercase().to_owned();
base_name.push_str(&plugin_name);
let plugin_dir: PathBuf = self.path.clone().into_::<PathBuf>();

let plugin_path: PathBuf =
RawLibrary::path_in_directory(&plugin_dir, &base_name, LibrarySuffix::NoSuffix);

if plugin_path.exists() {
debug!("Plugin '{}' also found in the `plugins` directory", plugin_name);
debug!(
"Plugin '{}' also found in the `plugins` directory",
plugin_name
);

debug!("Try to load plugin '{}'...", plugin_name);
let header = lib_header_from_path(&plugin_path)?;
Expand Down

0 comments on commit 0756b14

Please sign in to comment.