1use std::collections::HashMap;
7
8use crate::abi::method;
9use crate::api::{
10 QuotaDescribeRequest, QuotaDescribeResponse, QuotaFetchRequest, QuotaFetchResponse, QuotaResetRequest,
11 QuotaResetResponse,
12};
13use crate::auth::AuthView;
14use crate::callbacks::RequestScope;
15use crate::gojson::{DecodeError, GoJson, Node};
16use crate::host::{Host, Record, Snapshot, normalize_provider};
17use crate::rpc::CallError;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct QuotaProviderInfo {
22 pub plugin_id: String,
23 pub provider: String,
24 pub display_name: String,
25 pub supported_providers: Vec<String>,
26 pub supports_reset: bool,
27}
28
29#[derive(Debug, Clone, Default, PartialEq)]
31struct FetchWire(QuotaFetchResponse);
32
33impl GoJson for FetchWire {
34 const GO_TYPE: &'static str = "pluginapi.QuotaFetchResponse";
35 fn encode(&self, out: &mut Vec<u8>) {
36 self.0.encode(out)
37 }
38 fn decode_value(v: &Node) -> Result<Self, DecodeError> {
39 crate::api::quota_fetch_from_value(v).map(FetchWire)
40 }
41 fn is_empty(&self) -> bool {
42 false
43 }
44}
45
46impl Host {
47 fn quota_records(&self) -> Vec<Record> {
49 self.quota_records_in(&self.snapshot())
50 .into_iter()
51 .filter(|r| !self.is_fused(&r.id))
52 .collect()
53 }
54
55 fn quota_records_in(&self, snapshot: &Snapshot) -> Vec<Record> {
56 self.current_records(snapshot)
57 .into_iter()
58 .filter(|r| r.plugin.caps.quota_provider)
59 .collect()
60 }
61
62 fn quota_identifier(record: &Record) -> String {
63 normalize_provider(&record.plugin.quota_identifier)
64 }
65
66 pub fn quota_provider_identifiers(&self) -> Vec<String> {
68 let mut out: Vec<String> = Vec::new();
69 for record in self.quota_records() {
70 let id = Self::quota_identifier(&record);
71 if !id.is_empty() && !out.contains(&id) {
72 out.push(id);
73 }
74 }
75 out
76 }
77
78 async fn describe_quota_record(&self, record: &Record) -> Result<Option<QuotaDescribeResponse>, CallError> {
80 if self.is_fused(&record.id) || !self.record_current(record) {
81 return Ok(None);
82 }
83 let req = QuotaDescribeRequest {
84 plugin: record.plugin.metadata.clone(),
85 };
86 self.call(record, method::QUOTA_DESCRIBE, &req).await.map(Some)
87 }
88
89 async fn supported_providers(&self, snapshot: &Snapshot, record: &Record) -> Vec<String> {
92 if let Some(cached) = crate::host::lock(&snapshot.quota_supported).get(&record.id) {
93 return cached.clone();
94 }
95 let Ok(Some(desc)) = self.describe_quota_record(record).await else {
96 return Vec::new();
97 };
98 crate::host::lock(&snapshot.quota_supported).insert(record.id.clone(), desc.supported_providers.clone());
99 desc.supported_providers
100 }
101
102 pub async fn quota_providers(&self) -> Vec<QuotaProviderInfo> {
104 let mut out = Vec::new();
105 for record in self.quota_records() {
106 if self.is_fused(&record.id) {
107 continue;
108 }
109 let mut identifier = Self::quota_identifier(&record);
110 if identifier.is_empty() {
111 identifier = normalize_provider(&record.id);
112 }
113 let desc = self
114 .describe_quota_record(&record)
115 .await
116 .ok()
117 .flatten()
118 .unwrap_or_default();
119 let supported = if desc.supported_providers.is_empty() && !identifier.is_empty() {
120 vec![identifier.clone()]
121 } else {
122 desc.supported_providers
123 };
124 let display_name = [
125 desc.display_name.as_str(),
126 record.plugin.metadata.name.as_str(),
127 identifier.as_str(),
128 ]
129 .into_iter()
130 .find(|s| !s.is_empty())
131 .unwrap_or_default()
132 .to_owned();
133 out.push(QuotaProviderInfo {
134 plugin_id: record.id.clone(),
135 provider: identifier,
136 display_name,
137 supported_providers: supported,
138 supports_reset: desc.supports_reset,
139 });
140 }
141 out
142 }
143
144 pub async fn quota_provider_plugin_ids(&self) -> HashMap<String, String> {
148 let snapshot = self.snapshot();
149 let mut candidates: HashMap<String, Vec<String>> = HashMap::new();
151 let mut add = |provider: String, id: &str| {
152 if !provider.is_empty() {
153 candidates.entry(provider).or_default().push(id.to_owned());
154 }
155 };
156 let mut records = Vec::new();
157 for record in self.quota_records_in(&snapshot) {
159 if self.is_fused(&record.id) {
160 continue;
161 }
162 add(Self::quota_identifier(&record), &record.id);
163 add(normalize_provider(&record.id), &record.id);
164 if record.plugin.caps.auth_provider {
165 add(normalize_provider(&record.plugin.auth_identifier), &record.id);
166 }
167 records.push(record);
168 }
169 for record in &records {
171 if self.is_fused(&record.id) {
172 continue;
173 }
174 for p in self.supported_providers(&snapshot, record).await {
175 add(normalize_provider(&p), &record.id);
176 }
177 }
178 candidates
179 .into_iter()
180 .filter_map(|(provider, ids)| Some((provider, ids.into_iter().find(|id| !self.is_fused(id))?)))
181 .collect()
182 }
183
184 pub async fn quota_provider_record(&self, provider: &str) -> Option<Record> {
186 let provider = normalize_provider(provider);
187 if provider.is_empty() {
188 return None;
189 }
190 let snapshot = self.snapshot();
191 let records = self.quota_records_in(&snapshot);
192 for record in &records {
193 if self.is_fused(&record.id) {
194 continue;
195 }
196 if Self::quota_identifier(record) == provider
197 || normalize_provider(&record.id) == provider
198 || (record.plugin.caps.auth_provider && normalize_provider(&record.plugin.auth_identifier) == provider)
199 {
200 return Some(record.clone());
201 }
202 }
203 for record in &records {
204 if self.is_fused(&record.id) {
205 continue;
206 }
207 if self
208 .supported_providers(&snapshot, record)
209 .await
210 .iter()
211 .any(|p| normalize_provider(p) == provider)
212 {
213 return Some(record.clone());
214 }
215 }
216 None
217 }
218
219 pub fn quota_provider_record_by_plugin(&self, plugin_id: &str) -> Option<Record> {
221 let plugin_id = plugin_id.trim();
222 self.quota_records().into_iter().find(|r| r.id == plugin_id)
223 }
224
225 pub async fn has_quota_provider(&self, provider: &str) -> bool {
227 self.quota_provider_record(provider).await.is_some()
228 }
229
230 pub fn has_quota_provider_for_plugin(&self, plugin_id: &str) -> bool {
232 self.quota_provider_record_by_plugin(plugin_id).is_some()
233 }
234
235 pub async fn describe_quota(&self, plugin_id: &str) -> Result<Option<QuotaDescribeResponse>, CallError> {
237 let record = match self.quota_provider_record_by_plugin(plugin_id) {
238 Some(record) => Some(record),
239 None => self.quota_provider_record(plugin_id).await,
240 };
241 match record {
242 Some(record) => self.describe_quota_record(&record).await,
243 None => Ok(None),
244 }
245 }
246
247 pub async fn fetch_quota(
250 &self,
251 req: QuotaFetchRequest,
252 auth: Option<&AuthView>,
253 scope: &RequestScope,
254 ) -> Result<Option<QuotaFetchResponse>, CallError> {
255 let mut record = self.quota_provider_record(&req.provider).await;
256 if record.is_none() && !req.provider.is_empty() {
257 record = self.quota_provider_record_by_plugin(&req.provider);
258 }
259 match record {
260 Some(record) => self.call_quota_fetch(&record, req, auth, scope).await,
261 None => Ok(None),
262 }
263 }
264
265 pub async fn fetch_quota_by_plugin(
267 &self,
268 plugin_id: &str,
269 req: QuotaFetchRequest,
270 auth: Option<&AuthView>,
271 scope: &RequestScope,
272 ) -> Result<Option<QuotaFetchResponse>, CallError> {
273 match self.quota_provider_record_by_plugin(plugin_id) {
274 Some(record) => self.call_quota_fetch(&record, req, auth, scope).await,
275 None => Ok(None),
276 }
277 }
278
279 pub async fn reset_quota(
281 &self,
282 req: QuotaResetRequest,
283 auth: Option<&AuthView>,
284 scope: &RequestScope,
285 ) -> Result<Option<QuotaResetResponse>, CallError> {
286 let mut record = self.quota_provider_record(&req.provider).await;
287 if record.is_none() && !req.provider.is_empty() {
288 record = self.quota_provider_record_by_plugin(&req.provider);
289 }
290 match record {
291 Some(record) => self.call_quota_reset(&record, req, auth, scope).await,
292 None => Ok(None),
293 }
294 }
295
296 pub async fn reset_quota_by_plugin(
298 &self,
299 plugin_id: &str,
300 req: QuotaResetRequest,
301 auth: Option<&AuthView>,
302 scope: &RequestScope,
303 ) -> Result<Option<QuotaResetResponse>, CallError> {
304 match self.quota_provider_record_by_plugin(plugin_id) {
305 Some(record) => self.call_quota_reset(&record, req, auth, scope).await,
306 None => Ok(None),
307 }
308 }
309
310 async fn call_quota_fetch(
311 &self,
312 record: &Record,
313 mut req: QuotaFetchRequest,
314 auth: Option<&AuthView>,
315 scope: &RequestScope,
316 ) -> Result<Option<QuotaFetchResponse>, CallError> {
317 if self.is_fused(&record.id) || !self.record_current(record) {
318 return Ok(None);
319 }
320 if !req.auth_index.is_empty()
321 && let Some(auth) = auth
322 {
323 fill_from_auth(
324 &mut req.auth_id,
325 &mut req.provider,
326 &mut req.storage_json,
327 &mut req.metadata,
328 &mut req.attributes,
329 auth,
330 );
331 }
332 req.host = self.host_config_summary();
333 let resp: FetchWire = self
334 .call_with_callback(record, method::QUOTA_FETCH, &req, scope)
335 .await?;
336 Ok(Some(resp.0))
337 }
338
339 async fn call_quota_reset(
340 &self,
341 record: &Record,
342 mut req: QuotaResetRequest,
343 auth: Option<&AuthView>,
344 scope: &RequestScope,
345 ) -> Result<Option<QuotaResetResponse>, CallError> {
346 if self.is_fused(&record.id) || !self.record_current(record) {
347 return Ok(None);
348 }
349 if !req.auth_index.is_empty()
350 && let Some(auth) = auth
351 {
352 fill_from_auth(
353 &mut req.auth_id,
354 &mut req.provider,
355 &mut req.storage_json,
356 &mut req.metadata,
357 &mut req.attributes,
358 auth,
359 );
360 }
361 req.host = self.host_config_summary();
362 self.call_with_callback(record, method::QUOTA_RESET, &req, scope)
363 .await
364 .map(Some)
365 }
366}
367
368fn fill_from_auth(
371 auth_id: &mut String,
372 provider: &mut String,
373 storage_json: &mut bytes::Bytes,
374 metadata: &mut crate::gojson::Metadata,
375 attributes: &mut crate::gojson::StringMap,
376 auth: &AuthView,
377) {
378 if auth_id.is_empty() {
379 *auth_id = auth.id.clone();
380 }
381 if provider.is_empty() {
382 *provider = auth.provider.clone();
383 }
384 if storage_json.is_empty() {
385 *storage_json = auth.storage_json.clone();
386 }
387 if metadata.is_empty() {
388 *metadata = auth.metadata.clone();
389 }
390 if attributes.is_empty() {
391 *attributes = auth.attributes.clone();
392 }
393}