use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use crate::{ErpcError, Result, rest::RestTransport};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonthlyApiKeyMethodUsage {
pub count: f64,
pub credit_cost: f64,
pub credits: f64,
pub method: String,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonthlyApiKeyChainUsage {
pub chain: String,
pub count: f64,
pub credits: f64,
pub methods: Vec<MonthlyApiKeyMethodUsage>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonthlyApiKeyUsageEntry {
pub api_key_last4: String,
pub api_key_length: f64,
pub chains: Vec<MonthlyApiKeyChainUsage>,
pub count: f64,
pub credits: f64,
pub key_id: Option<f64>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonthlyApiKeyUsage {
pub api_keys: Vec<MonthlyApiKeyUsageEntry>,
pub chains: Vec<MonthlyApiKeyChainUsage>,
pub has_stranded_usage: bool,
pub key_count: f64,
pub total_count: f64,
pub total_credits: f64,
pub updated_at: Option<String>,
pub year_month: String,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MonthlyApiKeyUsageParams {
pub year_month: Option<String>,
}
#[derive(Clone)]
pub struct UsageClient {
transport: RestTransport,
}
impl UsageClient {
pub(crate) const fn new(transport: RestTransport) -> Self {
Self { transport }
}
pub async fn get_monthly_api_key_usage(
&self,
params: MonthlyApiKeyUsageParams,
) -> Result<MonthlyApiKeyUsage> {
self.get_monthly_api_key_usage_with(params, None).await
}
pub async fn get_monthly_api_key_usage_with(
&self,
params: MonthlyApiKeyUsageParams,
cancellation: Option<&CancellationToken>,
) -> Result<MonthlyApiKeyUsage> {
if let Some(year_month) = ¶ms.year_month {
if !valid_year_month(year_month) {
return Err(ErpcError::Config(
"year_month must use YYYY-MM format".to_owned(),
));
}
}
let query = params
.year_month
.map(|value| vec![("yearMonth".to_owned(), value)])
.unwrap_or_default();
let envelope: Envelope<MonthlyApiKeyUsage> = self
.transport
.get("/v3/user/api-keys/usage", query, cancellation)
.await?;
if !envelope.success || !valid_year_month(&envelope.message.year_month) {
return Err(ErpcError::InvalidResponse(
"ERPC returned an invalid monthly API key usage response".to_owned(),
));
}
Ok(envelope.message)
}
}
#[derive(Deserialize)]
struct Envelope<T> {
success: bool,
message: T,
}
fn valid_year_month(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 7
&& bytes[0..4].iter().all(u8::is_ascii_digit)
&& bytes[4] == b'-'
&& matches!(
&bytes[5..7],
b"01"
| b"02"
| b"03"
| b"04"
| b"05"
| b"06"
| b"07"
| b"08"
| b"09"
| b"10"
| b"11"
| b"12"
)
}