Skip to content

Commit

Permalink
Refactor code for enhanced readability and flexibility
Browse files Browse the repository at this point in the history
  • Loading branch information
715209 committed Jun 9, 2024
1 parent fb0705b commit c14ae18
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 166 deletions.
4 changes: 2 additions & 2 deletions src/database/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::api::Status;
use rusqlite::{Connection, Result};
use std::path::PathBuf;
use std::path::Path;
use uuid::Uuid;

pub struct Source {
Expand All @@ -20,7 +20,7 @@ pub struct Build {
pub status: Status,
}

pub fn connect(path: PathBuf) -> Result<Connection> {
pub fn connect<P: AsRef<Path>>(path: P) -> Result<Connection> {
Connection::open(path)
}

Expand Down
5 changes: 3 additions & 2 deletions src/notary/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ use rsa::signature::RandomizedSigner;
use rsa::{RsaPrivateKey, RsaPublicKey};
use tokio::fs;

const BITS: usize = 2048;

pub fn generate_keys() -> Result<(), anyhow::Error> {
let mut rng = rand::thread_rng();

let bits = 2048;
let private_key_path = store::get_private_key_path();
let private_key = RsaPrivateKey::new(&mut rng, bits)?;
let private_key = RsaPrivateKey::new(&mut rng, BITS)?;
let private_key_der = private_key.to_pkcs8_der()?;
private_key_der.write_pem_file(&private_key_path, "PRIVATE KEY", LineEnding::LF)?;

Expand Down
7 changes: 3 additions & 4 deletions src/service/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn start(port: u16) -> Result<(), anyhow::Error> {
println!("Public key: {:?}", public_key_path);

let db_path = store::get_database_path();
let db = database::connect(db_path.clone())?;
let db = database::connect(&db_path)?;

db.execute(
"CREATE TABLE IF NOT EXISTS source (
Expand All @@ -52,9 +52,8 @@ pub async fn start(port: u16) -> Result<(), anyhow::Error> {

println!("Database path: {:?}", db_path.display());

match db.close() {
Ok(_) => (),
Err(e) => eprintln!("Failed to close database: {:?}", e),
if let Err(e) = db.close() {
eprintln!("Failed to close database: {:?}", e)
}

let addr = format!("[::1]:{}", port).parse()?;
Expand Down
91 changes: 36 additions & 55 deletions src/service/build/run_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,15 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons
}

let db_path = store::get_database_path();
let db = match database::connect(db_path) {
Ok(conn) => conn,
Err(e) => {
eprintln!("Failed to connect to database: {:?}", e);
return Err(Status::internal("Failed to connect to database"));
}
};
let db = database::connect(db_path).map_err(|e| {
eprintln!("Failed to connect to database: {:?}", e);
Status::internal("Failed to connect to database")
})?;

let source = match database::find_source_by_id(&db, message.source_id) {
Ok(source) => source,
Err(e) => {
eprintln!("Failed to find source: {:?}", e);
return Err(Status::internal("Failed to find source"));
}
};
let source = database::find_source_by_id(&db, message.source_id).map_err(|e| {
eprintln!("Failed to find source: {:?}", e);
Status::internal("Failed to find source")
})?;

let store_path = store::get_store_dir_path();
let store_output_path = store_path.join(format!("{}-{}", source.name, source.hash));
Expand Down Expand Up @@ -71,13 +65,10 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons
let source_temp_dir = TempDir::new()?;
let source_temp_dir_path = source_temp_dir.into_path().canonicalize()?;

match store::unpack_source(&source_temp_dir_path, &source_tar_path) {
Ok(_) => (),
Err(e) => {
eprintln!("Failed to unpack source: {:?}", e);
return Err(Status::internal("Failed to unpack source"));
}
};
store::unpack_source(&source_temp_dir_path, &source_tar_path).map_err(|e| {
eprintln!("Failed to unpack source: {:?}", e);
Status::internal("Failed to unpack source")
})?;

let source_temp_vorpal_dir = source_temp_dir_path.join(".vorpal");

Expand All @@ -98,15 +89,15 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons
.collect::<Vec<&str>>()
.join("\n");

let automation_script: Vec<String> = vec![
"#!/bin/bash".to_string(),
"set -e pipefail".to_string(),
"echo \"Starting build phase\"".to_string(),
build_phase_steps,
"echo \"Finished build phase\"".to_string(),
"echo \"Starting install phase\"".to_string(),
install_phase_steps,
"echo \"Finished install phase\"".to_string(),
let automation_script = [
"#!/bin/bash",
"set -e pipefail",
"echo \"Starting build phase\"",
&build_phase_steps,
"echo \"Finished build phase\"",
"echo \"Starting install phase\"",
&install_phase_steps,
"echo \"Finished install phase\"",
];

let automation_script_data = automation_script.join("\n");
Expand Down Expand Up @@ -139,9 +130,9 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons
context.insert("tmpdir", source_temp_dir_path.to_str().unwrap());
let sandbox_profile = tera.render("sandbox_default", &context).unwrap();

fs::write(&sandbox_profile_path, sandbox_profile.clone()).await?;
fs::write(&sandbox_profile_path, sandbox_profile).await?;

let sandbox_command_args = vec![
let sandbox_command_args = [
"-f",
sandbox_profile_path.to_str().unwrap(),
automation_script_path.to_str().unwrap(),
Expand Down Expand Up @@ -172,13 +163,10 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons

if sandbox_output_path.is_dir() {
for entry in WalkDir::new(&sandbox_output_path) {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
eprintln!("Failed to walk sandbox output: {:?}", e);
return Err(Status::internal("Failed to walk sandbox output"));
}
};
let entry = entry.map_err(|e| {
eprintln!("Failed to walk sandbox output: {:?}", e);
Status::internal("Failed to walk sandbox output")
})?;
let output_path = entry.path().strip_prefix(&sandbox_output_path).unwrap();
let output_store_path = store_output_path.join(output_path);
if entry.path().is_dir() {
Expand All @@ -188,35 +176,28 @@ pub async fn run(request: Request<BuildRequest>) -> Result<Response<BuildRespons
}
}

let store_output_files = match store::get_file_paths(&store_output_path, &Vec::new()) {
Ok(files) => files,
Err(_) => {
return Err(Status::internal("Failed to get sandbox output files"));
}
};
let store_output_files = store::get_file_paths(&store_output_path, &Vec::<&str>::new())
.map_err(|_| Status::internal("Failed to get sandbox output files"))?;

match store::compress_files(&store_output_path, &store_output_tar, &store_output_files) {
Ok(_) => (),
Err(_) => {
return Err(Status::internal("Failed to compress sandbox output"));
}
};
store::compress_files(&store_output_path, &store_output_tar, &store_output_files)
.map_err(|_| Status::internal("Failed to compress sandbox output"))?;
} else {
fs::copy(&sandbox_output_path, &store_output_path).await?;
}

fs::remove_dir_all(&source_temp_dir_path).await?;

let package_data_path = if store_output_tar.exists() {
store_output_tar.clone()
let is_compressed = store_output_tar.exists();
let package_data_path = if is_compressed {
store_output_tar
} else {
store_output_path.clone()
store_output_path
};

println!("Build output: {}", package_data_path.display());

let response = BuildResponse {
is_compressed: store_output_tar.exists(),
is_compressed,
package_data: fs::read(&package_data_path).await?,
};

Expand Down
93 changes: 38 additions & 55 deletions src/service/build/run_prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,53 +75,41 @@ pub async fn run(

if !source_tar_path.exists() {
let mut source_tar = File::create(&source_tar_path)?;
match source_tar.write_all(&source_data) {
Ok(_) => {
let metadata = fs::metadata(&source_tar_path).await?;
let mut permissions = metadata.permissions();
permissions.set_mode(0o444);
fs::set_permissions(source_tar_path.clone(), permissions).await?;
let file_name = source_tar_path.file_name().unwrap();
println!("Source tar: {}", file_name.to_string_lossy());
}
Err(e) => eprintln!("Failed source file: {}", e),
if let Err(e) = source_tar.write_all(&source_data) {
eprintln!("Failed source file: {}", e)
} else {
let metadata = fs::metadata(&source_tar_path).await?;
let mut permissions = metadata.permissions();
permissions.set_mode(0o444);
fs::set_permissions(&source_tar_path, permissions).await?;
let file_name = source_tar_path.file_name().unwrap();
println!("Source tar: {}", file_name.to_string_lossy());
}

fs::create_dir_all(&source_dir_path).await?;

match store::unpack_source(&source_dir_path, &source_tar_path) {
Ok(_) => (),
Err(e) => {
eprintln!("Failed to unpack source: {:?}", e);
return Err(Status::internal("Failed to unpack source"));
}
};

let source_files = match store::get_file_paths(&source_dir_path, &[]) {
Ok(files) => files,
Err(e) => {
store::unpack_source(&source_dir_path, &source_tar_path).map_err(|e| {
eprintln!("Failed to unpack source: {:?}", e);
Status::internal("Failed to unpack source")
})?;

let source_files =
store::get_file_paths(&source_dir_path, &Vec::<&str>::new()).map_err(|e| {
eprintln!("Failed to get source files: {}", e);
return Err(Status::internal("Failed to get source files"));
}
};
Status::internal("Failed to get source files")
})?;

println!("Source files: {:?}", source_files);

let source_files_hashes = match store::get_file_hashes(&source_files) {
Ok(hashes) => hashes,
Err(e) => {
eprintln!("Failed to get source files hashes: {}", e);
return Err(Status::internal("Failed to get source files hashes"));
}
};

let source_hash_computed = match store::get_source_hash(&source_files_hashes) {
Ok(hash) => hash,
Err(e) => {
eprintln!("Failed to get source hash: {}", e);
return Err(Status::internal("Failed to get source hash"));
}
};
let source_files_hashes = store::get_file_hashes(&source_files).map_err(|e| {
eprintln!("Failed to get source files hashes: {}", e);
Status::internal("Failed to get source files hashes")
})?;

let source_hash_computed = store::get_source_hash(&source_files_hashes).map_err(|e| {
eprintln!("Failed to get source hash: {}", e);
Status::internal("Failed to get source hash")
})?;

println!("Message source hash: {}", source_hash);
println!("Computed source hash: {}", source_hash_computed);
Expand All @@ -131,28 +119,23 @@ pub async fn run(
return Err(Status::internal("Source hash mismatch"));
}

match database::insert_source(&db, &source_hash, &source_name) {
Ok(_) => (),
Err(e) => {
eprintln!("Failed to insert source: {:?}", e);
return Err(Status::internal("Failed to insert source"));
}
}
database::insert_source(&db, &source_hash, &source_name).map_err(|e| {
eprintln!("Failed to insert source: {:?}", e);
Status::internal("Failed to insert source")
})?;

fs::remove_dir_all(source_dir_path).await?;
}

let source_id = match database::find_source(&db, &source_hash, &source_name) {
Ok(source) => source.id,
Err(e) => {
let source_id = database::find_source(&db, &source_hash, &source_name)
.map(|source| source.id)
.map_err(|e| {
eprintln!("Failed to find source: {:?}", e);
return Err(Status::internal("Failed to find source"));
}
};
Status::internal("Failed to find source")
})?;

match db.close() {
Ok(_) => (),
Err(e) => eprintln!("Failed to close database: {:?}", e),
if let Err(e) = db.close() {
eprintln!("Failed to close database: {:?}", e)
}

let response = PrepareResponse { source_id };
Expand Down
Loading

0 comments on commit c14ae18

Please sign in to comment.