cargo fmt

This commit is contained in:
Daan Boerlage 2023-04-06 18:31:40 +02:00
parent 6c37b2a0b0
commit 6612e020ff
Signed by: daan
GPG key ID: FCE070E1E4956606
12 changed files with 49 additions and 53 deletions

View file

@ -3,10 +3,7 @@ pub mod worlds;
use crate::collectors::PromMetric; use crate::collectors::PromMetric;
fn convert_into_prom_metrics(data: Vec<impl PromMetric>) -> String { fn convert_into_prom_metrics(data: Vec<impl PromMetric>) -> String {
let metrics: Vec<String> = data let metrics: Vec<String> = data.into_iter().map(|w| w.to_metric_string()).collect();
.into_iter()
.map(|w| w.to_metric_string())
.collect();
metrics.join("\n") metrics.join("\n")
} }

View file

@ -1,14 +1,14 @@
use super::convert_into_prom_metrics;
use crate::collectors::stats::get_player_stats;
use axum::extract::Path; use axum::extract::Path;
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::IntoResponse; use axum::response::IntoResponse;
use crate::collectors::stats::get_player_stats;
use super::convert_into_prom_metrics;
pub async fn get_stats(Path(rsn): Path<String>) -> impl IntoResponse { pub async fn get_stats(Path(rsn): Path<String>) -> impl IntoResponse {
let resp = match get_player_stats(&rsn).await { let resp = match get_player_stats(&rsn).await {
Ok(r) => r, Ok(r) => r,
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Nope".to_string()) Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Nope".to_string()),
}; };
(StatusCode::OK, convert_into_prom_metrics(resp)) (StatusCode::OK, convert_into_prom_metrics(resp))
} }

View file

@ -1,13 +1,13 @@
use super::convert_into_prom_metrics;
use crate::collectors::player_count::get_player_count;
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::IntoResponse; use axum::response::IntoResponse;
use crate::collectors::player_count::get_player_count;
use super::convert_into_prom_metrics;
pub async fn get_worlds() -> impl IntoResponse { pub async fn get_worlds() -> impl IntoResponse {
let resp = match get_player_count().await { let resp = match get_player_count().await {
Ok(r) => r, Ok(r) => r,
Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Nope".to_string()) Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "Nope".to_string()),
}; };
(StatusCode::OK, convert_into_prom_metrics(resp)) (StatusCode::OK, convert_into_prom_metrics(resp))
} }

View file

@ -1 +1 @@
pub mod endpoints; pub mod endpoints;

View file

@ -23,6 +23,8 @@ async fn get_runelite_version() -> eyre::Result<String> {
if let Some(latest) = resp.first() { if let Some(latest) = resp.first() {
Ok(latest.name.replace("parent-", "")) Ok(latest.name.replace("parent-", ""))
} else { } else {
Err(eyre::eyre!("Failed to get github tags for runelite version")) Err(eyre::eyre!(
"Failed to get github tags for runelite version"
))
} }
} }

View file

@ -1,7 +1,7 @@
use super::PromMetric;
use serde::{Deserialize, Deserializer}; use serde::{Deserialize, Deserializer};
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use std::str; use std::str;
use super::PromMetric;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct Worlds { pub struct Worlds {
@ -19,8 +19,8 @@ pub enum WorldLocation {
impl<'de> Deserialize<'de> for WorldLocation { impl<'de> Deserialize<'de> for WorldLocation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
let field = i16::deserialize(deserializer)?; let field = i16::deserialize(deserializer)?;
let world = match field { let world = match field {
@ -67,8 +67,8 @@ pub enum WorldType {
impl<'de> Deserialize<'de> for WorldType { impl<'de> Deserialize<'de> for WorldType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
let field = String::deserialize(deserializer)?; let field = String::deserialize(deserializer)?;
let res = match field.as_str() { let res = match field.as_str() {

View file

@ -1,5 +1,5 @@
use std::fmt::{Display, Formatter};
use eyre::eyre; use eyre::eyre;
use std::fmt::{Display, Formatter};
#[derive(Debug)] #[derive(Debug)]
pub struct SkillInfo { pub struct SkillInfo {
@ -67,11 +67,11 @@ const SKILLS: [&str; 25] = [
]; ];
pub async fn get_player_stats(rsn: &str) -> eyre::Result<Vec<SkillInfo>> { pub async fn get_player_stats(rsn: &str) -> eyre::Result<Vec<SkillInfo>> {
let req_url = format!("https://oldschool.runescape.wiki/cors/m=hiscore_oldschool/index_lite.ws?player={}", rsn); let req_url = format!(
let resp = crate::transport::http::new() "https://oldschool.runescape.wiki/cors/m=hiscore_oldschool/index_lite.ws?player={}",
.get(req_url) rsn
.send() );
.await?; let resp = crate::transport::http::new().get(req_url).send().await?;
if resp.status() != 200 { if resp.status() != 200 {
return Err(eyre!("Player not found")); return Err(eyre!("Player not found"));
@ -106,27 +106,18 @@ impl super::PromMetric for SkillInfo {
let lines: Vec<String> = vec![ let lines: Vec<String> = vec![
format!( format!(
"osrs_player_rank{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}", "osrs_player_rank{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}",
self.name, self.name, self.player, self.profile, self.rank
self.player,
self.profile,
self.rank
), ),
format!( format!(
"osrs_player_level{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}", "osrs_player_level{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}",
self.name, self.name, self.player, self.profile, self.level
self.player,
self.profile,
self.level
), ),
format!( format!(
"osrs_player_xp{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}", "osrs_player_xp{{skill=\"{}\",player=\"{}\",profile=\"{}\"}} {}",
self.name, self.name, self.player, self.profile, self.xp
self.player,
self.profile,
self.xp
), ),
]; ];
lines.join("\n") lines.join("\n")
} }
} }

View file

@ -1 +1 @@
pub mod shutdown; pub mod shutdown;

View file

@ -6,7 +6,7 @@ pub async fn shutdown_signal() {
}; };
#[cfg(unix)] #[cfg(unix)]
let terminate = async { let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install signal handler") .expect("failed to install signal handler")
.recv() .recv()
@ -14,7 +14,7 @@ pub async fn shutdown_signal() {
}; };
#[cfg(not(unix))] #[cfg(not(unix))]
let terminate = std::future::pending::<()>(); let terminate = std::future::pending::<()>();
tokio::select! { tokio::select! {
_ = ctrl_c => {}, _ = ctrl_c => {},

View file

@ -3,12 +3,12 @@ mod collectors;
mod lifecycle; mod lifecycle;
mod transport; mod transport;
use axum::{Router, BoxError};
use axum::routing::get;
use axum_tracing_opentelemetry::{response_with_trace_layer, opentelemetry_tracing_layer};
use std::net::SocketAddr;
use api::endpoints::stats; use api::endpoints::stats;
use api::endpoints::worlds; use api::endpoints::worlds;
use axum::routing::get;
use axum::{BoxError, Router};
use axum_tracing_opentelemetry::{opentelemetry_tracing_layer, response_with_trace_layer};
use std::net::SocketAddr;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), BoxError> { async fn main() -> Result<(), BoxError> {

View file

@ -1,9 +1,9 @@
use async_trait::async_trait;
use reqwest::{Request, Response}; use reqwest::{Request, Response};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use reqwest_middleware::{Middleware, Next, Result}; use reqwest_middleware::{Middleware, Next, Result};
use reqwest_retry::{RetryTransientMiddleware, policies::ExponentialBackoff}; use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
use reqwest_tracing::TracingMiddleware; use reqwest_tracing::TracingMiddleware;
use async_trait::async_trait;
pub const USER_AGENT: &str = "osrs-prometheus-exporter"; pub const USER_AGENT: &str = "osrs-prometheus-exporter";
@ -24,14 +24,20 @@ struct DefaultHeaderMiddleware {}
impl DefaultHeaderMiddleware { impl DefaultHeaderMiddleware {
fn new() -> Self { fn new() -> Self {
DefaultHeaderMiddleware{} DefaultHeaderMiddleware {}
} }
} }
#[async_trait] #[async_trait]
impl Middleware for DefaultHeaderMiddleware { impl Middleware for DefaultHeaderMiddleware {
async fn handle(&self, mut req: Request, extensions: &mut task_local_extensions::Extensions, next: Next<'_>) -> Result<Response> { async fn handle(
req.headers_mut().insert("User-Agent", USER_AGENT.parse().unwrap()); &self,
mut req: Request,
extensions: &mut task_local_extensions::Extensions,
next: Next<'_>,
) -> Result<Response> {
req.headers_mut()
.insert("User-Agent", USER_AGENT.parse().unwrap());
next.run(req, extensions).await next.run(req, extensions).await
} }
} }

View file

@ -1 +1 @@
pub mod http; pub mod http;