forked from mirror/Riven
Compare commits
4 Commits
v/2.x.x
...
users/ming
Author | SHA1 | Date |
---|---|---|
Mingwei Samuel | 30401e6004 | |
Mingwei Samuel | ded6a5af07 | |
Mingwei Samuel | 83a4b456d0 | |
Mingwei Samuel | 31c2794863 |
|
@ -90,31 +90,31 @@ jobs:
|
|||
RUSTLOG: riven=trace
|
||||
RGAPI_KEY: ${{ secrets.RGAPI_KEY }}
|
||||
|
||||
# lints:
|
||||
# name: Lints
|
||||
# needs: pre_job
|
||||
# if: ${{ needs.pre_job.outputs.should_skip != 'true' }}
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - name: Checkout sources
|
||||
# uses: actions/checkout@v2
|
||||
lints:
|
||||
name: Lints
|
||||
needs: pre_job
|
||||
if: ${{ needs.pre_job.outputs.should_skip != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# - name: Install nightly toolchain
|
||||
# uses: actions-rs/toolchain@v1
|
||||
# with:
|
||||
# profile: minimal
|
||||
# toolchain: nightly
|
||||
# override: true
|
||||
# components: rustfmt, clippy
|
||||
- name: Install nightly toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: nightly
|
||||
override: true
|
||||
components: rustfmt, clippy
|
||||
|
||||
# - name: Run cargo fmt
|
||||
# uses: actions-rs/cargo@v1
|
||||
# with:
|
||||
# command: fmt
|
||||
# args: --all -- --check
|
||||
- name: Run cargo fmt
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
|
||||
# - name: Run cargo clippy
|
||||
# uses: actions-rs/cargo@v1
|
||||
# with:
|
||||
# command: clippy
|
||||
# args: -- -D warnings
|
||||
- name: Run cargo clippy
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: -- -D warnings
|
||||
|
|
|
@ -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<Body> {
|
||||
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<Body>) -> Result<Response<Body>, 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,
|
||||
};
|
||||
|
||||
|
@ -91,32 +108,38 @@ async fn handle_request(req: Request<Body>) -> Result<Response<Body>, Infallible
|
|||
// 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());
|
||||
*out_response.body_mut() = Body::from(bytes);
|
||||
}
|
||||
Ok(out_response)
|
||||
}
|
||||
|
||||
/// 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<dyn std::error::Error + Send + Sync>> {
|
|||
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);
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "riven"
|
||||
version = "2.17.0"
|
||||
version = "2.18.0"
|
||||
authors = ["Mingwei Samuel <mingwei.samuel@gmail.com>"]
|
||||
repository = "https://github.com/MingweiSamuel/Riven"
|
||||
description = "Riot Games API Library"
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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,11 +12,22 @@ 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
|
||||
|
@ -29,7 +40,7 @@ pub enum Division {
|
|||
/// Division 4, the fourth and lowest division since 2019.
|
||||
IV = 4,
|
||||
/// Division 5, the lowest division, only used before 2019.
|
||||
#[deprecated(note="Removed for 2019.")]
|
||||
#[deprecated(note = "Removed for 2019.")]
|
||||
V = 5,
|
||||
}
|
||||
|
||||
|
@ -39,7 +50,7 @@ pub enum Division {
|
|||
impl IntoEnumIterator for Division {
|
||||
type Iterator = std::iter::Copied<std::slice::Iter<'static, Self>>;
|
||||
fn iter() -> Self::Iterator {
|
||||
[ Self::I, Self::II, Self::III, Self::IV ].iter().copied()
|
||||
[Self::I, Self::II, Self::III, Self::IV].iter().copied()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ macro_rules! serde_strum_unknown {
|
|||
impl<'de> serde::de::Deserialize<'de> for $name {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
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 {
|
||||
<&str>::deserialize(deserializer)
|
||||
.map(Into::into)
|
||||
.and_then(|item| match item {
|
||||
Self::UNKNOWN(unknown) => Err(serde::de::Error::unknown_variant(
|
||||
&*unknown,
|
||||
<Self as strum::VariantNames>::VARIANTS,
|
||||
)),
|
||||
other => Ok(other),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! arr {
|
||||
|
|
|
@ -8,35 +8,43 @@
|
|||
|
||||
mod macros;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod champion;
|
||||
pub use champion::*;
|
||||
|
||||
mod division;
|
||||
pub use division::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod game_mode;
|
||||
pub use game_mode::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod game_type;
|
||||
pub use game_type::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod map;
|
||||
pub use map::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod queue_type;
|
||||
pub use queue_type::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod queue;
|
||||
pub use queue::*;
|
||||
|
||||
pub mod ranks;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod route;
|
||||
pub use route::*;
|
||||
|
||||
mod route_ext;
|
||||
pub use route_ext::*;
|
||||
|
||||
#[rustfmt::skip]
|
||||
mod season;
|
||||
pub use season::*;
|
||||
|
||||
|
|
|
@ -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,8 +20,7 @@ impl Iterator for Iter {
|
|||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// 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(|| {
|
||||
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();
|
||||
|
@ -36,7 +35,7 @@ impl Iterator for Iter {
|
|||
self.div_iter = Division::iter();
|
||||
}
|
||||
|
||||
Some(( tier, div ))
|
||||
Some((tier, div))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -66,25 +65,24 @@ 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());
|
||||
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!(Some((Tier::IRON, Division::IV)), last);
|
||||
assert_eq!(None, it.next());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn non_apex_iter() {
|
||||
let mut it = super::non_apex_iter();
|
||||
|
|
|
@ -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<Self, num_enum::TryFromPrimitiveError<Self>> {
|
||||
fn try_from_primitive(
|
||||
number: Self::Primitive,
|
||||
) -> Result<Self, num_enum::TryFromPrimitiveError<Self>> {
|
||||
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<Self, Self::Err> {
|
||||
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<Item = Self> {
|
||||
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]
|
||||
|
|
|
@ -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).
|
||||
|
|
|
@ -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,11 +10,24 @@ 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`.
|
||||
|
@ -77,7 +90,11 @@ impl Tier {
|
|||
|
||||
/// Converts UNRANKED to None and all ranked tiers to Some(...).
|
||||
pub fn to_ranked(self) -> Option<Self> {
|
||||
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<std::slice::Iter<'static, Self>>;
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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<T> = std::result::Result<T, RiotApiError>;
|
||||
|
@ -17,7 +17,12 @@ pub struct RiotApiError {
|
|||
status_code: Option<StatusCode>,
|
||||
}
|
||||
impl RiotApiError {
|
||||
pub(crate) fn new(reqwest_error: Error, retries: u8, response: Option<Response>, status_code: Option<StatusCode>) -> Self {
|
||||
pub(crate) fn new(
|
||||
reqwest_error: Error,
|
||||
retries: u8,
|
||||
response: Option<Response>,
|
||||
status_code: Option<StatusCode>,
|
||||
) -> Self {
|
||||
Self {
|
||||
reqwest_error,
|
||||
retries,
|
||||
|
|
|
@ -177,12 +177,12 @@
|
|||
// Re-exported reqwest types.
|
||||
pub use reqwest;
|
||||
|
||||
|
||||
mod config;
|
||||
pub use config::RiotApiConfig;
|
||||
|
||||
pub mod consts;
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub mod endpoints;
|
||||
|
||||
mod error;
|
||||
|
@ -190,6 +190,7 @@ pub use error::*;
|
|||
|
||||
pub mod meta;
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub mod models;
|
||||
mod models_impls;
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -1,19 +1,17 @@
|
|||
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(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 +40,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 +63,19 @@ impl RateLimit {
|
|||
}
|
||||
}
|
||||
|
||||
fn acquire_both_or_duration(app_rate_limit: &Self, method_rate_limit: &Self) -> Option<Duration> {
|
||||
fn acquire_both_or_duration(
|
||||
app_rate_limit: &Self,
|
||||
method_rate_limit: &Self,
|
||||
) -> Option<Duration> {
|
||||
// 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 +92,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<Duration> {
|
||||
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 +163,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,21 +201,42 @@ 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) {
|
||||
{
|
||||
let buckets = self.buckets.upgradable_read();
|
||||
if !buckets_require_updating(limit_header, &*buckets) {
|
||||
if !buckets_require_updating(limit_header, &buckets) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 +250,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 +262,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<VectorTokenBucket> {
|
||||
fn buckets_from_header(
|
||||
config: &RiotApiConfig,
|
||||
limit_header: &str,
|
||||
count_header: &str,
|
||||
rate_limit_type: RateLimitType,
|
||||
) -> Vec<VectorTokenBucket> {
|
||||
// Limits: "20000:10,1200000:600"
|
||||
// Counts: "7:10,58:600"
|
||||
let size = limit_header.split(',').count();
|
||||
|
@ -238,11 +290,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
|
||||
}
|
||||
|
|
|
@ -1,14 +1,12 @@
|
|||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(not(feature="tracing"))]
|
||||
use log as log;
|
||||
#[cfg(feature="tracing")]
|
||||
#[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,19 +38,21 @@ impl RegionalRequester {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn execute<'a>(self: Arc<Self>,
|
||||
pub fn execute<'a>(
|
||||
self: Arc<Self>,
|
||||
config: &'a RiotApiConfig,
|
||||
method_id: &'static str, request: RequestBuilder)
|
||||
-> impl Future<Output = Result<ResponseInfo>> + 'a
|
||||
{
|
||||
method_id: &'static str,
|
||||
request: RequestBuilder,
|
||||
) -> impl Future<Output = Result<ResponseInfo>> + 'a {
|
||||
async move {
|
||||
let mut retries: u8 = 0;
|
||||
loop {
|
||||
let method_rate_limit: Arc<RateLimit> = self.method_rate_limits
|
||||
let method_rate_limit: Arc<RateLimit> = self
|
||||
.method_rate_limits
|
||||
.get_or_insert_with(method_id, || RateLimit::new(RateLimitType::Method));
|
||||
|
||||
// Rate limit.
|
||||
let rate_limit = RateLimit::acquire_both(&self.app_rate_limit, &*method_rate_limit);
|
||||
let rate_limit = RateLimit::acquire_both(&self.app_rate_limit, &method_rate_limit);
|
||||
#[cfg(feature = "tracing")]
|
||||
let rate_limit = rate_limit.instrument(tracing::info_span!("rate_limit"));
|
||||
rate_limit.await;
|
||||
|
@ -79,24 +79,40 @@ impl RegionalRequester {
|
|||
let status_none = Self::NONE_STATUS_CODES.contains(&status);
|
||||
// Success case.
|
||||
if status.is_success() || status_none {
|
||||
log::trace!("Response {} (retried {} times), success, returning result.", status, retries);
|
||||
log::trace!(
|
||||
"Response {} (retried {} times), success, returning result.",
|
||||
status,
|
||||
retries
|
||||
);
|
||||
break Ok(ResponseInfo {
|
||||
response,
|
||||
retries,
|
||||
status_none,
|
||||
});
|
||||
}
|
||||
let err = response.error_for_status_ref().err().unwrap_or_else(
|
||||
|| panic!("Unhandlable response status code, neither success nor failure: {}.", status));
|
||||
let err = response.error_for_status_ref().err().unwrap_or_else(|| {
|
||||
panic!(
|
||||
"Unhandlable response status code, neither success nor failure: {}.",
|
||||
status
|
||||
)
|
||||
});
|
||||
// Failure, may or may not be retryable.
|
||||
// Not-retryable: no more retries or 4xx or ? (3xx, redirects exceeded).
|
||||
// Retryable: retries remaining, and 429 or 5xx.
|
||||
if retries >= config.retries ||
|
||||
(StatusCode::TOO_MANY_REQUESTS != status
|
||||
&& !status.is_server_error())
|
||||
if retries >= config.retries
|
||||
|| (StatusCode::TOO_MANY_REQUESTS != status && !status.is_server_error())
|
||||
{
|
||||
log::debug!("Response {} (retried {} times), failure, returning error.", status, retries);
|
||||
break Err(RiotApiError::new(err, retries, Some(response), Some(status)));
|
||||
log::debug!(
|
||||
"Response {} (retried {} times), failure, returning error.",
|
||||
status,
|
||||
retries
|
||||
);
|
||||
break Err(RiotApiError::new(
|
||||
err,
|
||||
retries,
|
||||
Some(response),
|
||||
Some(status),
|
||||
));
|
||||
}
|
||||
|
||||
// Is retryable, do exponential backoff if retry-after wasn't specified.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use std::fmt;
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::time::Duration;
|
||||
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
|
@ -58,32 +58,41 @@ pub struct VectorTokenBucket {
|
|||
/// Limit allowed per burst_duration, for burst factor.
|
||||
burst_limit: usize,
|
||||
|
||||
|
||||
/// Record of timestamps (synchronized).
|
||||
timestamps: Mutex<VecDeque<Instant>>,
|
||||
}
|
||||
|
||||
impl VectorTokenBucket {
|
||||
pub fn new(duration: Duration, given_total_limit: usize,
|
||||
duration_overhead: Duration, burst_factor: f32,
|
||||
rate_usage_factor: f32) -> Self
|
||||
{
|
||||
debug_assert!(0.0 < rate_usage_factor && rate_usage_factor <= 1.0,
|
||||
"BAD rate_usage_factor {}.", rate_usage_factor);
|
||||
debug_assert!(0.0 < burst_factor && burst_factor <= 1.0,
|
||||
"BAD burst_factor {}.", burst_factor);
|
||||
pub fn new(
|
||||
duration: Duration,
|
||||
given_total_limit: usize,
|
||||
duration_overhead: Duration,
|
||||
burst_factor: f32,
|
||||
rate_usage_factor: f32,
|
||||
) -> Self {
|
||||
debug_assert!(
|
||||
0.0 < rate_usage_factor && rate_usage_factor <= 1.0,
|
||||
"BAD rate_usage_factor {}.",
|
||||
rate_usage_factor
|
||||
);
|
||||
debug_assert!(
|
||||
0.0 < burst_factor && burst_factor <= 1.0,
|
||||
"BAD burst_factor {}.",
|
||||
burst_factor
|
||||
);
|
||||
// Float ops may lose precision, but nothing should be that precise.
|
||||
// API always uses round numbers, burst_factor is frac of 256.
|
||||
|
||||
// Adjust everything by rate_usage_factor.
|
||||
let total_limit = std::cmp::max(1,
|
||||
(given_total_limit as f32 * rate_usage_factor).floor() as usize);
|
||||
let total_limit = std::cmp::max(
|
||||
1,
|
||||
(given_total_limit as f32 * rate_usage_factor).floor() as usize,
|
||||
);
|
||||
|
||||
// Effective duration.
|
||||
let d_eff = duration + duration_overhead;
|
||||
let burst_duration = d_eff.mul_f32(burst_factor);
|
||||
let burst_limit = std::cmp::max(1,
|
||||
(total_limit as f32 * burst_factor).floor() as usize);
|
||||
let burst_limit = std::cmp::max(1, (total_limit as f32 * burst_factor).floor() as usize);
|
||||
debug_assert!(burst_limit <= total_limit);
|
||||
|
||||
VectorTokenBucket {
|
||||
|
@ -113,21 +122,23 @@ impl VectorTokenBucket {
|
|||
}
|
||||
|
||||
impl TokenBucket for VectorTokenBucket {
|
||||
|
||||
fn get_delay(&self) -> Option<Duration> {
|
||||
let timestamps = self.update_get_timestamps();
|
||||
|
||||
// Full rate limit.
|
||||
if let Some(ts) = timestamps.get(self.total_limit - 1) {
|
||||
// Return amount of time needed for timestamp `ts` to go away.
|
||||
Instant::now().checked_duration_since(*ts)
|
||||
.and_then(|passed_dur| (self.duration + self.duration_overhead)
|
||||
.checked_sub(passed_dur))
|
||||
Instant::now()
|
||||
.checked_duration_since(*ts)
|
||||
.and_then(|passed_dur| {
|
||||
(self.duration + self.duration_overhead).checked_sub(passed_dur)
|
||||
})
|
||||
}
|
||||
// Otherwise burst rate limit.
|
||||
else if let Some(ts) = timestamps.get(self.burst_limit - 1) {
|
||||
// Return amount of time needed for timestamp `ts` to go away.
|
||||
Instant::now().checked_duration_since(*ts)
|
||||
Instant::now()
|
||||
.checked_duration_since(*ts)
|
||||
.and_then(|passed_dur| self.burst_duration.checked_sub(passed_dur))
|
||||
}
|
||||
// No delay needed.
|
||||
|
@ -173,6 +184,12 @@ impl TokenBucket for VectorTokenBucket {
|
|||
|
||||
impl fmt::Debug for VectorTokenBucket {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "({}/{}:{})", self.timestamps.lock().len(), self.total_limit, self.duration.as_secs())
|
||||
write!(
|
||||
f,
|
||||
"({}/{}:{})",
|
||||
self.timestamps.lock().len(),
|
||||
self.total_limit,
|
||||
self.duration.as_secs()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,19 +1,17 @@
|
|||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(not(feature="tracing"))]
|
||||
use log as log;
|
||||
#[cfg(feature="tracing")]
|
||||
#[cfg(feature = "tracing")]
|
||||
use tracing as log;
|
||||
|
||||
use reqwest::{ Client, RequestBuilder, Method };
|
||||
use reqwest::{Client, Method, RequestBuilder};
|
||||
|
||||
use crate::Result;
|
||||
use crate::ResponseInfo;
|
||||
use crate::RiotApiConfig;
|
||||
use crate::RiotApiError;
|
||||
use crate::req::RegionalRequester;
|
||||
use crate::util::InsertOnlyCHashMap;
|
||||
use crate::ResponseInfo;
|
||||
use crate::Result;
|
||||
use crate::RiotApiConfig;
|
||||
use crate::RiotApiError;
|
||||
|
||||
/// For retrieving data from the Riot Games API.
|
||||
///
|
||||
|
@ -59,11 +57,15 @@ impl RiotApi {
|
|||
/// Constructs a new instance from an API key (e.g. `"RGAPI-01234567-89ab-cdef-0123-456789abcdef"`) or a [RiotApiConfig].
|
||||
pub fn new(config: impl Into<RiotApiConfig>) -> Self {
|
||||
let mut config = config.into();
|
||||
let client_builder = config.client_builder.take()
|
||||
let client_builder = config
|
||||
.client_builder
|
||||
.take()
|
||||
.expect("CLIENT_BUILDER IN CONFIG SHOULD NOT BE NONE.");
|
||||
Self {
|
||||
config,
|
||||
client: client_builder.build().expect("Failed to create client from builder."),
|
||||
client: client_builder
|
||||
.build()
|
||||
.expect("Failed to create client from builder."),
|
||||
regional_requesters: InsertOnlyCHashMap::new(),
|
||||
}
|
||||
}
|
||||
|
@ -78,7 +80,8 @@ impl RiotApi {
|
|||
/// * `path` - The URL path, appended to the base URL.
|
||||
pub fn request(&self, method: Method, region_platform: &str, path: &str) -> RequestBuilder {
|
||||
let base_url_platform = self.config.base_url.replace("{}", region_platform);
|
||||
self.client.request(method, format!("{}{}", base_url_platform, path))
|
||||
self.client
|
||||
.request(method, format!("{}{}", base_url_platform, path))
|
||||
}
|
||||
|
||||
/// This method should generally not be used directly. Consider using endpoint wrappers instead.
|
||||
|
@ -92,11 +95,15 @@ impl RiotApi {
|
|||
///
|
||||
/// # Returns
|
||||
/// A future resolving to a `Result` containg either a `T` (success) or a `RiotApiError` (failure).
|
||||
pub async fn execute_val<'a, T: serde::de::DeserializeOwned + 'a>(&'a self,
|
||||
method_id: &'static str, region_platform: &'static str, request: RequestBuilder)
|
||||
-> Result<T>
|
||||
{
|
||||
let rinfo = self.execute_raw(method_id, region_platform, request).await?;
|
||||
pub async fn execute_val<'a, T: serde::de::DeserializeOwned + 'a>(
|
||||
&'a self,
|
||||
method_id: &'static str,
|
||||
region_platform: &'static str,
|
||||
request: RequestBuilder,
|
||||
) -> Result<T> {
|
||||
let rinfo = self
|
||||
.execute_raw(method_id, region_platform, request)
|
||||
.await?;
|
||||
let retries = rinfo.retries;
|
||||
let status = rinfo.response.status();
|
||||
let value = rinfo.response.json::<T>().await;
|
||||
|
@ -114,11 +121,15 @@ impl RiotApi {
|
|||
///
|
||||
/// # Returns
|
||||
/// A future resolving to a `Result` containg either an `Option<T>` (success) or a `RiotApiError` (failure).
|
||||
pub async fn execute_opt<'a, T: serde::de::DeserializeOwned + 'a>(&'a self,
|
||||
method_id: &'static str, region_platform: &'static str, request: RequestBuilder)
|
||||
-> Result<Option<T>>
|
||||
{
|
||||
let rinfo = self.execute_raw(method_id, region_platform, request).await?;
|
||||
pub async fn execute_opt<'a, T: serde::de::DeserializeOwned + 'a>(
|
||||
&'a self,
|
||||
method_id: &'static str,
|
||||
region_platform: &'static str,
|
||||
request: RequestBuilder,
|
||||
) -> Result<Option<T>> {
|
||||
let rinfo = self
|
||||
.execute_raw(method_id, region_platform, request)
|
||||
.await?;
|
||||
if rinfo.status_none {
|
||||
return Ok(None);
|
||||
}
|
||||
|
@ -139,14 +150,20 @@ impl RiotApi {
|
|||
///
|
||||
/// # Returns
|
||||
/// A future resolving to a `Result` containg either `()` (success) or a `RiotApiError` (failure).
|
||||
pub async fn execute(&self,
|
||||
method_id: &'static str, region_platform: &'static str, request: RequestBuilder)
|
||||
-> Result<()>
|
||||
{
|
||||
let rinfo = self.execute_raw(method_id, region_platform, request).await?;
|
||||
pub async fn execute(
|
||||
&self,
|
||||
method_id: &'static str,
|
||||
region_platform: &'static str,
|
||||
request: RequestBuilder,
|
||||
) -> Result<()> {
|
||||
let rinfo = self
|
||||
.execute_raw(method_id, region_platform, request)
|
||||
.await?;
|
||||
let retries = rinfo.retries;
|
||||
let status = rinfo.response.status();
|
||||
rinfo.response.error_for_status()
|
||||
rinfo
|
||||
.response
|
||||
.error_for_status()
|
||||
.map(|_| ())
|
||||
.map_err(|e| RiotApiError::new(e, retries, None, Some(status)))
|
||||
}
|
||||
|
@ -164,17 +181,24 @@ impl RiotApi {
|
|||
///
|
||||
/// # Returns
|
||||
/// A future resolving to a `Result` containg either a `ResponseInfo` (success) or a `RiotApiError` (failure).
|
||||
pub fn execute_raw(&self, method_id: &'static str, region_platform: &'static str, request: RequestBuilder)
|
||||
-> impl Future<Output = Result<ResponseInfo>> + '_
|
||||
{
|
||||
pub fn execute_raw(
|
||||
&self,
|
||||
method_id: &'static str,
|
||||
region_platform: &'static str,
|
||||
request: RequestBuilder,
|
||||
) -> impl Future<Output = Result<ResponseInfo>> + '_ {
|
||||
self.regional_requester(region_platform)
|
||||
.execute(&self.config, method_id, request)
|
||||
}
|
||||
|
||||
/// Get or create the RegionalRequester for the given region.
|
||||
fn regional_requester(&self, region_platform: &'static str) -> Arc<RegionalRequester> {
|
||||
self.regional_requesters.get_or_insert_with(region_platform, || {
|
||||
log::debug!("Creating requester for region platform {}.", region_platform);
|
||||
self.regional_requesters
|
||||
.get_or_insert_with(region_platform, || {
|
||||
log::debug!(
|
||||
"Creating requester for region platform {}.",
|
||||
region_platform
|
||||
);
|
||||
RegionalRequester::new()
|
||||
})
|
||||
}
|
||||
|
|
|
@ -13,7 +13,7 @@ impl<K: Hash + Eq, V> InsertOnlyCHashMap<K, V> {
|
|||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
base: Mutex::new(HashMap::new())
|
||||
base: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -27,10 +27,12 @@ impl<K: Hash + Eq, V> InsertOnlyCHashMap<K, V> {
|
|||
// }
|
||||
|
||||
#[inline]
|
||||
pub fn get_or_insert_with<F: FnOnce() -> V>(&self, key: K, default: F) -> Arc<V>
|
||||
{
|
||||
Arc::clone(self.base.lock()
|
||||
pub fn get_or_insert_with<F: FnOnce() -> V>(&self, key: K, default: F) -> Arc<V> {
|
||||
Arc::clone(
|
||||
self.base
|
||||
.lock()
|
||||
.entry(key)
|
||||
.or_insert_with(|| Arc::new(default())))
|
||||
.or_insert_with(|| Arc::new(default())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,18 +7,18 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
{{~ readme :line }}
|
||||
//! {{= line }}
|
||||
//!{{= line ? (' ' + line) : '' }}
|
||||
{{~}}
|
||||
|
||||
// Re-exported reqwest types.
|
||||
pub use reqwest;
|
||||
|
||||
|
||||
mod config;
|
||||
pub use config::RiotApiConfig;
|
||||
|
||||
pub mod consts;
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub mod endpoints;
|
||||
|
||||
mod error;
|
||||
|
@ -26,6 +26,7 @@ pub use error::*;
|
|||
|
||||
pub mod meta;
|
||||
|
||||
#[rustfmt::skip]
|
||||
pub mod models;
|
||||
mod models_impls;
|
||||
|
||||
|
|
|
@ -18,14 +18,13 @@ static MATCHES: &[&str] = &[
|
|||
"NA1_4052515784",
|
||||
"NA1_4062578191",
|
||||
"NA1_4097036960",
|
||||
|
||||
// New games with `match-v5.ParticipantDto.challenges` field.
|
||||
"NA1_4209556127",
|
||||
"NA1_4212715433",
|
||||
"NA1_4265913704", // `match-v5.ParticipantDto.challenges.mejaisFullStackInTime`
|
||||
];
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
// TODO FAILING since 2022/11/28 https://github.com/MingweiSamuel/Riven/actions/runs/3571320200/jobs/6003088646
|
||||
// // Champion Mastery tests.
|
||||
|
|
|
@ -11,14 +11,14 @@ use riven::consts::*;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::EUW1;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
// Champion Mastery tests.
|
||||
championmastery_getscore_ma5tery: async {
|
||||
let sum = RIOT_API.summoner_v4().get_by_summoner_name(ROUTE, "ma5tery");
|
||||
let sum = sum.await.map_err(|e| e.to_string())?.ok_or_else(|| "Failed to get summoner".to_owned())?;
|
||||
|
||||
let p = RIOT_API.champion_mastery_v4().get_champion_mastery_score(ROUTE, &*sum.id);
|
||||
let p = RIOT_API.champion_mastery_v4().get_champion_mastery_score(ROUTE, &sum.id);
|
||||
let s = p.await.map_err(|e| e.to_string())?;
|
||||
rassert!((969..=1000).contains(&s), "Unexpected ma5tery score: {}.", s);
|
||||
Ok(())
|
||||
|
@ -27,7 +27,7 @@ async_tests!{
|
|||
let sum = RIOT_API.summoner_v4().get_by_summoner_name(ROUTE, "ma5tery");
|
||||
let sum = sum.await.map_err(|e| e.to_string())?.ok_or_else(|| "Failed to get summoner".to_owned())?;
|
||||
|
||||
let p = RIOT_API.champion_mastery_v4().get_all_champion_masteries(ROUTE, &*sum.id);
|
||||
let p = RIOT_API.champion_mastery_v4().get_all_champion_masteries(ROUTE, &sum.id);
|
||||
let s = p.await.map_err(|e| e.to_string())?;
|
||||
rassert!(s.len() >= 142, "Expected masteries: {}.", s.len());
|
||||
Ok(())
|
||||
|
|
|
@ -53,13 +53,13 @@ async_tests! {
|
|||
tft_combo: async {
|
||||
let top_players = RIOT_API.tft_league_v1().get_top_rated_ladder(ROUTE, QueueType::RANKED_TFT_TURBO);
|
||||
let top_players = top_players.await.map_err(|e| e.to_string())?;
|
||||
rassert!(0 < top_players.len());
|
||||
rassert!(!top_players.is_empty());
|
||||
let top_player_entry = &top_players[0];
|
||||
let top_player = RIOT_API.tft_summoner_v1().get_by_summoner_id(ROUTE, &*top_player_entry.summoner_id);
|
||||
let top_player = RIOT_API.tft_summoner_v1().get_by_summoner_id(ROUTE, &top_player_entry.summoner_id);
|
||||
let top_player = top_player.await.map_err(|e| e.to_string())?;
|
||||
println!("Top player is {} with `puuid` {}.", top_player.name, top_player.puuid);
|
||||
let match_ids = RIOT_API.tft_match_v1().get_match_ids_by_puuid(
|
||||
ROUTE.to_regional(), &*top_player.puuid, Some(10), None, None, None);
|
||||
ROUTE.to_regional(), &top_player.puuid, Some(10), None, None, None);
|
||||
let match_ids = match_ids.await.map_err(|e| e.to_string())?;
|
||||
tft_match_v1_get(ROUTE.to_regional(), &*match_ids).await?;
|
||||
Ok(())
|
||||
|
|
|
@ -40,7 +40,7 @@ async_tests! {
|
|||
// Spot check 10% for `player-data`.
|
||||
for entry in leaderboard.iter().step_by(10)
|
||||
{
|
||||
let _player_data = RIOT_API.lol_challenges_v1().get_player_data(ROUTE, &*entry.puuid)
|
||||
let _player_data = RIOT_API.lol_challenges_v1().get_player_data(ROUTE, &entry.puuid)
|
||||
.await.map_err(|e| format!("Failed to get player data PUUID {}: {}", entry.puuid, e))?;
|
||||
}
|
||||
|
||||
|
|
|
@ -13,13 +13,18 @@ use riven::models::summoner_v4::*;
|
|||
fn validate_summoners(s1: Summoner, s2: Summoner) -> Result<(), String> {
|
||||
rassert_eq!(s1.name, s2.name, "Names didn't match {}.", "");
|
||||
rassert_eq!(s1.id, s2.id, "SummonerId didn't match {}.", "");
|
||||
rassert_eq!(s1.account_id, s2.account_id, "AccountId didn't match {}.", "");
|
||||
rassert_eq!(
|
||||
s1.account_id,
|
||||
s2.account_id,
|
||||
"AccountId didn't match {}.",
|
||||
""
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::NA1;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
// Summoner tests.
|
||||
summoner_double: async {
|
||||
|
@ -53,10 +58,10 @@ async_tests!{
|
|||
// summoner must have double-up rank.
|
||||
league_getforsummoner_tftbug: async {
|
||||
// TODO(mingwei): get summoner from leaderboard to avoid updating this all the time.
|
||||
const SUMMONER_NAME: &'static str = "Vincentscc";
|
||||
const SUMMONER_NAME: &str = "Vincentscc";
|
||||
let summoner_fut = RIOT_API.summoner_v4().get_by_summoner_name(ROUTE, SUMMONER_NAME);
|
||||
let summoner = summoner_fut.await.map_err(|e| e.to_string())?.ok_or_else(|| format!("Failed to get \"{}\"", SUMMONER_NAME))?;
|
||||
let league_fut = RIOT_API.league_v4().get_league_entries_for_summoner(ROUTE, &*summoner.id);
|
||||
let league_fut = RIOT_API.league_v4().get_league_entries_for_summoner(ROUTE, &summoner.id);
|
||||
let leagues = league_fut.await.map_err(|e| e.to_string())?;
|
||||
let tft_league = leagues.iter().find(|league| QueueType::RANKED_TFT_DOUBLE_UP == league.queue_type);
|
||||
rassert!(tft_league.is_some());
|
||||
|
|
|
@ -11,7 +11,7 @@ use riven::consts::*;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::PH2;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
status: async {
|
||||
let p = RIOT_API.lol_status_v4().get_platform_data(ROUTE);
|
||||
|
|
|
@ -11,7 +11,7 @@ use riven::consts::*;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::SG2;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
status: async {
|
||||
let p = RIOT_API.lol_status_v4().get_platform_data(ROUTE);
|
||||
|
|
|
@ -11,7 +11,7 @@ use riven::consts::*;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::TH2;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
status: async {
|
||||
let p = RIOT_API.lol_status_v4().get_platform_data(ROUTE);
|
||||
|
|
|
@ -12,8 +12,7 @@ use riven::models::summoner_v4::Summoner;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::TR1;
|
||||
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
league_summoner_bulk_test: async {
|
||||
let p = RIOT_API.league_v4().get_challenger_league(ROUTE, QueueType::RANKED_SOLO_5x5);
|
||||
|
|
|
@ -11,7 +11,7 @@ use riven::consts::*;
|
|||
|
||||
const ROUTE: PlatformRoute = PlatformRoute::VN2;
|
||||
|
||||
async_tests!{
|
||||
async_tests! {
|
||||
my_runner {
|
||||
status: async {
|
||||
let p = RIOT_API.lol_status_v4().get_platform_data(ROUTE);
|
||||
|
|
|
@ -23,7 +23,7 @@ pub async fn league_v4_match_v5_latest_combo(route: PlatformRoute) -> Result<(),
|
|||
.get_challenger_league(route, QueueType::RANKED_SOLO_5x5);
|
||||
let challenger_league = challenger_future.await.map_err(|e| e.to_string())?;
|
||||
|
||||
if &QueueType::RANKED_SOLO_5x5 != &challenger_league.queue {
|
||||
if QueueType::RANKED_SOLO_5x5 != challenger_league.queue {
|
||||
return Err(format!("Unexpected `queue`: {}", challenger_league.queue));
|
||||
}
|
||||
if challenger_league.entries.is_empty() {
|
||||
|
@ -42,7 +42,7 @@ pub async fn league_v4_match_v5_latest_combo(route: PlatformRoute) -> Result<(),
|
|||
|
||||
let match_ids_future = RIOT_API.match_v5().get_match_ids_by_puuid(
|
||||
route.to_regional(),
|
||||
&*summoner_info.puuid,
|
||||
&summoner_info.puuid,
|
||||
Some(5),
|
||||
None,
|
||||
None,
|
||||
|
|
Loading…
Reference in New Issue