use cloud_terrastodon_azure_types::AzureLocationName;
use cloud_terrastodon_azure_types::ComputeSkuName;
use cloud_terrastodon_azure_types::Price;
use cloud_terrastodon_command::CacheKey;
use cloud_terrastodon_command::CacheableCommand;
use cloud_terrastodon_command::CommandBuilder;
use cloud_terrastodon_command::CommandKind;
use cloud_terrastodon_command::async_trait;
use compact_str::CompactString;
use std::path::PathBuf;
pub struct ComputeSkuPricesRequest {
pub location: AzureLocationName,
pub sku: ComputeSkuName,
}
pub fn fetch_compute_sku_prices(
location: AzureLocationName,
sku: ComputeSkuName,
) -> ComputeSkuPricesRequest {
ComputeSkuPricesRequest { location, sku }
}
#[async_trait]
impl CacheableCommand for ComputeSkuPricesRequest {
type Output = Vec<Price>;
fn cache_key(&self) -> CacheKey {
CacheKey::new(PathBuf::from_iter([
"az",
"vm",
"list-sku-pricings",
self.location.to_string().as_ref(),
self.sku.as_ref(),
]))
}
async fn run(self) -> eyre::Result<Self::Output> {
let url = format!(
"https://prices.azure.com/api/retail/prices?{filter}&meterRegion='primary'¤cyCode='CAD'",
filter = format_args!(
"$filter=serviceName eq '{service_name}' and tolower(armRegionName) eq tolower('{location}') and armSkuName eq '{sku}'",
service_name = "Virtual Machines",
location = self.location,
sku = self.sku
)
);
let mut cmd = CommandBuilder::new(CommandKind::AzureCLI);
cmd.args(["rest", "--method", "GET", "--url"]);
cmd.azure_file_arg("url.txt", url);
cmd.cache(self.cache_key());
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct Response {
billing_currency: CompactString,
count: usize,
customer_entity_id: CompactString,
customer_entity_type: CompactString,
items: Vec<Price>,
next_page_link: Option<String>,
}
let rtn = cmd.run::<Response>().await?.items;
Ok(rtn)
}
}
cloud_terrastodon_command::impl_cacheable_into_future!(ComputeSkuPricesRequest);
#[cfg(test)]
mod test {
use crate::fetch_compute_sku_prices;
use cloud_terrastodon_azure_types::AzureLocationName;
use cloud_terrastodon_azure_types::ComputeSkuName;
#[tokio::test]
pub async fn it_works() -> eyre::Result<()> {
let sku = ComputeSkuName::try_new("Standard_D2s_v5")?;
let location = AzureLocationName::CanadaCentral;
let prices = fetch_compute_sku_prices(location, sku).await?;
assert!(!prices.is_empty()); assert!(prices.iter().any(|price| price.unit_price > 0.0));
Ok(())
}
}