Skip to content

Commit

Permalink
add a new visitor instead of using unpack function
Browse files Browse the repository at this point in the history
  • Loading branch information
rawdaGastan committed Sep 16, 2024
1 parent edac067 commit 5311d2d
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 84 deletions.
12 changes: 6 additions & 6 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,17 @@ 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,
}))
}

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

pub fn encode_jwt(
Expand Down Expand Up @@ -138,7 +138,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 +147,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)
}
97 changes: 19 additions & 78 deletions fl-server/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ use std::{
fs,
sync::{mpsc, Arc},
};
use tokio::io;
use walkdir::WalkDir;

use bollard::auth::DockerCredentials;
use serde::{Deserialize, Serialize};
Expand All @@ -25,10 +23,7 @@ use crate::{
response::{FileInfo, ResponseError, ResponseResult},
serve_flists::visit_dir_one_level,
};
use rfs::{
cache,
fungi::{Reader, Writer},
};
use rfs::fungi::{Reader, Writer};
use utoipa::{OpenApi, ToSchema};
use uuid::Uuid;

Expand Down Expand Up @@ -126,16 +121,8 @@ pub async fn create_flist_handler(
let fl_name = docker_image.replace([':', '/'], "-") + ".fl";
let username_dir = format!("{}/{}", cfg.flist_dir, username);

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 std::path::Path::new(std::path::Path::new(&username_dir).join(&fl_name).as_path()).exists() {
return Err(ResponseError::Conflict("flist already exists".to_string()));
}

let created = fs::create_dir_all(&username_dir);
Expand Down Expand Up @@ -397,7 +384,7 @@ pub async fn preview_flist_handler(
Err(err) => return Err(ResponseError::BadRequest(err.to_string())),
};

let content = match unpack_flist(&fl_path).await {
let content = match get_flist_content(&fl_path).await {
Ok(paths) => paths,
Err(_) => return Err(ResponseError::InternalServerError),
};
Expand All @@ -421,20 +408,6 @@ pub async fn preview_flist_handler(
}))
}

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)
}

async fn validate_flist_path(
users: Vec<User>,
flist_dir: &String,
Expand Down Expand Up @@ -466,7 +439,7 @@ async fn validate_flist_path(
}

// validate username
match get_user_by_username(users, parts[1]) {
match get_user_by_username(&users, parts[1]) {
Some(_) => (),
None => {
return Err(anyhow::anyhow!(
Expand Down Expand Up @@ -494,22 +467,18 @@ async fn validate_flist_path(

// validate flist existence
let username_dir = format!("{}/{}", parts[0], parts[1]);
match flist_exists(std::path::Path::new(&username_dir), &fl_name).await {
Ok(exists) => {
if !exists {
return Err(anyhow::anyhow!("flist '{}' doesn't exist", fl_path));
}
}
Err(e) => {
log::error!("failed to check flist existence with error {:?}", e);
return Err(anyhow::anyhow!("Internal server error"));
}
if !std::path::Path::new(std::path::Path::new(&username_dir).join(&fl_name).as_path()).exists()
{
return Err(anyhow::anyhow!("flist '{}' doesn't exist", fl_path));
}

Ok(())
}

async fn unpack_flist(fl_path: &String) -> Result<Vec<std::string::String>, Error> {
async fn get_flist_content(fl_path: &String) -> Result<Vec<std::string::String>, Error> {
let mut content = Vec::new();
let mut visitor = rfs::fungi::meta::ReadVisitor::new(&mut content);

let meta = match Reader::new(&fl_path).await {
Ok(reader) => reader,
Err(err) => {
Expand All @@ -522,43 +491,15 @@ async fn unpack_flist(fl_path: &String) -> Result<Vec<std::string::String>, Erro
}
};

let router = match rfs::store::get_router(&meta).await {
Ok(r) => r,
match meta.walk(&mut visitor).await {
Ok(()) => return Ok(visitor.content.to_vec()),
Err(err) => {
log::error!("failed to get router with error {}", err);
return Err(anyhow::anyhow!("Internal server error"));
}
};

let cache = cache::Cache::new(String::from("/tmp/cache"), router);
let tmp_target = match tempdir::TempDir::new("target") {
Ok(dir) => dir,
Err(err) => {
log::error!("failed to create tmp dir with error {}", err);
return Err(anyhow::anyhow!("Internal server error"));
}
};
let tmp_target_path = tmp_target.path().to_owned();

match rfs::unpack(&meta, &cache, &tmp_target_path, false).await {
Ok(_) => (),
Err(err) => {
log::error!("failed to unpack flist {} with error {}", fl_path, err);
log::error!(
"failed to walk through metadata for flist `{}` with error {}",
fl_path,
err
);
return Err(anyhow::anyhow!("Internal server error"));
}
};

let mut paths = Vec::new();
for file in WalkDir::new(tmp_target_path.clone())
.into_iter()
.filter_map(|file| file.ok())
{
let path = file.path().to_string_lossy().to_string();
match path.strip_prefix(&tmp_target_path.to_string_lossy().to_string()) {
Some(p) => paths.push(p.to_string()),
None => return Err(anyhow::anyhow!("Internal server error")),
};
}

Ok(paths)
}
30 changes: 30 additions & 0 deletions rfs/src/fungi/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,36 @@ impl Writer {
}
}

pub struct ReadVisitor<'a>
{

Check warning on line 422 in rfs/src/fungi/meta.rs

View workflow job for this annotation

GitHub Actions / check_fmt

Suggested formatting at lines 421-422 (replaced with 1 line)

pub struct ReadVisitor<'a> {
pub content: &'a mut Vec<String>,
}

impl<'a> ReadVisitor<'a>
{

Check warning on line 427 in rfs/src/fungi/meta.rs

View workflow job for this annotation

GitHub Actions / check_fmt

Suggested formatting at lines 426-427 (replaced with 1 line)

impl<'a> ReadVisitor<'a> {
pub fn new(content: &'a mut Vec<String>) -> Self {
Self {
content
}

Check warning on line 431 in rfs/src/fungi/meta.rs

View workflow job for this annotation

GitHub Actions / check_fmt

Suggested formatting at lines 429-431 (replaced with 1 line)

Self { content }
}
}

#[async_trait::async_trait]
impl<'a> WalkVisitor for ReadVisitor<'a>
{

Check warning on line 437 in rfs/src/fungi/meta.rs

View workflow job for this annotation

GitHub Actions / check_fmt

Suggested formatting at lines 436-437 (replaced with 1 line)

impl<'a> WalkVisitor for ReadVisitor<'a> {
async fn visit(&mut self, path: &Path, node: &Inode) -> Result<Walk> {
if node.mode.file_type() == FileType::Dir ||
node.mode.file_type() == FileType::Regular ||
node.mode.file_type() == FileType::Link {

Check warning on line 441 in rfs/src/fungi/meta.rs

View workflow job for this annotation

GitHub Actions / check_fmt

Suggested formatting at lines 439-441 (replaced with 4 lines)

if node.mode.file_type() == FileType::Dir || node.mode.file_type() == FileType::Regular || node.mode.file_type() == FileType::Link {
self.content.push(path.to_string_lossy().to_string());
} else {
warn!("unknown file kind: {:?}", node.mode.file_type());
}

Ok(Walk::Continue)
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down

0 comments on commit 5311d2d

Please sign in to comment.