Skip to content

Commit

Permalink
Visualization: added configuration page
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelWats0n committed Jul 15, 2022
1 parent ad24a9c commit 962d906
Show file tree
Hide file tree
Showing 25 changed files with 281 additions and 59 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ target
*credentials*
.DS_Store
.idea

*.log
*.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE settings;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE settings
(
code text NOT NULL
CONSTRAINT settings_pk PRIMARY KEY,
content text
);
8 changes: 8 additions & 0 deletions visualization/api/policy/policy.csv
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ p,user,/api/account/login,POST
p,user,/api/account/clientdomain,GET
p,user,/api/account/clienttype,GET
p,user,/api/liquidity/supported-exchanges,GET

p,admin,/api/account/login,POST
p,admin,/api/account/clientdomain,GET
p,admin,/api/account/clienttype,GET
p,admin,/api/configuration,GET
p,admin,/api/configuration,PUT
p,admin,/api/configuration/validate,POST
p,admin,/api/liquidity/supported-exchanges,GET
2 changes: 1 addition & 1 deletion visualization/api/src/handlers/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn login(
let error = json!({"error": "Incorrect username or password"});
return Ok(HttpResponse::Ok().json(error));
}
let role = "user";
let role = "admin";
success_login_response(&token_service, &payload.username, role)
}

Expand Down
81 changes: 81 additions & 0 deletions visualization/api/src/handlers/configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use crate::services::settings::{SettingCodes, SettingsService};
use actix_web::web::Data;
use actix_web::{get, post, put, web, Error, HttpResponse};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use toml::Value;

#[derive(Deserialize)]
pub struct ConfigPayload {
config: String,
}

#[derive(Serialize)]
pub struct GetConfigResponse {
config: Option<String>,
}

#[get("")]
pub async fn get(settings_service: Data<Arc<SettingsService>>) -> Result<HttpResponse, Error> {
let configuration = settings_service
.get_settings(SettingCodes::Configuration)
.await;
match configuration {
Ok(configuration) => Ok(HttpResponse::Ok().json(GetConfigResponse {
config: configuration.content,
})),
Err(e) => match e {
sqlx::Error::RowNotFound => {
Ok(HttpResponse::Ok().json(GetConfigResponse { config: None }))
}
_ => {
log::error!("Get config error: {:?}", e);
Ok(HttpResponse::InternalServerError().finish())
}
},
}
}

#[put("")]
pub async fn save(
payload: web::Json<ConfigPayload>,
settings_service: Data<Arc<SettingsService>>,
) -> Result<HttpResponse, Error> {
if toml::from_str::<Value>(&payload.config).is_err() {
return Ok(HttpResponse::BadRequest().finish());
}
match settings_service
.save_setting(SettingCodes::Configuration, &payload.config)
.await
{
Ok(()) => Ok(HttpResponse::Ok().finish()),
Err(e) => {
log::error!("Save config error: {:?}. Config {}", e, &payload.config);
Ok(HttpResponse::InternalServerError().finish())
}
}
}

#[derive(Serialize)]
pub struct ValidateResponse {
valid: bool,
error: Option<String>,
}

#[post("/validate")]
pub async fn validate(
payload: web::Json<ConfigPayload>,
) -> Result<web::Json<ValidateResponse>, Error> {
let response = match toml::from_str::<Value>(&payload.config) {
Ok(_) => ValidateResponse {
valid: true,
error: None,
},
Err(e) => ValidateResponse {
valid: false,
error: Some(e.to_string()),
},
};

Ok(web::Json(response))
}
1 change: 1 addition & 0 deletions visualization/api/src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod account;
pub mod configuration;
pub mod liquidity;
pub mod ws;
9 changes: 8 additions & 1 deletion visualization/api/src/routes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::handlers::account::{client_domain, client_type, login, refresh_token};
use crate::handlers::configuration::{get, save, validate};
use crate::handlers::liquidity::supported_exchanges;
use crate::ws_client;
use actix_web::web;
Expand All @@ -18,6 +19,12 @@ pub(crate) fn routes(app: &mut ServiceConfig) {
.service(client_domain)
.service(refresh_token),
)
.service(web::scope("/liquidity").service(supported_exchanges)),
.service(web::scope("/liquidity").service(supported_exchanges))
.service(
web::scope("/configuration")
.service(get)
.service(save)
.service(validate),
),
);
}
5 changes: 4 additions & 1 deletion visualization/api/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::routes::routes;
use crate::services::account::AccountService;
use crate::services::auth::AuthService;
use crate::services::market_settings::MarketSettingsService;
use crate::services::settings::SettingsService;
use crate::services::token::TokenService;
use crate::ws::actors::error_listener::ErrorListener;
use crate::ws::actors::new_data_listener::NewDataListener;
Expand Down Expand Up @@ -44,7 +45,7 @@ pub async fn start(
.await
.expect("Unable to connect to DB");

let liquidity_service = LiquidityService::new(connection_pool);
let liquidity_service = LiquidityService::new(connection_pool.clone());
let new_data_listener = NewDataListener::default().start();
let error_listener = ErrorListener::default().start();
let account_service = AccountService::default();
Expand All @@ -57,6 +58,7 @@ pub async fn start(
let subscription_manager = SubscriptionManager::default().start();
let auth_service = Arc::new(AuthService::new(enforcer));
let market_settings_service = Arc::new(MarketSettingsService::from(markets));
let settings_service = Arc::new(SettingsService::new(connection_pool));

spawn(data_provider(
subscription_manager,
Expand All @@ -79,6 +81,7 @@ pub async fn start(
.app_data(Data::new(auth_service.clone()))
.app_data(Data::new(token_service.clone()))
.app_data(Data::new(market_settings_service.clone()))
.app_data(Data::new(settings_service.clone()))
})
.workers(2)
.bind(address)?
Expand Down
1 change: 1 addition & 0 deletions visualization/api/src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ pub mod account;
pub mod auth;
pub mod liquidity;
pub mod market_settings;
pub mod settings;
pub mod token;
38 changes: 38 additions & 0 deletions visualization/api/src/services/settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};

#[derive(Clone)]
pub struct SettingsService {
pool: Pool<Postgres>,
}

#[derive(Debug)]
pub enum SettingCodes {
Configuration,
}

#[derive(sqlx::FromRow, Serialize, Deserialize, Clone)]
pub struct Setting {
pub content: Option<String>,
}

impl SettingsService {
pub fn new(pool: Pool<Postgres>) -> Self {
Self { pool }
}
pub async fn get_settings(&self, code: SettingCodes) -> Result<Setting, sqlx::Error> {
sqlx::query_as::<Postgres, Setting>(include_str!("sql/get_settings_by_code.sql"))
.bind(format!("{:?}", code))
.fetch_one(&self.pool)
.await
}

pub async fn save_setting(&self, code: SettingCodes, content: &str) -> Result<(), sqlx::Error> {
sqlx::query(include_str!("sql/merge_settings.sql"))
.bind(format!("{:?}", code))
.bind(content)
.execute(&self.pool)
.await?;
Ok(())
}
}
3 changes: 3 additions & 0 deletions visualization/api/src/services/sql/get_settings_by_code.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SELECT content
FROM settings
WHERE code = $1
3 changes: 3 additions & 0 deletions visualization/api/src/services/sql/merge_settings.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
INSERT INTO settings(code, content)
VALUES ($1, $2)
ON CONFLICT (code) DO UPDATE SET content = $2
8 changes: 8 additions & 0 deletions visualization/web/public/css/crypto-lp-dashboard.webflow.css
Original file line number Diff line number Diff line change
Expand Up @@ -1788,4 +1788,12 @@ h5 {
src: url('../fonts/fa-regular-400.woff2') format('woff2'), url('../fonts/fa-brands-400.woff2') format('woff2'), url('../fonts/fa-regular-400.eot') format('embedded-opentype'), url('../fonts/fa-brands-400.eot') format('embedded-opentype'), url('../fonts/fa-regular-400.woff') format('woff'), url('../fonts/fa-brands-400.woff') format('woff'), url('../fonts/fa-regular-400.ttf') format('truetype'), url('../fonts/fa-brands-400.ttf') format('truetype'), url('../fonts/fa-brands-400.svg') format('svg'), url('../fonts/fa-regular-400.svg') format('svg');
font-weight: 400;
font-style: normal;
}

.row-index {
position: absolute;
top: 10px;
right: 10px;
background: silver;
padding: 5px;
}
20 changes: 10 additions & 10 deletions visualization/web/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,19 @@ class App extends Component {
const isIco = CryptolpAxios.clientType === constants.clientType.ico;
const isSignals = CryptolpAxios.clientType === constants.clientType.signals;

const isUser =
CryptolpAxios.role &&
CryptolpAxios.role.toUpperCase() === constants.clientRoles.user;
const isAdmin =
CryptolpAxios.role &&
CryptolpAxios.role.toUpperCase() === constants.clientRoles.admin;
const isSuperAdmin =
CryptolpAxios.role &&
CryptolpAxios.role.toUpperCase() === constants.clientRoles.superAdmin;

let routes = null;
let headers = null;
if (this.state.isAuthorized) {
routes = (
<Switch>
{isAdmin && (
{isUser && (
<Route
exact
path="/users"
Expand All @@ -91,7 +91,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/configuration"
Expand All @@ -105,7 +105,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/postponed-fills"
Expand All @@ -119,7 +119,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/explanation/:exchangeName?/:urlCurrencyCodePair?"
Expand All @@ -136,7 +136,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/plgraph/:exchangeName?/:urlCurrencyCodePair?"
Expand Down Expand Up @@ -321,7 +321,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/explanation/:exchangeName?/:urlCurrencyCodePair?"
Expand All @@ -340,7 +340,7 @@ class App extends Component {
/>
)}

{isSuperAdmin && (
{isAdmin && (
<Route
exact
path="/plgraph/:exchangeName?/:urlCurrencyCodePair?"
Expand Down
6 changes: 6 additions & 0 deletions visualization/web/src/Style.css
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,9 @@ a:hover {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
background: rgba(0, 0, 0, 0.2);
}


/* !TODO Temporary while few items at nav*/
.nav-link:first-child {
margin-right: 0 !important;
}
Loading

0 comments on commit 962d906

Please sign in to comment.