fastly_api/apis/
rate_limiter_api.rs

1/*
2 * Fastly API
3 *
4 * Via the Fastly API you can perform any of the operations that are possible within the management console,  including creating services, domains, and backends, configuring rules or uploading your own application code, as well as account operations such as user administration and billing reports. The API is organized into collections of endpoints that allow manipulation of objects related to Fastly services and accounts. For the most accurate and up-to-date API reference content, visit our [Developer Hub](https://www.fastly.com/documentation/reference/api/) 
5 *
6 */
7
8
9use reqwest;
10
11use crate::apis::ResponseContent;
12use super::{Error, configuration};
13
14/// struct for passing parameters to the method [`create_rate_limiter`]
15#[derive(Clone, Debug, Default)]
16pub struct CreateRateLimiterParams {
17    /// Alphanumeric string identifying the service.
18    pub service_id: String,
19    /// Integer identifying a service version.
20    pub version_id: i32,
21    /// A human readable name for the rate limiting rule.
22    pub name: Option<String>,
23    /// The name of an Edge Dictionary containing URIs as keys. If not defined or `null`, all origin URIs will be rate limited.
24    pub uri_dictionary_name: Option<String>,
25    /// Array of HTTP methods to apply rate limiting to.
26    pub http_methods: Option<Vec<String>>,
27    /// Upper limit of requests per second allowed by the rate limiter.
28    pub rps_limit: Option<i32>,
29    /// Number of seconds during which the RPS limit must be exceeded in order to trigger a violation.
30    pub window_size: Option<i32>,
31    /// Array of VCL variables used to generate a counter key to identify a client. Example variables include `req.http.Fastly-Client-IP`, `req.http.User-Agent`, or a custom header like `req.http.API-Key`.
32    pub client_key: Option<Vec<String>>,
33    /// Length of time in minutes that the rate limiter is in effect after the initial violation is detected.
34    pub penalty_box_duration: Option<i32>,
35    /// The action to take when a rate limiter violation is detected.
36    pub action: Option<String>,
37    /// Name of existing response object. Required if `action` is `response_object`. Note that the rate limiter response is only updated to reflect the response object content when saving the rate limiter configuration.
38    pub response_object_name: Option<String>,
39    /// Name of the type of logging endpoint to be used when action is `log_only`. The logging endpoint type is used to determine the appropriate log format to use when emitting log entries.
40    pub logger_type: Option<String>,
41    /// Revision number of the rate limiting feature implementation. Defaults to the most recent revision.
42    pub feature_revision: Option<i32>
43}
44
45/// struct for passing parameters to the method [`delete_rate_limiter`]
46#[derive(Clone, Debug, Default)]
47pub struct DeleteRateLimiterParams {
48    /// Alphanumeric string identifying the rate limiter.
49    pub rate_limiter_id: String
50}
51
52/// struct for passing parameters to the method [`get_rate_limiter`]
53#[derive(Clone, Debug, Default)]
54pub struct GetRateLimiterParams {
55    /// Alphanumeric string identifying the rate limiter.
56    pub rate_limiter_id: String
57}
58
59/// struct for passing parameters to the method [`list_rate_limiters`]
60#[derive(Clone, Debug, Default)]
61pub struct ListRateLimitersParams {
62    /// Alphanumeric string identifying the service.
63    pub service_id: String,
64    /// Integer identifying a service version.
65    pub version_id: i32
66}
67
68/// struct for passing parameters to the method [`update_rate_limiter`]
69#[derive(Clone, Debug, Default)]
70pub struct UpdateRateLimiterParams {
71    /// Alphanumeric string identifying the rate limiter.
72    pub rate_limiter_id: String,
73    /// A human readable name for the rate limiting rule.
74    pub name: Option<String>,
75    /// The name of an Edge Dictionary containing URIs as keys. If not defined or `null`, all origin URIs will be rate limited.
76    pub uri_dictionary_name: Option<String>,
77    /// Array of HTTP methods to apply rate limiting to.
78    pub http_methods: Option<Vec<String>>,
79    /// Upper limit of requests per second allowed by the rate limiter.
80    pub rps_limit: Option<i32>,
81    /// Number of seconds during which the RPS limit must be exceeded in order to trigger a violation.
82    pub window_size: Option<i32>,
83    /// Array of VCL variables used to generate a counter key to identify a client. Example variables include `req.http.Fastly-Client-IP`, `req.http.User-Agent`, or a custom header like `req.http.API-Key`.
84    pub client_key: Option<Vec<String>>,
85    /// Length of time in minutes that the rate limiter is in effect after the initial violation is detected.
86    pub penalty_box_duration: Option<i32>,
87    /// The action to take when a rate limiter violation is detected.
88    pub action: Option<String>,
89    /// Name of existing response object. Required if `action` is `response_object`. Note that the rate limiter response is only updated to reflect the response object content when saving the rate limiter configuration.
90    pub response_object_name: Option<String>,
91    /// Name of the type of logging endpoint to be used when action is `log_only`. The logging endpoint type is used to determine the appropriate log format to use when emitting log entries.
92    pub logger_type: Option<String>,
93    /// Revision number of the rate limiting feature implementation. Defaults to the most recent revision.
94    pub feature_revision: Option<i32>
95}
96
97
98/// struct for typed errors of method [`create_rate_limiter`]
99#[derive(Debug, Clone, Serialize, Deserialize)]
100#[serde(untagged)]
101pub enum CreateRateLimiterError {
102    UnknownValue(serde_json::Value),
103}
104
105/// struct for typed errors of method [`delete_rate_limiter`]
106#[derive(Debug, Clone, Serialize, Deserialize)]
107#[serde(untagged)]
108pub enum DeleteRateLimiterError {
109    UnknownValue(serde_json::Value),
110}
111
112/// struct for typed errors of method [`get_rate_limiter`]
113#[derive(Debug, Clone, Serialize, Deserialize)]
114#[serde(untagged)]
115pub enum GetRateLimiterError {
116    UnknownValue(serde_json::Value),
117}
118
119/// struct for typed errors of method [`list_rate_limiters`]
120#[derive(Debug, Clone, Serialize, Deserialize)]
121#[serde(untagged)]
122pub enum ListRateLimitersError {
123    UnknownValue(serde_json::Value),
124}
125
126/// struct for typed errors of method [`update_rate_limiter`]
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(untagged)]
129pub enum UpdateRateLimiterError {
130    UnknownValue(serde_json::Value),
131}
132
133
134/// Create a rate limiter for a particular service and version.
135pub async fn create_rate_limiter(configuration: &mut configuration::Configuration, params: CreateRateLimiterParams) -> Result<crate::models::RateLimiterResponse, Error<CreateRateLimiterError>> {
136    let local_var_configuration = configuration;
137
138    // unbox the parameters
139    let service_id = params.service_id;
140    let version_id = params.version_id;
141    let name = params.name;
142    let uri_dictionary_name = params.uri_dictionary_name;
143    let http_methods = params.http_methods;
144    let rps_limit = params.rps_limit;
145    let window_size = params.window_size;
146    let client_key = params.client_key;
147    let penalty_box_duration = params.penalty_box_duration;
148    let action = params.action;
149    let response_object_name = params.response_object_name;
150    let logger_type = params.logger_type;
151    let feature_revision = params.feature_revision;
152
153
154    let local_var_client = &local_var_configuration.client;
155
156    let local_var_uri_str = format!("{}/service/{service_id}/version/{version_id}/rate-limiters", local_var_configuration.base_path, service_id=crate::apis::urlencode(service_id), version_id=version_id);
157    let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());
158
159    if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
160        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
161    }
162    if let Some(ref local_var_apikey) = local_var_configuration.api_key {
163        let local_var_key = local_var_apikey.key.clone();
164        let local_var_value = match local_var_apikey.prefix {
165            Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
166            None => local_var_key,
167        };
168        local_var_req_builder = local_var_req_builder.header("Fastly-Key", local_var_value);
169    };
170    let mut local_var_form_params = std::collections::HashMap::new();
171    if let Some(local_var_param_value) = name {
172        local_var_form_params.insert("name", local_var_param_value.to_string());
173    }
174    if let Some(local_var_param_value) = uri_dictionary_name {
175        local_var_form_params.insert("uri_dictionary_name", local_var_param_value.to_string());
176    }
177    if let Some(local_var_param_value) = http_methods {
178        local_var_form_params.insert("http_methods[]", local_var_param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string());
179    }
180    if let Some(local_var_param_value) = rps_limit {
181        local_var_form_params.insert("rps_limit", local_var_param_value.to_string());
182    }
183    if let Some(local_var_param_value) = window_size {
184        local_var_form_params.insert("window_size", local_var_param_value.to_string());
185    }
186    if let Some(local_var_param_value) = client_key {
187        local_var_form_params.insert("client_key[]", local_var_param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string());
188    }
189    if let Some(local_var_param_value) = penalty_box_duration {
190        local_var_form_params.insert("penalty_box_duration", local_var_param_value.to_string());
191    }
192    if let Some(local_var_param_value) = action {
193        local_var_form_params.insert("action", local_var_param_value.to_string());
194    }
195    if let Some(local_var_param_value) = response_object_name {
196        local_var_form_params.insert("response_object_name", local_var_param_value.to_string());
197    }
198    if let Some(local_var_param_value) = logger_type {
199        local_var_form_params.insert("logger_type", local_var_param_value.to_string());
200    }
201    if let Some(local_var_param_value) = feature_revision {
202        local_var_form_params.insert("feature_revision", local_var_param_value.to_string());
203    }
204    local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
205
206    let local_var_req = local_var_req_builder.build()?;
207    let local_var_resp = local_var_client.execute(local_var_req).await?;
208
209    if "POST" != "GET" && "POST" != "HEAD" {
210      let headers = local_var_resp.headers();
211      local_var_configuration.rate_limit_remaining = match headers.get("Fastly-RateLimit-Remaining") {
212          Some(v) => v.to_str().unwrap().parse().unwrap(),
213          None => configuration::DEFAULT_RATELIMIT,
214      };
215      local_var_configuration.rate_limit_reset = match headers.get("Fastly-RateLimit-Reset") {
216          Some(v) => v.to_str().unwrap().parse().unwrap(),
217          None => 0,
218      };
219    }
220
221    let local_var_status = local_var_resp.status();
222    let local_var_content = local_var_resp.text().await?;
223
224    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
225        serde_json::from_str(&local_var_content).map_err(Error::from)
226    } else {
227        let local_var_entity: Option<CreateRateLimiterError> = serde_json::from_str(&local_var_content).ok();
228        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
229        Err(Error::ResponseError(local_var_error))
230    }
231}
232
233/// Delete a rate limiter by its ID.
234pub async fn delete_rate_limiter(configuration: &mut configuration::Configuration, params: DeleteRateLimiterParams) -> Result<crate::models::InlineResponse200, Error<DeleteRateLimiterError>> {
235    let local_var_configuration = configuration;
236
237    // unbox the parameters
238    let rate_limiter_id = params.rate_limiter_id;
239
240
241    let local_var_client = &local_var_configuration.client;
242
243    let local_var_uri_str = format!("{}/rate-limiters/{rate_limiter_id}", local_var_configuration.base_path, rate_limiter_id=crate::apis::urlencode(rate_limiter_id));
244    let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str());
245
246    if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
247        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
248    }
249    if let Some(ref local_var_apikey) = local_var_configuration.api_key {
250        let local_var_key = local_var_apikey.key.clone();
251        let local_var_value = match local_var_apikey.prefix {
252            Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
253            None => local_var_key,
254        };
255        local_var_req_builder = local_var_req_builder.header("Fastly-Key", local_var_value);
256    };
257
258    let local_var_req = local_var_req_builder.build()?;
259    let local_var_resp = local_var_client.execute(local_var_req).await?;
260
261    if "DELETE" != "GET" && "DELETE" != "HEAD" {
262      let headers = local_var_resp.headers();
263      local_var_configuration.rate_limit_remaining = match headers.get("Fastly-RateLimit-Remaining") {
264          Some(v) => v.to_str().unwrap().parse().unwrap(),
265          None => configuration::DEFAULT_RATELIMIT,
266      };
267      local_var_configuration.rate_limit_reset = match headers.get("Fastly-RateLimit-Reset") {
268          Some(v) => v.to_str().unwrap().parse().unwrap(),
269          None => 0,
270      };
271    }
272
273    let local_var_status = local_var_resp.status();
274    let local_var_content = local_var_resp.text().await?;
275
276    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
277        serde_json::from_str(&local_var_content).map_err(Error::from)
278    } else {
279        let local_var_entity: Option<DeleteRateLimiterError> = serde_json::from_str(&local_var_content).ok();
280        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
281        Err(Error::ResponseError(local_var_error))
282    }
283}
284
285/// Get a rate limiter by its ID.
286pub async fn get_rate_limiter(configuration: &mut configuration::Configuration, params: GetRateLimiterParams) -> Result<crate::models::RateLimiterResponse, Error<GetRateLimiterError>> {
287    let local_var_configuration = configuration;
288
289    // unbox the parameters
290    let rate_limiter_id = params.rate_limiter_id;
291
292
293    let local_var_client = &local_var_configuration.client;
294
295    let local_var_uri_str = format!("{}/rate-limiters/{rate_limiter_id}", local_var_configuration.base_path, rate_limiter_id=crate::apis::urlencode(rate_limiter_id));
296    let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
297
298    if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
299        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
300    }
301    if let Some(ref local_var_apikey) = local_var_configuration.api_key {
302        let local_var_key = local_var_apikey.key.clone();
303        let local_var_value = match local_var_apikey.prefix {
304            Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
305            None => local_var_key,
306        };
307        local_var_req_builder = local_var_req_builder.header("Fastly-Key", local_var_value);
308    };
309
310    let local_var_req = local_var_req_builder.build()?;
311    let local_var_resp = local_var_client.execute(local_var_req).await?;
312
313    if "GET" != "GET" && "GET" != "HEAD" {
314      let headers = local_var_resp.headers();
315      local_var_configuration.rate_limit_remaining = match headers.get("Fastly-RateLimit-Remaining") {
316          Some(v) => v.to_str().unwrap().parse().unwrap(),
317          None => configuration::DEFAULT_RATELIMIT,
318      };
319      local_var_configuration.rate_limit_reset = match headers.get("Fastly-RateLimit-Reset") {
320          Some(v) => v.to_str().unwrap().parse().unwrap(),
321          None => 0,
322      };
323    }
324
325    let local_var_status = local_var_resp.status();
326    let local_var_content = local_var_resp.text().await?;
327
328    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
329        serde_json::from_str(&local_var_content).map_err(Error::from)
330    } else {
331        let local_var_entity: Option<GetRateLimiterError> = serde_json::from_str(&local_var_content).ok();
332        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
333        Err(Error::ResponseError(local_var_error))
334    }
335}
336
337/// List all rate limiters for a particular service and version.
338pub async fn list_rate_limiters(configuration: &mut configuration::Configuration, params: ListRateLimitersParams) -> Result<Vec<crate::models::RateLimiterResponse>, Error<ListRateLimitersError>> {
339    let local_var_configuration = configuration;
340
341    // unbox the parameters
342    let service_id = params.service_id;
343    let version_id = params.version_id;
344
345
346    let local_var_client = &local_var_configuration.client;
347
348    let local_var_uri_str = format!("{}/service/{service_id}/version/{version_id}/rate-limiters", local_var_configuration.base_path, service_id=crate::apis::urlencode(service_id), version_id=version_id);
349    let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
350
351    if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
352        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
353    }
354    if let Some(ref local_var_apikey) = local_var_configuration.api_key {
355        let local_var_key = local_var_apikey.key.clone();
356        let local_var_value = match local_var_apikey.prefix {
357            Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
358            None => local_var_key,
359        };
360        local_var_req_builder = local_var_req_builder.header("Fastly-Key", local_var_value);
361    };
362
363    let local_var_req = local_var_req_builder.build()?;
364    let local_var_resp = local_var_client.execute(local_var_req).await?;
365
366    if "GET" != "GET" && "GET" != "HEAD" {
367      let headers = local_var_resp.headers();
368      local_var_configuration.rate_limit_remaining = match headers.get("Fastly-RateLimit-Remaining") {
369          Some(v) => v.to_str().unwrap().parse().unwrap(),
370          None => configuration::DEFAULT_RATELIMIT,
371      };
372      local_var_configuration.rate_limit_reset = match headers.get("Fastly-RateLimit-Reset") {
373          Some(v) => v.to_str().unwrap().parse().unwrap(),
374          None => 0,
375      };
376    }
377
378    let local_var_status = local_var_resp.status();
379    let local_var_content = local_var_resp.text().await?;
380
381    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
382        serde_json::from_str(&local_var_content).map_err(Error::from)
383    } else {
384        let local_var_entity: Option<ListRateLimitersError> = serde_json::from_str(&local_var_content).ok();
385        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
386        Err(Error::ResponseError(local_var_error))
387    }
388}
389
390/// Update a rate limiter by its ID.
391pub async fn update_rate_limiter(configuration: &mut configuration::Configuration, params: UpdateRateLimiterParams) -> Result<crate::models::RateLimiterResponse, Error<UpdateRateLimiterError>> {
392    let local_var_configuration = configuration;
393
394    // unbox the parameters
395    let rate_limiter_id = params.rate_limiter_id;
396    let name = params.name;
397    let uri_dictionary_name = params.uri_dictionary_name;
398    let http_methods = params.http_methods;
399    let rps_limit = params.rps_limit;
400    let window_size = params.window_size;
401    let client_key = params.client_key;
402    let penalty_box_duration = params.penalty_box_duration;
403    let action = params.action;
404    let response_object_name = params.response_object_name;
405    let logger_type = params.logger_type;
406    let feature_revision = params.feature_revision;
407
408
409    let local_var_client = &local_var_configuration.client;
410
411    let local_var_uri_str = format!("{}/rate-limiters/{rate_limiter_id}", local_var_configuration.base_path, rate_limiter_id=crate::apis::urlencode(rate_limiter_id));
412    let mut local_var_req_builder = local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str());
413
414    if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
415        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
416    }
417    if let Some(ref local_var_apikey) = local_var_configuration.api_key {
418        let local_var_key = local_var_apikey.key.clone();
419        let local_var_value = match local_var_apikey.prefix {
420            Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
421            None => local_var_key,
422        };
423        local_var_req_builder = local_var_req_builder.header("Fastly-Key", local_var_value);
424    };
425    let mut local_var_form_params = std::collections::HashMap::new();
426    if let Some(local_var_param_value) = name {
427        local_var_form_params.insert("name", local_var_param_value.to_string());
428    }
429    if let Some(local_var_param_value) = uri_dictionary_name {
430        local_var_form_params.insert("uri_dictionary_name", local_var_param_value.to_string());
431    }
432    if let Some(local_var_param_value) = http_methods {
433        local_var_form_params.insert("http_methods[]", local_var_param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string());
434    }
435    if let Some(local_var_param_value) = rps_limit {
436        local_var_form_params.insert("rps_limit", local_var_param_value.to_string());
437    }
438    if let Some(local_var_param_value) = window_size {
439        local_var_form_params.insert("window_size", local_var_param_value.to_string());
440    }
441    if let Some(local_var_param_value) = client_key {
442        local_var_form_params.insert("client_key[]", local_var_param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string());
443    }
444    if let Some(local_var_param_value) = penalty_box_duration {
445        local_var_form_params.insert("penalty_box_duration", local_var_param_value.to_string());
446    }
447    if let Some(local_var_param_value) = action {
448        local_var_form_params.insert("action", local_var_param_value.to_string());
449    }
450    if let Some(local_var_param_value) = response_object_name {
451        local_var_form_params.insert("response_object_name", local_var_param_value.to_string());
452    }
453    if let Some(local_var_param_value) = logger_type {
454        local_var_form_params.insert("logger_type", local_var_param_value.to_string());
455    }
456    if let Some(local_var_param_value) = feature_revision {
457        local_var_form_params.insert("feature_revision", local_var_param_value.to_string());
458    }
459    local_var_req_builder = local_var_req_builder.form(&local_var_form_params);
460
461    let local_var_req = local_var_req_builder.build()?;
462    let local_var_resp = local_var_client.execute(local_var_req).await?;
463
464    if "PUT" != "GET" && "PUT" != "HEAD" {
465      let headers = local_var_resp.headers();
466      local_var_configuration.rate_limit_remaining = match headers.get("Fastly-RateLimit-Remaining") {
467          Some(v) => v.to_str().unwrap().parse().unwrap(),
468          None => configuration::DEFAULT_RATELIMIT,
469      };
470      local_var_configuration.rate_limit_reset = match headers.get("Fastly-RateLimit-Reset") {
471          Some(v) => v.to_str().unwrap().parse().unwrap(),
472          None => 0,
473      };
474    }
475
476    let local_var_status = local_var_resp.status();
477    let local_var_content = local_var_resp.text().await?;
478
479    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
480        serde_json::from_str(&local_var_content).map_err(Error::from)
481    } else {
482        let local_var_entity: Option<UpdateRateLimiterError> = serde_json::from_str(&local_var_content).ok();
483        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
484        Err(Error::ResponseError(local_var_error))
485    }
486}
487