detached http client from context struct
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Paul 2023-05-06 10:36:50 +02:00
parent 89c6796935
commit cd33f9cf35
4 changed files with 43 additions and 53 deletions

View File

@ -24,7 +24,6 @@ const WEB_CLIENT_TIMEOUT: i64 = 5;
pub struct Context { pub struct Context {
pub blocklist: HashMap<String, BlockIpData>, pub blocklist: HashMap<String, BlockIpData>,
pub cfg: Config, pub cfg: Config,
pub client: Client,
pub discovery: Discovery, pub discovery: Discovery,
pub flags: Flags, pub flags: Flags,
pub hostname: String, pub hostname: String,
@ -66,17 +65,6 @@ impl Context {
version: "1.0".to_string(), version: "1.0".to_string(),
urls: HashMap::new(), urls: HashMap::new(),
}, },
client: Client::builder()
.user_agent(format!(
"{}/{}@{}/{}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
GIT_VERSION,
gethostname(false)
))
.timeout(Duration::seconds(WEB_CLIENT_TIMEOUT).to_std().unwrap())
.build()
.unwrap(),
sas: HashMap::new(), sas: HashMap::new(),
instance: Box::new(Inotify::init(InitFlags::empty()).unwrap()), instance: Box::new(Inotify::init(InitFlags::empty()).unwrap()),
blocklist: HashMap::new(), blocklist: HashMap::new(),
@ -113,8 +101,7 @@ impl Context {
#[allow(dead_code)] #[allow(dead_code)]
pub async fn discovery(&self) -> Result<Discovery, ReqError> { pub async fn discovery(&self) -> Result<Discovery, ReqError> {
let resp: Result<Response, ReqError> = self let resp: Result<Response, ReqError> = httpclient()
.client
.get(format!("{server}/discovery", server = self.flags.server)) .get(format!("{server}/discovery", server = self.flags.server))
.send() .send()
.await; .await;
@ -135,7 +122,7 @@ impl Context {
} }
let mut last_in_err = false; let mut last_in_err = false;
loop { loop {
let res = self.cfg.load(self.clone()).await; let res = self.cfg.load(&self.flags.server).await;
match res { match res {
Ok(()) => { Ok(()) => {
if last_in_err { if last_in_err {
@ -365,20 +352,17 @@ impl Config {
} }
} }
pub async fn load(&mut self, ctx: Context) -> Result<(), ReqError> { pub async fn load(&mut self, server: &String) -> Result<(), ReqError> {
self.get_global_config(&ctx).await?; self.get_global_config(server).await?;
self.get_trustnets(&ctx).await?; self.get_trustnets(server).await?;
self.get_sets(&ctx).await?; self.get_sets(server).await?;
self.get_ws_config(&ctx).await?; self.get_ws_config(server).await?;
Ok(()) Ok(())
} }
async fn get_global_config(&mut self, ctx: &Context) -> Result<(), ReqError> { async fn get_global_config(&mut self, server: &String) -> Result<(), ReqError> {
let resp: Result<Response, ReqError> = ctx let resp: Result<Response, ReqError> =
.client httpclient().get(format!("{server}/config")).send().await;
.get(format!("{server}/config", server = ctx.flags.server))
.send()
.await;
let req = match resp { let req = match resp {
Ok(re) => re, Ok(re) => re,
Err(err) => return Err(err), Err(err) => return Err(err),
@ -405,13 +389,9 @@ impl Config {
Ok(()) Ok(())
} }
async fn get_trustnets(&mut self, ctx: &Context) -> Result<(), ReqError> { async fn get_trustnets(&mut self, server: &String) -> Result<(), ReqError> {
let resp: Result<Response, ReqError> = ctx let resp: Result<Response, ReqError> = httpclient()
.client .get(format!("{server}/config/trustlist"))
.get(format!(
"{server}/config/trustlist",
server = ctx.flags.server
))
.send() .send()
.await; .await;
let req = match resp { let req = match resp {
@ -426,10 +406,9 @@ impl Config {
Ok(()) Ok(())
} }
async fn get_sets(&mut self, ctx: &Context) -> Result<(), ReqError> { async fn get_sets(&mut self, server: &String) -> Result<(), ReqError> {
let resp: Result<Response, ReqError> = ctx let resp: Result<Response, ReqError> = httpclient()
.client .get(format!("{server}/config/sets"))
.get(format!("{server}/config/sets", server = ctx.flags.server))
.send() .send()
.await; .await;
let req = match resp { let req = match resp {
@ -446,12 +425,9 @@ impl Config {
Ok(()) Ok(())
} }
async fn get_ws_config(&mut self, ctx: &Context) -> Result<(), ReqError> { async fn get_ws_config(&mut self, server: &String) -> Result<(), ReqError> {
let resp: Result<Response, ReqError> = ctx let resp: Result<Response, ReqError> =
.client httpclient().get(format!("{server}/config/ws")).send().await;
.get(format!("{server}/config/ws", server = ctx.flags.server))
.send()
.await;
let req = match resp { let req = match resp {
Ok(re) => re, Ok(re) => re,
Err(err) => return Err(err), Err(err) => return Err(err),
@ -498,6 +474,21 @@ impl Config {
} }
} }
pub fn httpclient() -> Client {
let client = Client::builder()
.user_agent(format!(
"{}/{}@{}/{}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
GIT_VERSION,
gethostname(false)
))
.timeout(Duration::seconds(WEB_CLIENT_TIMEOUT).to_std().unwrap())
.build()
.unwrap();
client
}
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
pub struct GlobalConfig { pub struct GlobalConfig {
pub key: String, pub key: String,

View File

@ -1,4 +1,4 @@
use crate::config::Context; use crate::config::httpclient;
use crate::utils::gethostname; use crate::utils::gethostname;
use chrono::prelude::*; use chrono::prelude::*;
@ -178,10 +178,9 @@ fn is_trusted(ip: &IpAddr, trustnets: &Vec<IpNet>) -> bool {
false false
} }
pub async fn _get_last(ctx: &Context) -> Result<Vec<IpData>, ReqError> { pub async fn _get_last(server: &String) -> Result<Vec<IpData>, ReqError> {
let resp = ctx let resp = httpclient()
.client .get(format!("{server}/ips/last"))
.get(format!("{server}/ips/last", server = ctx.flags.server))
.query(&[("interval", "3 hours")]) .query(&[("interval", "3 hours")])
.send() .send()
.await; .await;

View File

@ -97,7 +97,7 @@ pub async fn run() {
hostname: gethostname(true), hostname: gethostname(true),
ipdata: ipevent.ipdata, ipdata: ipevent.ipdata,
}; };
send_to_ipbl_api(&ctx.client, &ctx.flags.server, &ipe).await; send_to_ipbl_api(&ctx.flags.server, &ipe).await;
let status = send_to_ipbl_websocket(&mut wssocketrr, &ipe).await; let status = send_to_ipbl_websocket(&mut wssocketrr, &ipe).await;
drop(ctx); drop(ctx);
if !status { if !status {

View File

@ -1,4 +1,4 @@
use crate::config::Context; use crate::config::{httpclient, Context};
use crate::ip::{IpData, IpEvent}; use crate::ip::{IpData, IpEvent};
use crate::utils::sleep_s; use crate::utils::sleep_s;
@ -7,8 +7,9 @@ use reqwest::Error as ReqError;
const MAX_FAILED_API_RATE: u64 = 10; const MAX_FAILED_API_RATE: u64 = 10;
pub async fn send_to_ipbl_api(client: &Client, server: &str, ip: &IpEvent) { pub async fn send_to_ipbl_api(server: &str, ip: &IpEvent) {
let mut i = 0; let mut i = 0;
let client = httpclient();
loop { loop {
match push_ip(&client, &server, &ip.ipdata).await { match push_ip(&client, &server, &ip.ipdata).await {
Ok(_) => { Ok(_) => {
@ -62,8 +63,7 @@ async fn _push_ip_bulk(
}) })
} }
let resp = ctx let resp = httpclient()
.client
.post(format!("{server}/ips", server = ctx.flags.server)) .post(format!("{server}/ips", server = ctx.flags.server))
.json(&data) .json(&data)
.send() .send()