Skip to content

Commit

Permalink
Return error if sending request timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
SpriteOvO committed Jul 18, 2024
1 parent df9ff2b commit b2cb33f
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 12 deletions.
17 changes: 17 additions & 0 deletions src/helper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::time::Duration;

use anyhow::anyhow;

pub fn reqwest_client() -> anyhow::Result<reqwest::Client> {
reqwest_client_with(|_| {})
}

pub fn reqwest_client_with(
configure: impl FnOnce(&mut reqwest::ClientBuilder),
) -> anyhow::Result<reqwest::Client> {
let mut builder = reqwest::ClientBuilder::new().timeout(Duration::from_secs(30));
configure(&mut builder);
builder
.build()
.map_err(|err| anyhow!("failed to build reqwest client: {err}"))
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod cli;
mod config;
mod helper;
mod notify;
mod platform;
pub mod prop;
Expand Down
3 changes: 2 additions & 1 deletion src/notify/qq/lagrange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serde_json::{self as json, json};
use tokio::time::timeout;

use super::ConfigChat;
use crate::helper;

#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct ConfigLagrange {
Expand Down Expand Up @@ -39,7 +40,7 @@ impl<'a> LagrangeOnebot<'a> {
arguments: Option<json::Value>,
) -> anyhow::Result<Response<T>> {
async {
let mut resp = reqwest::Client::new()
let mut resp = helper::reqwest_client()?
.post(format!(
"http://{}:{}/{method}",
self.config.http_host, self.config.http_port
Expand Down
17 changes: 12 additions & 5 deletions src/notify/telegram/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use serde_json::{self as json, json};
use spdlog::prelude::*;

use super::ConfigChat;
use crate::source::{PostAttachmentImage, PostAttachmentVideo};
use crate::{
helper,
source::{PostAttachmentImage, PostAttachmentVideo},
};

pub struct Request<'a> {
token: &'a str,
Expand Down Expand Up @@ -43,7 +46,7 @@ impl<'a> Request<'a> {
) -> anyhow::Result<Response<T>> {
let url = format!("https://api.telegram.org/bot{}/{}", self.token, method);

let mut client = reqwest::Client::new().post(url);
let mut client = helper::reqwest_client()?.post(url);

if let Some(file_urls) = file_urls {
let form = form_append_json(Form::new(), body.as_object().unwrap());
Expand All @@ -54,9 +57,13 @@ impl<'a> Request<'a> {
.try_fold(form, |form, (i, file_url)| async move {
trace!("downloading media from url '{}'", file_url.url);

let file = reqwest::get(file_url.url).await.map_err(|err| {
anyhow!("failed to download file: {err} from url '{}'", file_url.url)
})?;
let file = helper::reqwest_client()?
.get(file_url.url)
.send()
.await
.map_err(|err| {
anyhow!("failed to download file: {err} from url '{}'", file_url.url)
})?;

let status = file.status();
anyhow::ensure!(
Expand Down
3 changes: 2 additions & 1 deletion src/source/bilibili/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use tokio::sync::Mutex;

use super::{upgrade_to_https, Response};
use crate::{
helper,
platform::{PlatformMetadata, PlatformTrait},
source::{
FetcherTrait, LiveStatus, LiveStatusKind, Status, StatusKind, StatusSource,
Expand Down Expand Up @@ -134,7 +135,7 @@ impl Fetcher {
async fn fetch_live_info(user_id: u64) -> anyhow::Result<RoomData> {
let body = json!({ "uids": [user_id] });

let resp = reqwest::Client::new()
let resp = helper::reqwest_client()?
.post(BILIBILI_LIVE_API)
.json(&body)
.send()
Expand Down
3 changes: 2 additions & 1 deletion src/source/bilibili/space.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use tokio::sync::{Mutex, OnceCell};

use super::{upgrade_to_https, Response};
use crate::{
helper,
platform::{PlatformMetadata, PlatformTrait},
source::{
FetcherTrait, Notification, NotificationKind, Post, PostAttachment, PostAttachmentImage,
Expand Down Expand Up @@ -378,7 +379,7 @@ fn fetch_space_history_impl(
.map(|(name, value)| format!("{}={}", name, value))
.collect::<Vec<_>>()
.join("; ");
let resp = reqwest::Client::new()
let resp = helper::reqwest_client()?
.get(format!(
"https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?host_mid={}",
user_id
Expand Down
3 changes: 2 additions & 1 deletion src/source/bilibili/video.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serde_json as json;

use super::{upgrade_to_https, Response};
use crate::{
helper,
platform::{PlatformMetadata, PlatformTrait},
source::{
FetcherTrait, Post, PostAttachment, PostAttachmentImage, PostUrl, Posts, Status,
Expand Down Expand Up @@ -90,7 +91,7 @@ impl Fetcher {
}

async fn fetch_series_archives(user_id: u64, series_id: u64) -> anyhow::Result<Posts> {
let resp = reqwest::Client::new()
let resp = helper::reqwest_client()?
.get(format!(
"https://api.bilibili.com/x/series/archives?mid={user_id}&series_id={series_id}"
))
Expand Down
4 changes: 3 additions & 1 deletion src/source/twitter/request.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use anyhow::{anyhow, ensure};
use reqwest::header::COOKIE;

use crate::helper;

pub struct TwitterCookies {
pub raw: String,
pub ct0: String,
Expand Down Expand Up @@ -52,7 +54,7 @@ impl TwitterRequester {
}

async fn request(&self, url: impl AsRef<str>) -> anyhow::Result<reqwest::Response> {
let resp = reqwest::Client::new()
let resp = helper::reqwest_client()?
.get(url.as_ref())
.bearer_auth(BEARER_TOKEN)
.header(COOKIE, &self.cookies.raw)
Expand Down
7 changes: 5 additions & 2 deletions src/task/reporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use spdlog::prelude::*;
use tokio::time::MissedTickBehavior;

use super::{Task, TaskKind};
use crate::reporter::{ConfigHeartbeat, ConfigHeartbeatKind, ReporterParams};
use crate::{
helper,
reporter::{ConfigHeartbeat, ConfigHeartbeatKind, ReporterParams},
};

pub struct TaskReporter {
params: ReporterParams,
Expand Down Expand Up @@ -35,7 +38,7 @@ impl TaskReporter {
async fn run_once(heartbeat: &ConfigHeartbeat) -> anyhow::Result<()> {
match &heartbeat.kind {
ConfigHeartbeatKind::HttpGet(http_get) => {
let response = reqwest::get(http_get.url()).await?;
let response = helper::reqwest_client()?.get(http_get.url()).send().await?;
let status = response.status();
ensure!(
status.is_success(),
Expand Down

0 comments on commit b2cb33f

Please sign in to comment.