Skip to content

Commit

Permalink
feat(apis/pricing): comment on github commit
Browse files Browse the repository at this point in the history
  • Loading branch information
suptejas committed Sep 30, 2023
1 parent 801885b commit 3c60440
Show file tree
Hide file tree
Showing 9 changed files with 327 additions and 36 deletions.
32 changes: 17 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions services/cost-bot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,9 @@ math = { path = "../../math" }
types = { path = "../../types" }
git2 = "0.18.1"
walkdir = "2.4.0"
indexmap = "2.0.2"
sqlx = { version = "0.7.1", features = [
"postgres",
"runtime-tokio",
"tls-rustls",
] }
10 changes: 7 additions & 3 deletions services/cost-bot/src/cost.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::str::FromStr;

use indexmap::IndexMap;
use types::{
config::InfrastructureConfiguration, deployment_configuration::DeploymentConfiguration,
region::AwsRegion,
};

pub async fn calculate_cost(configuration: InfrastructureConfiguration) {
pub async fn calculate_cost(configuration: &InfrastructureConfiguration) -> IndexMap<String, f64> {
let result = math::calculate_deployment(DeploymentConfiguration {
regions: vec![AwsRegion::from_str(&configuration.app.region).unwrap()],
control_plane_specs: Some((1, 1.0)),
Expand All @@ -14,11 +15,14 @@ pub async fn calculate_cost(configuration: InfrastructureConfiguration) {
configuration.shape.as_ref().unwrap().vcpu,
configuration.shape.as_ref().unwrap().memory,
),
storage_size_gb: configuration.storage.unwrap().size,
storage_size_gb: configuration.storage.as_ref().unwrap().size,
node_count: 1.0,
outbound_data_gb: 0,
})
.await;

println!("Cost: ${:#?}", result);
return result
.get(&AwsRegion::from_str(&configuration.app.region).unwrap())
.unwrap()
.clone();
}
65 changes: 65 additions & 0 deletions services/cost-bot/src/db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::collections::HashMap;

use indexmap::IndexMap;

pub async fn create_pool(database_url: &str) -> PgPool {
PgPool::connect(database_url).await.unwrap()
}

use serde_json::Value;
use sqlx::{Error, PgPool, Row};

pub async fn store_breakdown(
pool: &PgPool,
repository_id: i64,
commit_ref: &str,
breakdowns: IndexMap<String, IndexMap<String, f64>>,
) -> Result<(), Error> {
// Convert the nested IndexMap to a nested HashMap
let breakdowns_hash_map: HashMap<_, _> = breakdowns
.into_iter()
.map(|(k, v)| (k, v.into_iter().collect::<HashMap<_, _>>()))
.collect();

// Serialize the HashMap to a JSON string
let breakdowns_json = serde_json::to_string(&breakdowns_hash_map).unwrap();

// Prepare and execute the SQL INSERT statement
sqlx::query(
"INSERT INTO cost_runs (repository_id, commit_ref, cost_breakdown) VALUES ($1, $2, $3)",
)
.bind(repository_id)
.bind(commit_ref)
.bind(breakdowns_json)
.execute(pool)
.await?;

// Return success
Ok(())
}

pub async fn fetch_previous_breakdown(
pool: &PgPool,
repository_id: i64,
commit_ref: &str,
) -> Result<Option<IndexMap<String, IndexMap<String, f64>>>, Error> {
let row = sqlx::query(
"SELECT cost_breakdown FROM cost_runs WHERE repository_id = $1 AND commit_ref = $2 LIMIT 1",
)
.bind(repository_id)
.bind(commit_ref)
.fetch_optional(pool)
.await?;

if let Some(row) = row {
let cost_breakdown: Value = row.get("cost_breakdown");

// Convert Value to your desired IndexMap type
let parsed: IndexMap<String, IndexMap<String, f64>> =
serde_json::from_value(cost_breakdown).unwrap();

Ok(Some(parsed))
} else {
Ok(None)
}
}
29 changes: 23 additions & 6 deletions services/cost-bot/src/git.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use std::path::{Path, PathBuf};

use git2::{build::RepoBuilder, FetchOptions, RemoteCallbacks};
use indexmap::IndexMap;
use walkdir::WalkDir;

pub fn clone(repository_name: String, _credentials: String, mut builder: RepoBuilder) {
Expand All @@ -26,8 +24,16 @@ pub fn clone(repository_name: String, _credentials: String, mut builder: RepoBui
.unwrap();
}

pub fn configuration_files(repository_name: String) -> HashMap<PathBuf, String> {
let mut files = HashMap::new();
pub fn delete(repository_name: String) {
std::fs::remove_dir_all(Path::new(&format!(
"./{}",
repository_name.split('/').last().unwrap()
)))
.unwrap();
}

pub fn configuration_files(repository_name: String) -> IndexMap<PathBuf, String> {
let mut files = IndexMap::new();

// Search for all infra.toml files recursively using the walkdir crate
let walker = WalkDir::new(Path::new(&format!(
Expand All @@ -44,5 +50,16 @@ pub fn configuration_files(repository_name: String) -> HashMap<PathBuf, String>
}
}

let mut file_vec: Vec<(PathBuf, String)> = files.into_iter().collect();

// Sort the vector based on the depth of the file tree
file_vec.sort_by(|a, b| {
let depth_a = a.0.components().count();
let depth_b = b.0.components().count();
depth_a.cmp(&depth_b)
});

files = file_vec.into_iter().collect();

files
}
Loading

0 comments on commit 3c60440

Please sign in to comment.