1use serde::{Deserialize, Serialize};
2use tokio_util::sync::CancellationToken;
3
4use crate::{ErpcError, Result, rest::RestTransport};
5
6#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
8#[serde(rename_all = "camelCase")]
9pub struct MonthlyApiKeyMethodUsage {
10 pub count: f64,
12 pub credit_cost: f64,
14 pub credits: f64,
16 pub method: String,
18 pub updated_at: Option<String>,
20}
21
22#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct MonthlyApiKeyChainUsage {
26 pub chain: String,
28 pub count: f64,
30 pub credits: f64,
32 pub methods: Vec<MonthlyApiKeyMethodUsage>,
34 pub updated_at: Option<String>,
36}
37
38#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
40#[serde(rename_all = "camelCase")]
41pub struct MonthlyApiKeyUsageEntry {
42 pub api_key_last4: String,
44 pub api_key_length: f64,
46 pub chains: Vec<MonthlyApiKeyChainUsage>,
48 pub count: f64,
50 pub credits: f64,
52 pub key_id: Option<f64>,
54 pub updated_at: Option<String>,
56}
57
58#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
60#[serde(rename_all = "camelCase")]
61pub struct MonthlyApiKeyUsage {
62 pub api_keys: Vec<MonthlyApiKeyUsageEntry>,
64 pub chains: Vec<MonthlyApiKeyChainUsage>,
66 pub has_stranded_usage: bool,
68 pub key_count: f64,
70 pub total_count: f64,
72 pub total_credits: f64,
74 pub updated_at: Option<String>,
76 pub year_month: String,
78}
79
80#[derive(Clone, Debug, Default, Eq, PartialEq)]
82pub struct MonthlyApiKeyUsageParams {
83 pub year_month: Option<String>,
85}
86
87#[derive(Clone)]
89pub struct UsageClient {
90 transport: RestTransport,
91}
92
93impl UsageClient {
94 pub(crate) const fn new(transport: RestTransport) -> Self {
95 Self { transport }
96 }
97
98 pub async fn get_monthly_api_key_usage(
100 &self,
101 params: MonthlyApiKeyUsageParams,
102 ) -> Result<MonthlyApiKeyUsage> {
103 self.get_monthly_api_key_usage_with(params, None).await
104 }
105
106 pub async fn get_monthly_api_key_usage_with(
108 &self,
109 params: MonthlyApiKeyUsageParams,
110 cancellation: Option<&CancellationToken>,
111 ) -> Result<MonthlyApiKeyUsage> {
112 if let Some(year_month) = ¶ms.year_month {
113 if !valid_year_month(year_month) {
114 return Err(ErpcError::Config(
115 "year_month must use YYYY-MM format".to_owned(),
116 ));
117 }
118 }
119 let query = params
120 .year_month
121 .map(|value| vec![("yearMonth".to_owned(), value)])
122 .unwrap_or_default();
123 let envelope: Envelope<MonthlyApiKeyUsage> = self
124 .transport
125 .get("/v3/user/api-keys/usage", query, cancellation)
126 .await?;
127 if !envelope.success || !valid_year_month(&envelope.message.year_month) {
128 return Err(ErpcError::InvalidResponse(
129 "ERPC returned an invalid monthly API key usage response".to_owned(),
130 ));
131 }
132 Ok(envelope.message)
133 }
134}
135
136#[derive(Deserialize)]
137struct Envelope<T> {
138 success: bool,
139 message: T,
140}
141
142fn valid_year_month(value: &str) -> bool {
143 let bytes = value.as_bytes();
144 bytes.len() == 7
145 && bytes[0..4].iter().all(u8::is_ascii_digit)
146 && bytes[4] == b'-'
147 && matches!(
148 &bytes[5..7],
149 b"01"
150 | b"02"
151 | b"03"
152 | b"04"
153 | b"05"
154 | b"06"
155 | b"07"
156 | b"08"
157 | b"09"
158 | b"10"
159 | b"11"
160 | b"12"
161 )
162}