diff --git a/example/proxy/src/main.rs b/example/proxy/src/main.rs
index 0d6a92d..10c0642 100644
--- a/example/proxy/src/main.rs
+++ b/example/proxy/src/main.rs
@@ -2,16 +2,16 @@
use std::convert::Infallible;
-use hyper::http;
-use http::{ Method, Request, Response, StatusCode };
-use hyper::{ Body, Server };
-use hyper::service::{ make_service_fn, service_fn };
+use http::{Method, Request, Response, StatusCode};
use hyper::header::HeaderValue;
+use hyper::http;
+use hyper::service::{make_service_fn, service_fn};
+use hyper::{Body, Server};
use lazy_static::lazy_static;
use tracing as log;
-use riven::{ RiotApi, RiotApiConfig };
use riven::consts::Route;
+use riven::{RiotApi, RiotApiConfig};
lazy_static! {
/// Create lazy static RiotApi instance.
@@ -31,47 +31,64 @@ lazy_static! {
fn create_json_response(body: &'static str, status: StatusCode) -> Response
{
let mut resp = Response::new(Body::from(body));
*resp.status_mut() = status;
- resp.headers_mut().insert(hyper::header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
+ resp.headers_mut().insert(
+ hyper::header::CONTENT_TYPE,
+ HeaderValue::from_static("application/json"),
+ );
resp
}
/// Main request handler service.
async fn handle_request(req: Request) -> Result, Infallible> {
-
let (parts, body) = req.into_parts();
let http::request::Parts { method, uri, .. } = parts;
// Handle path.
let path_data_opt = parse_path(&method, uri.path());
- let ( route, method_id, req_path ) = match path_data_opt {
- None => return Ok(create_json_response(
- r#"{"error":"Riot API endpoint method not found."}"#, StatusCode::NOT_FOUND)),
+ let (route, method_id, req_path) = match path_data_opt {
+ None => {
+ return Ok(create_json_response(
+ r#"{"error":"Riot API endpoint method not found."}"#,
+ StatusCode::NOT_FOUND,
+ ))
+ }
Some(path_data) => path_data,
};
- log::debug!("Request to route {:?}, method ID {:?}: {} {:?}.", route, method_id, method, req_path);
+ log::debug!(
+ "Request to route {:?}, method ID {:?}: {} {:?}.",
+ route,
+ method_id,
+ method,
+ req_path
+ );
// Convert http:request::Parts from hyper to reqwest's RequestBuilder.
let body = match hyper::body::to_bytes(body).await {
Err(err) => {
log::info!("Error handling request body: {:#?}", err);
return Ok(create_json_response(
- r#"{"error":"Failed to handle request body."}"#, StatusCode::BAD_REQUEST));
- },
+ r#"{"error":"Failed to handle request body."}"#,
+ StatusCode::BAD_REQUEST,
+ ));
+ }
Ok(bytes) => bytes,
};
- let req_builder = RIOT_API.request(method, route.into(), req_path)
- .body(body);
+ let req_builder = RIOT_API.request(method, route.into(), req_path).body(body);
// Send request to Riot API.
- let resp_result = RIOT_API.execute_raw(method_id, route.into(), req_builder).await;
+ let resp_result = RIOT_API
+ .execute_raw(method_id, route.into(), req_builder)
+ .await;
let resp_info = match resp_result {
Err(err) => {
log::info!("Riot API error: {:#?}", err.source_reqwest_error());
return Ok(create_json_response(
- r#"{"error":"Riot API request failed."}"#, StatusCode::INTERNAL_SERVER_ERROR));
- },
+ r#"{"error":"Riot API request failed."}"#,
+ StatusCode::INTERNAL_SERVER_ERROR,
+ ));
+ }
Ok(resp_info) => resp_info,
};
@@ -86,13 +103,17 @@ async fn handle_request(req: Request) -> Result, Infallible
}
// Otherwise copy body.
else {
- *out_response.status_mut() = api_response.status();
+ *out_response.status_mut() = api_response.status();
// Using streams would be faster.
let bytes_result = api_response.bytes().await;
let bytes = match bytes_result {
- Err(_err) => return Ok(create_json_response(
- r#"{"error":"Failed to get body from Riot API response."}"#, StatusCode::INTERNAL_SERVER_ERROR)),
+ Err(_err) => {
+ return Ok(create_json_response(
+ r#"{"error":"Failed to get body from Riot API response."}"#,
+ StatusCode::INTERNAL_SERVER_ERROR,
+ ))
+ }
Ok(bytes) => bytes,
};
*out_response.body_mut() = Body::from((&bytes[..]).to_vec());
@@ -101,22 +122,24 @@ async fn handle_request(req: Request) -> Result, Infallible
}
/// Gets the region, method_id, and Riot API path based on the given http method and path.
-fn parse_path<'a>(http_method: &Method, req_path: &'a str) -> Option<( Route, &'static str, &'a str )> {
-
+fn parse_path<'a>(
+ http_method: &Method,
+ req_path: &'a str,
+) -> Option<(Route, &'static str, &'a str)> {
// Split URI into region and rest of path.
let req_path = req_path.trim_start_matches('/');
- let ( route, req_path ) = req_path.split_at(req_path.find('/')?);
+ let (route, req_path) = req_path.split_at(req_path.find('/')?);
let route: Route = route.to_uppercase().parse().ok()?;
// Find method_id for given path.
let method_id = find_matching_method_id(http_method, req_path)?;
- Some(( route, method_id, req_path ))
+ Some((route, method_id, req_path))
}
/// Finds the method_id given the request path.
fn find_matching_method_id(http_method: &Method, req_path: &str) -> Option<&'static str> {
- for ( endpoint_http_method, ref_path, method_id ) in &riven::meta::ALL_ENDPOINTS {
+ for (endpoint_http_method, ref_path, method_id) in &riven::meta::ALL_ENDPOINTS {
if http_method == endpoint_http_method && paths_match(ref_path, req_path) {
return Some(method_id);
}
@@ -160,7 +183,7 @@ pub async fn main() -> Result<(), Box> {
async { Ok::<_, Infallible>(service_fn(handle_request)) }
});
- let addr = ([ 127, 0, 0, 1 ], 3000).into();
+ let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
diff --git a/riven/src/config.rs b/riven/src/config.rs
index 6132c8c..4627d4c 100644
--- a/riven/src/config.rs
+++ b/riven/src/config.rs
@@ -1,8 +1,8 @@
//! Configuration of RiotApi.
use std::time::Duration;
+use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::ClientBuilder;
-use reqwest::header::{ HeaderMap, HeaderValue };
/// Configuration for instantiating RiotApi.
///
@@ -72,7 +72,7 @@ impl RiotApiConfig {
let mut default_headers = HeaderMap::new();
default_headers.insert(
Self::RIOT_KEY_HEADER,
- HeaderValue::from_bytes(api_key.as_ref()).unwrap()
+ HeaderValue::from_bytes(api_key.as_ref()).unwrap(),
);
Self {
@@ -82,10 +82,7 @@ impl RiotApiConfig {
method_rate_usage_factor: Self::DEFAULT_RATE_USAGE_FACTOR,
burst_factor: Self::PRECONFIG_BURST_BURST_FACTOR,
duration_overhead: Self::PRECONFIG_BURST_DURATION_OVERHEAD,
- client_builder: Some(
- ClientBuilder::new()
- .default_headers(default_headers)
- ),
+ client_builder: Some(ClientBuilder::new().default_headers(default_headers)),
}
}
@@ -191,7 +188,10 @@ impl RiotApiConfig {
self.method_rate_usage_factor = rate_usage_factor;
return self;
}
- panic!("rate_usage_factor \"{}\" not in range (0, 1].", rate_usage_factor);
+ panic!(
+ "rate_usage_factor \"{}\" not in range (0, 1].",
+ rate_usage_factor
+ );
}
/// See [Self::set_rate_usage_factor]. Setting this is useful if you have multiple
@@ -209,7 +209,10 @@ impl RiotApiConfig {
self.app_rate_usage_factor = app_rate_usage_factor;
return self;
}
- panic!("app_rate_usage_factor \"{}\" not in range (0, 1].", app_rate_usage_factor);
+ panic!(
+ "app_rate_usage_factor \"{}\" not in range (0, 1].",
+ app_rate_usage_factor
+ );
}
/// See [Self::set_rate_usage_factor] and [Self::set_app_rate_usage_factor].
@@ -227,7 +230,10 @@ impl RiotApiConfig {
self.method_rate_usage_factor = method_rate_usage_factor;
return self;
}
- panic!("method_rate_usage_factor \"{}\" not in range (0, 1].", method_rate_usage_factor);
+ panic!(
+ "method_rate_usage_factor \"{}\" not in range (0, 1].",
+ method_rate_usage_factor
+ );
}
/// Burst percentage controls how many burst requests are allowed and
diff --git a/riven/src/consts/division.rs b/riven/src/consts/division.rs
index 5d38135..7f16cc4 100644
--- a/riven/src/consts/division.rs
+++ b/riven/src/consts/division.rs
@@ -1,9 +1,9 @@
use std::cmp::Ordering;
-use num_enum::{ IntoPrimitive, TryFromPrimitive };
-use serde::{ Serialize, Deserialize };
+use num_enum::{IntoPrimitive, TryFromPrimitive};
+use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
-use strum_macros::{ EnumString, Display, AsRefStr, IntoStaticStr };
+use strum_macros::{AsRefStr, Display, EnumString, IntoStaticStr};
/// LoL and TFT rank divisions, I, II, III, IV, and (deprecated) V.
///
@@ -12,25 +12,36 @@ use strum_macros::{ EnumString, Display, AsRefStr, IntoStaticStr };
/// Repr'd as equivalent numeric values, (1, 2, 3, 4, 5).
///
/// Implements [IntoEnumIterator](super::IntoEnumIterator). Iterator excludes deprecated `Division::V`.
-#[derive(Debug, Copy, Clone)]
-#[derive(Eq, PartialEq, Hash)]
-#[derive(EnumString, Display, AsRefStr, IntoStaticStr)]
-#[derive(IntoPrimitive, TryFromPrimitive)]
-#[derive(Serialize, Deserialize)]
+#[derive(
+ Debug,
+ Copy,
+ Clone,
+ Eq,
+ PartialEq,
+ Hash,
+ EnumString,
+ Display,
+ AsRefStr,
+ IntoStaticStr,
+ IntoPrimitive,
+ TryFromPrimitive,
+ Serialize,
+ Deserialize,
+)]
#[repr(u8)]
pub enum Division {
/// Division 1, the best/highest division in a [`Tier`](crate::consts::Tier), or the only division in
/// [apex tiers](crate::consts::Tier::is_apex).
- I = 1,
+ I = 1,
/// Division 2, the second highest division.
- II = 2,
+ II = 2,
/// Division 3, the third highest division.
III = 3,
/// Division 4, the fourth and lowest division since 2019.
- IV = 4,
+ IV = 4,
/// Division 5, the lowest division, only used before 2019.
- #[deprecated(note="Removed for 2019.")]
- V = 5,
+ #[deprecated(note = "Removed for 2019.")]
+ V = 5,
}
/// Returns a DoubleEndedIterator of I, II, III, IV.
@@ -39,7 +50,7 @@ pub enum Division {
impl IntoEnumIterator for Division {
type Iterator = std::iter::Copied>;
fn iter() -> Self::Iterator {
- [ Self::I, Self::II, Self::III, Self::IV ].iter().copied()
+ [Self::I, Self::II, Self::III, Self::IV].iter().copied()
}
}
@@ -63,4 +74,4 @@ mod tests {
fn sort() {
assert!(Division::IV < Division::I);
}
-}
\ No newline at end of file
+}
diff --git a/riven/src/consts/macros.rs b/riven/src/consts/macros.rs
index 2b4bd30..26fe1a6 100644
--- a/riven/src/consts/macros.rs
+++ b/riven/src/consts/macros.rs
@@ -38,7 +38,7 @@ macro_rules! serde_strum_unknown {
impl<'de> serde::de::Deserialize<'de> for $name {
fn deserialize(deserializer: D) -> Result
where
- D: serde::de::Deserializer<'de>
+ D: serde::de::Deserializer<'de>,
{
#[cfg(not(feature = "deny-unknown-enum-variants-strings"))]
{
@@ -46,20 +46,19 @@ macro_rules! serde_strum_unknown {
}
#[cfg(feature = "deny-unknown-enum-variants-strings")]
{
- <&str>::deserialize(deserializer).map(Into::into)
- .and_then(|item| {
- match item {
- Self::UNKNOWN(unknown) => Err(serde::de::Error::unknown_variant(
- &*unknown,
- ::VARIANTS,
- )),
- other => Ok(other),
- }
+ <&str>::deserialize(deserializer)
+ .map(Into::into)
+ .and_then(|item| match item {
+ Self::UNKNOWN(unknown) => Err(serde::de::Error::unknown_variant(
+ &*unknown,
+ ::VARIANTS,
+ )),
+ other => Ok(other),
})
}
}
}
- }
+ };
}
macro_rules! arr {
diff --git a/riven/src/consts/ranks.rs b/riven/src/consts/ranks.rs
index 4489010..d9353ec 100644
--- a/riven/src/consts/ranks.rs
+++ b/riven/src/consts/ranks.rs
@@ -4,10 +4,10 @@ use std::iter::Peekable;
use strum::IntoEnumIterator;
-use super::{ Tier, Division };
+use super::{Division, Tier};
/// (Tier, Division) tuple representing a rank.
-pub type Rank = ( Tier, Division );
+pub type Rank = (Tier, Division);
/// Iterator for iterating `(Tier, Division)` rank tuples.
pub struct Iter {
@@ -20,13 +20,12 @@ impl Iterator for Iter {
fn next(&mut self) -> Option {
// First find the tier (innermost loop).
// If none found, we go to next tier (in unwrap_or_else case).
- let div = self.div_iter.next()
- .unwrap_or_else(|| {
- // If no divisions available, go to next tier, reset the divisions, and return I.
- self.tier_iter.next();
- self.div_iter = Division::iter();
- self.div_iter.next().unwrap()
- });
+ let div = self.div_iter.next().unwrap_or_else(|| {
+ // If no divisions available, go to next tier, reset the divisions, and return I.
+ self.tier_iter.next();
+ self.div_iter = Division::iter();
+ self.div_iter.next().unwrap()
+ });
// Then find the tier.
let tier = *self.tier_iter.peek()?;
@@ -36,7 +35,7 @@ impl Iterator for Iter {
self.div_iter = Division::iter();
}
- Some(( tier, div ))
+ Some((tier, div))
}
}
@@ -66,33 +65,16 @@ pub fn non_apex_iter() -> Iter {
#[cfg(test)]
mod tests {
- use super::{ Tier, Division };
+ use super::{Division, Tier};
#[test]
fn iter() {
let mut it = super::iter();
- assert_eq!(Some(( Tier::CHALLENGER, Division::I )), it.next());
- assert_eq!(Some(( Tier::GRANDMASTER, Division::I )), it.next());
- assert_eq!(Some(( Tier::MASTER, Division::I )), it.next());
- assert_eq!(Some(( Tier::DIAMOND, Division::I )), it.next());
- assert_eq!(Some(( Tier::DIAMOND, Division::II )), it.next());
- let mut last = None;
- for next in &mut it {
- last = Some(next);
- }
- assert_eq!(Some(( Tier::IRON, Division::IV )), last);
- assert_eq!(None, it.next());
- }
-
-
- #[test]
- fn non_apex_iter() {
- let mut it = super::non_apex_iter();
- assert_eq!(Some((Tier::DIAMOND, Division::I)), it.next());
- assert_eq!(Some((Tier::DIAMOND, Division::II)), it.next());
- assert_eq!(Some((Tier::DIAMOND, Division::III)), it.next());
- assert_eq!(Some((Tier::DIAMOND, Division::IV)), it.next());
- assert_eq!(Some((Tier::PLATINUM, Division::I)), it.next());
+ assert_eq!(Some((Tier::CHALLENGER, Division::I)), it.next());
+ assert_eq!(Some((Tier::GRANDMASTER, Division::I)), it.next());
+ assert_eq!(Some((Tier::MASTER, Division::I)), it.next());
+ assert_eq!(Some((Tier::DIAMOND, Division::I)), it.next());
+ assert_eq!(Some((Tier::DIAMOND, Division::II)), it.next());
let mut last = None;
for next in &mut it {
last = Some(next);
@@ -100,4 +82,20 @@ mod tests {
assert_eq!(Some((Tier::IRON, Division::IV)), last);
assert_eq!(None, it.next());
}
-}
\ No newline at end of file
+
+ #[test]
+ fn non_apex_iter() {
+ let mut it = super::non_apex_iter();
+ assert_eq!(Some((Tier::DIAMOND, Division::I)), it.next());
+ assert_eq!(Some((Tier::DIAMOND, Division::II)), it.next());
+ assert_eq!(Some((Tier::DIAMOND, Division::III)), it.next());
+ assert_eq!(Some((Tier::DIAMOND, Division::IV)), it.next());
+ assert_eq!(Some((Tier::PLATINUM, Division::I)), it.next());
+ let mut last = None;
+ for next in &mut it {
+ last = Some(next);
+ }
+ assert_eq!(Some((Tier::IRON, Division::IV)), last);
+ assert_eq!(None, it.next());
+ }
+}
diff --git a/riven/src/consts/route_ext.rs b/riven/src/consts/route_ext.rs
index b2da7f2..34e592f 100644
--- a/riven/src/consts/route_ext.rs
+++ b/riven/src/consts/route_ext.rs
@@ -1,9 +1,7 @@
-use super::{ RegionalRoute, PlatformRoute, ValPlatformRoute };
+use super::{PlatformRoute, RegionalRoute, ValPlatformRoute};
/// Utility enum containing all routing variants.
-#[derive(Debug)]
-#[derive(PartialEq, Eq, Hash, PartialOrd, Ord)]
-#[derive(Clone, Copy)]
+#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)]
#[repr(u8)]
#[non_exhaustive]
pub enum Route {
@@ -40,13 +38,13 @@ impl num_enum::TryFromPrimitive for Route {
const NAME: &'static str = stringify!(Route);
- fn try_from_primitive(number: Self::Primitive) -> Result> {
+ fn try_from_primitive(
+ number: Self::Primitive,
+ ) -> Result> {
RegionalRoute::try_from_primitive(number)
.map(Route::Regional)
- .or_else(|_| PlatformRoute::try_from_primitive(number)
- .map(Route::Platform))
- .or_else(|_| ValPlatformRoute::try_from_primitive(number)
- .map(Route::ValPlatform))
+ .or_else(|_| PlatformRoute::try_from_primitive(number).map(Route::Platform))
+ .or_else(|_| ValPlatformRoute::try_from_primitive(number).map(Route::ValPlatform))
.map_err(|_| num_enum::TryFromPrimitiveError { number })
}
}
@@ -73,10 +71,8 @@ impl std::str::FromStr for Route {
fn from_str(s: &str) -> Result {
RegionalRoute::from_str(s)
.map(Self::Regional)
- .or_else(|_| PlatformRoute::from_str(s)
- .map(Self::Platform))
- .or_else(|_| ValPlatformRoute::from_str(s)
- .map(Self::ValPlatform))
+ .or_else(|_| PlatformRoute::from_str(s).map(Self::Platform))
+ .or_else(|_| ValPlatformRoute::from_str(s).map(Self::ValPlatform))
.map_err(|_| strum::ParseError::VariantNotFound)
}
}
@@ -87,16 +83,11 @@ impl Route {
pub fn iter() -> impl Iterator- {
use strum::IntoEnumIterator;
- let regional = RegionalRoute::iter()
- .map(Self::Regional);
- let platform = PlatformRoute::iter()
- .map(Self::Platform);
- let val_platform = ValPlatformRoute::iter()
- .map(Self::ValPlatform);
+ let regional = RegionalRoute::iter().map(Self::Regional);
+ let platform = PlatformRoute::iter().map(Self::Platform);
+ let val_platform = ValPlatformRoute::iter().map(Self::ValPlatform);
- regional
- .chain(platform)
- .chain(val_platform)
+ regional.chain(platform).chain(val_platform)
}
}
@@ -106,9 +97,18 @@ mod tests {
#[test]
fn test_route_tostring() {
- assert_eq!("AMERICAS", Into::<&'static str>::into(Route::Regional(RegionalRoute::AMERICAS)));
- assert_eq!("KR", Into::<&'static str>::into(Route::Platform(PlatformRoute::KR)));
- assert_eq!("KR", Into::<&'static str>::into(Route::ValPlatform(ValPlatformRoute::KR)));
+ assert_eq!(
+ "AMERICAS",
+ Into::<&'static str>::into(Route::Regional(RegionalRoute::AMERICAS))
+ );
+ assert_eq!(
+ "KR",
+ Into::<&'static str>::into(Route::Platform(PlatformRoute::KR))
+ );
+ assert_eq!(
+ "KR",
+ Into::<&'static str>::into(Route::ValPlatform(ValPlatformRoute::KR))
+ );
}
#[test]
@@ -132,7 +132,10 @@ mod tests {
assert_eq!("AMERICAS", RegionalRoute::AMERICAS.to_string());
assert_eq!("SEA", RegionalRoute::SEA.to_string());
- assert_eq!("AMERICAS", Into::<&'static str>::into(RegionalRoute::AMERICAS));
+ assert_eq!(
+ "AMERICAS",
+ Into::<&'static str>::into(RegionalRoute::AMERICAS)
+ );
assert_eq!("SEA", Into::<&'static str>::into(RegionalRoute::SEA));
}
@@ -171,7 +174,10 @@ mod tests {
assert_eq!("AP", Into::<&'static str>::into(ValPlatformRoute::AP));
assert_eq!("KR", Into::<&'static str>::into(ValPlatformRoute::KR));
- assert_eq!("ESPORTS", Into::<&'static str>::into(ValPlatformRoute::ESPORTS));
+ assert_eq!(
+ "ESPORTS",
+ Into::<&'static str>::into(ValPlatformRoute::ESPORTS)
+ );
}
#[test]
diff --git a/riven/src/consts/team.rs b/riven/src/consts/team.rs
index 9aea966..5484a10 100644
--- a/riven/src/consts/team.rs
+++ b/riven/src/consts/team.rs
@@ -1,11 +1,21 @@
-use serde_repr::{ Serialize_repr, Deserialize_repr };
-use num_enum::{ IntoPrimitive, TryFromPrimitive };
+use num_enum::{IntoPrimitive, TryFromPrimitive};
+use serde_repr::{Deserialize_repr, Serialize_repr};
/// League of Legends team.
-#[derive(Debug, Copy, Clone)]
-#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)]
-#[derive(Serialize_repr, Deserialize_repr)]
-#[derive(IntoPrimitive, TryFromPrimitive)]
+#[derive(
+ Debug,
+ Copy,
+ Clone,
+ Eq,
+ PartialEq,
+ Hash,
+ Ord,
+ PartialOrd,
+ Serialize_repr,
+ Deserialize_repr,
+ IntoPrimitive,
+ TryFromPrimitive,
+)]
#[repr(u16)]
pub enum Team {
/// Blue team (bottom left on Summoner's Rift).
diff --git a/riven/src/consts/tier.rs b/riven/src/consts/tier.rs
index 703c12c..992ed0c 100644
--- a/riven/src/consts/tier.rs
+++ b/riven/src/consts/tier.rs
@@ -1,7 +1,7 @@
-use num_enum::{ IntoPrimitive, TryFromPrimitive };
-use serde::{ Serialize, Deserialize };
+use num_enum::{IntoPrimitive, TryFromPrimitive};
+use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
-use strum_macros::{ EnumString, Display, AsRefStr, IntoStaticStr };
+use strum_macros::{AsRefStr, Display, EnumString, IntoStaticStr};
/// LoL and TFT ranked tiers, such as gold, diamond, challenger, etc.
///
@@ -10,36 +10,49 @@ use strum_macros::{ EnumString, Display, AsRefStr, IntoStaticStr };
/// Repr'd as arbitrary `u8` values.
///
/// Implements [IntoEnumIterator](super::IntoEnumIterator).
-#[derive(Debug, Copy, Clone)]
-#[derive(Eq, PartialEq, Hash, PartialOrd, Ord)]
-#[derive(IntoPrimitive, TryFromPrimitive)]
-#[derive(EnumString, Display, AsRefStr, IntoStaticStr)]
-#[derive(Serialize, Deserialize)]
+#[derive(
+ Debug,
+ Copy,
+ Clone,
+ Eq,
+ PartialEq,
+ Hash,
+ PartialOrd,
+ Ord,
+ IntoPrimitive,
+ TryFromPrimitive,
+ EnumString,
+ Display,
+ AsRefStr,
+ IntoStaticStr,
+ Serialize,
+ Deserialize,
+)]
#[repr(u8)]
pub enum Tier {
/// Challenger, the highest tier, an apex tier. Repr: `220_u8`.
- CHALLENGER = 220,
+ CHALLENGER = 220,
/// Grand Master, an apex tier. Repr: `200_u8`.
GRANDMASTER = 200,
/// Master, an apex tier. Repr: `180_u8`.
- MASTER = 180,
+ MASTER = 180,
/// Diamond, the higest non-apex tier. Repr: `140_u8`.
- DIAMOND = 140,
+ DIAMOND = 140,
/// Platinum. Repr: `120_u8`.
- PLATINUM = 120,
+ PLATINUM = 120,
/// Gold. Repr: `100_u8`.
- GOLD = 100,
+ GOLD = 100,
/// Silver. Repr: `80_u8`.
- SILVER = 80,
+ SILVER = 80,
/// Bronze. Repr: `60_u8`.
- BRONZE = 60,
+ BRONZE = 60,
/// Iron, the lowest tier. Repr: `40_u8`.
- IRON = 40,
+ IRON = 40,
/// Unranked, no tier. Repr: `0_u8`.
/// Also deserializes from "NONE" returned by `lol-challenges-v1.getChallengePercentiles`.
#[serde(alias = "NONE")]
- UNRANKED = 0,
+ UNRANKED = 0,
}
impl Tier {
@@ -63,7 +76,7 @@ impl Tier {
/// If this tier is ranked. Returns true for iron through challenger, false for unranked.
pub const fn is_ranked(self) -> bool {
- // Casts needed for const.
+ // Casts needed for const.
(Self::UNRANKED as u8) < (self as u8)
}
@@ -77,7 +90,11 @@ impl Tier {
/// Converts UNRANKED to None and all ranked tiers to Some(...).
pub fn to_ranked(self) -> Option {
- if self.is_unranked() { None } else { Some(self) }
+ if self.is_unranked() {
+ None
+ } else {
+ Some(self)
+ }
}
}
@@ -88,10 +105,18 @@ impl IntoEnumIterator for Tier {
type Iterator = std::iter::Copied>;
fn iter() -> Self::Iterator {
[
- Self::CHALLENGER, Self::GRANDMASTER, Self::MASTER,
- Self::DIAMOND, Self::PLATINUM, Self::GOLD,
- Self::SILVER, Self::BRONZE, Self::IRON
- ].iter().copied()
+ Self::CHALLENGER,
+ Self::GRANDMASTER,
+ Self::MASTER,
+ Self::DIAMOND,
+ Self::PLATINUM,
+ Self::GOLD,
+ Self::SILVER,
+ Self::BRONZE,
+ Self::IRON,
+ ]
+ .iter()
+ .copied()
}
}
diff --git a/riven/src/error.rs b/riven/src/error.rs
index 76ba627..1253fa4 100644
--- a/riven/src/error.rs
+++ b/riven/src/error.rs
@@ -1,6 +1,6 @@
use std::fmt;
-use reqwest::{ Error, Response, StatusCode };
+use reqwest::{Error, Response, StatusCode};
/// Result containing RiotApiError on failure.
pub type Result = std::result::Result;
@@ -17,7 +17,12 @@ pub struct RiotApiError {
status_code: Option,
}
impl RiotApiError {
- pub(crate) fn new(reqwest_error: Error, retries: u8, response: Option, status_code: Option) -> Self {
+ pub(crate) fn new(
+ reqwest_error: Error,
+ retries: u8,
+ response: Option,
+ status_code: Option,
+ ) -> Self {
Self {
reqwest_error,
retries,
diff --git a/riven/src/models_impls.rs b/riven/src/models_impls.rs
index c042724..1ccc1e5 100644
--- a/riven/src/models_impls.rs
+++ b/riven/src/models_impls.rs
@@ -1,5 +1,5 @@
-use crate::models::match_v5::Participant;
use crate::consts::Champion;
+use crate::models::match_v5::Participant;
impl Participant {
/// This method takes the [`Self::champion_id`] field if it is valid
diff --git a/riven/src/req/rate_limit.rs b/riven/src/req/rate_limit.rs
index a7312d8..c4f018e 100644
--- a/riven/src/req/rate_limit.rs
+++ b/riven/src/req/rate_limit.rs
@@ -1,19 +1,19 @@
use std::cmp;
-use std::time::{ Duration, Instant };
+use std::time::{Duration, Instant};
-#[cfg(not(feature="tracing"))]
-use log as log;
-#[cfg(feature="tracing")]
+#[cfg(not(feature = "tracing"))]
+use log;
+#[cfg(feature = "tracing")]
use tracing as log;
-use parking_lot::{ RwLock, RwLockUpgradableReadGuard };
-use reqwest::{ StatusCode, Response };
+use parking_lot::{RwLock, RwLockUpgradableReadGuard};
+use reqwest::{Response, StatusCode};
use scan_fmt::scan_fmt;
use tokio::sync::Notify;
-use crate::RiotApiConfig;
-use super::{ TokenBucket, VectorTokenBucket };
use super::RateLimitType;
+use super::{TokenBucket, VectorTokenBucket};
+use crate::RiotApiConfig;
pub struct RateLimit {
rate_limit_type: RateLimitType,
@@ -42,8 +42,8 @@ impl RateLimit {
const HEADER_XRATELIMITTYPE_SERVICE: &'static str = "service";
pub fn new(rate_limit_type: RateLimitType) -> Self {
- let initial_bucket = VectorTokenBucket::new(
- Duration::from_secs(1), 1, Duration::new(0, 0), 1.0, 1.0);
+ let initial_bucket =
+ VectorTokenBucket::new(Duration::from_secs(1), 1, Duration::new(0, 0), 1.0, 1.0);
RateLimit {
rate_limit_type,
// Rate limit before getting from response: 1/s.
@@ -65,13 +65,19 @@ impl RateLimit {
}
}
- fn acquire_both_or_duration(app_rate_limit: &Self, method_rate_limit: &Self) -> Option {
+ fn acquire_both_or_duration(
+ app_rate_limit: &Self,
+ method_rate_limit: &Self,
+ ) -> Option {
// Check retry after.
{
- let retry_after_delay = app_rate_limit.get_retry_after_delay()
- .and_then(|a| method_rate_limit.get_retry_after_delay().map(|m| cmp::max(a, m)));
+ let retry_after_delay = app_rate_limit.get_retry_after_delay().and_then(|a| {
+ method_rate_limit
+ .get_retry_after_delay()
+ .map(|m| cmp::max(a, m))
+ });
if retry_after_delay.is_some() {
- return retry_after_delay
+ return retry_after_delay;
}
}
// Check buckets.
@@ -88,12 +94,18 @@ impl RateLimit {
bucket.get_tokens(1);
}
- log::trace!("Tokens obtained, buckets: APP {:?} METHOD {:?}", app_buckets, method_buckets);
+ log::trace!(
+ "Tokens obtained, buckets: APP {:?} METHOD {:?}",
+ app_buckets,
+ method_buckets
+ );
None
}
pub fn get_retry_after_delay(&self) -> Option {
- self.retry_after.read().and_then(|i| Instant::now().checked_duration_since(i))
+ self.retry_after
+ .read()
+ .and_then(|i| Instant::now().checked_duration_since(i))
}
/// Update retry-after and rate limits based on an API response.
@@ -153,13 +165,25 @@ impl RateLimit {
}
// Get retry after header. Only care if it exists.
- let retry_after_header = response.headers()
+ let retry_after_header = response
+ .headers()
.get(reqwest::header::RETRY_AFTER)
- .and_then(|h| h
- .to_str()
- .map_err(|e| log::error!("Failed to read retry-after header as visible ASCII string: {:?}.", e)).ok())?;
+ .and_then(|h| {
+ h.to_str()
+ .map_err(|e| {
+ log::error!(
+ "Failed to read retry-after header as visible ASCII string: {:?}.",
+ e
+ )
+ })
+ .ok()
+ })?;
- log::info!("429 response, rate limit {:?}, retry-after {} secs.", self.rate_limit_type, retry_after_header);
+ log::info!(
+ "429 response, rate limit {:?}, retry-after {} secs.",
+ self.rate_limit_type,
+ retry_after_header
+ );
// Header currently only returns ints, but float is more general. Can be zero.
let retry_after_secs = retry_after_header
@@ -179,10 +203,30 @@ impl RateLimit {
fn on_response_rate_limits(&self, config: &RiotApiConfig, response: &Response) {
// Check if rate limits changed.
let headers = response.headers();
- let limit_header_opt = headers.get(self.rate_limit_type.limit_header())
- .and_then(|h| h.to_str().map_err(|e| log::error!("Failed to read limit header as visible ASCII string: {:?}.", e)).ok());
- let count_header_opt = headers.get(self.rate_limit_type.count_header())
- .and_then(|h| h.to_str().map_err(|e| log::error!("Failed to read count header as visible ASCII string: {:?}.", e)).ok());
+ let limit_header_opt = headers
+ .get(self.rate_limit_type.limit_header())
+ .and_then(|h| {
+ h.to_str()
+ .map_err(|e| {
+ log::error!(
+ "Failed to read limit header as visible ASCII string: {:?}.",
+ e
+ )
+ })
+ .ok()
+ });
+ let count_header_opt = headers
+ .get(self.rate_limit_type.count_header())
+ .and_then(|h| {
+ h.to_str()
+ .map_err(|e| {
+ log::error!(
+ "Failed to read count header as visible ASCII string: {:?}.",
+ e
+ )
+ })
+ .ok()
+ });
if let (Some(limit_header), Some(count_header)) = (limit_header_opt, count_header_opt) {
{
@@ -193,7 +237,8 @@ impl RateLimit {
// Buckets require updating. Upgrade to write lock.
let mut buckets = RwLockUpgradableReadGuard::upgrade(buckets);
- *buckets = buckets_from_header(config, limit_header, count_header, self.rate_limit_type);
+ *buckets =
+ buckets_from_header(config, limit_header, count_header, self.rate_limit_type);
}
// Notify waiters that buckets have updated (after unlocking).
self.update_notify.notify_waiters();
@@ -207,7 +252,11 @@ fn buckets_require_updating(limit_header: &str, buckets: &[VectorTokenBucket]) -
}
for (limit_header_entry, bucket) in limit_header.split(',').zip(buckets) {
// limit_header_entry "100:60" means 100 req per 60 sec.
- let bucket_entry = format!("{}:{}", bucket.get_total_limit(), bucket.get_bucket_duration().as_secs());
+ let bucket_entry = format!(
+ "{}:{}",
+ bucket.get_total_limit(),
+ bucket.get_bucket_duration().as_secs()
+ );
if limit_header_entry != bucket_entry {
return true;
}
@@ -215,7 +264,12 @@ fn buckets_require_updating(limit_header: &str, buckets: &[VectorTokenBucket]) -
false
}
-fn buckets_from_header(config: &RiotApiConfig, limit_header: &str, count_header: &str, rate_limit_type: RateLimitType) -> Vec {
+fn buckets_from_header(
+ config: &RiotApiConfig,
+ limit_header: &str,
+ count_header: &str,
+ rate_limit_type: RateLimitType,
+) -> Vec {
// Limits: "20000:10,1200000:600"
// Counts: "7:10,58:600"
let size = limit_header.split(',').count();
@@ -238,11 +292,20 @@ fn buckets_from_header(config: &RiotApiConfig, limit_header: &str, count_header:
let limit_f32 = limit as f32;
let scaled_burst_factor = config.burst_factor * limit_f32 / (limit_f32 + 1.0);
- let bucket = VectorTokenBucket::new(Duration::from_secs(limit_secs), limit,
- config.duration_overhead, scaled_burst_factor, rate_usage_factor);
+ let bucket = VectorTokenBucket::new(
+ Duration::from_secs(limit_secs),
+ limit,
+ config.duration_overhead,
+ scaled_burst_factor,
+ rate_usage_factor,
+ );
bucket.get_tokens(count);
out.push(bucket);
}
- log::debug!("Set buckets to {} limit, {} count.", limit_header, count_header);
+ log::debug!(
+ "Set buckets to {} limit, {} count.",
+ limit_header,
+ count_header
+ );
out
}
diff --git a/riven/src/req/regional_requester.rs b/riven/src/req/regional_requester.rs
index 58a6c89..ddb3b11 100644
--- a/riven/src/req/regional_requester.rs
+++ b/riven/src/req/regional_requester.rs
@@ -1,14 +1,14 @@
use std::future::Future;
use std::sync::Arc;
-#[cfg(not(feature="tracing"))]
-use log as log;
-#[cfg(feature="tracing")]
+#[cfg(not(feature = "tracing"))]
+use log;
+#[cfg(feature = "tracing")]
use tracing as log;
#[cfg(feature = "tracing")]
use tracing::Instrument;
-use reqwest::{ StatusCode, RequestBuilder };
+use reqwest::{RequestBuilder, StatusCode};
use crate::util::InsertOnlyCHashMap;
use crate::ResponseInfo;
@@ -40,15 +40,17 @@ impl RegionalRequester {
}
}
- pub fn execute<'a>(self: Arc,
+ pub fn execute<'a>(
+ self: Arc,
config: &'a RiotApiConfig,
- method_id: &'static str, request: RequestBuilder)
- -> impl Future