mirror of
https://codeberg.org/icewind/rss-webhook-trigger.git
synced 2026-11-30 04:00:49 +01:00
make sync, switch to ureq
This commit is contained in:
parent
bdf01dced0
commit
ae1ef0657a
7 changed files with 603 additions and 948 deletions
1363
Cargo.lock
generated
1363
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -7,18 +7,15 @@ repository = "https://codeberg.org/icewind/rss-webhook-trigger"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
ctrlc = "3.5.2"
|
||||||
main_error = "0.1.2"
|
main_error = "0.1.2"
|
||||||
reqwest = { version = "0.12.9", default-features = false, features = [
|
|
||||||
"json",
|
|
||||||
"rustls-tls"
|
|
||||||
] }
|
|
||||||
secretfile = "0.1.0"
|
secretfile = "0.1.0"
|
||||||
serde = { version = "1.0.216", features = ["derive"] }
|
serde = { version = "1.0.216", features = ["derive"] }
|
||||||
serde_json = "1.0.134"
|
serde_json = "1.0.134"
|
||||||
syndication = "0.5.0"
|
syndication = "0.5.0"
|
||||||
thiserror = "2.0.9"
|
thiserror = "2.0.9"
|
||||||
time = { version = "0.3.37", features = ["serde", "serde-well-known"] }
|
time = { version = "0.3.37", features = ["serde", "serde-well-known"] }
|
||||||
tokio = { version = "1.42.0", features = ["macros", "rt-multi-thread", "signal"] }
|
toml = "1.1.8"
|
||||||
toml = "0.8.19"
|
|
||||||
tracing = "0.1.41"
|
tracing = "0.1.41"
|
||||||
tracing-subscriber = "0.3.19"
|
tracing-subscriber = "0.3.19"
|
||||||
|
ureq = { version = "3.4.2", features = ["json"] }
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
use crate::error::ConfigError;
|
use crate::error::ConfigError;
|
||||||
use reqwest::header::{HeaderValue, InvalidHeaderValue};
|
|
||||||
use secretfile::{load, SecretError};
|
use secretfile::{load, SecretError};
|
||||||
use serde::de::Error;
|
use serde::de::Error;
|
||||||
use serde::{Deserialize, Deserializer};
|
use serde::{Deserialize, Deserializer};
|
||||||
|
|
@ -8,7 +7,8 @@ use std::collections::HashMap;
|
||||||
use std::convert::{TryFrom, TryInto};
|
use std::convert::{TryFrom, TryInto};
|
||||||
use std::fs::read_to_string;
|
use std::fs::read_to_string;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use tokio::time::Duration;
|
use std::time::Duration;
|
||||||
|
use ureq::http::header::{HeaderValue, InvalidHeaderValue};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
use reqwest::StatusCode;
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
use ureq::http::StatusCode;
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum ParseFeedError {
|
pub enum ParseFeedError {
|
||||||
|
|
@ -16,7 +16,7 @@ pub enum ParseFeedError {
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum FetchFeedError {
|
pub enum FetchFeedError {
|
||||||
#[error("Error while fetching feed: {0:#}")]
|
#[error("Error while fetching feed: {0:#}")]
|
||||||
Network(#[from] reqwest::Error),
|
Network(#[from] ureq::Error),
|
||||||
#[error("Error while parsing feed: {0:#}")]
|
#[error("Error while parsing feed: {0:#}")]
|
||||||
Parse(#[from] ParseFeedError),
|
Parse(#[from] ParseFeedError),
|
||||||
#[error("Docker hub returned a server error {0}")]
|
#[error("Docker hub returned a server error {0}")]
|
||||||
|
|
@ -42,7 +42,7 @@ pub enum ConfigError {
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum HubError {
|
pub enum HubError {
|
||||||
#[error("Error while fetching docker hub info: {0:#}")]
|
#[error("Error while fetching docker hub info: {0:#}")]
|
||||||
Network(#[from] reqwest::Error),
|
Network(#[from] ureq::Error),
|
||||||
#[error("Error while parsing hub response: {0:#}")]
|
#[error("Error while parsing hub response: {0:#}")]
|
||||||
Parse(#[from] serde_json::Error),
|
Parse(#[from] serde_json::Error),
|
||||||
#[error("Docker hub returned a server error {0}")]
|
#[error("Docker hub returned a server error {0}")]
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
use reqwest::header::{
|
|
||||||
HeaderMap, HeaderValue, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, RETRY_AFTER,
|
|
||||||
};
|
|
||||||
use reqwest::{Response, StatusCode};
|
|
||||||
use std::future::Future;
|
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use time::format_description::well_known::Rfc2822;
|
use time::format_description::well_known::Rfc2822;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
|
use ureq::http::header::{
|
||||||
|
HeaderMap, HeaderValue, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED, RETRY_AFTER,
|
||||||
|
};
|
||||||
|
use ureq::http::{Response, StatusCode};
|
||||||
|
use ureq::Body;
|
||||||
|
|
||||||
/// waiting 6 hours after a 429 should be slow enough for everyone
|
/// waiting 6 hours after a 429 should be slow enough for everyone
|
||||||
const DEFAULT_BACKOFF: Duration = Duration::from_secs(6 * 60 * 60);
|
const DEFAULT_BACKOFF: Duration = Duration::from_secs(6 * 60 * 60);
|
||||||
|
|
@ -74,12 +74,6 @@ impl CacheHeaders {
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn headers(&self) -> HeaderMap {
|
|
||||||
let mut headers = HeaderMap::new();
|
|
||||||
self.set_headers(&mut headers);
|
|
||||||
headers
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FetchPlan {
|
pub struct FetchPlan {
|
||||||
|
|
@ -168,8 +162,8 @@ impl<T, E> FetchResponse<T, E> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E> FetchResponse<Response, E> {
|
impl<E> FetchResponse<Response<Body>, E> {
|
||||||
pub fn from_result(result: Result<Response, E>) -> FetchResponse<Response, E> {
|
pub fn from_result(result: Result<Response<Body>, E>) -> FetchResponse<Response<Body>, E> {
|
||||||
match result {
|
match result {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
let cache_header = CacheHeaders::from_headers(response.headers());
|
let cache_header = CacheHeaders::from_headers(response.headers());
|
||||||
|
|
@ -231,16 +225,15 @@ impl<E> FetchResponse<Response, E> {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, E> FetchResponse<T, E> {
|
impl<T, E> FetchResponse<T, E> {
|
||||||
pub async fn map<U, Fut, F>(self, f: F) -> FetchResponse<U, E>
|
pub fn map<U, F>(self, f: F) -> FetchResponse<U, E>
|
||||||
where
|
where
|
||||||
Fut: Future<Output = U>,
|
F: Fn(T) -> U,
|
||||||
F: Fn(T) -> Fut,
|
|
||||||
{
|
{
|
||||||
match self {
|
match self {
|
||||||
FetchResponse::Retry { time, headers } => FetchResponse::Retry { time, headers },
|
FetchResponse::Retry { time, headers } => FetchResponse::Retry { time, headers },
|
||||||
FetchResponse::Ok { headers, response } => FetchResponse::Ok {
|
FetchResponse::Ok { headers, response } => FetchResponse::Ok {
|
||||||
headers,
|
headers,
|
||||||
response: f(response).await,
|
response: f(response),
|
||||||
},
|
},
|
||||||
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
||||||
FetchResponse::Error { error, headers } => FetchResponse::Error { error, headers },
|
FetchResponse::Error { error, headers } => FetchResponse::Error { error, headers },
|
||||||
|
|
@ -275,10 +268,7 @@ impl<T, E> FetchResponse<Result<T, E>, E> {
|
||||||
response: Err(error),
|
response: Err(error),
|
||||||
} => FetchResponse::Error { error, headers },
|
} => FetchResponse::Error { error, headers },
|
||||||
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
FetchResponse::NotModified { headers } => FetchResponse::NotModified { headers },
|
||||||
FetchResponse::Error { error, headers } => FetchResponse::Error {
|
FetchResponse::Error { error, headers } => FetchResponse::Error { error, headers },
|
||||||
error,
|
|
||||||
headers,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
33
src/hub.rs
33
src/hub.rs
|
|
@ -1,40 +1,43 @@
|
||||||
use crate::error::HubError;
|
use crate::error::HubError;
|
||||||
use crate::fetcher::{CacheHeaders, FetchResponse};
|
use crate::fetcher::{CacheHeaders, FetchResponse};
|
||||||
use reqwest::{Client};
|
use crate::FETCHER_USER_AGENT;
|
||||||
use reqwest::header::{HeaderValue, USER_AGENT};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use crate::FETCHER_USER_AGENT;
|
use ureq::http::header::USER_AGENT;
|
||||||
|
use ureq::http::HeaderValue;
|
||||||
|
use ureq::Agent;
|
||||||
|
|
||||||
#[instrument(skip(client))]
|
#[instrument(skip(client))]
|
||||||
pub async fn tags(
|
pub fn tags(
|
||||||
client: &Client,
|
client: &Agent,
|
||||||
user: &str,
|
user: &str,
|
||||||
repo: &str,
|
repo: &str,
|
||||||
cache_headers: &CacheHeaders,
|
cache_headers: &CacheHeaders,
|
||||||
) -> FetchResponse<Vec<HubTag>, HubError> {
|
) -> FetchResponse<Vec<HubTag>, HubError> {
|
||||||
let result = client
|
let mut req = client
|
||||||
.get(format!(
|
.get(format!(
|
||||||
"https://hub.docker.com/v2/repositories/{}/{}/tags",
|
"https://hub.docker.com/v2/repositories/{}/{}/tags",
|
||||||
user, repo
|
user, repo
|
||||||
))
|
))
|
||||||
.headers(cache_headers.headers())
|
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT));
|
||||||
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT))
|
cache_headers.set_headers(req.headers_mut().unwrap());
|
||||||
.send()
|
let result = req.call();
|
||||||
.await;
|
|
||||||
|
|
||||||
FetchResponse::from_result(result)
|
FetchResponse::from_result(result)
|
||||||
.map_err(HubError::Network)
|
.map_err(HubError::Network)
|
||||||
.check_status_code(HubError::ClientError, HubError::ServerError)
|
.check_status_code(HubError::ClientError, HubError::ServerError)
|
||||||
.map(|response| async {
|
.map(|response| {
|
||||||
response
|
response
|
||||||
.text()
|
.into_body()
|
||||||
.await
|
.read_to_string()
|
||||||
.map_err(HubError::Network)
|
.map_err(HubError::Network)
|
||||||
.and_then(|text| serde_json::from_str::<HubTagResponse>(&text).map_err(HubError::Parse))
|
.and_then(|text| {
|
||||||
|
serde_json::from_str::<HubTagResponse>(&text).map_err(HubError::Parse)
|
||||||
|
})
|
||||||
.map(|result| result.results)
|
.map(|result| result.results)
|
||||||
}).await.flatten()
|
})
|
||||||
|
.flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
|
|
||||||
96
src/main.rs
96
src/main.rs
|
|
@ -7,24 +7,31 @@ use crate::config::{Config, FeedConfig};
|
||||||
use crate::error::{FetchError, FetchFeedError, HubError, ParseFeedError};
|
use crate::error::{FetchError, FetchFeedError, HubError, ParseFeedError};
|
||||||
use crate::fetcher::{next_fetch, CacheHeaders, FetchPlan, FetchResponse};
|
use crate::fetcher::{next_fetch, CacheHeaders, FetchPlan, FetchResponse};
|
||||||
use main_error::MainResult;
|
use main_error::MainResult;
|
||||||
use reqwest::{Client, Response};
|
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::future::ready;
|
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::{Duration};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use reqwest::header::{HeaderValue, USER_AGENT};
|
use std::thread::sleep;
|
||||||
|
use std::time::Duration;
|
||||||
use syndication::Feed;
|
use syndication::Feed;
|
||||||
use tokio::select;
|
|
||||||
use tokio::signal::ctrl_c;
|
|
||||||
use tokio::time::sleep;
|
|
||||||
use tracing::{debug, error, info, instrument, warn};
|
use tracing::{debug, error, info, instrument, warn};
|
||||||
|
use ureq::http::header::{HeaderValue, USER_AGENT};
|
||||||
|
use ureq::http::Response;
|
||||||
|
use ureq::{Agent, Body};
|
||||||
|
|
||||||
const FETCHER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"), " (", env!("CARGO_PKG_REPOSITORY"), ")");
|
const FETCHER_USER_AGENT: &str = concat!(
|
||||||
|
env!("CARGO_PKG_NAME"),
|
||||||
|
"/",
|
||||||
|
env!("CARGO_PKG_VERSION"),
|
||||||
|
" (",
|
||||||
|
env!("CARGO_PKG_REPOSITORY"),
|
||||||
|
")"
|
||||||
|
);
|
||||||
|
|
||||||
#[tokio::main]
|
static RUNNING: AtomicBool = AtomicBool::new(true);
|
||||||
async fn main() -> MainResult {
|
|
||||||
|
fn main() -> MainResult {
|
||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
let mut args = std::env::args();
|
let mut args = std::env::args();
|
||||||
let bin = args.next().unwrap();
|
let bin = args.next().unwrap();
|
||||||
|
|
@ -41,37 +48,33 @@ async fn main() -> MainResult {
|
||||||
|
|
||||||
info!("Running rss trigger for {} feeds", config.feed.len());
|
info!("Running rss trigger for {} feeds", config.feed.len());
|
||||||
|
|
||||||
let ctrl_c = async {
|
ctrlc::set_handler(|| RUNNING.store(false, Ordering::SeqCst))?;
|
||||||
ctrl_c().await.ok();
|
|
||||||
};
|
main_loop(config);
|
||||||
|
|
||||||
select! {
|
|
||||||
_ = ctrl_c => {},
|
|
||||||
_ = main_loop(config) => {}
|
|
||||||
}
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn main_loop(config: Config) {
|
fn main_loop(config: Config) {
|
||||||
let mut fetcher = FeedFetcher::new(config.interval());
|
let mut fetcher = FeedFetcher::new(config.interval());
|
||||||
|
|
||||||
loop {
|
while RUNNING.load(Ordering::SeqCst) {
|
||||||
for feed in config.feed.iter() {
|
for feed in config.feed.iter() {
|
||||||
match fetcher.check_feed_updated(&feed.feed).await {
|
match fetcher.check_feed_updated(&feed.feed) {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
trigger(&fetcher.client, feed).await;
|
trigger(&fetcher.client, feed);
|
||||||
}
|
}
|
||||||
Err(e) => error!(error = ?e, feed = feed.feed, "failed to check feed"),
|
Err(e) => error!(error = ?e, feed = feed.feed, "failed to check feed"),
|
||||||
Ok(false) => {}
|
Ok(false) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sleep(config.interval()).await;
|
sleep(config.interval());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip_all, fields(feed = feed.feed))]
|
#[instrument(skip_all, fields(feed = feed.feed))]
|
||||||
async fn trigger(client: &Client, feed: &FeedConfig) {
|
fn trigger(client: &Agent, feed: &FeedConfig) {
|
||||||
info!("Triggering hook");
|
info!("Triggering hook");
|
||||||
let mut req = client
|
let mut req = client
|
||||||
.post(&feed.hook)
|
.post(&feed.hook)
|
||||||
|
|
@ -79,17 +82,20 @@ async fn trigger(client: &Client, feed: &FeedConfig) {
|
||||||
for (key, value) in &feed.headers {
|
for (key, value) in &feed.headers {
|
||||||
req = req.header(key, value);
|
req = req.header(key, value);
|
||||||
}
|
}
|
||||||
if !feed.body.is_null() {
|
|
||||||
req = req.json(&feed.body);
|
|
||||||
}
|
|
||||||
debug!(request = ?req, "sending trigger request");
|
debug!(request = ?req, "sending trigger request");
|
||||||
if let Err(e) = req.send().await.and_then(|res| res.error_for_status()) {
|
let res = if feed.body.is_null() {
|
||||||
|
req.send_json(&feed.body)
|
||||||
|
} else {
|
||||||
|
req.send_empty()
|
||||||
|
};
|
||||||
|
if let Err(e) = res {
|
||||||
error!("{:#}", e);
|
error!("{:#}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FeedFetcher {
|
pub struct FeedFetcher {
|
||||||
client: Client,
|
client: Agent,
|
||||||
base_interval: Duration,
|
base_interval: Duration,
|
||||||
cache: HashMap<String, u64>,
|
cache: HashMap<String, u64>,
|
||||||
fetch_plans: HashMap<String, FetchPlan>,
|
fetch_plans: HashMap<String, FetchPlan>,
|
||||||
|
|
@ -98,7 +104,7 @@ pub struct FeedFetcher {
|
||||||
impl FeedFetcher {
|
impl FeedFetcher {
|
||||||
pub fn new(interval: Duration) -> Self {
|
pub fn new(interval: Duration) -> Self {
|
||||||
FeedFetcher {
|
FeedFetcher {
|
||||||
client: Client::default(),
|
client: Agent::new_with_defaults(),
|
||||||
base_interval: interval,
|
base_interval: interval,
|
||||||
cache: HashMap::default(),
|
cache: HashMap::default(),
|
||||||
fetch_plans: HashMap::default(),
|
fetch_plans: HashMap::default(),
|
||||||
|
|
@ -113,17 +119,18 @@ impl FeedFetcher {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip(self))]
|
#[instrument(skip(self))]
|
||||||
pub async fn check_feed_updated(&mut self, feed: &str) -> Result<bool, FetchError> {
|
pub fn check_feed_updated(&mut self, feed: &str) -> Result<bool, FetchError> {
|
||||||
if !self.should_update(feed) {
|
if !self.should_update(feed) {
|
||||||
warn!("skipping feed util rate limited expires");
|
warn!("skipping feed util rate limited expires");
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
let plan = self.fetch_plans.remove(feed).unwrap_or_default();
|
let plan = self.fetch_plans.remove(feed).unwrap_or_default();
|
||||||
|
|
||||||
let fetch_result = self.get_feed_key(feed, &plan.headers).await;
|
let fetch_result = self.get_feed_key(feed, &plan.headers);
|
||||||
let (result, new_plan) = fetch_result.into_result();
|
let (result, new_plan) = fetch_result.into_result();
|
||||||
let is_retry = new_plan.is_retry();
|
let is_retry = new_plan.is_retry();
|
||||||
self.fetch_plans.insert(feed.into(), next_fetch(self.base_interval, Some(new_plan)));
|
self.fetch_plans
|
||||||
|
.insert(feed.into(), next_fetch(self.base_interval, Some(new_plan)));
|
||||||
let new_key = result?;
|
let new_key = result?;
|
||||||
|
|
||||||
Ok(match (self.cache.get_mut(feed), new_key) {
|
Ok(match (self.cache.get_mut(feed), new_key) {
|
||||||
|
|
@ -156,7 +163,7 @@ impl FeedFetcher {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip(self))]
|
#[instrument(skip(self))]
|
||||||
async fn get_feed_key(
|
fn get_feed_key(
|
||||||
&self,
|
&self,
|
||||||
feed: &str,
|
feed: &str,
|
||||||
cache_headers: &CacheHeaders,
|
cache_headers: &CacheHeaders,
|
||||||
|
|
@ -164,15 +171,14 @@ impl FeedFetcher {
|
||||||
if let Some(hub) = feed.strip_prefix("docker-hub://") {
|
if let Some(hub) = feed.strip_prefix("docker-hub://") {
|
||||||
if let Some((user, repo)) = hub.split_once('/') {
|
if let Some((user, repo)) = hub.split_once('/') {
|
||||||
hub::tags(&self.client, user, repo, cache_headers)
|
hub::tags(&self.client, user, repo, cache_headers)
|
||||||
.await
|
|
||||||
.map(|tags| {
|
.map(|tags| {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
for tag in tags {
|
for tag in tags {
|
||||||
tag.id.hash(&mut hasher);
|
tag.id.hash(&mut hasher);
|
||||||
tag.last_updated.hash(&mut hasher);
|
tag.last_updated.hash(&mut hasher);
|
||||||
}
|
}
|
||||||
ready(hasher.finish())
|
hasher.finish()
|
||||||
}).await
|
})
|
||||||
.map_err(FetchError::Hub)
|
.map_err(FetchError::Hub)
|
||||||
} else {
|
} else {
|
||||||
FetchResponse::Error {
|
FetchResponse::Error {
|
||||||
|
|
@ -182,37 +188,35 @@ impl FeedFetcher {
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.get_rss_feed_key(feed, cache_headers)
|
self.get_rss_feed_key(feed, cache_headers)
|
||||||
.await
|
|
||||||
.map_err(FetchError::Feed)
|
.map_err(FetchError::Feed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(skip(self))]
|
#[instrument(skip(self))]
|
||||||
async fn get_rss_feed_key(
|
fn get_rss_feed_key(
|
||||||
&self,
|
&self,
|
||||||
feed: &str,
|
feed: &str,
|
||||||
cache_headers: &CacheHeaders,
|
cache_headers: &CacheHeaders,
|
||||||
) -> FetchResponse<u64, FetchFeedError> {
|
) -> FetchResponse<u64, FetchFeedError> {
|
||||||
let response = self
|
let mut req = self
|
||||||
.client
|
.client
|
||||||
.get(feed)
|
.get(feed)
|
||||||
.headers(cache_headers.headers())
|
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT));
|
||||||
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT))
|
cache_headers.set_headers(req.headers_mut().unwrap());
|
||||||
.send()
|
|
||||||
.await;
|
let response = req.call();
|
||||||
|
|
||||||
let plan_result = FetchResponse::from_result(response);
|
let plan_result = FetchResponse::from_result(response);
|
||||||
plan_result
|
plan_result
|
||||||
.map_err(FetchFeedError::Network)
|
.map_err(FetchFeedError::Network)
|
||||||
.check_status_code(FetchFeedError::ClientError, FetchFeedError::ServerError)
|
.check_status_code(FetchFeedError::ClientError, FetchFeedError::ServerError)
|
||||||
.map(parse_rss_response)
|
.map(parse_rss_response)
|
||||||
.await
|
|
||||||
.flatten()
|
.flatten()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn parse_rss_response(response: Response) -> Result<u64, FetchFeedError> {
|
fn parse_rss_response(response: Response<Body>) -> Result<u64, FetchFeedError> {
|
||||||
let content = response.text().await?;
|
let content = response.into_body().read_to_string()?;
|
||||||
let channel = Feed::from_str(&content).map_err(ParseFeedError::Parse)?;
|
let channel = Feed::from_str(&content).map_err(ParseFeedError::Parse)?;
|
||||||
|
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue