Skip to main content

acosmi/billing/
entitlements.rs

1//! Entitlements + V29 Per-Model Bucket 业务方法。端口自 `billing/entitlements.ts`
2//! (declaration-merging → 此处 `impl Client` 块)。
3
4use super::types::{
5    BalanceDetail, ConsumeRecordPage, EntitlementBalance, EntitlementItem, ModelBucket,
6    ModelByQuotaResponse, ModelCoefficient,
7};
8use crate::core::client::Client;
9use crate::core::http::COEF_CACHE_TTL_MS;
10use crate::shared::{Error, Result};
11use tokio_util::sync::CancellationToken;
12
13impl Client {
14    /// 查询当前用户的权益余额(聚合)。对应 TS `getBalance`。
15    pub async fn get_balance(
16        &self,
17        signal: Option<CancellationToken>,
18    ) -> Result<EntitlementBalance> {
19        self.billing_get("/entitlements/balance", signal).await
20    }
21
22    /// 查询详细余额(含每条权益明细)。对应 TS `getBalanceDetail`。
23    pub async fn get_balance_detail(
24        &self,
25        signal: Option<CancellationToken>,
26    ) -> Result<BalanceDetail> {
27        self.billing_get("/entitlements/balance-detail", signal)
28            .await
29    }
30
31    /// 查询当前用户权益列表;status:"ACTIVE" / "EXPIRED" / ""(全部)。对应 TS `listEntitlements`。
32    pub async fn list_entitlements(
33        &self,
34        status: &str,
35        signal: Option<CancellationToken>,
36    ) -> Result<Vec<EntitlementItem>> {
37        let path = if status.is_empty() {
38            "/entitlements".to_string()
39        } else {
40            format!("/entitlements?status={}", urlencoding(status))
41        };
42        self.billing_get(&path, signal).await
43    }
44
45    /// 查询核销记录(分页)。对应 TS `listConsumeRecords`。
46    pub async fn list_consume_records(
47        &self,
48        page: i64,
49        page_size: i64,
50        signal: Option<CancellationToken>,
51    ) -> Result<ConsumeRecordPage> {
52        let path = format!("/entitlements/consume-records?page={page}&pageSize={page_size}");
53        self.billing_get(&path, signal).await
54    }
55
56    /// 领取当月免费额度 —— 幂等:已领取时返回已有权益。对应 TS `claimMonthlyFree`。
57    pub async fn claim_monthly_free(
58        &self,
59        signal: Option<CancellationToken>,
60    ) -> Result<EntitlementItem> {
61        self.billing_post("/entitlements/claim-monthly", signal)
62            .await
63    }
64
65    /// 查询当前用户在指定模型下的剩余 token(raw + ETU)。对应 TS `getByModel`。
66    pub async fn get_by_model(
67        &self,
68        model_id: &str,
69        signal: Option<CancellationToken>,
70    ) -> Result<ModelByQuotaResponse> {
71        if model_id.is_empty() {
72            return Err(Error::other("modelID required"));
73        }
74        let path = format!("/entitlements/by-model?modelId={}", urlencoding(model_id));
75        self.billing_get(&path, signal).await
76    }
77
78    /// 列出当前用户的全部桶。对应 TS `listBuckets`。
79    pub async fn list_buckets(
80        &self,
81        signal: Option<CancellationToken>,
82    ) -> Result<Vec<ModelBucket>> {
83        self.billing_get("/entitlements/buckets", signal).await
84    }
85
86    /// 拉取模型系数表;SDK 自带 8s TTL 内存缓存以减小调用风暴。对应 TS `listCoefficients`。
87    ///
88    /// **@deprecated** 系数已退役,网关恒返回 `[]`。
89    pub async fn list_coefficients(
90        &self,
91        signal: Option<CancellationToken>,
92    ) -> Result<Vec<ModelCoefficient>> {
93        // 简单内存缓存 + TTL(8s)。
94        {
95            let cache = self.coef_cache().read().unwrap();
96            if let Some((data, t)) = cache.as_ref() {
97                if (t.elapsed().as_millis() as u64) < COEF_CACHE_TTL_MS {
98                    return Ok(data.clone()); // shallow copy 防外部篡改。
99                }
100            }
101        }
102        let data: Vec<ModelCoefficient> = self
103            .billing_get("/entitlements/coefficients", signal)
104            .await?;
105        *self.coef_cache().write().unwrap() = Some((data.clone(), std::time::Instant::now()));
106        Ok(data)
107    }
108
109    /// 手动失效系数缓存(admin 调价后建议立即调一次)。对应 TS `invalidateCoefficientCache`。
110    ///
111    /// **@deprecated** 系数已退役。
112    pub fn invalidate_coefficient_cache(&self) {
113        *self.coef_cache().write().unwrap() = None;
114    }
115}
116
117/// `encodeURIComponent` 等价:保留与 JS 一致的未编码集(字母数字 + `-_.!~*'()`)。
118pub(crate) fn urlencoding(s: &str) -> String {
119    let mut out = String::with_capacity(s.len());
120    for b in s.bytes() {
121        match b {
122            b'A'..=b'Z'
123            | b'a'..=b'z'
124            | b'0'..=b'9'
125            | b'-'
126            | b'_'
127            | b'.'
128            | b'!'
129            | b'~'
130            | b'*'
131            | b'\''
132            | b'('
133            | b')' => out.push(b as char),
134            _ => out.push_str(&format!("%{b:02X}")),
135        }
136    }
137    out
138}