Skip to content

Commit

Permalink
Merge branch 'development_fl_server' of github.com:threefoldtech/rfs …
Browse files Browse the repository at this point in the history
…into development_support_conversion_progress
  • Loading branch information
rawdaGastan committed Sep 17, 2024
2 parents 5051d73 + 5a2deda commit 2523b5c
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 51 deletions.
13 changes: 6 additions & 7 deletions fl-server/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub async fn sign_in_handler(
Extension(cfg): Extension<config::Config>,
Json(user_data): Json<SignInBody>,
) -> impl IntoResponse {
let user = match get_user_by_username(cfg.users, &user_data.username) {
let user = match get_user_by_username(&cfg.users, &user_data.username) {
Some(user) => user,
None => {
return Err(ResponseError::Unauthorized(
Expand All @@ -70,17 +70,16 @@ pub async fn sign_in_handler(
));
}

let token = encode_jwt(user.username, cfg.jwt_secret, cfg.jwt_expire_hours)
let token = encode_jwt(user.username.clone(), cfg.jwt_secret, cfg.jwt_expire_hours)
.map_err(|_| ResponseError::InternalServerError)?;

Ok(ResponseResult::SignedIn(SignInResponse {
access_token: token,
}))
}

fn get_user_by_username(users: Vec<User>, username: &str) -> Option<User> {
let user = users.iter().find(|u| u.username == username)?;
Some(user.clone())
pub fn get_user_by_username<'a>(users: &'a [User], username: &str) -> Option<&'a User> {
users.iter().find(|u| u.username == username)
}

pub fn encode_jwt(
Expand Down Expand Up @@ -138,7 +137,7 @@ pub async fn authorize(
}
};

let current_user = match get_user_by_username(cfg.users, &token_data.claims.username) {
let current_user = match get_user_by_username(&cfg.users, &token_data.claims.username) {
Some(user) => user,
None => {
return Err(ResponseError::Unauthorized(
Expand All @@ -147,6 +146,6 @@ pub async fn authorize(
}
};

req.extensions_mut().insert(current_user.username);
req.extensions_mut().insert(current_user.username.clone());
Ok(next.run(req).await)
}
4 changes: 2 additions & 2 deletions fl-server/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs, sync::Mutex};
use std::{collections::HashMap, fs, path::PathBuf, sync::Mutex};
use utoipa::ToSchema;

use crate::{auth, handlers};
Expand All @@ -13,7 +13,7 @@ pub struct Job {
#[derive(Debug, ToSchema)]
pub struct AppState {
pub jobs_state: Mutex<HashMap<String, handlers::FlistState>>,
pub flists_progress: Mutex<HashMap<String, f32>>,
pub flists_progress: Mutex<HashMap<PathBuf, f32>>,
}

#[derive(Debug, Default, Clone, Deserialize)]
Expand Down
43 changes: 9 additions & 34 deletions fl-server/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use std::{
fs,
sync::{mpsc, Arc},
};
use tokio::io;

use bollard::auth::DockerCredentials;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -109,37 +108,28 @@ pub async fn create_flist_handler(
}

let fl_name = docker_image.replace([':', '/'], "-") + ".fl";
let username_dir = format!("{}/{}", cfg.flist_dir, username);
let username_dir = std::path::Path::new(&cfg.flist_dir).join(&username);
let fl_path = username_dir.join(&fl_name);

match flist_exists(std::path::Path::new(&username_dir), &fl_name).await {
Ok(exists) => {
if exists {
return Err(ResponseError::Conflict("flist already exists".to_string()));
}
}
Err(e) => {
log::error!("failed to check flist existence with error {:?}", e);
return Err(ResponseError::InternalServerError);
}
if fl_path.exists() {
return Err(ResponseError::Conflict("flist already exists".to_string()));
}

let created = fs::create_dir_all(&username_dir);
if created.is_err() {
log::error!(
"failed to create user flist directory `{}` with error {:?}",
"failed to create user flist directory `{:?}` with error {:?}",
&username_dir,
created.err()
);
return Err(ResponseError::InternalServerError);
}

let fl_path: String = format!("{}/{}", username_dir, fl_name);

let meta = match Writer::new(&fl_path).await {
Ok(writer) => writer,
Err(err) => {
log::error!(
"failed to create a new writer for flist `{}` with error {}",
"failed to create a new writer for flist `{:?}` with error {}",
fl_path,
err
);
Expand Down Expand Up @@ -242,7 +232,7 @@ pub async fn create_flist_handler(
state.jobs_state.lock().unwrap().insert(
job.id.clone(),
FlistState::Created(format!(
"flist {}:{}/{} is created successfully",
"flist {}:{}/{:?} is created successfully",
cfg.host, cfg.port, fl_path
)),
);
Expand Down Expand Up @@ -330,13 +320,12 @@ pub async fn list_flists_handler(
) -> impl IntoResponse {
let mut flists: HashMap<String, Vec<FileInfo>> = HashMap::new();

let rs = visit_dir_one_level(std::path::Path::new(&cfg.flist_dir), &state).await;
let rs = visit_dir_one_level(&cfg.flist_dir, &state).await;
match rs {
Ok(files) => {
for file in files {
if !file.is_file {
let flists_per_username =
visit_dir_one_level(std::path::Path::new(&file.path_uri), &state).await;
let flists_per_username = visit_dir_one_level(&file.path_uri, &state).await;
match flists_per_username {
Ok(files) => flists.insert(file.name, files),
Err(e) => {
Expand All @@ -355,17 +344,3 @@ pub async fn list_flists_handler(

Ok(ResponseResult::Flists(flists))
}

pub async fn flist_exists(dir_path: &std::path::Path, flist_name: &String) -> io::Result<bool> {
let mut dir = tokio::fs::read_dir(dir_path).await?;

while let Some(child) = dir.next_entry().await? {
let file_name = child.file_name().to_string_lossy().to_string();

if file_name.eq(flist_name) {
return Ok(true);
}
}

Ok(false)
}
18 changes: 10 additions & 8 deletions fl-server/src/serve_flists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,11 @@ pub async fn serve_flists(
};
}

pub async fn visit_dir_one_level(
path: &std::path::Path,
pub async fn visit_dir_one_level<P: AsRef<std::path::Path>>(
path: P,
state: &Arc<config::AppState>,
) -> io::Result<Vec<FileInfo>> {
let path = path.as_ref();
let mut dir = tokio::fs::read_dir(path).await?;
let mut files: Vec<FileInfo> = Vec::new();

Expand All @@ -99,12 +100,13 @@ pub async fn visit_dir_one_level(

let mut progress = 0.0;
if is_file {
match state.flists_progress.lock().unwrap().get(&format!(
"{}/{}",
path.to_string_lossy().to_string(),
name
)) {
Some(p) => progress = p.to_owned(),
match state
.flists_progress
.lock()
.unwrap()
.get(&path.join(&name).to_path_buf())
{
Some(p) => progress = *p,
None => progress = 100.0,
}

Expand Down

0 comments on commit 2523b5c

Please sign in to comment.